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
sequence
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
sequence
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
a2f9e56e632c2e989d30e6e46b8af5078990f96e
25,262,997,641,204
4691acca4e62da71a857385cffce2b6b4aef3bb3
/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/SerializableLambdaExpression.java
74541013bb9713da1fbef9f1a7c0f193e02eb8c2
[ "MIT" ]
permissive
lor6/tutorials
https://github.com/lor6/tutorials
800f2e48d7968c047407bbd8a61b47be7ec352f2
e993db2c23d559d503b8bf8bc27aab0847224593
refs/heads/master
2023-05-29T06:17:47.980000
2023-05-19T08:37:45
2023-05-19T08:37:45
145,218,314
7
11
MIT
true
2018-08-18T12:29:20
2018-08-18T12:29:19
2018-08-18T12:01:20
2018-08-18T12:01:05
108,692
0
0
0
null
false
null
package com.baeldung.java8.lambda.serialization; import java.io.Serializable; public class SerializableLambdaExpression { public static Object getLambdaExpressionObject() { Runnable r = (Runnable & Serializable) () -> System.out.println("please serialize this message"); return r; } }
UTF-8
Java
311
java
SerializableLambdaExpression.java
Java
[]
null
[]
package com.baeldung.java8.lambda.serialization; import java.io.Serializable; public class SerializableLambdaExpression { public static Object getLambdaExpressionObject() { Runnable r = (Runnable & Serializable) () -> System.out.println("please serialize this message"); return r; } }
311
0.726688
0.723473
10
30.1
31.832216
105
false
false
0
0
0
0
0
0
0.4
false
false
11
fb7a9eea4fa8e5c7517fb9b914f56e585220c142
77,309,422,011
871c7479b1cb0aa22909f974492f4eeb4238a5d8
/src/main/java/com/acme/webserviceserentcar/client/resource/CreateCommentResource.java
45004afc48ab3f4d76262dacf3fcd6f1e7d1cfdb
[]
no_license
SebastianBran/Web-Services-eRentCar
https://github.com/SebastianBran/Web-Services-eRentCar
7cd00db9f620646f1576f754c023a88711ec8a3c
bc1c2ea80bfcfd06dcf926d849c375e478e41237
refs/heads/master
2023-09-02T11:11:17.612000
2021-11-23T08:05:31
2021-11-23T08:05:31
404,839,159
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.acme.webserviceserentcar.client.resource; import lombok.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @With public class CreateCommentResource { @NotNull @NotBlank @Size(max = 8) private String date; @NotNull private int stars; @NotNull @NotBlank @Size(max = 100) private String comment; }
UTF-8
Java
492
java
CreateCommentResource.java
Java
[]
null
[]
package com.acme.webserviceserentcar.client.resource; import lombok.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @With public class CreateCommentResource { @NotNull @NotBlank @Size(max = 8) private String date; @NotNull private int stars; @NotNull @NotBlank @Size(max = 100) private String comment; }
492
0.739837
0.731707
27
17.222221
15.014397
53
false
false
0
0
0
0
0
0
0.296296
false
false
11
dbe04c93955b21f15e8d9de47663f1899e9ac264
77,309,421,415
ab964d1a95a6324f6e59bf522fdee674b9464e09
/tiger-core/src/main/java/tiger/core/service/department/impl/SalesManServiceImpl.java
97d807fa38a44dab67a92415150b7d4447b6f6b7
[]
no_license
liu412825long/tigerback
https://github.com/liu412825long/tigerback
0e4865909d61b3cdfd1f8a1a8e26e4fad9113458
50779083615842a7bfd5b4c43b18a0b311317d94
refs/heads/master
2018-04-06T14:40:00.688000
2017-04-26T01:54:50
2017-04-26T01:54:50
89,425,187
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tiger.core.service.department.impl; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import tiger.common.dal.dataobject.CustomerDO; import tiger.common.dal.dataobject.SalesManDO; import tiger.common.dal.persistence.DepartmentSalesManMapper; import tiger.common.dal.persistence.SalesManMapper; import tiger.common.dal.query.CustomerQuery; import tiger.common.util.DateUtil; import tiger.common.util.Paginator; import tiger.core.base.PageResult; import tiger.core.domain.CustomerDomain; import tiger.core.domain.department.SalesManDomain; import tiger.core.domain.department.convert.SalesManConvert; import tiger.core.service.department.DepartmentSalesManService; import tiger.core.service.department.SalesManService; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author LiuHaiLong * Created by xgkj01 on 17/1/3. */ @Service public class SalesManServiceImpl implements SalesManService { private final Logger logger= Logger.getLogger(SalesManServiceImpl.class); @Autowired private SalesManMapper salesManMapper; @Autowired private DepartmentSalesManService departmentSalesManService; /** * * 创建业务员,部门ID必填,外部判断 * @param salesManDomain * * */ @Override @Transactional public SalesManDomain createSalesMan(SalesManDomain salesManDomain) { Date currentDate=new Date(); salesManDomain.setCreateTime(currentDate); salesManDomain.setUpdateTime(currentDate); SalesManDO salesManDO=SalesManConvert.convert2DO(salesManDomain); if(salesManDO!=null){ int result= salesManMapper.insertSelective(salesManDO); if(result>0){ logger.info("创建业务员成功。业务员信息为:"+salesManDomain); int ds=departmentSalesManService.createRelate(salesManDomain.getDepartmentId(),salesManDO.getId()); SalesManDomain readSalesMan=readSalesMan(salesManDO.getId()); readSalesMan.setDepartmentId(salesManDomain.getDepartmentId()); return readSalesMan; } logger.info("创建业务员失败"); } return null; } /** * 逻辑删除业务员 * @param id * */ @Override public boolean deleteSalesMan(Long id) { List<Long> ids=new ArrayList<>(); ids.add(id); return salesManMapper.deleteSalesManByIds(ids)>0; } /** * 修改业务员信息 * @param salesManDomain * */ @Override public SalesManDomain updateSalesMan(SalesManDomain salesManDomain) { int result=salesManMapper.updateByPrimaryKeySelective(SalesManConvert.convert2DO(salesManDomain)); if(result>0){ return readSalesMan(salesManDomain.getId()); } return null; } /** * 通过业务员ID查询业务员信息 * @param salesManId * */ @Override public SalesManDomain readSalesMan(Long salesManId) { SalesManDO salesManDO=salesManMapper.selectByPrimaryKey(salesManId); return SalesManConvert.convert2Domain(salesManDO); } private SalesManDomain readById(Long salesManId) { SalesManDO salesManDO=salesManMapper.selectById(salesManId); return SalesManConvert.convert2Domain(salesManDO); } /** * 通过部门ID查询所有的业务员 * @param departmentId * */ @Override public List<SalesManDomain> readByDepartmentId(Long departmentId) { List<Long> salesManIds= departmentSalesManService.readByDepartmentId(departmentId); if(salesManIds!=null&&!salesManIds.isEmpty()){ List<SalesManDO> salesMan=salesManMapper.selectByIds(salesManIds); logger.info("查询到部门ID:"+departmentId+",的业务员为:"+salesMan); List<SalesManDomain> salesManDomains=SalesManConvert.convert2Domains(salesMan); salesManDomains.forEach(salesManDomain -> { salesManDomain.setDepartmentId(departmentId); }); return salesManDomains; } return null; } @Override public List<SalesManDomain> batchRead(List<Long> ids) { List<SalesManDomain> salesManDomains=new ArrayList<>(); ids.forEach(id->{ salesManDomains.add(readById(id)); }); return salesManDomains; } }
UTF-8
Java
4,569
java
SalesManServiceImpl.java
Java
[ { "context": ".util.Date;\nimport java.util.List;\n\n/**\n * @author LiuHaiLong\n * Created by xgkj01 on 17/1/3.\n */\n@Service\npubl", "end": 985, "score": 0.9997953176498413, "start": 975, "tag": "NAME", "value": "LiuHaiLong" }, { "context": "til.List;\n\n/**\n * @author LiuHaiLong\n * Created by xgkj01 on 17/1/3.\n */\n@Service\npublic class SalesManServ", "end": 1006, "score": 0.9994800686836243, "start": 1000, "tag": "USERNAME", "value": "xgkj01" } ]
null
[]
package tiger.core.service.department.impl; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import tiger.common.dal.dataobject.CustomerDO; import tiger.common.dal.dataobject.SalesManDO; import tiger.common.dal.persistence.DepartmentSalesManMapper; import tiger.common.dal.persistence.SalesManMapper; import tiger.common.dal.query.CustomerQuery; import tiger.common.util.DateUtil; import tiger.common.util.Paginator; import tiger.core.base.PageResult; import tiger.core.domain.CustomerDomain; import tiger.core.domain.department.SalesManDomain; import tiger.core.domain.department.convert.SalesManConvert; import tiger.core.service.department.DepartmentSalesManService; import tiger.core.service.department.SalesManService; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author LiuHaiLong * Created by xgkj01 on 17/1/3. */ @Service public class SalesManServiceImpl implements SalesManService { private final Logger logger= Logger.getLogger(SalesManServiceImpl.class); @Autowired private SalesManMapper salesManMapper; @Autowired private DepartmentSalesManService departmentSalesManService; /** * * 创建业务员,部门ID必填,外部判断 * @param salesManDomain * * */ @Override @Transactional public SalesManDomain createSalesMan(SalesManDomain salesManDomain) { Date currentDate=new Date(); salesManDomain.setCreateTime(currentDate); salesManDomain.setUpdateTime(currentDate); SalesManDO salesManDO=SalesManConvert.convert2DO(salesManDomain); if(salesManDO!=null){ int result= salesManMapper.insertSelective(salesManDO); if(result>0){ logger.info("创建业务员成功。业务员信息为:"+salesManDomain); int ds=departmentSalesManService.createRelate(salesManDomain.getDepartmentId(),salesManDO.getId()); SalesManDomain readSalesMan=readSalesMan(salesManDO.getId()); readSalesMan.setDepartmentId(salesManDomain.getDepartmentId()); return readSalesMan; } logger.info("创建业务员失败"); } return null; } /** * 逻辑删除业务员 * @param id * */ @Override public boolean deleteSalesMan(Long id) { List<Long> ids=new ArrayList<>(); ids.add(id); return salesManMapper.deleteSalesManByIds(ids)>0; } /** * 修改业务员信息 * @param salesManDomain * */ @Override public SalesManDomain updateSalesMan(SalesManDomain salesManDomain) { int result=salesManMapper.updateByPrimaryKeySelective(SalesManConvert.convert2DO(salesManDomain)); if(result>0){ return readSalesMan(salesManDomain.getId()); } return null; } /** * 通过业务员ID查询业务员信息 * @param salesManId * */ @Override public SalesManDomain readSalesMan(Long salesManId) { SalesManDO salesManDO=salesManMapper.selectByPrimaryKey(salesManId); return SalesManConvert.convert2Domain(salesManDO); } private SalesManDomain readById(Long salesManId) { SalesManDO salesManDO=salesManMapper.selectById(salesManId); return SalesManConvert.convert2Domain(salesManDO); } /** * 通过部门ID查询所有的业务员 * @param departmentId * */ @Override public List<SalesManDomain> readByDepartmentId(Long departmentId) { List<Long> salesManIds= departmentSalesManService.readByDepartmentId(departmentId); if(salesManIds!=null&&!salesManIds.isEmpty()){ List<SalesManDO> salesMan=salesManMapper.selectByIds(salesManIds); logger.info("查询到部门ID:"+departmentId+",的业务员为:"+salesMan); List<SalesManDomain> salesManDomains=SalesManConvert.convert2Domains(salesMan); salesManDomains.forEach(salesManDomain -> { salesManDomain.setDepartmentId(departmentId); }); return salesManDomains; } return null; } @Override public List<SalesManDomain> batchRead(List<Long> ids) { List<SalesManDomain> salesManDomains=new ArrayList<>(); ids.forEach(id->{ salesManDomains.add(readById(id)); }); return salesManDomains; } }
4,569
0.695929
0.692518
135
31.57037
26.762201
115
false
false
0
0
0
0
0
0
0.451852
false
false
11
917d8d219bd017cafe42611d5cf23641b8cdf1b6
20,229,295,966,624
38d1b53f272f91de55e11351b112885cf9b569b4
/src/main/java/com/leiming/blog/controller/BlogController.java
3b44901db75bdb05a84bf3860382ff004393e039
[]
no_license
LovelyLM/blog_competition
https://github.com/LovelyLM/blog_competition
eb110dea6ce406b1b8f6a0e2bd3a056021e5d093
efe5a6a395d05bb363a3edcd27cf15da2b83d5aa
refs/heads/master
2022-06-22T16:15:14.636000
2019-10-17T01:40:25
2019-10-17T01:40:25
204,953,719
1
0
null
false
2022-06-21T01:45:58
2019-08-28T14:38:39
2019-10-17T01:40:28
2022-06-21T01:45:54
7,643
1
0
3
CSS
false
false
package com.leiming.blog.controller; import com.leiming.blog.domain.Blog; import com.leiming.blog.domain.BlogComment; import com.leiming.blog.domain.Catalog; import com.leiming.blog.domain.User; import com.leiming.blog.dto.PageBean; import com.leiming.blog.service.BlogCommentService; import com.leiming.blog.service.BlogService; import com.leiming.blog.service.CatalogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.List; @Controller public class BlogController { @Autowired private BlogService blogService; @Autowired private CatalogService catalogsService; @Autowired private BlogCommentService blogCommentService; @RequestMapping("/saveBlog") @ResponseBody public String saveMood(Blog blog, HttpServletRequest servletRequest, String catalogString){ Date date = new Date(System.currentTimeMillis()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String createTime = format.format(date); blog.setCreateTime(createTime); blog.setCatalogs(new HashSet<Catalog>()); if (servletRequest.getSession().getAttribute("cover")!=null){ blog.setCover((String) servletRequest.getSession().getAttribute("cover")); }else { blog.setCover("default.jpeg"); } blog.setCommentNumber(0L); blog.setViewNumber(0L); String[] split = catalogString.split(";"); for (String s:split) { Catalog catalog =new Catalog(null,s,new HashSet<Blog>()); Catalog temp = catalogsService.findCatalogByCatalog(s); if (temp==null){ catalogsService.saveCatalog(catalog); }else { catalog = temp; } blog.getCatalogs().add(catalog); } blogService.save(blog); servletRequest.getSession().setAttribute("cover","default.jpeg"); return "redirect:/blog"; } @RequestMapping("blog") @ResponseBody public ModelAndView findAllBlog(Model model){ List<Blog> blogList = blogService.findAllBlogLimit7(); List<Catalog> catalogList= catalogsService.findAllCatalog(); model.addAttribute("blogList",blogList); model.addAttribute("catalogList",catalogList); return new ModelAndView("blog.html","blogModel",model); } @RequestMapping("blogDetail") @ResponseBody public ModelAndView blogDetail(Model model,String id,Integer currentPage){ blogService.updateReads(Long.valueOf(id)); Blog blog = blogService.findAllById(Long.valueOf(id)); PageBean blogCommentPageBean = blogCommentService.getMessagePageBean(Long.valueOf(id),currentPage); model.addAttribute("blogCommentPageBean",blogCommentPageBean); model.addAttribute("blog",blog); return new ModelAndView("detail.html","blogModel",model); } @RequestMapping(value = "/delBlog",method = RequestMethod.POST ) @ResponseBody public String delBlog(String blogId){ if (blogId!=null&&blogId!=""){ blogService.delBlog(blogId); return "ok"; } return "no"; } }
UTF-8
Java
3,700
java
BlogController.java
Java
[]
null
[]
package com.leiming.blog.controller; import com.leiming.blog.domain.Blog; import com.leiming.blog.domain.BlogComment; import com.leiming.blog.domain.Catalog; import com.leiming.blog.domain.User; import com.leiming.blog.dto.PageBean; import com.leiming.blog.service.BlogCommentService; import com.leiming.blog.service.BlogService; import com.leiming.blog.service.CatalogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.List; @Controller public class BlogController { @Autowired private BlogService blogService; @Autowired private CatalogService catalogsService; @Autowired private BlogCommentService blogCommentService; @RequestMapping("/saveBlog") @ResponseBody public String saveMood(Blog blog, HttpServletRequest servletRequest, String catalogString){ Date date = new Date(System.currentTimeMillis()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String createTime = format.format(date); blog.setCreateTime(createTime); blog.setCatalogs(new HashSet<Catalog>()); if (servletRequest.getSession().getAttribute("cover")!=null){ blog.setCover((String) servletRequest.getSession().getAttribute("cover")); }else { blog.setCover("default.jpeg"); } blog.setCommentNumber(0L); blog.setViewNumber(0L); String[] split = catalogString.split(";"); for (String s:split) { Catalog catalog =new Catalog(null,s,new HashSet<Blog>()); Catalog temp = catalogsService.findCatalogByCatalog(s); if (temp==null){ catalogsService.saveCatalog(catalog); }else { catalog = temp; } blog.getCatalogs().add(catalog); } blogService.save(blog); servletRequest.getSession().setAttribute("cover","default.jpeg"); return "redirect:/blog"; } @RequestMapping("blog") @ResponseBody public ModelAndView findAllBlog(Model model){ List<Blog> blogList = blogService.findAllBlogLimit7(); List<Catalog> catalogList= catalogsService.findAllCatalog(); model.addAttribute("blogList",blogList); model.addAttribute("catalogList",catalogList); return new ModelAndView("blog.html","blogModel",model); } @RequestMapping("blogDetail") @ResponseBody public ModelAndView blogDetail(Model model,String id,Integer currentPage){ blogService.updateReads(Long.valueOf(id)); Blog blog = blogService.findAllById(Long.valueOf(id)); PageBean blogCommentPageBean = blogCommentService.getMessagePageBean(Long.valueOf(id),currentPage); model.addAttribute("blogCommentPageBean",blogCommentPageBean); model.addAttribute("blog",blog); return new ModelAndView("detail.html","blogModel",model); } @RequestMapping(value = "/delBlog",method = RequestMethod.POST ) @ResponseBody public String delBlog(String blogId){ if (blogId!=null&&blogId!=""){ blogService.delBlog(blogId); return "ok"; } return "no"; } }
3,700
0.702703
0.701892
93
38.784946
23.046867
107
false
false
0
0
0
0
0
0
0.806452
false
false
11
c4efc486c05c1ace3ed9ef0294dfb75b01db872c
7,043,746,383,963
55c6117713b890a1e08839d4ccdf0ee6d9b55f85
/src/main/java/card/action/SmithyAction.java
71f28ed5674f709c5b71fde0d6ec1c6989ccff5b
[]
no_license
CarpeQueso/all-about-that-big-money
https://github.com/CarpeQueso/all-about-that-big-money
6358230e1eb3f79f581020f082debb1a70da3365
aeb84daa1e8d1bb85dc7d48f4ffcdff631229388
refs/heads/master
2016-08-05T01:47:10.307000
2015-04-19T03:02:54
2015-04-19T03:02:54
30,127,900
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.card.action; import main.java.player.Player; /** * Created by jon on 1/26/15. */ public class SmithyAction implements Action { public void onPlay(Player player) { player.drawToHand(3); } }
UTF-8
Java
228
java
SmithyAction.java
Java
[ { "context": "import main.java.player.Player;\n\n/**\n * Created by jon on 1/26/15.\n */\npublic class SmithyAction impleme", "end": 86, "score": 0.9565260410308838, "start": 83, "tag": "USERNAME", "value": "jon" } ]
null
[]
package main.java.card.action; import main.java.player.Player; /** * Created by jon on 1/26/15. */ public class SmithyAction implements Action { public void onPlay(Player player) { player.drawToHand(3); } }
228
0.675439
0.649123
13
16.538462
16.588297
45
false
false
0
0
0
0
0
0
0.230769
false
false
11
3dd1efe76b5a5d89e96bcf9821ece71cca151ce9
9,577,777,080,030
cb9814c176d452943d5f98d15811733ff91b4211
/src/java/sait/dataaccess/UserDB.java
b1b836c34344d54b8751e16a8466e5204674988a
[]
no_license
MTocchettoP/NoteKeepr
https://github.com/MTocchettoP/NoteKeepr
23769a8141e543b1b9ceae79ab88261afaa471d6
d9ae98f349c9b80c89f77f10d436cf3508a3279b
refs/heads/master
2021-09-04T12:37:20.939000
2017-12-06T00:06:23
2017-12-06T00:06:23
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 sait.dataaccess; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import sait.domainmodel.Company; import sait.domainmodel.Role; import sait.domainmodel.User; /** * * @author awarsyle */ public class UserDB { public User getUser(String username) throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); try { User user = em.find(User.class, username); return user; } catch (Exception ex) { Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, "Cannot get user", ex); throw new NotesDBException("Error getting user"); } finally { em.close(); } } public List<User> getAllUsers() throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); try { List<User> users = em.createNamedQuery("User.findAll", User.class).getResultList(); return users; } catch (Exception ex) { Logger.getLogger(NoteDB.class.getName()).log(Level.SEVERE, "Cannot get users", ex); throw new NotesDBException("Error getting users"); } finally { em.close(); } } public int update(User newUser) throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); EntityTransaction trans = em.getTransaction(); try { trans.begin(); em.merge(newUser); trans.commit(); return 1; } catch (Exception ex) { Logger.getLogger(NoteDB.class.getName()).log(Level.SEVERE, "Cannot update " + newUser.toString(), ex); throw new NotesDBException("Error updating user"); } finally { em.close(); } } public int addUser(User newUser) throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); EntityTransaction trans = em.getTransaction(); Company comp = newUser.getCompany(); comp.getUserCollection().add(newUser); try { trans.begin(); em.merge(newUser); em.merge(comp); trans.commit(); return 1; } catch (Exception ex) { Logger.getLogger(NoteDB.class.getName()).log(Level.SEVERE, "Cannot insert " + newUser.toString(), ex); throw new NotesDBException("Error inserting user"); } finally { em.close(); } } public int removeUser(User user) throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); EntityTransaction trans = em.getTransaction(); Company comp = user.getCompany(); comp.getUserCollection().remove(user); try { trans.begin(); em.merge(comp); em.remove(em.merge(user)); trans.commit(); return 1; } catch (Exception ex) { Logger.getLogger(NoteDB.class.getName()).log(Level.SEVERE, "Cannot delete " + user.toString(), ex); throw new NotesDBException("Error deleting User"); } finally { em.close(); } } public Role getRole(int roleID) throws Exception{ EntityManager em = DBUtil.getEmFactory().createEntityManager(); try { Role role = em.find(Role.class, roleID); return role; } catch (Exception ex) { Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, "Cannot get role", ex); throw new NotesDBException("Error getting role"); } finally { em.close(); } } public Company getCompany(String company) throws NotesDBException { EntityManager em = DBUtil.getEmFactory().createEntityManager(); try { Company comp = em.find(Company.class, Integer.parseInt(company)); return comp; } catch (Exception ex) { Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, "Cannot get company", ex); throw new NotesDBException("Error getting company"); } finally { em.close(); } } }
UTF-8
Java
4,667
java
UserDB.java
Java
[ { "context": "port sait.domainmodel.User;\r\n\r\n/**\r\n *\r\n * @author awarsyle\r\n */\r\npublic class UserDB {\r\n\r\n public User ge", "end": 550, "score": 0.9995987415313721, "start": 542, "tag": "USERNAME", "value": "awarsyle" } ]
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 sait.dataaccess; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import sait.domainmodel.Company; import sait.domainmodel.Role; import sait.domainmodel.User; /** * * @author awarsyle */ public class UserDB { public User getUser(String username) throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); try { User user = em.find(User.class, username); return user; } catch (Exception ex) { Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, "Cannot get user", ex); throw new NotesDBException("Error getting user"); } finally { em.close(); } } public List<User> getAllUsers() throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); try { List<User> users = em.createNamedQuery("User.findAll", User.class).getResultList(); return users; } catch (Exception ex) { Logger.getLogger(NoteDB.class.getName()).log(Level.SEVERE, "Cannot get users", ex); throw new NotesDBException("Error getting users"); } finally { em.close(); } } public int update(User newUser) throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); EntityTransaction trans = em.getTransaction(); try { trans.begin(); em.merge(newUser); trans.commit(); return 1; } catch (Exception ex) { Logger.getLogger(NoteDB.class.getName()).log(Level.SEVERE, "Cannot update " + newUser.toString(), ex); throw new NotesDBException("Error updating user"); } finally { em.close(); } } public int addUser(User newUser) throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); EntityTransaction trans = em.getTransaction(); Company comp = newUser.getCompany(); comp.getUserCollection().add(newUser); try { trans.begin(); em.merge(newUser); em.merge(comp); trans.commit(); return 1; } catch (Exception ex) { Logger.getLogger(NoteDB.class.getName()).log(Level.SEVERE, "Cannot insert " + newUser.toString(), ex); throw new NotesDBException("Error inserting user"); } finally { em.close(); } } public int removeUser(User user) throws Exception { EntityManager em = DBUtil.getEmFactory().createEntityManager(); EntityTransaction trans = em.getTransaction(); Company comp = user.getCompany(); comp.getUserCollection().remove(user); try { trans.begin(); em.merge(comp); em.remove(em.merge(user)); trans.commit(); return 1; } catch (Exception ex) { Logger.getLogger(NoteDB.class.getName()).log(Level.SEVERE, "Cannot delete " + user.toString(), ex); throw new NotesDBException("Error deleting User"); } finally { em.close(); } } public Role getRole(int roleID) throws Exception{ EntityManager em = DBUtil.getEmFactory().createEntityManager(); try { Role role = em.find(Role.class, roleID); return role; } catch (Exception ex) { Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, "Cannot get role", ex); throw new NotesDBException("Error getting role"); } finally { em.close(); } } public Company getCompany(String company) throws NotesDBException { EntityManager em = DBUtil.getEmFactory().createEntityManager(); try { Company comp = em.find(Company.class, Integer.parseInt(company)); return comp; } catch (Exception ex) { Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, "Cannot get company", ex); throw new NotesDBException("Error getting company"); } finally { em.close(); } } }
4,667
0.579173
0.57853
140
31.335714
27.921986
114
false
false
0
0
0
0
0
0
0.628571
false
false
11
152c54ac61aea38d36f045f469bf6debb934f160
27,290,222,239,143
9fc1482d79c847c0a317359f8d2bfd88dcca6353
/TrabajoFinal/src/Modelo/SaldoClientes.java
4518ca15c00cf4c4bdc76702904b1bae4dad7a26
[]
no_license
LorenzoChiocarello/Trabajo-Final
https://github.com/LorenzoChiocarello/Trabajo-Final
274158b3e2ee37b09ce77e2e2d10bd1bfee7e2f3
c90f37aea48ac7dd7253027f04f87f73b142e1ca
refs/heads/master
2023-06-14T03:12:56.595000
2021-07-10T23:02:23
2021-07-10T23:02:23
384,812,974
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Modelo; import java.util.Date; public class SaldoClientes { private int id; private int idCliente; private double monto; private double resto; private String descripcion; private String forma_pago; private Date fecha; public SaldoClientes() { } public SaldoClientes(int id, int idCliente, double monto, double resto, String descripcion, String forma_pago, Date fecha) { this.id = id; this.idCliente = idCliente; this.monto = monto; this.resto = resto; this.descripcion = descripcion; this.forma_pago = forma_pago; this.fecha = fecha; } public SaldoClientes(int idCliente, double monto, double resto, String descripcion, String forma_pago, Date fecha) { this.idCliente = idCliente; this.monto = monto; this.resto = resto; this.descripcion = descripcion; this.forma_pago = forma_pago; this.fecha = fecha; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getIdCliente() { return idCliente; } public void setIdCliente(int idCliente) { this.idCliente = idCliente; } public double getMonto() { return monto; } public void setMonto(double monto) { this.monto = monto; } public double getResto() { return resto; } public void setResto(double resto) { this.resto = resto; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getForma_pago() { return forma_pago; } public void setForma_pago(String forma_pago) { this.forma_pago = forma_pago; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } }
UTF-8
Java
2,046
java
SaldoClientes.java
Java
[]
null
[]
package Modelo; import java.util.Date; public class SaldoClientes { private int id; private int idCliente; private double monto; private double resto; private String descripcion; private String forma_pago; private Date fecha; public SaldoClientes() { } public SaldoClientes(int id, int idCliente, double monto, double resto, String descripcion, String forma_pago, Date fecha) { this.id = id; this.idCliente = idCliente; this.monto = monto; this.resto = resto; this.descripcion = descripcion; this.forma_pago = forma_pago; this.fecha = fecha; } public SaldoClientes(int idCliente, double monto, double resto, String descripcion, String forma_pago, Date fecha) { this.idCliente = idCliente; this.monto = monto; this.resto = resto; this.descripcion = descripcion; this.forma_pago = forma_pago; this.fecha = fecha; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getIdCliente() { return idCliente; } public void setIdCliente(int idCliente) { this.idCliente = idCliente; } public double getMonto() { return monto; } public void setMonto(double monto) { this.monto = monto; } public double getResto() { return resto; } public void setResto(double resto) { this.resto = resto; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getForma_pago() { return forma_pago; } public void setForma_pago(String forma_pago) { this.forma_pago = forma_pago; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } }
2,046
0.584555
0.584555
104
18.663462
20.817713
128
false
false
0
0
0
0
0
0
0.451923
false
false
11
520c0e5cd1c302a686b565a0878a7f69d8335a64
18,940,805,794,736
a22984789554dc0460b0d123764522f70b12bf16
/dolphin-server/src/main/java/com/xxx/server/mapper/MenuMapper.java
c6480b9c484b8af85607efa08785dbe9a6a23ad5
[]
no_license
xiaozhu260600866/java_dolphin
https://github.com/xiaozhu260600866/java_dolphin
22edd792005a19715e5405d6217ae463bc7d5490
a8ce997be55db0c41629ba9a4a860a6f722da690
refs/heads/master
2023-06-05T10:42:18.816000
2021-06-12T10:02:51
2021-06-12T10:02:51
369,779,608
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xxx.server.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xxx.server.pojo.Menu; import java.util.List; /** * <p> * Mapper 接口 * </p> * * @author zhoubin * @since 2021-05-01 */ public interface MenuMapper extends BaseMapper<Menu> { List<Menu> getMenusWithRole(); }
UTF-8
Java
324
java
MenuMapper.java
Java
[ { "context": ";\n\n\n/**\n * <p>\n * Mapper 接口\n * </p>\n *\n * @author zhoubin\n * @since 2021-05-01\n */\npublic interface MenuMap", "end": 201, "score": 0.9996744394302368, "start": 194, "tag": "USERNAME", "value": "zhoubin" } ]
null
[]
package com.xxx.server.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xxx.server.pojo.Menu; import java.util.List; /** * <p> * Mapper 接口 * </p> * * @author zhoubin * @since 2021-05-01 */ public interface MenuMapper extends BaseMapper<Menu> { List<Menu> getMenusWithRole(); }
324
0.696875
0.671875
20
15
17.329166
55
false
false
0
0
0
0
0
0
0.25
false
false
11
d2509fd27f71bbbe3236d9af73651196507f8011
19,842,748,917,195
b54aa1e633126a85b4778c02f5e4e93061c89ab5
/toolkit/src/main/java/cn/jbricks/toolkit/web/session/constant/SessionAttribute.java
22cbf12379f51d572521c034f7eafef0bdf36d1e
[]
no_license
whting/Jbricks
https://github.com/whting/Jbricks
e0ca3d787bbe5eea2456e4370582e89a4249c700
e6e03aa7cb125fe1a0dc56e84f197532a557b8a1
refs/heads/master
2016-08-08T21:47:41.868000
2016-03-10T04:57:43
2016-03-10T04:57:43
53,480,109
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.jbricks.toolkit.web.session.constant; public class SessionAttribute { public static final String sessionId = "sid"; public static final String token = "token"; public static final String userId = "userId"; public static final String appId = "appId"; public static final String signature = "sign"; public static final String realName = "realName"; }
UTF-8
Java
387
java
SessionAttribute.java
Java
[]
null
[]
package cn.jbricks.toolkit.web.session.constant; public class SessionAttribute { public static final String sessionId = "sid"; public static final String token = "token"; public static final String userId = "userId"; public static final String appId = "appId"; public static final String signature = "sign"; public static final String realName = "realName"; }
387
0.72093
0.72093
12
31.25
22.502316
53
false
false
0
0
0
0
0
0
0.583333
false
false
11
ec0af9606d6699a71c50293d2d8bc133bfc86cdc
29,858,612,651,246
52bd9885183d4c1e6eca2a46039e8e7ade4029fb
/game/src/main/java/org/apollo/game/message/impl/IgnoreListMessage.java
cf492c02dac863a4d407b2d6101df93b6161da04
[ "ISC" ]
permissive
lare96/apollo
https://github.com/lare96/apollo
32a8aff6e6f0d76ec7487addcd9bf1c6ed416ef5
a0c78ced90eebf90ed9b0a4e51cece6ddf10932e
refs/heads/kotlin-experiments
2020-04-05T05:52:32.706000
2018-09-04T04:53:06
2018-09-04T04:53:06
156,615,242
1
1
ISC
true
2018-11-07T22:22:29
2018-11-07T22:13:55
2018-11-07T22:13:58
2018-11-07T22:22:15
3,464
0
0
0
Java
false
null
package org.apollo.game.message.impl; import java.util.List; import org.apollo.net.message.Message; /** * A {@link Message} sent to the client that updates the ignored user list. * * @author Major */ public final class IgnoreListMessage extends Message { /** * The list of ignored player usernames. */ private final List<String> usernames; /** * Creates a new ignore list message. * * @param usernames The {@link List} of usernames to send. */ public IgnoreListMessage(List<String> usernames) { this.usernames = usernames; } /** * Gets the list of ignored usernames. * * @return The usernames. */ public List<String> getUsernames() { return usernames; } }
UTF-8
Java
698
java
IgnoreListMessage.java
Java
[ { "context": " that updates the ignored user list.\n *\n * @author Major\n */\npublic final class IgnoreListMessage extends ", "end": 202, "score": 0.9677157402038574, "start": 197, "tag": "NAME", "value": "Major" } ]
null
[]
package org.apollo.game.message.impl; import java.util.List; import org.apollo.net.message.Message; /** * A {@link Message} sent to the client that updates the ignored user list. * * @author Major */ public final class IgnoreListMessage extends Message { /** * The list of ignored player usernames. */ private final List<String> usernames; /** * Creates a new ignore list message. * * @param usernames The {@link List} of usernames to send. */ public IgnoreListMessage(List<String> usernames) { this.usernames = usernames; } /** * Gets the list of ignored usernames. * * @return The usernames. */ public List<String> getUsernames() { return usernames; } }
698
0.689112
0.689112
37
17.891891
20.673502
75
false
false
0
0
0
0
0
0
0.756757
false
false
11
db85a006d551398a02ec643f70632202771f9bf9
14,697,378,099,811
44e21de049c9f5d907397528c6faa84519439cb7
/src/main/java/com/gabe/bedwars/Bedwars.java
f2ce284bc31bdac3fa8803b2019d53e8bb11fd57
[ "MIT" ]
permissive
ThatKingGuy/BedwarsPlus
https://github.com/ThatKingGuy/BedwarsPlus
e27a837f876b82fef2e5d6c14ca7efb3d6d88e5d
6c9c6c02e1c8c57b078c7fc0b3fee4f6b5e7ddb7
refs/heads/master
2023-07-09T14:11:00.600000
2023-06-08T22:23:44
2023-06-08T22:23:44
315,617,586
2
0
MIT
false
2021-06-04T19:50:47
2020-11-24T11:56:18
2021-06-01T19:44:05
2021-05-28T11:55:18
238
0
0
0
Java
false
false
package com.gabe.bedwars; import com.gabe.bedwars.arenas.Game; import com.gabe.bedwars.commands.admin.*; import com.gabe.bedwars.listeners.GameListener; import com.gabe.bedwars.listeners.ShopListener; import com.gabe.bedwars.listeners.UpgradeListener; import com.gabe.bedwars.managers.ArenaManager; import com.gabe.bedwars.managers.GameManager; import com.gabe.bedwars.shop.ShopCreator; import com.gabe.bedwars.stats.PlayerStats; import com.gabe.bedwars.stats.StatsManager; import com.gabe.bedwars.tabcomplete.AdminTabComplete; import com.gabe.bedwars.upgrade.UpgradeCreator; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.hover.content.Text; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.logging.Level; public final class Bedwars extends JavaPlugin { /* ---------- MANAGERS ----------- */ private static ArenaManager arenaManager; private static GameManager gameManager; public static ShopCreator shopCreator; public static UpgradeCreator upgradeCreator; private static StatsManager statsManager; /* ---------- DEFAULT CONFIG VALUES ----------- */ public static String primary = "&e"; public static String secondary = "&6"; public static String scoreboardPrimary = "&f"; public static String scoreboardSecondary = "&a"; public static String success = "&a"; public static String error = "&c"; public static String serverText = "yourserver.net"; public static String prefix = "&8[&6BW&8] &8> &e"; public static HashMap<Integer, String> gamemodes; public static List<String> bossBar = Arrays.asList("&e&lPlaying &f&lBEDWARS &e&lon &a&lYOURSERVER.NET", "&e&lPlaying &f&lBEDWARS &e&lon &b&lYOURSERVER.NET", "&e&lPlaying &f&lBEDWARS &e&lon &6&lYOURSERVER.NET"); public static long bossbarDelay = 20; private YamlConfiguration config; private String help1; private String help2; private TextComponent arrow; /* ---------- GETTERS ----------- */ public static UpgradeCreator getUpgradeCreator() { return upgradeCreator; } public static ShopCreator getShopCreator() { return shopCreator; } public static GameManager getGameManager() { return gameManager; } public static ArenaManager getArenaManager() { return arenaManager; } public static StatsManager getStatsManager() { return statsManager; } /* ---------- OVERRIDE ----------- */ public void onEnable() { TextComponent message = new TextComponent(">>"); message.setColor(net.md_5.bungee.api.ChatColor.AQUA); message.setBold(true); message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/bwa help 2")); message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("§b§lPage 2 >>"))); help1 = "\n§8§l§m*---------§r §d§lBedwarsPlus §b§lv" + this.getDescription().getVersion()+ "§r §8§l§m-----------*\n" + "§7/bwa §bcreate <name> <minplayers> <maxplayers>\n" + "§7/bwa §bdebug\n" + "§7/bwa §bsetlobby <name>\n" + "§7/bwa §bsetmainlobby <name>\n" + "§7/bwa §baddteam <name> <team name> <color>\n" + "§7/bwa §bsetspawn <name> <team>\n" + "§7/bwa §bsetteamgen <name> <team>\n" + "§7/bwa §bsetbed <name> <team>\n" + "§7/bwa §baddgen <name> <diamond/emerald>\n" + "§7/bwa §badditemshop\n" + "§7/bwa §baddteamshop\n" + "§7/bwa §bsave <name>\n" + "§7/bwa §breload\n" + "§8§l§m*------------------------------------*"; gamemodes = new HashMap<>(); saveConfig(); getCommand("bwa").setTabCompleter(new AdminTabComplete()); arenaManager = new ArenaManager(this); arenaManager.deserialize(); gameManager = new GameManager(this); statsManager = new StatsManager(this); shopCreator = new ShopCreator(); upgradeCreator = new UpgradeCreator(); statsManager.loadPlayerStats(); Bukkit.getPluginManager().registerEvents(new GameListener(), this); Bukkit.getPluginManager().registerEvents(new ShopListener(), this); Bukkit.getPluginManager().registerEvents(new UpgradeListener(), this); } public void onDisable() { statsManager.savePlayerStats(); //arenaManager.serialise(); if (gameManager != null) { for (Game game : gameManager.getGameList()) { if (gameManager.getGameList() != null) { if (game != null) { game.reset(); } } } } } /* ---------- CONFIG ----------- */ public void saveConfig() { File file = new File(getDataFolder(), "config.yml"); if (!file.exists()) { try { saveDefaultConfig(); List<List<String>> helps = new ArrayList<>(); List<String> helptest = new ArrayList<>(); helptest.add("hi"); helptest.add("hi1"); config.set("test", helps); saveConfig(); try { config.save(file); } catch (Exception ex) { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } } else { config = YamlConfiguration.loadConfiguration(file); try { loadValues(); } catch (IOException e) { Bukkit.getLogger().info(ChatColor.RED+"FAILED TO LOAD CONFIG"); } } } private void loadValues() throws IOException { File configFile = new File(getDataFolder() + "/config.yml"); YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); List<String> strings = config.getStringList("gamemodes"); config.save(configFile); gamemodes = new HashMap<>(); for(String string : strings){ if(string.split(":").length == 2){ int size = Integer.parseInt(string.split(":")[0]); String name = string.split(":")[1]; gamemodes.put(size, name); }else{ throw new IOException(); } } serverText = config.getString("servername"); if(serverText == null) throw new IOException(); bossbarDelay = config.getInt("bossbardelay"); bossBar = config.getStringList("bossbar"); prefix = config.getString("prefix"); if(prefix == null) throw new IOException(); primary = config.getString("primary-color"); if(primary == null) throw new IOException(); secondary = config.getString("secondary-color"); if(secondary == null) throw new IOException(); success = config.getString("success-color"); if(success == null) throw new IOException(); error = config.getString("error-color"); if(error == null) throw new IOException(); scoreboardPrimary = config.getString("scoreboard-primary"); if(scoreboardPrimary == null) throw new IOException(); scoreboardSecondary = config.getString("scoreboard-secondary"); if(scoreboardSecondary == null) throw new IOException(); } public void sendHelpMessage(Player player){ player.sendMessage(help1); } /* ---------- COMMANDS ----------- */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; if (label.equalsIgnoreCase("bwa")) { if (args.length > 0) { if (args[0].equalsIgnoreCase("help")) { if (player.hasPermission("bedwarsplus.admin.help")) { sendHelpMessage(player); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("reload")) { if (player.hasPermission("bedwarsplus.admin.reload")) { try { loadValues(); } catch (IOException e) { sendRawMessage(player, "&cError during config reload!"); return true; } for(Game game : gameManager.getGameList()){ game.updateScoreboards(); } sendMessage(player, "&aSuccessfully reloaded config!"); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("create")) { if (player.hasPermission("bedwarsplus.admin.create")) { CreateCommand cmd = new CreateCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("debug")) { if (player.hasPermission("bedwarsplus.admin.debug")) { DebugCommand cmd = new DebugCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("addteam")) { if (player.hasPermission("bedwarsplus.admin.configure")) { AddTeamCommand cmd = new AddTeamCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("bedwarsplus.admin.save")) { SaveCommand cmd = new SaveCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setlobby")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetLobbyCommand cmd = new SetLobbyCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setmainlobby")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetMainLobbyCommand cmd = new SetMainLobbyCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("addgen")) { if (player.hasPermission("bedwarsplus.admin.configure")) { AddGenCommand cmd = new AddGenCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setteamgen")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetTeamGenCommand cmd = new SetTeamGenCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setspawn")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetSpawnCommand cmd = new SetSpawnCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setbed")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetBedCommand cmd = new SetBedCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("additemshop")) { if (player.hasPermission("bedwarsplus.admin.shop")) { AddItemShopCommand cmd = new AddItemShopCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("addteamshop")) { if (player.hasPermission("bedwarsplus.admin.shop")) { AddTeamShopCommand cmd = new AddTeamShopCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else { Bedwars.sendMessage(player, "&cThat is not a command. Try /bwa help."); } } else { sendHelpMessage(player); } } if (label.equalsIgnoreCase("bw")) { if (args.length > 0) { if (args[0].equalsIgnoreCase("join")) { if (player.hasPermission("bedwarspro.player.join")) { if (args.length > 1) { if (gameManager.getGame(args[1]) != null) { if (gameManager.getGame(args[1]).getPlayers().contains(player)) { Bedwars.sendMessage(player, "&cYou are already in this game!"); return true; } Bedwars.sendMessage(player, "Joined arena named &6" + args[1] + "&e."); gameManager.getGame(args[1]).addPlayer(player); } else { Bedwars.sendMessage(player, "Arena named &6" + args[1] + "&e doesn't exists."); } } else { Bedwars.sendMessage(player, "&cIncorrect Usage. Do /bw join <name> "); } } else { Bedwars.sendMessage(player, "&cYou do not have permission to do that."); } } else if (args[0].equalsIgnoreCase("leave")) { if (player.hasPermission("bedwarspro.player.leave")) { if (gameManager.getGame(player) != null) { Bedwars.sendMessage(player, "Left arena " + gameManager.getGame(player).getName() + "!"); gameManager.getGame(player).removePlayer(player); } else { Bedwars.sendMessage(player, "&cYou are not in a game!"); } } else { Bedwars.sendMessage(player, "&cYou do not have permission to do that."); } } else if (args[0].equalsIgnoreCase("play")) { if (player.hasPermission("bedwarspro.player.play")) { if (gameManager.getGame(player) != null) { Bedwars.sendMessage(player, "&cYou are currently in a game!"); return true; } for (Game game : gameManager.getGameList()) { if (game.getState() == GameState.WAITING) { game.addPlayer(player); return true; } } Bedwars.sendMessage(player, "&cSorry, there are no available games at this time."); } else { Bedwars.sendMessage(player, "&cYou do not have permission to do that."); } } else if (args[0].equalsIgnoreCase("stats")) { if (player.hasPermission("bedwarspro.player.stats")) { PlayerStats stats = statsManager.getStats(player); Bedwars.sendMessage(player, "\n&8*------------------------------------* \n" + "&cBedwars Stats:\n" + "&eGames Played: &6" + stats.getGames() + "\n" + "&eWins: &6" + stats.getWins() + "\n" + "&eLosses: &6" + stats.getLosses() + "\n" + "&eWin Streak: &6" + stats.getWinStreak() + "\n" + "&eLoss Streak: &6" + stats.getLoseStreak() + "\n" + "&eKills: &6" + stats.getKills() + "\n" + "&eFinal Kills: &6" + stats.getFinalKills() + "\n" + "&eBeds Destroyed: &6" + stats.getBedsBroken() + "\n" + "&8*------------------------------------* \n"); } else { Bedwars.sendMessage(player, "&cYou do not have permission to do that."); } } else { Bedwars.sendMessage(player, "&cInvalid command. Try /bw help."); } } } } else { sender.sendMessage("This command can only be executed by a player!"); } return true; } /* ---------- UTILS ----------- */ public static boolean isColor(String string) { for (ChatColor c : ChatColor.values()) { if (c.name().equalsIgnoreCase(string)) { return true; } } return false; } public static void sendMessage(Player player, String msg) { msg = "&e" + msg; if(primary != null) msg = msg.replaceAll("&e", primary); if(secondary != null) msg = msg.replaceAll("&6", secondary); if(success != null) msg = msg.replaceAll("&a", success); if(error != null) msg = msg.replaceAll("&c", error); String message = prefix + msg; player.sendMessage(ChatColor.translateAlternateColorCodes('&', message)); } public static void sendRawMessage(Player player, String msg) { player.sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); } public static void sendMessage(Player player, boolean usePrefix, String msg) { if (usePrefix) { msg = "&e" + msg; if(primary != null) msg = msg.replaceAll("&e", primary); if(secondary != null) msg = msg.replaceAll("&6", secondary); if(success != null) msg = msg.replaceAll("&a", success); if(error != null) msg = msg.replaceAll("&c", error); String message = prefix + msg; player.sendMessage(ChatColor.translateAlternateColorCodes('&', message)); } else { msg = "&e" + msg; if(primary != null) msg = msg.replaceAll("&e", primary); if(secondary != null) msg = msg.replaceAll("&6", secondary); if(success != null) msg = msg.replaceAll("&a", success); if(error != null) msg = msg.replaceAll("&c", error); player.sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); } } public static Color translateChatColorToColor(ChatColor chatColor) { switch (chatColor) { case AQUA: return Color.AQUA; case BLACK: return Color.BLACK; case BLUE: return Color.BLUE; case DARK_AQUA: return Color.BLUE; case DARK_BLUE: return Color.BLUE; case DARK_GRAY: return Color.GRAY; case DARK_GREEN: return Color.GREEN; case DARK_PURPLE: return Color.PURPLE; case DARK_RED: return Color.RED; case GOLD: return Color.YELLOW; case GRAY: return Color.GRAY; case GREEN: return Color.GREEN; case LIGHT_PURPLE: return Color.PURPLE; case RED: return Color.RED; case WHITE: return Color.WHITE; case YELLOW: return Color.YELLOW; default: break; } return null; } public static Material translateChatColorToWool(ChatColor chatColor) { switch (chatColor) { case AQUA: return Material.LIGHT_BLUE_WOOL; case BLACK: return Material.BLACK_WOOL; case BLUE: return Material.LIGHT_BLUE_WOOL; case DARK_AQUA: return Material.CYAN_WOOL; case DARK_BLUE: return Material.BLUE_WOOL; case DARK_GRAY: return Material.GRAY_WOOL; case DARK_GREEN: return Material.GREEN_WOOL; case DARK_PURPLE: return Material.PURPLE_WOOL; case GRAY: return Material.LIGHT_GRAY_WOOL; case GREEN: return Material.LIME_WOOL; case LIGHT_PURPLE: return Material.PINK_WOOL; case RED: return Material.RED_WOOL; case WHITE: return Material.WHITE_WOOL; case YELLOW: return Material.YELLOW_WOOL; default: break; } return null; } }
UTF-8
Java
23,768
java
Bedwars.java
Java
[]
null
[]
package com.gabe.bedwars; import com.gabe.bedwars.arenas.Game; import com.gabe.bedwars.commands.admin.*; import com.gabe.bedwars.listeners.GameListener; import com.gabe.bedwars.listeners.ShopListener; import com.gabe.bedwars.listeners.UpgradeListener; import com.gabe.bedwars.managers.ArenaManager; import com.gabe.bedwars.managers.GameManager; import com.gabe.bedwars.shop.ShopCreator; import com.gabe.bedwars.stats.PlayerStats; import com.gabe.bedwars.stats.StatsManager; import com.gabe.bedwars.tabcomplete.AdminTabComplete; import com.gabe.bedwars.upgrade.UpgradeCreator; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.hover.content.Text; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.logging.Level; public final class Bedwars extends JavaPlugin { /* ---------- MANAGERS ----------- */ private static ArenaManager arenaManager; private static GameManager gameManager; public static ShopCreator shopCreator; public static UpgradeCreator upgradeCreator; private static StatsManager statsManager; /* ---------- DEFAULT CONFIG VALUES ----------- */ public static String primary = "&e"; public static String secondary = "&6"; public static String scoreboardPrimary = "&f"; public static String scoreboardSecondary = "&a"; public static String success = "&a"; public static String error = "&c"; public static String serverText = "yourserver.net"; public static String prefix = "&8[&6BW&8] &8> &e"; public static HashMap<Integer, String> gamemodes; public static List<String> bossBar = Arrays.asList("&e&lPlaying &f&lBEDWARS &e&lon &a&lYOURSERVER.NET", "&e&lPlaying &f&lBEDWARS &e&lon &b&lYOURSERVER.NET", "&e&lPlaying &f&lBEDWARS &e&lon &6&lYOURSERVER.NET"); public static long bossbarDelay = 20; private YamlConfiguration config; private String help1; private String help2; private TextComponent arrow; /* ---------- GETTERS ----------- */ public static UpgradeCreator getUpgradeCreator() { return upgradeCreator; } public static ShopCreator getShopCreator() { return shopCreator; } public static GameManager getGameManager() { return gameManager; } public static ArenaManager getArenaManager() { return arenaManager; } public static StatsManager getStatsManager() { return statsManager; } /* ---------- OVERRIDE ----------- */ public void onEnable() { TextComponent message = new TextComponent(">>"); message.setColor(net.md_5.bungee.api.ChatColor.AQUA); message.setBold(true); message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/bwa help 2")); message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("§b§lPage 2 >>"))); help1 = "\n§8§l§m*---------§r §d§lBedwarsPlus §b§lv" + this.getDescription().getVersion()+ "§r §8§l§m-----------*\n" + "§7/bwa §bcreate <name> <minplayers> <maxplayers>\n" + "§7/bwa §bdebug\n" + "§7/bwa §bsetlobby <name>\n" + "§7/bwa §bsetmainlobby <name>\n" + "§7/bwa §baddteam <name> <team name> <color>\n" + "§7/bwa §bsetspawn <name> <team>\n" + "§7/bwa §bsetteamgen <name> <team>\n" + "§7/bwa §bsetbed <name> <team>\n" + "§7/bwa §baddgen <name> <diamond/emerald>\n" + "§7/bwa §badditemshop\n" + "§7/bwa §baddteamshop\n" + "§7/bwa §bsave <name>\n" + "§7/bwa §breload\n" + "§8§l§m*------------------------------------*"; gamemodes = new HashMap<>(); saveConfig(); getCommand("bwa").setTabCompleter(new AdminTabComplete()); arenaManager = new ArenaManager(this); arenaManager.deserialize(); gameManager = new GameManager(this); statsManager = new StatsManager(this); shopCreator = new ShopCreator(); upgradeCreator = new UpgradeCreator(); statsManager.loadPlayerStats(); Bukkit.getPluginManager().registerEvents(new GameListener(), this); Bukkit.getPluginManager().registerEvents(new ShopListener(), this); Bukkit.getPluginManager().registerEvents(new UpgradeListener(), this); } public void onDisable() { statsManager.savePlayerStats(); //arenaManager.serialise(); if (gameManager != null) { for (Game game : gameManager.getGameList()) { if (gameManager.getGameList() != null) { if (game != null) { game.reset(); } } } } } /* ---------- CONFIG ----------- */ public void saveConfig() { File file = new File(getDataFolder(), "config.yml"); if (!file.exists()) { try { saveDefaultConfig(); List<List<String>> helps = new ArrayList<>(); List<String> helptest = new ArrayList<>(); helptest.add("hi"); helptest.add("hi1"); config.set("test", helps); saveConfig(); try { config.save(file); } catch (Exception ex) { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } } else { config = YamlConfiguration.loadConfiguration(file); try { loadValues(); } catch (IOException e) { Bukkit.getLogger().info(ChatColor.RED+"FAILED TO LOAD CONFIG"); } } } private void loadValues() throws IOException { File configFile = new File(getDataFolder() + "/config.yml"); YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); List<String> strings = config.getStringList("gamemodes"); config.save(configFile); gamemodes = new HashMap<>(); for(String string : strings){ if(string.split(":").length == 2){ int size = Integer.parseInt(string.split(":")[0]); String name = string.split(":")[1]; gamemodes.put(size, name); }else{ throw new IOException(); } } serverText = config.getString("servername"); if(serverText == null) throw new IOException(); bossbarDelay = config.getInt("bossbardelay"); bossBar = config.getStringList("bossbar"); prefix = config.getString("prefix"); if(prefix == null) throw new IOException(); primary = config.getString("primary-color"); if(primary == null) throw new IOException(); secondary = config.getString("secondary-color"); if(secondary == null) throw new IOException(); success = config.getString("success-color"); if(success == null) throw new IOException(); error = config.getString("error-color"); if(error == null) throw new IOException(); scoreboardPrimary = config.getString("scoreboard-primary"); if(scoreboardPrimary == null) throw new IOException(); scoreboardSecondary = config.getString("scoreboard-secondary"); if(scoreboardSecondary == null) throw new IOException(); } public void sendHelpMessage(Player player){ player.sendMessage(help1); } /* ---------- COMMANDS ----------- */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; if (label.equalsIgnoreCase("bwa")) { if (args.length > 0) { if (args[0].equalsIgnoreCase("help")) { if (player.hasPermission("bedwarsplus.admin.help")) { sendHelpMessage(player); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("reload")) { if (player.hasPermission("bedwarsplus.admin.reload")) { try { loadValues(); } catch (IOException e) { sendRawMessage(player, "&cError during config reload!"); return true; } for(Game game : gameManager.getGameList()){ game.updateScoreboards(); } sendMessage(player, "&aSuccessfully reloaded config!"); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("create")) { if (player.hasPermission("bedwarsplus.admin.create")) { CreateCommand cmd = new CreateCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("debug")) { if (player.hasPermission("bedwarsplus.admin.debug")) { DebugCommand cmd = new DebugCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("addteam")) { if (player.hasPermission("bedwarsplus.admin.configure")) { AddTeamCommand cmd = new AddTeamCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("save")) { if (player.hasPermission("bedwarsplus.admin.save")) { SaveCommand cmd = new SaveCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setlobby")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetLobbyCommand cmd = new SetLobbyCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setmainlobby")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetMainLobbyCommand cmd = new SetMainLobbyCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("addgen")) { if (player.hasPermission("bedwarsplus.admin.configure")) { AddGenCommand cmd = new AddGenCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setteamgen")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetTeamGenCommand cmd = new SetTeamGenCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setspawn")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetSpawnCommand cmd = new SetSpawnCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("setbed")) { if (player.hasPermission("bedwarsplus.admin.configure")) { SetBedCommand cmd = new SetBedCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("additemshop")) { if (player.hasPermission("bedwarsplus.admin.shop")) { AddItemShopCommand cmd = new AddItemShopCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else if (args[0].equalsIgnoreCase("addteamshop")) { if (player.hasPermission("bedwarsplus.admin.shop")) { AddTeamShopCommand cmd = new AddTeamShopCommand(player, args); } else { Bedwars.sendMessage(player, "&cYou do not have permission!"); } } else { Bedwars.sendMessage(player, "&cThat is not a command. Try /bwa help."); } } else { sendHelpMessage(player); } } if (label.equalsIgnoreCase("bw")) { if (args.length > 0) { if (args[0].equalsIgnoreCase("join")) { if (player.hasPermission("bedwarspro.player.join")) { if (args.length > 1) { if (gameManager.getGame(args[1]) != null) { if (gameManager.getGame(args[1]).getPlayers().contains(player)) { Bedwars.sendMessage(player, "&cYou are already in this game!"); return true; } Bedwars.sendMessage(player, "Joined arena named &6" + args[1] + "&e."); gameManager.getGame(args[1]).addPlayer(player); } else { Bedwars.sendMessage(player, "Arena named &6" + args[1] + "&e doesn't exists."); } } else { Bedwars.sendMessage(player, "&cIncorrect Usage. Do /bw join <name> "); } } else { Bedwars.sendMessage(player, "&cYou do not have permission to do that."); } } else if (args[0].equalsIgnoreCase("leave")) { if (player.hasPermission("bedwarspro.player.leave")) { if (gameManager.getGame(player) != null) { Bedwars.sendMessage(player, "Left arena " + gameManager.getGame(player).getName() + "!"); gameManager.getGame(player).removePlayer(player); } else { Bedwars.sendMessage(player, "&cYou are not in a game!"); } } else { Bedwars.sendMessage(player, "&cYou do not have permission to do that."); } } else if (args[0].equalsIgnoreCase("play")) { if (player.hasPermission("bedwarspro.player.play")) { if (gameManager.getGame(player) != null) { Bedwars.sendMessage(player, "&cYou are currently in a game!"); return true; } for (Game game : gameManager.getGameList()) { if (game.getState() == GameState.WAITING) { game.addPlayer(player); return true; } } Bedwars.sendMessage(player, "&cSorry, there are no available games at this time."); } else { Bedwars.sendMessage(player, "&cYou do not have permission to do that."); } } else if (args[0].equalsIgnoreCase("stats")) { if (player.hasPermission("bedwarspro.player.stats")) { PlayerStats stats = statsManager.getStats(player); Bedwars.sendMessage(player, "\n&8*------------------------------------* \n" + "&cBedwars Stats:\n" + "&eGames Played: &6" + stats.getGames() + "\n" + "&eWins: &6" + stats.getWins() + "\n" + "&eLosses: &6" + stats.getLosses() + "\n" + "&eWin Streak: &6" + stats.getWinStreak() + "\n" + "&eLoss Streak: &6" + stats.getLoseStreak() + "\n" + "&eKills: &6" + stats.getKills() + "\n" + "&eFinal Kills: &6" + stats.getFinalKills() + "\n" + "&eBeds Destroyed: &6" + stats.getBedsBroken() + "\n" + "&8*------------------------------------* \n"); } else { Bedwars.sendMessage(player, "&cYou do not have permission to do that."); } } else { Bedwars.sendMessage(player, "&cInvalid command. Try /bw help."); } } } } else { sender.sendMessage("This command can only be executed by a player!"); } return true; } /* ---------- UTILS ----------- */ public static boolean isColor(String string) { for (ChatColor c : ChatColor.values()) { if (c.name().equalsIgnoreCase(string)) { return true; } } return false; } public static void sendMessage(Player player, String msg) { msg = "&e" + msg; if(primary != null) msg = msg.replaceAll("&e", primary); if(secondary != null) msg = msg.replaceAll("&6", secondary); if(success != null) msg = msg.replaceAll("&a", success); if(error != null) msg = msg.replaceAll("&c", error); String message = prefix + msg; player.sendMessage(ChatColor.translateAlternateColorCodes('&', message)); } public static void sendRawMessage(Player player, String msg) { player.sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); } public static void sendMessage(Player player, boolean usePrefix, String msg) { if (usePrefix) { msg = "&e" + msg; if(primary != null) msg = msg.replaceAll("&e", primary); if(secondary != null) msg = msg.replaceAll("&6", secondary); if(success != null) msg = msg.replaceAll("&a", success); if(error != null) msg = msg.replaceAll("&c", error); String message = prefix + msg; player.sendMessage(ChatColor.translateAlternateColorCodes('&', message)); } else { msg = "&e" + msg; if(primary != null) msg = msg.replaceAll("&e", primary); if(secondary != null) msg = msg.replaceAll("&6", secondary); if(success != null) msg = msg.replaceAll("&a", success); if(error != null) msg = msg.replaceAll("&c", error); player.sendMessage(ChatColor.translateAlternateColorCodes('&', msg)); } } public static Color translateChatColorToColor(ChatColor chatColor) { switch (chatColor) { case AQUA: return Color.AQUA; case BLACK: return Color.BLACK; case BLUE: return Color.BLUE; case DARK_AQUA: return Color.BLUE; case DARK_BLUE: return Color.BLUE; case DARK_GRAY: return Color.GRAY; case DARK_GREEN: return Color.GREEN; case DARK_PURPLE: return Color.PURPLE; case DARK_RED: return Color.RED; case GOLD: return Color.YELLOW; case GRAY: return Color.GRAY; case GREEN: return Color.GREEN; case LIGHT_PURPLE: return Color.PURPLE; case RED: return Color.RED; case WHITE: return Color.WHITE; case YELLOW: return Color.YELLOW; default: break; } return null; } public static Material translateChatColorToWool(ChatColor chatColor) { switch (chatColor) { case AQUA: return Material.LIGHT_BLUE_WOOL; case BLACK: return Material.BLACK_WOOL; case BLUE: return Material.LIGHT_BLUE_WOOL; case DARK_AQUA: return Material.CYAN_WOOL; case DARK_BLUE: return Material.BLUE_WOOL; case DARK_GRAY: return Material.GRAY_WOOL; case DARK_GREEN: return Material.GREEN_WOOL; case DARK_PURPLE: return Material.PURPLE_WOOL; case GRAY: return Material.LIGHT_GRAY_WOOL; case GREEN: return Material.LIME_WOOL; case LIGHT_PURPLE: return Material.PINK_WOOL; case RED: return Material.RED_WOOL; case WHITE: return Material.WHITE_WOOL; case YELLOW: return Material.YELLOW_WOOL; default: break; } return null; } }
23,768
0.489863
0.486449
543
42.692448
27.38578
214
false
false
0
0
0
0
0
0
0.583794
false
false
11
74000c3caa18323d8ccadbde93b5aae002927ca9
21,139,829,041,560
86ba6a70502276d95014705a29d4bf6ea7ddc40c
/src/main/java/com/chainsys/collegefeeregister/servlet/AddStudentLoad.java
5222cb48e9440e0bed1e7f790ec9b70744cc7deb
[]
no_license
csys-fresher-batch-2019/collegefeeapp-spring-anand
https://github.com/csys-fresher-batch-2019/collegefeeapp-spring-anand
b95acfc565d00e68a8da0dc1ac175f15cacb5b9e
c12ddfe380cfd9c8594f96280356ff1748fa7283
refs/heads/master
2021-01-14T15:21:14.752000
2020-03-12T10:05:52
2020-03-12T10:05:52
242,660,292
0
0
null
false
2020-10-13T19:55:41
2020-02-24T06:11:35
2020-03-12T10:07:25
2020-10-13T19:55:40
187
0
0
1
Java
false
false
package com.chainsys.collegefeeregister.servlet; 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 com.chainsys.collegefeeregister.model.Course; import com.chainsys.collegefeeregister.service.CourseService; @WebServlet("/AddStudentLoad") public class AddStudentLoad extends HttpServlet { private static final long serialVersionUID = 1L; public AddStudentLoad() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { CourseService obj = new CourseService(); List<Course> Courses = obj.getAllCourse(); request.setAttribute("CoursesList", Courses); RequestDispatcher rd = request.getRequestDispatcher("AddStudent.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
1,089
java
AddStudentLoad.java
Java
[]
null
[]
package com.chainsys.collegefeeregister.servlet; 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 com.chainsys.collegefeeregister.model.Course; import com.chainsys.collegefeeregister.service.CourseService; @WebServlet("/AddStudentLoad") public class AddStudentLoad extends HttpServlet { private static final long serialVersionUID = 1L; public AddStudentLoad() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { CourseService obj = new CourseService(); List<Course> Courses = obj.getAllCourse(); request.setAttribute("CoursesList", Courses); RequestDispatcher rd = request.getRequestDispatcher("AddStudent.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } }
1,089
0.788797
0.787879
41
25.560976
23.042959
79
false
false
0
0
0
0
0
0
1.390244
false
false
11
15ea95b5fca295107994235d38701b9bb4afd74a
11,003,706,217,140
0aeeea50790fb70cbbc0d0927596b3c6d858eaf8
/src/models/Staff.java
4938e7d172fc07d8899aa72f11f774dffaf74c5a
[]
no_license
albertfiati/psm
https://github.com/albertfiati/psm
c2cb2a4f6cf51369ef786133b45fe4ec6aed3cf5
1533a7aae742dddb48efd367f6bea3ebe7cf7026
refs/heads/master
2021-01-16T00:27:48.469000
2014-11-20T04:18:45
2014-11-20T04:18:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package models; public class Staff extends Model{ public String name; public String staff_id; public Staff(){} public Staff(String name, String staff_id){ this.name = name; this.staff_id = staff_id; } }
UTF-8
Java
217
java
Staff.java
Java
[]
null
[]
package models; public class Staff extends Model{ public String name; public String staff_id; public Staff(){} public Staff(String name, String staff_id){ this.name = name; this.staff_id = staff_id; } }
217
0.695853
0.695853
13
15.692307
13.617775
44
false
false
0
0
0
0
0
0
1.307692
false
false
11
2043db27bd6efdb1def6dd12ae6dbf245c69a21e
32,890,859,581,868
19dd636fb3fb6485571f021d20aaf8443a06c2d4
/src/org/twak/tweed/gen/MiniGen.java
17943968394ff6892691b6f85ee57c87f39e0a06
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
twak/chordatlas
https://github.com/twak/chordatlas
b15e939d345e32ef459a0b1d22500a16eee4abee
9f5603b03a8e50570e00edad3f74ecb44b33df91
refs/heads/stable
2022-03-01T05:46:09.474000
2022-02-13T19:13:29
2022-02-13T19:13:29
93,035,129
99
28
Apache-2.0
false
2020-11-16T20:30:46
2017-06-01T08:33:28
2020-11-09T08:04:50
2020-11-16T20:30:45
41,672
65
17
3
Java
false
false
package org.twak.tweed.gen; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.stream.Collectors; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.vecmath.Matrix4d; import javax.vecmath.Point2d; import javax.vecmath.Point3d; import javax.vecmath.Tuple3d; import javax.vecmath.Vector3d; import org.twak.readTrace.MiniTransform; import org.twak.siteplan.jme.Jme3z; import org.twak.tweed.EventMoveHandle; import org.twak.tweed.Tweed; import org.twak.tweed.TweedSettings; import org.twak.tweed.handles.HandleMe; import org.twak.tweed.tools.AlignTool; import org.twak.utils.Filez; import org.twak.utils.Pair; import org.twak.utils.collections.Loop; import org.twak.utils.collections.Loopz; import org.twak.utils.geom.DRectangle; import org.twak.utils.geom.LinearForm3D; import org.twak.utils.geom.ObjDump; import org.twak.utils.geom.ObjDump.Face; import org.twak.utils.streams.InaxPoint2dCollector; import org.twak.utils.ui.ListDownLayout; import com.jme3.asset.ModelKey; import com.jme3.material.Material; import com.jme3.material.RenderState.BlendMode; import com.jme3.math.ColorRGBA; import com.jme3.math.Transform; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Mesh.Mode; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.thoughtworks.xstream.XStream; public class MiniGen extends Gen implements HandleMe, ICanSave { File root; transient MiniTransform trans; boolean renderLines = false; float transparency = 1; transient List<double[]> bounds = new ArrayList(); public MiniGen() {} public MiniGen(File root, Tweed tweed) { super (root.getName(), tweed); this.root = root; init(); } @Override public void onLoad( Tweed tweed ) { super.onLoad( tweed ); bounds = new ArrayList(); init(); } public void init() { trans = (MiniTransform) new XStream ().fromXML ( Tweed.toWorkspace( new File (root, "index.xml") ) ); } @Override public void calculate( ) { for (Spatial s : gNode.getChildren() ) s.removeFromParent(); Material mat; if (transparency == 1) mat = new Material(tweed.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md"); else { mat = new Material(tweed.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); mat.setColor("Color", new ColorRGBA( color.getRed()/255f, color.getGreen()/255f, color.getBlue()/255f, transparency ) ); } for (Map.Entry<Integer, Matrix4d> e : trans.index.entrySet() ) { if ( !inBounds( e.getValue(), bounds ) ) continue; File absRoot = Tweed.toWorkspace( MiniGen.this.root ); System.out.println("loading mesh " + e.getKey() +" from " + absRoot); File f = new File (absRoot, e.getKey() +"/model.obj" ); Spatial mesh = tweed.getAssetManager().loadModel( tweed.makeWorkspaceRelative( f ).toString() ); mesh.setLocalTransform( Jme3z.toJmeTransform( e.getValue() ) ); Mode mode = renderLines ? Mesh.Mode.Lines : Mesh.Mode.Triangles; List<Spatial> ls; if (mesh instanceof Node) ls = ((Node)mesh).getChildren(); else ls = Collections.singletonList( mesh ); for ( Spatial g : ls ) { Geometry geometry = (Geometry) g; Mesh m = geometry.getMesh(); m.setMode( mode ); if (geometry.getMaterial().getName() == null) mesh.setMaterial( mat ); gNode.attachChild( geometry ); mesh.setUserData( Gen.class.getSimpleName(), new Object[] { this } ); } } Transform t = new Transform(); t.fromTransformMatrix( trans.offset ); gNode.setLocalTransform( t ); gNode.setUserData( Gen.class.getSimpleName(), new Object[] { this } ); gNode.setUserData( HandleMe.class.getSimpleName(), true ); gNode.setUserData( EventMoveHandle.class.getSimpleName(),new Object[] { new EventMoveHandle() { @Override public void posChanged() { MiniGen.this.save(); } }} ); gNode.updateGeometricState(); super.calculate( ); } public void save() { trans.offset = gNode.getLocalTransform().toTransformMatrix(); System.out.println(trans.offset); new Thread() { public void run() { try { new XStream().toXML( trans, new FileOutputStream( Tweed.toWorkspace( new File( root, "index.xml" ) ) ) ); System.out.println("index file written"); } catch ( FileNotFoundException e ) { e.printStackTrace(); } }; }.start(); } private final static int MAX = 1000; // private static final boolean IMPORT_TEXTURES = true; @Override public JComponent getUI() { JPanel out = new JPanel(new ListDownLayout()); JButton clear = new JButton("hide all"); clear.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { bounds.clear(); tweed.enqueue( new Runnable() { public void run() { calculate(); }; }); } } ); JButton all = new JButton("load all"); all.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { bounds.clear(); bounds.add(new double[] {-Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE } ); tweed.enqueue( new Runnable() { public void run() { calculate(); }; }); } } ); final JCheckBox renderLines = new JCheckBox("wireframe"); renderLines.setSelected(this.renderLines); renderLines.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tweed.enqueue(new Callable<Spatial>() { public Spatial call() throws Exception { MiniGen.this.renderLines = renderLines.isSelected(); calculate(); return null; } }); } }); final JSlider renderTransparent = new JSlider(0, MAX, (int) (MAX * transparency)); renderTransparent.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { tweed.enqueue(new Callable<Spatial>() { public Spatial call() throws Exception { MiniGen.this.transparency = (renderTransparent.getValue() / (float) MAX); calculate(); return null; } }); } }); JButton align = new JButton("align tool"); align.addActionListener( e -> tweed.setTool(new AlignTool(tweed)) ); out.add(all); out.add(clear); out.add(renderLines); out.add(renderTransparent); out.add(align); return out; } public void moveTo( Transform t ) { tweed.enqueue( new Runnable() { public void run() { gNode.setLocalTransform( t ); tweed.gainFocus(); } } ); } public void addBounds( double lx, double ux, double ly, double uy ) { double[] b = new double[] { lx, ux, ly, uy }; for (double[] b2 : bounds) if (b2.equals( b )) return; bounds.add (b); calculate(); } public void clip ( Loop<Point3d> in, File objLocation ) { ObjDump obj = new ObjDump(); obj.REMOVE_DUPE_TEXTURES = true; double[] bounds = Loopz.minMaxXZ(in); List<LinearForm3D> halfPlanes = new ArrayList(); File writeFolder = objLocation.getParentFile(); for (Pair<Point3d, Point3d> p : in.pairs()) { Vector3d norm = new Vector3d( p.second() ); norm.sub(p.first()); norm = new Vector3d( -norm.z, 0, norm.x); norm.normalize(); halfPlanes.add ( new LinearForm3D( norm, p.first() ) ); } Map<File,File> copied = new HashMap<>(); int nameCount = 0; double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE; for ( Map.Entry<Integer, Matrix4d> e : trans.index.entrySet() ) { if ( !inBounds( e.getValue(), Collections.singletonList( bounds ) ) ) continue; else { Matrix4d m = new Matrix4d(); m.mul( Jme3z.fromMatrix( trans.offset ), e.getValue() ); File readFolder = new File( Tweed.toWorkspace( root ), e.getKey() + "" ); ObjDump or = new ObjDump( new File( readFolder, "model.obj" ) ); or.computeMissingNormals(); for ( ObjDump.Material mat : or.material2Face.keySet() ) { f: for ( Face f : or.material2Face.get( mat ) ) { for ( int j = 0; j < f.vtIndexes.size(); j++ ) { Point3d pt = new Point3d( or.orderVert.get( f.vtIndexes.get( j ) ) ); m.transform( pt ); if ( pt.x > bounds[ 0 ] && pt.x < bounds[ 1 ] && pt.z > bounds[ 2 ] && pt.z < bounds[ 3 ] ) if ( inside( pt, halfPlanes ) ) { if ( TweedSettings.settings.importMiniMeshTextures && ! ( (obj.currentMaterial != null && obj.currentMaterial.equals( mat ) ) || (obj.currentMaterial == null && mat == null ) ) ) { File source = new File( readFolder, mat.filename ); ObjDump.Material newMat; if (copied.containsKey( source )) { newMat = new ObjDump.Material(mat); newMat.filename = copied.get(source).getName(); } else { newMat = makeUnique (mat, writeFolder); File destFile = new File( writeFolder, newMat.filename ); copied.put( source, destFile ); try { Files.copy( source.toPath(), new FileOutputStream( destFile ) ); } catch ( IOException e1 ) { e1.printStackTrace(); } } newMat.diffuse = new double[] {0,0,0}; newMat.ambient = new double[] {1,1,1}; newMat.specular = new double[] {0,0,0}; newMat.name = "mat_"+(nameCount++); obj.setCurrentMaterial( newMat ); } List<Point3d> fVerts = new ArrayList<>(3), fNorms = new ArrayList<>(3); List<Point2d> fUVs = null; if (fUVs != null) fUVs = new ArrayList<>(2); for ( int i = 0; i < f.vtIndexes.size(); i++ ) { Point3d vts = new Point3d( or.orderVert.get( f.vtIndexes.get( i ) ) ); Point3d ns = new Point3d( or.orderNorm.get( f.normIndexes.get( i ) ) ); ns.add( vts ); m.transform( vts ); m.transform( ns ); ns.sub( vts ); minY = Math.min (vts.y, minY); maxY = Math.max (vts.y, maxY); fVerts.add( vts ); fNorms.add( ns ); if (fUVs != null) fUVs.add (new Point2d( or.orderUV.get( f.uvIndexes.get( i ) ) )); } obj.addFace( fVerts, fNorms, fUVs ); continue f; } } } } } } for ( Tuple3d t : obj.orderVert ) t.y -= (maxY - minY) * 0.03 + minY; obj.dump( objLocation ); } private ObjDump.Material makeUnique( ObjDump.Material mat, File writeFolder ) { ObjDump.Material out = new ObjDump.Material( mat ); int ind = 0; String newName; while (new File (writeFolder, newName = String.format( "%05d."+Filez.getExtn(mat.filename), ind )).exists()) ind++; out.filename = newName; return out; } private boolean inside( Point3d pt, List<LinearForm3D> halfPlanes ) { for (LinearForm3D lf : halfPlanes) if (!lf.inFront( pt )) return false; return true; } final static Point3d[] cubeCorners = new Point3d[] { new Point3d(0,0,0), new Point3d(255,0,0), new Point3d(255,255,0), new Point3d(0,255,0), new Point3d(0,0,255), new Point3d(255,0,255), new Point3d(0,255,255), new Point3d(255,255,255), } ; private boolean inBounds( Matrix4d mini, List<double[]> bounds ) { // mini matrix is in mini-mesh format: a translation from a 255^3 cube in the first quadrant // trans.offset is a transform from that space, into jme rendered space (cartesian in meters, around the origin) Matrix4d m = new Matrix4d(); m.mul( Jme3z.fromMatrix ( trans.offset ), mini ); double[] miniBounds = Arrays.stream( cubeCorners ).map( c -> { Point3d tmp = new Point3d(); m.transform( c, tmp ); return new Point2d(tmp.x, tmp.z); }).collect( new InaxPoint2dCollector() ); DRectangle miniRect = new DRectangle( miniBounds[0], miniBounds[2], miniBounds[1]-miniBounds[0], miniBounds[3]-miniBounds[2] ); for (double[] bound : bounds) { DRectangle plotRect = new DRectangle( bound[0], bound[2], bound[1]-bound[0], bound[3]-bound[2] ); if (plotRect.intersects( miniRect )) return true; } return false; } @Override public void kill() { for ( Map.Entry<Integer, Matrix4d> e : trans.index.entrySet() ) { if ( !inBounds( e.getValue(), bounds ) ) continue; File absRoot = Tweed.toWorkspace( MiniGen.this.root ); System.out.println( "loading mesh " + e.getKey() + " from " + absRoot ); File f = new File( absRoot, e.getKey() + "/model.obj" ); tweed.getAssetManager().deleteFromCache( new ModelKey ( tweed.makeWorkspaceRelative( f ).toString() ) ); } } }
UTF-8
Java
13,423
java
MiniGen.java
Java
[]
null
[]
package org.twak.tweed.gen; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.stream.Collectors; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.vecmath.Matrix4d; import javax.vecmath.Point2d; import javax.vecmath.Point3d; import javax.vecmath.Tuple3d; import javax.vecmath.Vector3d; import org.twak.readTrace.MiniTransform; import org.twak.siteplan.jme.Jme3z; import org.twak.tweed.EventMoveHandle; import org.twak.tweed.Tweed; import org.twak.tweed.TweedSettings; import org.twak.tweed.handles.HandleMe; import org.twak.tweed.tools.AlignTool; import org.twak.utils.Filez; import org.twak.utils.Pair; import org.twak.utils.collections.Loop; import org.twak.utils.collections.Loopz; import org.twak.utils.geom.DRectangle; import org.twak.utils.geom.LinearForm3D; import org.twak.utils.geom.ObjDump; import org.twak.utils.geom.ObjDump.Face; import org.twak.utils.streams.InaxPoint2dCollector; import org.twak.utils.ui.ListDownLayout; import com.jme3.asset.ModelKey; import com.jme3.material.Material; import com.jme3.material.RenderState.BlendMode; import com.jme3.math.ColorRGBA; import com.jme3.math.Transform; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Mesh.Mode; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.thoughtworks.xstream.XStream; public class MiniGen extends Gen implements HandleMe, ICanSave { File root; transient MiniTransform trans; boolean renderLines = false; float transparency = 1; transient List<double[]> bounds = new ArrayList(); public MiniGen() {} public MiniGen(File root, Tweed tweed) { super (root.getName(), tweed); this.root = root; init(); } @Override public void onLoad( Tweed tweed ) { super.onLoad( tweed ); bounds = new ArrayList(); init(); } public void init() { trans = (MiniTransform) new XStream ().fromXML ( Tweed.toWorkspace( new File (root, "index.xml") ) ); } @Override public void calculate( ) { for (Spatial s : gNode.getChildren() ) s.removeFromParent(); Material mat; if (transparency == 1) mat = new Material(tweed.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md"); else { mat = new Material(tweed.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); mat.setColor("Color", new ColorRGBA( color.getRed()/255f, color.getGreen()/255f, color.getBlue()/255f, transparency ) ); } for (Map.Entry<Integer, Matrix4d> e : trans.index.entrySet() ) { if ( !inBounds( e.getValue(), bounds ) ) continue; File absRoot = Tweed.toWorkspace( MiniGen.this.root ); System.out.println("loading mesh " + e.getKey() +" from " + absRoot); File f = new File (absRoot, e.getKey() +"/model.obj" ); Spatial mesh = tweed.getAssetManager().loadModel( tweed.makeWorkspaceRelative( f ).toString() ); mesh.setLocalTransform( Jme3z.toJmeTransform( e.getValue() ) ); Mode mode = renderLines ? Mesh.Mode.Lines : Mesh.Mode.Triangles; List<Spatial> ls; if (mesh instanceof Node) ls = ((Node)mesh).getChildren(); else ls = Collections.singletonList( mesh ); for ( Spatial g : ls ) { Geometry geometry = (Geometry) g; Mesh m = geometry.getMesh(); m.setMode( mode ); if (geometry.getMaterial().getName() == null) mesh.setMaterial( mat ); gNode.attachChild( geometry ); mesh.setUserData( Gen.class.getSimpleName(), new Object[] { this } ); } } Transform t = new Transform(); t.fromTransformMatrix( trans.offset ); gNode.setLocalTransform( t ); gNode.setUserData( Gen.class.getSimpleName(), new Object[] { this } ); gNode.setUserData( HandleMe.class.getSimpleName(), true ); gNode.setUserData( EventMoveHandle.class.getSimpleName(),new Object[] { new EventMoveHandle() { @Override public void posChanged() { MiniGen.this.save(); } }} ); gNode.updateGeometricState(); super.calculate( ); } public void save() { trans.offset = gNode.getLocalTransform().toTransformMatrix(); System.out.println(trans.offset); new Thread() { public void run() { try { new XStream().toXML( trans, new FileOutputStream( Tweed.toWorkspace( new File( root, "index.xml" ) ) ) ); System.out.println("index file written"); } catch ( FileNotFoundException e ) { e.printStackTrace(); } }; }.start(); } private final static int MAX = 1000; // private static final boolean IMPORT_TEXTURES = true; @Override public JComponent getUI() { JPanel out = new JPanel(new ListDownLayout()); JButton clear = new JButton("hide all"); clear.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { bounds.clear(); tweed.enqueue( new Runnable() { public void run() { calculate(); }; }); } } ); JButton all = new JButton("load all"); all.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { bounds.clear(); bounds.add(new double[] {-Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE } ); tweed.enqueue( new Runnable() { public void run() { calculate(); }; }); } } ); final JCheckBox renderLines = new JCheckBox("wireframe"); renderLines.setSelected(this.renderLines); renderLines.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tweed.enqueue(new Callable<Spatial>() { public Spatial call() throws Exception { MiniGen.this.renderLines = renderLines.isSelected(); calculate(); return null; } }); } }); final JSlider renderTransparent = new JSlider(0, MAX, (int) (MAX * transparency)); renderTransparent.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { tweed.enqueue(new Callable<Spatial>() { public Spatial call() throws Exception { MiniGen.this.transparency = (renderTransparent.getValue() / (float) MAX); calculate(); return null; } }); } }); JButton align = new JButton("align tool"); align.addActionListener( e -> tweed.setTool(new AlignTool(tweed)) ); out.add(all); out.add(clear); out.add(renderLines); out.add(renderTransparent); out.add(align); return out; } public void moveTo( Transform t ) { tweed.enqueue( new Runnable() { public void run() { gNode.setLocalTransform( t ); tweed.gainFocus(); } } ); } public void addBounds( double lx, double ux, double ly, double uy ) { double[] b = new double[] { lx, ux, ly, uy }; for (double[] b2 : bounds) if (b2.equals( b )) return; bounds.add (b); calculate(); } public void clip ( Loop<Point3d> in, File objLocation ) { ObjDump obj = new ObjDump(); obj.REMOVE_DUPE_TEXTURES = true; double[] bounds = Loopz.minMaxXZ(in); List<LinearForm3D> halfPlanes = new ArrayList(); File writeFolder = objLocation.getParentFile(); for (Pair<Point3d, Point3d> p : in.pairs()) { Vector3d norm = new Vector3d( p.second() ); norm.sub(p.first()); norm = new Vector3d( -norm.z, 0, norm.x); norm.normalize(); halfPlanes.add ( new LinearForm3D( norm, p.first() ) ); } Map<File,File> copied = new HashMap<>(); int nameCount = 0; double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE; for ( Map.Entry<Integer, Matrix4d> e : trans.index.entrySet() ) { if ( !inBounds( e.getValue(), Collections.singletonList( bounds ) ) ) continue; else { Matrix4d m = new Matrix4d(); m.mul( Jme3z.fromMatrix( trans.offset ), e.getValue() ); File readFolder = new File( Tweed.toWorkspace( root ), e.getKey() + "" ); ObjDump or = new ObjDump( new File( readFolder, "model.obj" ) ); or.computeMissingNormals(); for ( ObjDump.Material mat : or.material2Face.keySet() ) { f: for ( Face f : or.material2Face.get( mat ) ) { for ( int j = 0; j < f.vtIndexes.size(); j++ ) { Point3d pt = new Point3d( or.orderVert.get( f.vtIndexes.get( j ) ) ); m.transform( pt ); if ( pt.x > bounds[ 0 ] && pt.x < bounds[ 1 ] && pt.z > bounds[ 2 ] && pt.z < bounds[ 3 ] ) if ( inside( pt, halfPlanes ) ) { if ( TweedSettings.settings.importMiniMeshTextures && ! ( (obj.currentMaterial != null && obj.currentMaterial.equals( mat ) ) || (obj.currentMaterial == null && mat == null ) ) ) { File source = new File( readFolder, mat.filename ); ObjDump.Material newMat; if (copied.containsKey( source )) { newMat = new ObjDump.Material(mat); newMat.filename = copied.get(source).getName(); } else { newMat = makeUnique (mat, writeFolder); File destFile = new File( writeFolder, newMat.filename ); copied.put( source, destFile ); try { Files.copy( source.toPath(), new FileOutputStream( destFile ) ); } catch ( IOException e1 ) { e1.printStackTrace(); } } newMat.diffuse = new double[] {0,0,0}; newMat.ambient = new double[] {1,1,1}; newMat.specular = new double[] {0,0,0}; newMat.name = "mat_"+(nameCount++); obj.setCurrentMaterial( newMat ); } List<Point3d> fVerts = new ArrayList<>(3), fNorms = new ArrayList<>(3); List<Point2d> fUVs = null; if (fUVs != null) fUVs = new ArrayList<>(2); for ( int i = 0; i < f.vtIndexes.size(); i++ ) { Point3d vts = new Point3d( or.orderVert.get( f.vtIndexes.get( i ) ) ); Point3d ns = new Point3d( or.orderNorm.get( f.normIndexes.get( i ) ) ); ns.add( vts ); m.transform( vts ); m.transform( ns ); ns.sub( vts ); minY = Math.min (vts.y, minY); maxY = Math.max (vts.y, maxY); fVerts.add( vts ); fNorms.add( ns ); if (fUVs != null) fUVs.add (new Point2d( or.orderUV.get( f.uvIndexes.get( i ) ) )); } obj.addFace( fVerts, fNorms, fUVs ); continue f; } } } } } } for ( Tuple3d t : obj.orderVert ) t.y -= (maxY - minY) * 0.03 + minY; obj.dump( objLocation ); } private ObjDump.Material makeUnique( ObjDump.Material mat, File writeFolder ) { ObjDump.Material out = new ObjDump.Material( mat ); int ind = 0; String newName; while (new File (writeFolder, newName = String.format( "%05d."+Filez.getExtn(mat.filename), ind )).exists()) ind++; out.filename = newName; return out; } private boolean inside( Point3d pt, List<LinearForm3D> halfPlanes ) { for (LinearForm3D lf : halfPlanes) if (!lf.inFront( pt )) return false; return true; } final static Point3d[] cubeCorners = new Point3d[] { new Point3d(0,0,0), new Point3d(255,0,0), new Point3d(255,255,0), new Point3d(0,255,0), new Point3d(0,0,255), new Point3d(255,0,255), new Point3d(0,255,255), new Point3d(255,255,255), } ; private boolean inBounds( Matrix4d mini, List<double[]> bounds ) { // mini matrix is in mini-mesh format: a translation from a 255^3 cube in the first quadrant // trans.offset is a transform from that space, into jme rendered space (cartesian in meters, around the origin) Matrix4d m = new Matrix4d(); m.mul( Jme3z.fromMatrix ( trans.offset ), mini ); double[] miniBounds = Arrays.stream( cubeCorners ).map( c -> { Point3d tmp = new Point3d(); m.transform( c, tmp ); return new Point2d(tmp.x, tmp.z); }).collect( new InaxPoint2dCollector() ); DRectangle miniRect = new DRectangle( miniBounds[0], miniBounds[2], miniBounds[1]-miniBounds[0], miniBounds[3]-miniBounds[2] ); for (double[] bound : bounds) { DRectangle plotRect = new DRectangle( bound[0], bound[2], bound[1]-bound[0], bound[3]-bound[2] ); if (plotRect.intersects( miniRect )) return true; } return false; } @Override public void kill() { for ( Map.Entry<Integer, Matrix4d> e : trans.index.entrySet() ) { if ( !inBounds( e.getValue(), bounds ) ) continue; File absRoot = Tweed.toWorkspace( MiniGen.this.root ); System.out.println( "loading mesh " + e.getKey() + " from " + absRoot ); File f = new File( absRoot, e.getKey() + "/model.obj" ); tweed.getAssetManager().deleteFromCache( new ModelKey ( tweed.makeWorkspaceRelative( f ).toString() ) ); } } }
13,423
0.633092
0.619832
497
26.008049
25.130323
129
false
false
0
0
0
0
0
0
3.726358
false
false
11
a2b5d668ef293bb8cbe7b3fd1523d2180421d32f
29,214,367,575,960
58c11d3a4d57bf684fb53f098e23cb32e66b4fb0
/PUSHIOT/src/main/java/com/app/xxcpush/api/HttpApis.java
3d76dfeed0f586025d16ecb335cf1bffe610af76
[]
no_license
cckmit/PushIot
https://github.com/cckmit/PushIot
99c327cb1ea9697e8404f84ad6851d231bb55a96
1f83b6bd02d2b5a501406250fb4e5d84dd9d090f
refs/heads/master
2023-03-15T15:58:19.426000
2019-03-19T08:25:28
2019-03-19T08:25:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.xxcpush.api; /** * @Copyright 广州市数商云网络科技有限公司 * @Author XXC * @Date 2018/11/22 0022 13:13 * Describe */ public interface HttpApis { // String HostApi = BuildConfig.TESTSTATE ? "http://192.168.3.3:8080/" : "http://xiexc.cn:8080/";//保证打包为正式环境 // String HostApi = "http://xiexc.cn:8080/"; // String HostApi = "http://192.168.3.3:8080/";//服务器地址端口 // String HOST = "192.168.3.3"; int PORT = 9000;//端口号 String HOST = "xiexc.cn";//服务器地址 // String HostApi = "http://xiexc.cn:8080/SERIAL/";//保证打包为正式环境 // String getFacilityAll = HostApi + "appSerial/getFacilityAll"; }
UTF-8
Java
707
java
HttpApis.java
Java
[ { "context": ".api;\n\n/**\n * @Copyright 广州市数商云网络科技有限公司\n * @Author XXC\n * @Date 2018/11/22 0022 13:13\n * Describe\n */\npu", "end": 77, "score": 0.9992824792861938, "start": 74, "tag": "USERNAME", "value": "XXC" }, { "context": " String HostApi = BuildConfig.TESTSTATE ? \"http://192.168.3.3:8080/\" : \"http://xiexc.cn:8080/\";//保证打包为正式环境\n// ", "end": 224, "score": 0.9995601773262024, "start": 213, "tag": "IP_ADDRESS", "value": "192.168.3.3" }, { "context": "//xiexc.cn:8080/\";\n// String HostApi = \"http://192.168.3.3:8080/\";//服务器地址端口\n// String HOST = \"192.168.3.3", "end": 360, "score": 0.999696671962738, "start": 349, "tag": "IP_ADDRESS", "value": "192.168.3.3" }, { "context": "192.168.3.3:8080/\";//服务器地址端口\n// String HOST = \"192.168.3.3\";\n int PORT = 9000;//端口号\n String HOST = \"xi", "end": 410, "score": 0.9997272491455078, "start": 399, "tag": "IP_ADDRESS", "value": "192.168.3.3" } ]
null
[]
package com.app.xxcpush.api; /** * @Copyright 广州市数商云网络科技有限公司 * @Author XXC * @Date 2018/11/22 0022 13:13 * Describe */ public interface HttpApis { // String HostApi = BuildConfig.TESTSTATE ? "http://192.168.3.3:8080/" : "http://xiexc.cn:8080/";//保证打包为正式环境 // String HostApi = "http://xiexc.cn:8080/"; // String HostApi = "http://192.168.3.3:8080/";//服务器地址端口 // String HOST = "192.168.3.3"; int PORT = 9000;//端口号 String HOST = "xiexc.cn";//服务器地址 // String HostApi = "http://xiexc.cn:8080/SERIAL/";//保证打包为正式环境 // String getFacilityAll = HostApi + "appSerial/getFacilityAll"; }
707
0.636215
0.531811
20
29.65
28.858751
115
false
false
0
0
0
0
0
0
0.45
false
false
11
cb5f57d2b7f4f36edd7c48262d172b371d25d1f6
25,718,264,191,556
22a666e864f0c3379f8d6b70553c9596ffb7f1f2
/app/src/main/java/vn/com/misa/cukcuklite/utils/AppConstants.java
bee6ae5ff3949e18da4b4c86a304fce4b3f4b372
[]
no_license
linhtop97/CUKCUK
https://github.com/linhtop97/CUKCUK
25e0d28153067eea6711716687d3320eca11f757
8879f0bcc5897e7b63352d8a20186ce330ef7757
refs/heads/master
2020-05-03T22:10:07.405000
2019-04-04T10:48:29
2019-04-04T10:48:29
178,838,766
3
0
null
false
2019-04-17T10:16:59
2019-04-01T10:20:44
2019-04-04T10:51:38
2019-04-17T10:16:57
2,605
0
0
0
Java
false
false
package vn.com.misa.cukcuklite.utils; /** * Lớp chứa các định danh hằng được sử dụng trong app * Created_by Nguyễn Bá Linh on 20/03/2019 */ public final class AppConstants { public static final String EXTRA_ACCOUNT = "EXTRA_ACCOUNT"; public static final String ARG_DISH_COLOR_ID = "ARG_DISH_COLOR_ID"; public static final int POSITION_DEFAULT = 4; public static final String COLOR_DEFAULT = "#039BE5"; public static final String ICON_DEFAULT = "ic_default.png"; public static final String ARG_DISH = "ARG_DISH"; public static final String ARG_DISH_NAME = "ARG_DISH_NAME"; public static final String ARG_UNIT_NAME = "ARG_UNIT_NAME"; public static final String ARG_UNIT = "ARG_UNIT"; public static final String FIREBASE_ID = "id"; //các đường dẫn, hằng dành cho cloud fire store public static final String USER_COLLECTION = "users"; public static final String EXTRA_LOGIN_SUCCESS = "EXTRA_LOGIN_SUCCESS" ; }
UTF-8
Java
996
java
AppConstants.java
Java
[ { "context": "ịnh danh hằng được sử dụng trong app\n * Created_by Nguyễn Bá Linh on 20/03/2019\n */\npublic final class AppConstants", "end": 125, "score": 0.9998892545700073, "start": 111, "tag": "NAME", "value": "Nguyễn Bá Linh" } ]
null
[]
package vn.com.misa.cukcuklite.utils; /** * Lớp chứa các định danh hằng được sử dụng trong app * Created_by <NAME> on 20/03/2019 */ public final class AppConstants { public static final String EXTRA_ACCOUNT = "EXTRA_ACCOUNT"; public static final String ARG_DISH_COLOR_ID = "ARG_DISH_COLOR_ID"; public static final int POSITION_DEFAULT = 4; public static final String COLOR_DEFAULT = "#039BE5"; public static final String ICON_DEFAULT = "ic_default.png"; public static final String ARG_DISH = "ARG_DISH"; public static final String ARG_DISH_NAME = "ARG_DISH_NAME"; public static final String ARG_UNIT_NAME = "ARG_UNIT_NAME"; public static final String ARG_UNIT = "ARG_UNIT"; public static final String FIREBASE_ID = "id"; //các đường dẫn, hằng dành cho cloud fire store public static final String USER_COLLECTION = "users"; public static final String EXTRA_LOGIN_SUCCESS = "EXTRA_LOGIN_SUCCESS" ; }
985
0.709845
0.696373
24
39.208332
26.193159
76
false
false
0
0
0
0
0
0
0.583333
false
false
11
16ac92c6c6aab3079f5980ebead0faa9e935105a
31,645,319,060,081
cb89248b3a23cb9155deaa15d85d4414c03339a4
/src/main/java/org/lanadvice/service/QuestionnaireService.java
59a653b94099fac8c03f0ecc900e1781a25d9a6d
[]
no_license
bsdimer/lanAdvice-surveyApi
https://github.com/bsdimer/lanAdvice-surveyApi
32272704e560d2fb1922c9db76a75ec0aea252e1
7579247213ba3cdb30aeb58bba1b80c24a85a67a
refs/heads/master
2022-12-06T20:20:36.521000
2020-05-20T08:12:04
2020-05-20T08:12:04
264,911,547
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.lanadvice.service; import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import io.quarkus.hibernate.orm.panache.PanacheQuery; import org.lanadvice.model.Question; import org.lanadvice.model.Questionnaire; import org.lanadvice.model.Survey; import org.lanadvice.repository.QuestionRepository; import org.lanadvice.repository.QuestionnaireRepository; import org.lanadvice.repository.SurveyRepository; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.Transactional; import java.io.*; import java.text.MessageFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @ApplicationScoped public class QuestionnaireService { @Inject QuestionnaireRepository questionnaireRepository; @Inject QuestionRepository questionRepository; @Inject SurveyRepository surveyRepository; @Transactional public Questionnaire create(Questionnaire questionnaire) { questionnaireRepository.save(questionnaire); return questionnaire; } public List<Questionnaire> findAll() { return (List<Questionnaire>) questionnaireRepository.findAll(); } @Transactional public Survey addSurvey(String clid, String answer, Long question) { Survey survey = new Survey(); survey.setSource(clid); survey.setAnswer(answer); questionRepository.findById(question).ifPresent(survey::setQuestion); surveyRepository.save(survey); return survey; } public List<Survey> findByCreatedBetween(LocalDateTime periodStart, LocalDateTime periodEnd) { return surveyRepository.findByCreatedBetween(periodStart, periodEnd); } public File getAsCsv(LocalDateTime start, LocalDateTime end) throws IOException { List<Survey> list = findByCreatedBetween(start, end); String string = "id,clid,questionId,questionText,answer,created\n"; string = string + list.stream() .map(s -> MessageFormat.format("{0},{1},{2},{3},{4},{5}\n", s.getId(), s.getSource(), s.getQuestion().getId(), s.getQuestion().getText(), s.getAnswer(), s.getCreated().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) ) ) .collect(Collectors.joining()); File file = File.createTempFile(UUID.randomUUID().toString(), ".csv"); OutputStream os = new FileOutputStream(file); os.write(string.getBytes(), 0, string.length()); return file; } }
UTF-8
Java
2,854
java
QuestionnaireService.java
Java
[]
null
[]
package org.lanadvice.service; import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import io.quarkus.hibernate.orm.panache.PanacheQuery; import org.lanadvice.model.Question; import org.lanadvice.model.Questionnaire; import org.lanadvice.model.Survey; import org.lanadvice.repository.QuestionRepository; import org.lanadvice.repository.QuestionnaireRepository; import org.lanadvice.repository.SurveyRepository; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.Transactional; import java.io.*; import java.text.MessageFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @ApplicationScoped public class QuestionnaireService { @Inject QuestionnaireRepository questionnaireRepository; @Inject QuestionRepository questionRepository; @Inject SurveyRepository surveyRepository; @Transactional public Questionnaire create(Questionnaire questionnaire) { questionnaireRepository.save(questionnaire); return questionnaire; } public List<Questionnaire> findAll() { return (List<Questionnaire>) questionnaireRepository.findAll(); } @Transactional public Survey addSurvey(String clid, String answer, Long question) { Survey survey = new Survey(); survey.setSource(clid); survey.setAnswer(answer); questionRepository.findById(question).ifPresent(survey::setQuestion); surveyRepository.save(survey); return survey; } public List<Survey> findByCreatedBetween(LocalDateTime periodStart, LocalDateTime periodEnd) { return surveyRepository.findByCreatedBetween(periodStart, periodEnd); } public File getAsCsv(LocalDateTime start, LocalDateTime end) throws IOException { List<Survey> list = findByCreatedBetween(start, end); String string = "id,clid,questionId,questionText,answer,created\n"; string = string + list.stream() .map(s -> MessageFormat.format("{0},{1},{2},{3},{4},{5}\n", s.getId(), s.getSource(), s.getQuestion().getId(), s.getQuestion().getText(), s.getAnswer(), s.getCreated().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) ) ) .collect(Collectors.joining()); File file = File.createTempFile(UUID.randomUUID().toString(), ".csv"); OutputStream os = new FileOutputStream(file); os.write(string.getBytes(), 0, string.length()); return file; } }
2,854
0.675193
0.67274
81
34.23457
24.284971
85
false
false
0
0
0
0
0
0
0.814815
false
false
11
70f65b69cff137750a149079d38d48860857f4ae
14,147,622,322,955
477b8abad30c67f8976c2e13e713ac74f3210ffa
/spring-boot/spring-boot004/sb-ws/src/test/java/com/xa/dt/mode/factory/chouxiang/ProductAa.java
62a28f8a579c154b12ac96fe64887c95d0e8266d
[]
no_license
DanielHaiFeng/hello-world
https://github.com/DanielHaiFeng/hello-world
12f770105d31fb5659e1eb7f41ddb129572ea40e
143e7eee2816ea6fd4575975dbb1b8fc506e8187
refs/heads/master
2021-01-17T20:54:19.047000
2020-01-17T07:29:43
2020-01-17T07:29:43
62,312,403
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xa.dt.mode.factory.chouxiang; /** * @ ProductAa.java * 具体产品 (矿泉水) */ public class ProductAa extends ProductA { @Override void intro() { System.out.println("矿泉水"); } }
UTF-8
Java
225
java
ProductAa.java
Java
[]
null
[]
package com.xa.dt.mode.factory.chouxiang; /** * @ ProductAa.java * 具体产品 (矿泉水) */ public class ProductAa extends ProductA { @Override void intro() { System.out.println("矿泉水"); } }
225
0.609756
0.609756
13
14.769231
14.613765
41
false
false
0
0
0
0
0
0
0.153846
false
false
11
b60cf8f26633ba92b2be525f43cb0b259bccfdcf
7,550,552,518,842
a634abe28714c187057cdf9e0b469a6de1b3647e
/dmr/src/main/java/org/jboss/hal/dmr/Operation.java
1907874cdd36c83464edfe038be1e55484a796b2
[ "Apache-2.0" ]
permissive
hal/console
https://github.com/hal/console
23328a2ee8dd640e53cff81eaf1c519e3a98f024
32cbfefaa7ca9254e439dbd787bda58d8490b6e7
refs/heads/main
2023-08-21T11:06:39.446000
2023-08-16T06:17:17
2023-08-16T06:17:17
38,317,187
31
105
Apache-2.0
false
2023-09-14T21:26:53
2015-06-30T15:26:19
2023-06-26T11:24:02
2023-09-14T21:26:53
161,898
46
85
3
Java
false
false
/* * Copyright 2022 Red Hat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.dmr; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.jboss.hal.spi.EsReturn; import static java.util.stream.Collectors.toSet; import static com.google.common.collect.Sets.newHashSet; import static org.jboss.hal.dmr.ModelDescriptionConstants.ADDRESS; import static org.jboss.hal.dmr.ModelDescriptionConstants.OP; import static org.jboss.hal.dmr.ModelDescriptionConstants.OPERATION_HEADERS; import static org.jboss.hal.dmr.ModelDescriptionConstants.RESOLVE_EXPRESSION; import static org.jboss.hal.dmr.ModelDescriptionConstants.ROLES; import static org.jboss.hal.dmr.ModelDescriptionConstants.WHOAMI; /** * Represents a DMR operation. */ public class Operation extends ModelNode { private final String name; private final ResourceAddress address; private final ModelNode parameter; private final ModelNode header; private final Set<String> roles; public Operation(ModelNode modelNode) { this.name = modelNode.get(OP).asString(); this.address = new ResourceAddress(modelNode.get(ADDRESS)); this.parameter = modelNode.clone(); this.parameter.remove(OP); this.parameter.remove(ADDRESS); this.parameter.remove(OPERATION_HEADERS); this.header = modelNode.hasDefined(OPERATION_HEADERS) ? modelNode.get(OPERATION_HEADERS) : new ModelNode(); ModelNode roles = ModelNodeHelper.failSafeGet(modelNode, OPERATION_HEADERS + "/" + ROLES); if (roles.isDefined()) { if (roles.getType() == ModelType.LIST) { this.roles = roles.asList().stream().map(ModelNode::asString).collect(toSet()); } else if (roles.getType() == ModelType.STRING) { this.roles = new HashSet<>(); this.roles.add(roles.asString()); } else { this.roles = new HashSet<>(); } } else { this.roles = new HashSet<>(); } addRolesAsHeaders(); set(modelNode.clone()); } Operation(String name, ResourceAddress address, ModelNode parameter, ModelNode header, Set<String> roles) { this.name = name; this.address = address; this.parameter = parameter == null ? new ModelNode() : parameter; this.header = header; this.roles = roles; set(this.parameter.clone()); get(OP).set(name); get(ADDRESS).set(address); if (header.isDefined()) { get(OPERATION_HEADERS).set(header); } addRolesAsHeaders(); } private void addRolesAsHeaders() { if (roles != null && !roles.isEmpty() && !name.equals(WHOAMI)) { // roles are headers! if (roles.size() == 1) { header.get(ROLES).set(roles.iterator().next()); } else { roles.forEach(role -> header.get(ROLES).add(role)); } get(OPERATION_HEADERS).set(header); } } /** * @return the name of the operation */ public String getName() { return get(OP).asString(); } /** * @return the address of the operation */ public ResourceAddress getAddress() { return address; } /** * @return the parameters of the operation */ public ModelNode getParameter() { return parameter; } /** * @return the header of the operation */ public ModelNode getHeader() { return header; } public boolean hasParameter() { return parameter.isDefined() && !parameter.asList().isEmpty(); } public Set<String> getRoles() { return roles; } public Operation runAs(Set<String> runAs) { return new Operation(name, address, parameter, header, newHashSet(runAs)); } /** * @return the string representation of the operation as used in the CLI */ @Override public String toString() { return asCli(); } /** * @return the string representation of the operation as used in the CLI */ public String asCli() { StringBuilder builder = new StringBuilder(); if (address.isDefined() && !address.asList().isEmpty()) { builder.append(address); } builder.append(":").append(name); if (hasParameter()) { builder.append("("); for (Iterator<Property> iterator = parameter.asPropertyList().iterator(); iterator.hasNext();) { Property p = iterator.next(); builder.append(p.getName()).append("=").append(p.getValue().asString()); if (iterator.hasNext()) { builder.append(","); } } builder.append(")"); } if (header.isDefined() && !header.asList().isEmpty()) { builder.append("{"); for (Iterator<Property> iterator = header.asPropertyList().iterator(); iterator.hasNext();) { Property p = iterator.next(); builder.append(p.getName()).append("=").append(p.getValue().asString()); if (iterator.hasNext()) { builder.append(","); } } builder.append("}"); } return builder.toString(); } /** * A builder for operations. */ public static class Builder { private final String name; private final ResourceAddress address; private ModelNode parameter; private final ModelNode header; private final Set<String> roles; public Builder(ResourceAddress address, String name) { this(address, name, false); } public Builder(ResourceAddress address, String name, boolean resolveExpression) { this.address = address; this.name = name; this.parameter = new ModelNode(); this.header = new ModelNode(); this.roles = new HashSet<>(); if (resolveExpression) { parameter.get(RESOLVE_EXPRESSION).set(resolveExpression); } } public Builder param(String name, boolean value) { parameter.get(name).set(value); return this; } public Builder param(String name, int value) { parameter.get(name).set(value); return this; } public Builder param(String name, long value) { parameter.get(name).set(value); return this; } public Builder param(String name, double value) { parameter.get(name).set(value); return this; } public Builder param(String name, String value) { parameter.get(name).set(value); return this; } public Builder param(String name, String[] values) { for (String value : values) { parameter.get(name).add(value); } return this; } public Builder param(String name, ModelNode value) { parameter.get(name).set(value); return this; } public Builder header(String name, String value) { header.get(name).set(value); return this; } public Builder header(String name, int value) { header.get(name).set(value); return this; } public Builder header(String name, boolean value) { header.get(name).set(value); return this; } /** * Uses the specified payload for the operation. * * @param payload The operation as model node. * @return this builder */ @EsReturn("OperationBuilder") public Builder payload(ModelNode payload) { parameter = payload; return this; } /** * @return builds and returns the operation */ public Operation build() { return new Operation(name, address, parameter, header, roles); } } }
UTF-8
Java
8,720
java
Operation.java
Java
[]
null
[]
/* * Copyright 2022 Red Hat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.dmr; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.jboss.hal.spi.EsReturn; import static java.util.stream.Collectors.toSet; import static com.google.common.collect.Sets.newHashSet; import static org.jboss.hal.dmr.ModelDescriptionConstants.ADDRESS; import static org.jboss.hal.dmr.ModelDescriptionConstants.OP; import static org.jboss.hal.dmr.ModelDescriptionConstants.OPERATION_HEADERS; import static org.jboss.hal.dmr.ModelDescriptionConstants.RESOLVE_EXPRESSION; import static org.jboss.hal.dmr.ModelDescriptionConstants.ROLES; import static org.jboss.hal.dmr.ModelDescriptionConstants.WHOAMI; /** * Represents a DMR operation. */ public class Operation extends ModelNode { private final String name; private final ResourceAddress address; private final ModelNode parameter; private final ModelNode header; private final Set<String> roles; public Operation(ModelNode modelNode) { this.name = modelNode.get(OP).asString(); this.address = new ResourceAddress(modelNode.get(ADDRESS)); this.parameter = modelNode.clone(); this.parameter.remove(OP); this.parameter.remove(ADDRESS); this.parameter.remove(OPERATION_HEADERS); this.header = modelNode.hasDefined(OPERATION_HEADERS) ? modelNode.get(OPERATION_HEADERS) : new ModelNode(); ModelNode roles = ModelNodeHelper.failSafeGet(modelNode, OPERATION_HEADERS + "/" + ROLES); if (roles.isDefined()) { if (roles.getType() == ModelType.LIST) { this.roles = roles.asList().stream().map(ModelNode::asString).collect(toSet()); } else if (roles.getType() == ModelType.STRING) { this.roles = new HashSet<>(); this.roles.add(roles.asString()); } else { this.roles = new HashSet<>(); } } else { this.roles = new HashSet<>(); } addRolesAsHeaders(); set(modelNode.clone()); } Operation(String name, ResourceAddress address, ModelNode parameter, ModelNode header, Set<String> roles) { this.name = name; this.address = address; this.parameter = parameter == null ? new ModelNode() : parameter; this.header = header; this.roles = roles; set(this.parameter.clone()); get(OP).set(name); get(ADDRESS).set(address); if (header.isDefined()) { get(OPERATION_HEADERS).set(header); } addRolesAsHeaders(); } private void addRolesAsHeaders() { if (roles != null && !roles.isEmpty() && !name.equals(WHOAMI)) { // roles are headers! if (roles.size() == 1) { header.get(ROLES).set(roles.iterator().next()); } else { roles.forEach(role -> header.get(ROLES).add(role)); } get(OPERATION_HEADERS).set(header); } } /** * @return the name of the operation */ public String getName() { return get(OP).asString(); } /** * @return the address of the operation */ public ResourceAddress getAddress() { return address; } /** * @return the parameters of the operation */ public ModelNode getParameter() { return parameter; } /** * @return the header of the operation */ public ModelNode getHeader() { return header; } public boolean hasParameter() { return parameter.isDefined() && !parameter.asList().isEmpty(); } public Set<String> getRoles() { return roles; } public Operation runAs(Set<String> runAs) { return new Operation(name, address, parameter, header, newHashSet(runAs)); } /** * @return the string representation of the operation as used in the CLI */ @Override public String toString() { return asCli(); } /** * @return the string representation of the operation as used in the CLI */ public String asCli() { StringBuilder builder = new StringBuilder(); if (address.isDefined() && !address.asList().isEmpty()) { builder.append(address); } builder.append(":").append(name); if (hasParameter()) { builder.append("("); for (Iterator<Property> iterator = parameter.asPropertyList().iterator(); iterator.hasNext();) { Property p = iterator.next(); builder.append(p.getName()).append("=").append(p.getValue().asString()); if (iterator.hasNext()) { builder.append(","); } } builder.append(")"); } if (header.isDefined() && !header.asList().isEmpty()) { builder.append("{"); for (Iterator<Property> iterator = header.asPropertyList().iterator(); iterator.hasNext();) { Property p = iterator.next(); builder.append(p.getName()).append("=").append(p.getValue().asString()); if (iterator.hasNext()) { builder.append(","); } } builder.append("}"); } return builder.toString(); } /** * A builder for operations. */ public static class Builder { private final String name; private final ResourceAddress address; private ModelNode parameter; private final ModelNode header; private final Set<String> roles; public Builder(ResourceAddress address, String name) { this(address, name, false); } public Builder(ResourceAddress address, String name, boolean resolveExpression) { this.address = address; this.name = name; this.parameter = new ModelNode(); this.header = new ModelNode(); this.roles = new HashSet<>(); if (resolveExpression) { parameter.get(RESOLVE_EXPRESSION).set(resolveExpression); } } public Builder param(String name, boolean value) { parameter.get(name).set(value); return this; } public Builder param(String name, int value) { parameter.get(name).set(value); return this; } public Builder param(String name, long value) { parameter.get(name).set(value); return this; } public Builder param(String name, double value) { parameter.get(name).set(value); return this; } public Builder param(String name, String value) { parameter.get(name).set(value); return this; } public Builder param(String name, String[] values) { for (String value : values) { parameter.get(name).add(value); } return this; } public Builder param(String name, ModelNode value) { parameter.get(name).set(value); return this; } public Builder header(String name, String value) { header.get(name).set(value); return this; } public Builder header(String name, int value) { header.get(name).set(value); return this; } public Builder header(String name, boolean value) { header.get(name).set(value); return this; } /** * Uses the specified payload for the operation. * * @param payload The operation as model node. * @return this builder */ @EsReturn("OperationBuilder") public Builder payload(ModelNode payload) { parameter = payload; return this; } /** * @return builds and returns the operation */ public Operation build() { return new Operation(name, address, parameter, header, roles); } } }
8,720
0.58039
0.579358
277
30.480145
25.173845
115
false
false
0
0
0
0
0
0
0.512635
false
false
1
c5f750953b081c656ff450735423845ece1943b6
34,376,918,246,705
0ae6974ac62b54be7d7954430dd4839b1e3f67b0
/app/src/main/java/net/proyecto/tesis/agrario/sensor/LenturaSensorRasbian.java
ba61a97a0291357d3ace6e0271bebd2a050c0f53
[]
no_license
choquidownn25/agrario
https://github.com/choquidownn25/agrario
f86ae4ce3fa0264dac632171414e602d935b8dfd
1dff3ee784a7b2b2ba25eeaca9d12f57adb3f931
refs/heads/master
2016-09-05T23:04:15.446000
2015-10-10T18:12:27
2015-10-10T18:12:27
34,223,718
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.proyecto.tesis.agrario.sensor; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import net.proyecto.tesis.agrario.R; /** * Created by choqu_000 on 22/08/2015. * Clase donde creamos el web service * */ public class LenturaSensorRasbian extends Activity { //Atributos private TextView anno; //Creamos la Vista protected void onCreate(Bundle saveInstanceState){ super.onCreate(saveInstanceState); setContentView(R.layout.service_sensor_rasberrypi); // anno = (TextView)findViewById(R.id.textViewanno); } }
UTF-8
Java
615
java
LenturaSensorRasbian.java
Java
[ { "context": "t net.proyecto.tesis.agrario.R;\n\n/**\n * Created by choqu_000 on 22/08/2015.\n * Clase donde creamos el web serv", "end": 197, "score": 0.9996228218078613, "start": 188, "tag": "USERNAME", "value": "choqu_000" } ]
null
[]
package net.proyecto.tesis.agrario.sensor; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import net.proyecto.tesis.agrario.R; /** * Created by choqu_000 on 22/08/2015. * Clase donde creamos el web service * */ public class LenturaSensorRasbian extends Activity { //Atributos private TextView anno; //Creamos la Vista protected void onCreate(Bundle saveInstanceState){ super.onCreate(saveInstanceState); setContentView(R.layout.service_sensor_rasberrypi); // anno = (TextView)findViewById(R.id.textViewanno); } }
615
0.713821
0.695935
27
21.777779
20.261866
59
false
false
0
0
0
0
0
0
0.333333
false
false
1
5556ebac35a2d5e1977b7946ef7cf2296bf48b50
11,252,814,331,683
22296354fd89b6cab30eb6cce4dd140ae230a2dc
/src/game/CollisionDetector.java
9dd05b99db3baadf5fa06eb42e81727671c153d1
[]
no_license
DenisDuev/Tank_SoftUni_Game
https://github.com/DenisDuev/Tank_SoftUni_Game
03c2dbe76e53d7e1b6080ca9673b2df9d0548067
862bf4b2580fb55dd1652393e701a91af949f1ec
refs/heads/master
2021-01-18T23:01:15.461000
2016-05-22T11:01:23
2016-05-22T11:01:23
55,591,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game; import objects.game_objects.Bullet; import objects.game_objects.GameObject; import objects.game_objects.power_ups.PowerUp; import objects.game_objects.tanks.Tank; import java.util.List; import static constants.Constants.*; public class CollisionDetector { private int[][] matrix; private List<Tank> tanks; private List<PowerUp> powerups; private boolean isGameOver; public CollisionDetector(int[][] matrix, List<Tank> tanks, List<PowerUp> powerups) { this.matrix = matrix; this.tanks = tanks; this.powerups = powerups; this.isGameOver = false; } public boolean shouldTankMove(Tank tank, int x, int y) { int tankX = tank.getX() + x; int tankY = tank.getY() + y; if (tankX < 0 || tankX + TANK_SIZE + 2 > BOARD_SIZE || tankY < 0 || tankY + TANK_SIZE + 2 > BOARD_SIZE) { return false; } if (matrix[tankY / MATRIX_CELL_SIZE][tankX / MATRIX_CELL_SIZE] <= 11 && matrix[tankY / MATRIX_CELL_SIZE][tankX / MATRIX_CELL_SIZE] > 0 || matrix[tankY / MATRIX_CELL_SIZE][(tankX + TANK_SIZE) / MATRIX_CELL_SIZE] <= 11 && matrix[tankY / MATRIX_CELL_SIZE][(tankX + TANK_SIZE) / MATRIX_CELL_SIZE] > 0 || matrix[(tankY + TANK_SIZE) / MATRIX_CELL_SIZE][(tankX + TANK_SIZE) / MATRIX_CELL_SIZE] <= 11 && matrix[(tankY + TANK_SIZE) / MATRIX_CELL_SIZE][(tankX + TANK_SIZE) / MATRIX_CELL_SIZE] > 0 || matrix[(tankY + TANK_SIZE) / MATRIX_CELL_SIZE][tankX / MATRIX_CELL_SIZE] <= 11 && matrix[(tankY + TANK_SIZE) / MATRIX_CELL_SIZE][tankX / MATRIX_CELL_SIZE] > 0 ) { return false; } for (int i = 0; i < tanks.size(); i++) { Tank otherTank = tanks.get(i); if (!otherTank.isAlive()) { tanks.remove(i); } //check the tanks by reference, if they are equal, we don't have to check for collision if (tank == otherTank) { continue; } //are 4 point of Tank inside the other tank boolean isUpLeftPoint = otherTank.getX() <= tankX && tankX <= otherTank.getX() + TANK_SIZE && otherTank.getY() <= tankY && tankY <= otherTank.getY() + TANK_SIZE; boolean isUpRightPoint = otherTank.getX() <= tankX + TANK_SIZE && tankX + TANK_SIZE <= otherTank.getX() + TANK_SIZE && otherTank.getY() <= tankY && tankY <= otherTank.getY() + TANK_SIZE; boolean isDownLeftPoint = otherTank.getX() <= tankX && tankX <= otherTank.getX() + TANK_SIZE && otherTank.getY() <= tankY + TANK_SIZE && tankY + TANK_SIZE <= otherTank.getY() + TANK_SIZE; boolean isDownRightPoint = otherTank.getX() <= tankX + TANK_SIZE && tankX + TANK_SIZE <= otherTank.getX() + TANK_SIZE && otherTank.getY() <= tankY + TANK_SIZE && tankY + TANK_SIZE <= otherTank.getY() + TANK_SIZE; if (isUpLeftPoint || isUpRightPoint || isDownLeftPoint || isDownRightPoint) { return false; } } return true; } public boolean isBulletCollide(Bullet bullet) { int bulletX = bullet.getX(); int bulletY = bullet.getY(); if (bulletX < 0 || bulletX > BOARD_SIZE - Bullet.IMAGE_WIGHT || bulletY < 0 || bulletY >= BOARD_SIZE) { return true; } if (matrix[bulletY / MATRIX_CELL_SIZE][bulletX / MATRIX_CELL_SIZE] <= 10 && matrix[bulletY / MATRIX_CELL_SIZE][bulletX / MATRIX_CELL_SIZE] > 0) { matrix[bulletY / MATRIX_CELL_SIZE][bulletX / MATRIX_CELL_SIZE]-= bullet.getDamage() / 10; bullet.addScoreToParentTankWallShoot(); return true; } for (Tank tank : tanks) { if (tank.getX() <= bulletX && bulletX <= tank.getX() + TANK_SIZE && tank.getY() <= bulletY && bulletY <= tank.getY() + TANK_SIZE) { tank.decrementHealth(bullet.getDamage()); bullet.addScoreToParentTankTankShoot(); return true; } } //detectBird if (BIRD_X <= bulletX && bulletX <= BIRD_X + MATRIX_CELL_SIZE && BIRD_Y <= bulletY) { this.isGameOver = true; return false; } return false; } public boolean isBirdDeath(){ return this.isGameOver; } public void getPowerUps(){ for (int i = 0; i < this.powerups.size(); i++) { PowerUp powerup = this.powerups.get(i); if (!powerup.isAppear()){ this.powerups.remove(i); continue; } for (Tank tank : this.tanks) { if (isObjectsCollide(powerup, tank, PowerUp.WIDTH )){ powerup.SetEffect(tank); this.powerups.remove(i); break; } } } } private static boolean isObjectsCollide(GameObject firstObeject, GameObject secondObject, int firstObjectSize) { boolean isUpLeftPoint = secondObject.getX() <= firstObeject.getX() && firstObeject.getX() <= secondObject.getX() + firstObjectSize && secondObject.getY() <= firstObeject.getY() && firstObeject.getY() <= secondObject.getY() + firstObjectSize; boolean isUpRightPoint = secondObject.getX() <= firstObeject.getX() + firstObjectSize && firstObeject.getX() + firstObjectSize <= secondObject.getX() + firstObjectSize && secondObject.getY() <= firstObeject.getY() && firstObeject.getY() <= secondObject.getY() + firstObjectSize; boolean isDownLeftPoint = secondObject.getX() <= firstObeject.getX() && firstObeject.getX() <= secondObject.getX() + firstObjectSize && secondObject.getY() <= firstObeject.getY() + firstObjectSize && firstObeject.getY() + firstObjectSize <= secondObject.getY() + firstObjectSize; boolean isDownRightPoint = secondObject.getX() <= firstObeject.getX() + firstObjectSize && firstObeject.getX() + firstObjectSize <= secondObject.getX() + firstObjectSize && secondObject.getY() <= firstObeject.getY() + firstObjectSize && firstObeject.getY() + firstObjectSize <= secondObject.getY() + TANK_SIZE; return (isUpLeftPoint || isUpRightPoint || isDownLeftPoint || isDownRightPoint); } }
UTF-8
Java
6,215
java
CollisionDetector.java
Java
[]
null
[]
package game; import objects.game_objects.Bullet; import objects.game_objects.GameObject; import objects.game_objects.power_ups.PowerUp; import objects.game_objects.tanks.Tank; import java.util.List; import static constants.Constants.*; public class CollisionDetector { private int[][] matrix; private List<Tank> tanks; private List<PowerUp> powerups; private boolean isGameOver; public CollisionDetector(int[][] matrix, List<Tank> tanks, List<PowerUp> powerups) { this.matrix = matrix; this.tanks = tanks; this.powerups = powerups; this.isGameOver = false; } public boolean shouldTankMove(Tank tank, int x, int y) { int tankX = tank.getX() + x; int tankY = tank.getY() + y; if (tankX < 0 || tankX + TANK_SIZE + 2 > BOARD_SIZE || tankY < 0 || tankY + TANK_SIZE + 2 > BOARD_SIZE) { return false; } if (matrix[tankY / MATRIX_CELL_SIZE][tankX / MATRIX_CELL_SIZE] <= 11 && matrix[tankY / MATRIX_CELL_SIZE][tankX / MATRIX_CELL_SIZE] > 0 || matrix[tankY / MATRIX_CELL_SIZE][(tankX + TANK_SIZE) / MATRIX_CELL_SIZE] <= 11 && matrix[tankY / MATRIX_CELL_SIZE][(tankX + TANK_SIZE) / MATRIX_CELL_SIZE] > 0 || matrix[(tankY + TANK_SIZE) / MATRIX_CELL_SIZE][(tankX + TANK_SIZE) / MATRIX_CELL_SIZE] <= 11 && matrix[(tankY + TANK_SIZE) / MATRIX_CELL_SIZE][(tankX + TANK_SIZE) / MATRIX_CELL_SIZE] > 0 || matrix[(tankY + TANK_SIZE) / MATRIX_CELL_SIZE][tankX / MATRIX_CELL_SIZE] <= 11 && matrix[(tankY + TANK_SIZE) / MATRIX_CELL_SIZE][tankX / MATRIX_CELL_SIZE] > 0 ) { return false; } for (int i = 0; i < tanks.size(); i++) { Tank otherTank = tanks.get(i); if (!otherTank.isAlive()) { tanks.remove(i); } //check the tanks by reference, if they are equal, we don't have to check for collision if (tank == otherTank) { continue; } //are 4 point of Tank inside the other tank boolean isUpLeftPoint = otherTank.getX() <= tankX && tankX <= otherTank.getX() + TANK_SIZE && otherTank.getY() <= tankY && tankY <= otherTank.getY() + TANK_SIZE; boolean isUpRightPoint = otherTank.getX() <= tankX + TANK_SIZE && tankX + TANK_SIZE <= otherTank.getX() + TANK_SIZE && otherTank.getY() <= tankY && tankY <= otherTank.getY() + TANK_SIZE; boolean isDownLeftPoint = otherTank.getX() <= tankX && tankX <= otherTank.getX() + TANK_SIZE && otherTank.getY() <= tankY + TANK_SIZE && tankY + TANK_SIZE <= otherTank.getY() + TANK_SIZE; boolean isDownRightPoint = otherTank.getX() <= tankX + TANK_SIZE && tankX + TANK_SIZE <= otherTank.getX() + TANK_SIZE && otherTank.getY() <= tankY + TANK_SIZE && tankY + TANK_SIZE <= otherTank.getY() + TANK_SIZE; if (isUpLeftPoint || isUpRightPoint || isDownLeftPoint || isDownRightPoint) { return false; } } return true; } public boolean isBulletCollide(Bullet bullet) { int bulletX = bullet.getX(); int bulletY = bullet.getY(); if (bulletX < 0 || bulletX > BOARD_SIZE - Bullet.IMAGE_WIGHT || bulletY < 0 || bulletY >= BOARD_SIZE) { return true; } if (matrix[bulletY / MATRIX_CELL_SIZE][bulletX / MATRIX_CELL_SIZE] <= 10 && matrix[bulletY / MATRIX_CELL_SIZE][bulletX / MATRIX_CELL_SIZE] > 0) { matrix[bulletY / MATRIX_CELL_SIZE][bulletX / MATRIX_CELL_SIZE]-= bullet.getDamage() / 10; bullet.addScoreToParentTankWallShoot(); return true; } for (Tank tank : tanks) { if (tank.getX() <= bulletX && bulletX <= tank.getX() + TANK_SIZE && tank.getY() <= bulletY && bulletY <= tank.getY() + TANK_SIZE) { tank.decrementHealth(bullet.getDamage()); bullet.addScoreToParentTankTankShoot(); return true; } } //detectBird if (BIRD_X <= bulletX && bulletX <= BIRD_X + MATRIX_CELL_SIZE && BIRD_Y <= bulletY) { this.isGameOver = true; return false; } return false; } public boolean isBirdDeath(){ return this.isGameOver; } public void getPowerUps(){ for (int i = 0; i < this.powerups.size(); i++) { PowerUp powerup = this.powerups.get(i); if (!powerup.isAppear()){ this.powerups.remove(i); continue; } for (Tank tank : this.tanks) { if (isObjectsCollide(powerup, tank, PowerUp.WIDTH )){ powerup.SetEffect(tank); this.powerups.remove(i); break; } } } } private static boolean isObjectsCollide(GameObject firstObeject, GameObject secondObject, int firstObjectSize) { boolean isUpLeftPoint = secondObject.getX() <= firstObeject.getX() && firstObeject.getX() <= secondObject.getX() + firstObjectSize && secondObject.getY() <= firstObeject.getY() && firstObeject.getY() <= secondObject.getY() + firstObjectSize; boolean isUpRightPoint = secondObject.getX() <= firstObeject.getX() + firstObjectSize && firstObeject.getX() + firstObjectSize <= secondObject.getX() + firstObjectSize && secondObject.getY() <= firstObeject.getY() && firstObeject.getY() <= secondObject.getY() + firstObjectSize; boolean isDownLeftPoint = secondObject.getX() <= firstObeject.getX() && firstObeject.getX() <= secondObject.getX() + firstObjectSize && secondObject.getY() <= firstObeject.getY() + firstObjectSize && firstObeject.getY() + firstObjectSize <= secondObject.getY() + firstObjectSize; boolean isDownRightPoint = secondObject.getX() <= firstObeject.getX() + firstObjectSize && firstObeject.getX() + firstObjectSize <= secondObject.getX() + firstObjectSize && secondObject.getY() <= firstObeject.getY() + firstObjectSize && firstObeject.getY() + firstObjectSize <= secondObject.getY() + TANK_SIZE; return (isUpLeftPoint || isUpRightPoint || isDownLeftPoint || isDownRightPoint); } }
6,215
0.597426
0.593242
123
49.512196
65.643951
318
false
false
0
0
0
0
0
0
0.780488
false
false
1
172e1bb1ffba26b0b5e6057eb533703e140d65f4
35,115,652,614,084
87acadfc0966c6c7a71ef41f5a34bf08c4e360ac
/javautils/src/main/java/com/java/utils/beantomap/BeanToMapUtil.java
0821dfde077deedf70db88e80e815096633eb025
[]
no_license
changecode/javautils
https://github.com/changecode/javautils
f511e97c49ab94c400493187661680ff56a5b32c
7926a967ca4b4163306a5d6f9131551fb94b1620
refs/heads/master
2021-09-04T10:29:19.096000
2018-01-18T01:50:43
2018-01-18T01:50:43
64,804,812
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.java.utils.beantomap; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * bean 与 map之间的转换 * @author Tim * */ public class BeanToMapUtil { private static final Logger log = LoggerFactory.getLogger(BeanToMapUtil.class); /** * 将bean转换成map对象 * @param object * @return */ public static Map<String, Object> beanToMap(Object object) { if(object == null){ return null; } Map<String, Object> mapResult = new HashMap<String, Object>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (!key.equals("class")) { // 得到property对应的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(object); mapResult.put(key, value); } } } catch (Exception e) { if(log.isErrorEnabled()) { log.error("bean to map errror", e); } } return mapResult; } /** * map转换成object * @param paramMap * @param object * @return */ public static Object mapToObject(Map<Object, Object> paramMap, Object object) { if(paramMap == null || object == null){ return null; } try { BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (paramMap.containsKey(key)) { Object value = paramMap.get(key); Method setter = property.getWriteMethod(); setter.invoke(object, value); } } } catch (Exception e) { if(log.isErrorEnabled()) { log.error("map to object error", e); } } return object; } }
UTF-8
Java
2,377
java
BeanToMapUtil.java
Java
[ { "context": "gerFactory;\r\n\r\n/**\r\n * bean 与 map之间的转换\r\n * @author Tim\r\n *\r\n */\r\npublic class BeanToMapUtil {\r\n\r\n\tprivat", "end": 324, "score": 0.988655686378479, "start": 321, "tag": "NAME", "value": "Tim" } ]
null
[]
package com.java.utils.beantomap; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * bean 与 map之间的转换 * @author Tim * */ public class BeanToMapUtil { private static final Logger log = LoggerFactory.getLogger(BeanToMapUtil.class); /** * 将bean转换成map对象 * @param object * @return */ public static Map<String, Object> beanToMap(Object object) { if(object == null){ return null; } Map<String, Object> mapResult = new HashMap<String, Object>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (!key.equals("class")) { // 得到property对应的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(object); mapResult.put(key, value); } } } catch (Exception e) { if(log.isErrorEnabled()) { log.error("bean to map errror", e); } } return mapResult; } /** * map转换成object * @param paramMap * @param object * @return */ public static Object mapToObject(Map<Object, Object> paramMap, Object object) { if(paramMap == null || object == null){ return null; } try { BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (paramMap.containsKey(key)) { Object value = paramMap.get(key); Method setter = property.getWriteMethod(); setter.invoke(object, value); } } } catch (Exception e) { if(log.isErrorEnabled()) { log.error("map to object error", e); } } return object; } }
2,377
0.591942
0.591084
83
26.108435
24.16161
89
false
false
0
0
0
0
0
0
1.457831
false
false
1
1c4f4207f19e34291ac604da821f858cc78fb15a
34,213,709,486,407
abd40ab24c20db709b0ee32f156c11914f83e683
/src/com/company/CaesarCipher.java
b1ede113d048dacaf986cc6f87e56902eb9831a7
[]
no_license
Dyazho/COMP307_lab01
https://github.com/Dyazho/COMP307_lab01
d2f201b288b91eee4e584b158436889b15e05a9d
ea7da6691d1058c0766a4b82433e1c64dc84a3a5
refs/heads/master
2023-08-02T10:28:41.368000
2021-09-09T15:36:45
2021-09-09T15:36:45
404,777,769
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.Scanner; public class CaesarCipher { public static void main(String[] args) { // write your code here int userChoice; int userKey; String userInput; String result; Scanner input = new Scanner(System.in); System.out.println("Caesar Cipher:"); System.out.print("Encryption(1);Decryption(2): "); userChoice = input.nextInt(); System.out.print("Message: "); userInput = new Scanner(System.in).nextLine(); System.out.print("Key: "); userKey = input.nextInt(); System.out.print("Result: "); if(userChoice == 1){ result = caesarCipherEncrypt(userInput,userKey); } else if(userChoice == 2){ result = caesarCipherDecrypt(userInput,userKey); } else { System.out.println("Choice not enter correctly!"); result = ""; } System.out.println(result); } public static char caesarCipher(char letter, int key){ if(!Character.isLetter(letter)){ return letter; } char offset; if(Character.isUpperCase(letter)){ offset = 'A'; }else { offset='a'; } return (char)((((letter+key)-offset)%26)+offset); } public static String caesarCipherEncrypt(String phrase, int key){ String result = ""; for (char index : phrase.toCharArray()) { result += caesarCipher(index,key); } return result; } public static String caesarCipherDecrypt(String phrase, int key){ return caesarCipherEncrypt(phrase,26-key); } }
UTF-8
Java
1,707
java
CaesarCipher.java
Java
[]
null
[]
package com.company; import java.util.Scanner; public class CaesarCipher { public static void main(String[] args) { // write your code here int userChoice; int userKey; String userInput; String result; Scanner input = new Scanner(System.in); System.out.println("Caesar Cipher:"); System.out.print("Encryption(1);Decryption(2): "); userChoice = input.nextInt(); System.out.print("Message: "); userInput = new Scanner(System.in).nextLine(); System.out.print("Key: "); userKey = input.nextInt(); System.out.print("Result: "); if(userChoice == 1){ result = caesarCipherEncrypt(userInput,userKey); } else if(userChoice == 2){ result = caesarCipherDecrypt(userInput,userKey); } else { System.out.println("Choice not enter correctly!"); result = ""; } System.out.println(result); } public static char caesarCipher(char letter, int key){ if(!Character.isLetter(letter)){ return letter; } char offset; if(Character.isUpperCase(letter)){ offset = 'A'; }else { offset='a'; } return (char)((((letter+key)-offset)%26)+offset); } public static String caesarCipherEncrypt(String phrase, int key){ String result = ""; for (char index : phrase.toCharArray()) { result += caesarCipher(index,key); } return result; } public static String caesarCipherDecrypt(String phrase, int key){ return caesarCipherEncrypt(phrase,26-key); } }
1,707
0.564733
0.560047
63
26.095238
20.399746
69
false
false
0
0
0
0
0
0
0.603175
false
false
1
50b2d4111767dbd09693f0848245399b1dd5a97b
34,522,947,132,964
6d08e7dbabff98687f1007a4fcc3f8f155eb5ba1
/src/com/wfsc/http/HttpConnectionManager.java
900ee923c8614c6074bbf584ee22daaf907bf04c
[]
no_license
Code-God/zysq
https://github.com/Code-God/zysq
df1f7ff554b8648773603ec2548749d03e77284c
c7a6f08f889ae369cbb73ceca0d55c91e2a639a6
refs/heads/master
2020-03-21T12:34:34.764000
2018-06-25T07:43:13
2018-06-25T07:43:13
138,560,140
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wfsc.http; /** * Created with IntelliJ IDEA. * User: jia * Date: 13-7-8 * Time: 下午11:37 * To change this template use File | Settings | File Templates. */ import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.http.client.HttpClient; import org.apache.http.client.params.ClientPNames; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class HttpConnectionManager { public static HttpClient getHttpClient() { HttpParams params = new BasicHttpParams(); /* 连接超时 */ HttpConnectionParams.setConnectionTimeout(params, 3000); /* 请求超时 */ HttpConnectionParams.setSoTimeout(params, 10000); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); // Increase max total connection to 200 cm.setMaxTotal(200); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(20); // Increase max connections for localhost:80 to 50 // HttpHost localhost = new HttpHost("locahost", 80); // cm.setMaxPerRoute(new HttpRoute(localhost), 50); DefaultHttpClient httpClient = new DefaultHttpClient(cm, params); // // 自定义cookies***************** // CookieSpecFactory csf = new CookieSpecFactory() { // // public CookieSpec newInstance(HttpParams params) { // return new BrowserCompatSpec() { // // @Override // public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // // Oh, I am easy // } // }; // } // }; // httpClient.getCookieSpecs().register("easy", csf); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); // 自定义cookies***************** return wrapClient(httpClient); } /** * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常 * 不用导入SSL证书 */ public static HttpClient wrapClient(HttpClient base) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } } }
UTF-8
Java
3,867
java
HttpConnectionManager.java
Java
[ { "context": "http;\n\n/**\n * Created with IntelliJ IDEA.\n * User: jia\n * Date: 13-7-8\n * Time: 下午11:37\n * To change thi", "end": 71, "score": 0.992337703704834, "start": 68, "tag": "USERNAME", "value": "jia" } ]
null
[]
package com.wfsc.http; /** * Created with IntelliJ IDEA. * User: jia * Date: 13-7-8 * Time: 下午11:37 * To change this template use File | Settings | File Templates. */ import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.http.client.HttpClient; import org.apache.http.client.params.ClientPNames; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class HttpConnectionManager { public static HttpClient getHttpClient() { HttpParams params = new BasicHttpParams(); /* 连接超时 */ HttpConnectionParams.setConnectionTimeout(params, 3000); /* 请求超时 */ HttpConnectionParams.setSoTimeout(params, 10000); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); // Increase max total connection to 200 cm.setMaxTotal(200); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(20); // Increase max connections for localhost:80 to 50 // HttpHost localhost = new HttpHost("locahost", 80); // cm.setMaxPerRoute(new HttpRoute(localhost), 50); DefaultHttpClient httpClient = new DefaultHttpClient(cm, params); // // 自定义cookies***************** // CookieSpecFactory csf = new CookieSpecFactory() { // // public CookieSpec newInstance(HttpParams params) { // return new BrowserCompatSpec() { // // @Override // public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // // Oh, I am easy // } // }; // } // }; // httpClient.getCookieSpecs().register("easy", csf); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); // 自定义cookies***************** return wrapClient(httpClient); } /** * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常 * 不用导入SSL证书 */ public static HttpClient wrapClient(HttpClient base) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } } }
3,867
0.739564
0.723549
110
33.627274
26.622566
102
false
false
0
0
0
0
0
0
2.481818
false
false
1
25f6ec257a86e285909dabead50278e9a2d28017
10,402,410,844,883
386ea4778f25ffbb2d32ca0a3ace60cb4ed3e6a9
/src/L1A6.java
8793523c2cae58a14850de0edb5efb395d525700
[]
no_license
emil10001/ReignOfBrains_Pandora
https://github.com/emil10001/ReignOfBrains_Pandora
bded498724a6aaef461cb3173e3a68330d2e782f
4c482313b78bf27e3cb6c0b4d12f20d672e103ab
refs/heads/master
2021-01-10T19:44:53.162000
2013-12-01T22:04:57
2013-12-01T22:04:57
1,211,054
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
public class L1A6 extends Area{ //Hospital, roof }
UTF-8
Java
52
java
L1A6.java
Java
[]
null
[]
public class L1A6 extends Area{ //Hospital, roof }
52
0.730769
0.692308
3
16
12.247449
31
false
false
0
0
0
0
0
0
0.333333
false
false
1
0d5824d309797f36a16b586b79d589f3427f2f27
10,402,410,844,423
20e3fb7a9a0d3119ac5d5131fcd484eb79c7255d
/src/main/java/org/example/warehouse/types/input/Inventory.java
f84cfcee5a4937403a90e9743a464dc019fab451
[]
no_license
christianfrid/service-digital-warehouse
https://github.com/christianfrid/service-digital-warehouse
689213ab449b8bef983b63d448f979fd8ff9cfa1
a33f8d2caa2b23827aec4926098357eb7cbf718e
refs/heads/main
2023-07-13T19:51:46.970000
2021-08-20T08:45:27
2021-08-20T08:45:27
344,174,694
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.example.warehouse.types.input; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.example.warehouse.types.Article; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Schema(description = "API model for the inventory of articles") public class Inventory { private List<Article> inventory; }
UTF-8
Java
476
java
Inventory.java
Java
[]
null
[]
package org.example.warehouse.types.input; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.example.warehouse.types.Article; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Schema(description = "API model for the inventory of articles") public class Inventory { private List<Article> inventory; }
476
0.777311
0.77521
19
23.052631
18.065594
64
false
false
0
0
0
0
0
0
0.473684
false
false
1
d42183ce959a46a210ecbd0c156f7cad4beef232
154,618,850,113
eb23a2338064a923d637eb4ba53940423eb222dd
/product-authority/src/main/java/cn/cloudwalk/product/authority/config/UserUtil.java
63f84fa94faa16382a820c379dcb7629b9f13f1f
[]
no_license
YuLGitHub/product-manage
https://github.com/YuLGitHub/product-manage
f8fae4ef900e6b37df30d18df5b4a50d31d8e9a7
ef570508db803fcbff727c474cd1e38ea9825999
refs/heads/master
2018-11-02T15:54:38.017000
2018-09-03T01:38:41
2018-09-03T01:38:41
146,082,973
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.cloudwalk.product.authority.config; import cn.cloudwalk.product.authority.model.User; import org.apache.shiro.SecurityUtils; /** * 获取系统中登录用户信息类 * @author YCKJ1127 * @date 2018/08/25 */ public class UserUtil { public static User getCurrentUser() { return (User) SecurityUtils.getSubject().getSession().getAttribute("user"); } }
UTF-8
Java
386
java
UserUtil.java
Java
[ { "context": "iro.SecurityUtils;\n\n/**\n * 获取系统中登录用户信息类\n * @author YCKJ1127\n * @date 2018/08/25\n */\npublic class UserUtil {\n\n", "end": 177, "score": 0.9996122717857361, "start": 169, "tag": "USERNAME", "value": "YCKJ1127" } ]
null
[]
package cn.cloudwalk.product.authority.config; import cn.cloudwalk.product.authority.model.User; import org.apache.shiro.SecurityUtils; /** * 获取系统中登录用户信息类 * @author YCKJ1127 * @date 2018/08/25 */ public class UserUtil { public static User getCurrentUser() { return (User) SecurityUtils.getSubject().getSession().getAttribute("user"); } }
386
0.720994
0.687845
17
20.294117
23.072174
83
false
false
0
0
0
0
0
0
0.235294
false
false
1
3c6e207f5de98496496e9360ac424870fdf588fd
17,386,027,667,018
72bae081467df7dc6c6add2a024bfe8c6a8ad75e
/src/Users/upload.java
ba81b7dd37c2feadad0571589b4a65a40a99b9be
[]
no_license
rupss/QuizAmp
https://github.com/rupss/QuizAmp
62c8badfc695d7f542c91b07d09af122e82d064a
9505e095c28c24bf28f073f94dbc05c5d8d2c3c6
refs/heads/master
2020-05-17T10:16:20.822000
2013-12-01T03:27:06
2013-12-01T03:27:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Users; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.FileItemFactory; import org.apache.tomcat.util.http.fileupload.FileUploadException; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class upload */ @WebServlet("/upload") public class upload extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public upload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* from http://www.coderanch.com/t/537264/open-source/Image-Upload-directory-HTML-form*/ /* also: http://commons.apache.org/proper/commons-fileupload//using.html*/ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { // System.out.println("request: "+request); // System.out.println("request end"); List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); String root = getServletContext().getRealPath("/"); // System.out.println(root); File path = new File(root + "WebContent/images"); // System.out.println(path); if (!path.exists()) { boolean status = path.mkdirs(); } File uploadedFile = new File(path + "/" + fileName); // System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
3,150
java
upload.java
Java
[]
null
[]
package Users; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.FileItemFactory; import org.apache.tomcat.util.http.fileupload.FileUploadException; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class upload */ @WebServlet("/upload") public class upload extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public upload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* from http://www.coderanch.com/t/537264/open-source/Image-Upload-directory-HTML-form*/ /* also: http://commons.apache.org/proper/commons-fileupload//using.html*/ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { // System.out.println("request: "+request); // System.out.println("request end"); List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); String root = getServletContext().getRealPath("/"); // System.out.println(root); File path = new File(root + "WebContent/images"); // System.out.println(path); if (!path.exists()) { boolean status = path.mkdirs(); } File uploadedFile = new File(path + "/" + fileName); // System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
3,150
0.648571
0.646349
90
34
28.326273
119
false
false
0
0
0
0
0
0
0.755556
false
false
1
d38a59557ffa3105d8e0f21b6461f08ac2f04042
34,359,738,381,446
ae0bda88e8dec455c3347927ec5424a79dbaf7f6
/src/main/java/com/ps/network/MD2HashSample.java
2aa85a10c3c96cfd95ecca12b4164391eb81f4a5
[]
no_license
prempocs/Java-8-proc
https://github.com/prempocs/Java-8-proc
22e02a8c0ae327d69a5e9ac7fc4ddf2f35dde594
4690405c26c5ce31d5983651d708cb1b668178be
refs/heads/master
2020-03-31T07:43:56.839000
2018-10-13T08:38:47
2018-10-13T08:38:47
152,032,973
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ps.network; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD2HashSample { public static String encryptThisString(String input, String algorithm ) { try { // getInstance() method is called with algorithm MD2 MessageDigest md = MessageDigest.getInstance(algorithm); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = "0" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { System.out.println("HashCode Generated by MD2 for: "); String s1 = "GeeksForGeeks"; String s2 = "hello world"; System.out.println("MD2:- \n" + s1 + " : " + encryptThisString(s1,"MD2")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"MD2")); System.out.println("MD5:- \n" + s1 + " : " + encryptThisString(s1,"MD5")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"MD5")); System.out.println("SHA-1:- \n" + s1 + " : " + encryptThisString(s1,"SHA-1")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-1")); System.out.println("SHA-224:- \n" + s1 + " : " + encryptThisString(s1,"SHA-224")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-224")); System.out.println("SHA-256:- \n" + s1 + " : " + encryptThisString(s1,"SHA-256")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-256")); System.out.println("SHA-384:-\n" + s1 + " : " + encryptThisString(s1,"SHA-384")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-384")); System.out.println("SHA-512:- \n" + s1 + " : " + encryptThisString(s1,"SHA-512")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-512")); } }
UTF-8
Java
2,406
java
MD2HashSample.java
Java
[ { "context": " Generated by MD2 for: \");\r\n\r\n\t\tString s1 = \"GeeksForGeeks\";\r\n\t\tString s2 = \"hello world\";\r\n\t\tSystem.ou", "end": 1243, "score": 0.5064119696617126, "start": 1240, "tag": "USERNAME", "value": "For" } ]
null
[]
package com.ps.network; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD2HashSample { public static String encryptThisString(String input, String algorithm ) { try { // getInstance() method is called with algorithm MD2 MessageDigest md = MessageDigest.getInstance(algorithm); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = "0" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { System.out.println("HashCode Generated by MD2 for: "); String s1 = "GeeksForGeeks"; String s2 = "hello world"; System.out.println("MD2:- \n" + s1 + " : " + encryptThisString(s1,"MD2")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"MD2")); System.out.println("MD5:- \n" + s1 + " : " + encryptThisString(s1,"MD5")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"MD5")); System.out.println("SHA-1:- \n" + s1 + " : " + encryptThisString(s1,"SHA-1")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-1")); System.out.println("SHA-224:- \n" + s1 + " : " + encryptThisString(s1,"SHA-224")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-224")); System.out.println("SHA-256:- \n" + s1 + " : " + encryptThisString(s1,"SHA-256")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-256")); System.out.println("SHA-384:-\n" + s1 + " : " + encryptThisString(s1,"SHA-384")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-384")); System.out.println("SHA-512:- \n" + s1 + " : " + encryptThisString(s1,"SHA-512")); System.out.println("\n" + s2 + " : " + encryptThisString(s2,"SHA-512")); } }
2,406
0.633832
0.597672
68
33.382355
29.955864
84
false
false
0
0
0
0
0
0
2.132353
false
false
1
f8331263f772697ed1a8d4f9671559707e4975a1
35,270,271,443,577
700411b471a464574257a4d6b1de09fc7200f2d9
/DecisionFactory.java
7c186873e7851445f762da03d690d1cf83dc42a0
[ "MIT" ]
permissive
hdhami2/CS342_Senator
https://github.com/hdhami2/CS342_Senator
c06e64bb3d52164a1321a87247b7696fc1652e86
e53b21065c39fc19cfb8d6ba81e3fde06066e33f
refs/heads/master
2020-03-13T21:42:10.932000
2017-04-27T15:09:10
2017-04-27T15:09:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class DecisionFactory { public DecisionFactory(){ }; //only send two arguements here for now private String[] packageStrings (String...strings) { return strings; } /* * Here are the different Decisions you can make * Format is like this: * method to create decision * interface that the decision class uses */ public Decision vaccination (District d) { //2 decisions String descString = "It's flu season, and many of the people in your district are unvaccinated. Will you spend funds for a free vaccination program?"; String[] decisionDescString = packageStrings ( "Allocate $50,000 to fund the vaccination program.", "The funds will be better used elsewhere."); String[] outcomeDescString = packageStrings ( "The vaccination program is a success! There are no deaths from the flu this year.", "This season's flu is especially bad. People die. You bring shame and dishonor to your family."); return new Decision(new DVaccination(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d); } class DVaccination implements Behavior { //reduce money, change nothing else public void AcceptDecision(District d) { d.updateBudget(d.getBudget() - 50000); } //decrease population public void IgnoreDecision(District d) { d.updatePop(d.getPop() * 0.95); } } public Decision road (District d) { //2 decisions String descString = "Many of the roads in your district are out of repair, and your office has been receiving complaints from the citizenry. Will you allocate funds to repair the roads?"; String[] decisionDescString = packageStrings ( "Roads are important. Allocate $200,000 to start the repairs", "The roads are fine. At least near your house."); String[] outcomeDescString = packageStrings ( "You've allocated funds to improve the roads around town. In a few months, the town's roads will be nice and shiny, but in the meantime the citizens have to deal with increased traffic and the noise of jackhammers.", "The roads are not repaired. They continue to fall into disrepair, making the citizens unhappy. A few traffic accidents also occur."); return new Decision(new DBuildRoads(), Category.Infrastructure, descString, 2, decisionDescString, outcomeDescString, d); } class DBuildRoads implements Behavior { //reduce money //TODO reduce approval public void AcceptDecision(District d) { d.updateBudget(d.getBudget() - 200000); } //increase death rate public void IgnoreDecision(District d) { d.updateDeath(d.getDeath() + d.getPop() * 0.01); } } public Decision kill (District d) { //2 decisions String descString = "A mysterious man approaches you. He asks, 'Would you like to kill everyone in your district?' What do you say?"; String[] decisionDescString = packageStrings ( "hell ya", "hell naw"); String[] outcomeDescString = packageStrings ( "Congratulations! You've killed everyone in your district. Are you proud of yourself?", "Uh, congrats. You didn't kill your entire town."); return new Decision(new DKILL(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d); } class DKILL implements Behavior { //kill everyone public void AcceptDecision(District d) { d.updatePop(0); } //do nothing public void IgnoreDecision(District d) { } } public Decision foodInspection (District d) { //2 decisions String descString = "The food inspection department is running over budget."; String[] decisionDescString = packageStrings ( "Give them $200,000 of extra funding.", "Let them find their own sources for money."); String[] outcomeDescString = packageStrings ( "The food inspection department continues to request more money. Eventually someone notices that their balances don't add up, but no one is able to find out where the money went or who is responsible.", "The food inspection department undergoes restructuring. People are laid off, and inspections stop for the forseeable future."); return new Decision(new DFoodInspection(), Category.Commerce, descString, 2, decisionDescString, outcomeDescString, d); } class DFoodInspection implements Behavior { //Spend money //[TODO] Lower population satisfaction public void AcceptDecision(District d) { d.updateBudget(d.getBudget() - 200000); } //Increase death rate slightly //[TODO] Lower population satisfaction public void IgnoreDecision(District d) { d.updateDeath(d.getDeath() + d.getPop() * 0.001); } } public Decision schoolTalk (District d) { //2 decisions String descString = "The local high school invites you to give a presentation about your role in the government to their current students."; String[] decisionDescString = packageStrings ( "Accept. You like talking about yourself.", "Decline. They're high school students. You don't like high school students."); String[] outcomeDescString = packageStrings ( "Your speech is generally successful. The local newspaper covers the event, and your approval goes up.", "Eh, the kids probably didn't want to listen to you anyways."); return new Decision(new DSchoolTalk(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d); } class DSchoolTalk implements Behavior { //[TODO] Approval rating goes up public void AcceptDecision(District d) { } //nothing happens public void IgnoreDecision(District d) { } } public Decision merchantInvestigation (District d) { //2 decisions String descString = "You are approached by a wealthy businessman, one of the most influential in the district. 'I'm under investigation for municipal tax evasion,' he mutters, eyes darting around the room. 'Help me out, and I'll make it worth your while'."; String[] decisionDescString = packageStrings ( "Accept.", "Decline."); String[] outcomeDescString = packageStrings ( "The charges against the businessman are dropped. Everyone knows something suspicious went on, but no one has solid proof you helped. But the rumors start anyways.", "The businessman, obviously flustered by your refusal, hems and haws for a few minutes before leaving. The courts slap him with a heavy fine."); return new Decision(new DMerchantInvestigation(), Category.Personal, descString, 2, decisionDescString, outcomeDescString, d); } class DMerchantInvestigation implements Behavior { //Receive money //[TODO] Decrease approval public void AcceptDecision(District d) { d.updateBudget(d.getBudget() + 1000000); } //receive money public void IgnoreDecision(District d) { d.updateBudget(d.getBudget() + 100000); } } public Decision amazonTax (District d) { //2 decisions String descString = "Some members of your cabinet want to collect sales tax from online retailers that ship to your region."; String[] decisionDescString = packageStrings ( "Tax them. They get free shipping anyways.", "Don't tax them. You don't want to pay sales tax on that new washing machine you're buying."); String[] outcomeDescString = packageStrings ( "The tax passes. Revenue increases.", "Your washing machine arrives. Free shipping, no sales tax. How nice."); return new Decision(new DAmazonTax(), Category.Commerce, descString, 2, decisionDescString, outcomeDescString, d); } class DAmazonTax implements Behavior { //Get money //[TODO] Lower approval public void AcceptDecision(District d) { d.updateBudget(d.getBudget() + 500000); } //Nothing happens public void IgnoreDecision(District d) { } } //template /* public Decision ["NAMEOFDECISION"] (District d) { //2 decisions String descString = "[DESCRIPTION]"; String[] decisionDescString = packageStrings ( "[OPTION1]", "[OPTION2"); String[] outcomeDescString = packageStrings ( "[OUTCOME1]", "[OUTCOME2]"); return new Decision(new ["INTERFACE"](), Category.["CATEGORY"], descString, 2, decisionDescString, outcomeDescString, d); } class ["INTERFACE"] implements Behavior { //[DOCUMENTATION] public void AcceptDecision(District d) { } //[DOCUMENTATION] public void IgnoreDecision(District d) { } } */ }
UTF-8
Java
8,643
java
DecisionFactory.java
Java
[]
null
[]
public class DecisionFactory { public DecisionFactory(){ }; //only send two arguements here for now private String[] packageStrings (String...strings) { return strings; } /* * Here are the different Decisions you can make * Format is like this: * method to create decision * interface that the decision class uses */ public Decision vaccination (District d) { //2 decisions String descString = "It's flu season, and many of the people in your district are unvaccinated. Will you spend funds for a free vaccination program?"; String[] decisionDescString = packageStrings ( "Allocate $50,000 to fund the vaccination program.", "The funds will be better used elsewhere."); String[] outcomeDescString = packageStrings ( "The vaccination program is a success! There are no deaths from the flu this year.", "This season's flu is especially bad. People die. You bring shame and dishonor to your family."); return new Decision(new DVaccination(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d); } class DVaccination implements Behavior { //reduce money, change nothing else public void AcceptDecision(District d) { d.updateBudget(d.getBudget() - 50000); } //decrease population public void IgnoreDecision(District d) { d.updatePop(d.getPop() * 0.95); } } public Decision road (District d) { //2 decisions String descString = "Many of the roads in your district are out of repair, and your office has been receiving complaints from the citizenry. Will you allocate funds to repair the roads?"; String[] decisionDescString = packageStrings ( "Roads are important. Allocate $200,000 to start the repairs", "The roads are fine. At least near your house."); String[] outcomeDescString = packageStrings ( "You've allocated funds to improve the roads around town. In a few months, the town's roads will be nice and shiny, but in the meantime the citizens have to deal with increased traffic and the noise of jackhammers.", "The roads are not repaired. They continue to fall into disrepair, making the citizens unhappy. A few traffic accidents also occur."); return new Decision(new DBuildRoads(), Category.Infrastructure, descString, 2, decisionDescString, outcomeDescString, d); } class DBuildRoads implements Behavior { //reduce money //TODO reduce approval public void AcceptDecision(District d) { d.updateBudget(d.getBudget() - 200000); } //increase death rate public void IgnoreDecision(District d) { d.updateDeath(d.getDeath() + d.getPop() * 0.01); } } public Decision kill (District d) { //2 decisions String descString = "A mysterious man approaches you. He asks, 'Would you like to kill everyone in your district?' What do you say?"; String[] decisionDescString = packageStrings ( "hell ya", "hell naw"); String[] outcomeDescString = packageStrings ( "Congratulations! You've killed everyone in your district. Are you proud of yourself?", "Uh, congrats. You didn't kill your entire town."); return new Decision(new DKILL(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d); } class DKILL implements Behavior { //kill everyone public void AcceptDecision(District d) { d.updatePop(0); } //do nothing public void IgnoreDecision(District d) { } } public Decision foodInspection (District d) { //2 decisions String descString = "The food inspection department is running over budget."; String[] decisionDescString = packageStrings ( "Give them $200,000 of extra funding.", "Let them find their own sources for money."); String[] outcomeDescString = packageStrings ( "The food inspection department continues to request more money. Eventually someone notices that their balances don't add up, but no one is able to find out where the money went or who is responsible.", "The food inspection department undergoes restructuring. People are laid off, and inspections stop for the forseeable future."); return new Decision(new DFoodInspection(), Category.Commerce, descString, 2, decisionDescString, outcomeDescString, d); } class DFoodInspection implements Behavior { //Spend money //[TODO] Lower population satisfaction public void AcceptDecision(District d) { d.updateBudget(d.getBudget() - 200000); } //Increase death rate slightly //[TODO] Lower population satisfaction public void IgnoreDecision(District d) { d.updateDeath(d.getDeath() + d.getPop() * 0.001); } } public Decision schoolTalk (District d) { //2 decisions String descString = "The local high school invites you to give a presentation about your role in the government to their current students."; String[] decisionDescString = packageStrings ( "Accept. You like talking about yourself.", "Decline. They're high school students. You don't like high school students."); String[] outcomeDescString = packageStrings ( "Your speech is generally successful. The local newspaper covers the event, and your approval goes up.", "Eh, the kids probably didn't want to listen to you anyways."); return new Decision(new DSchoolTalk(), Category.Population, descString, 2, decisionDescString, outcomeDescString, d); } class DSchoolTalk implements Behavior { //[TODO] Approval rating goes up public void AcceptDecision(District d) { } //nothing happens public void IgnoreDecision(District d) { } } public Decision merchantInvestigation (District d) { //2 decisions String descString = "You are approached by a wealthy businessman, one of the most influential in the district. 'I'm under investigation for municipal tax evasion,' he mutters, eyes darting around the room. 'Help me out, and I'll make it worth your while'."; String[] decisionDescString = packageStrings ( "Accept.", "Decline."); String[] outcomeDescString = packageStrings ( "The charges against the businessman are dropped. Everyone knows something suspicious went on, but no one has solid proof you helped. But the rumors start anyways.", "The businessman, obviously flustered by your refusal, hems and haws for a few minutes before leaving. The courts slap him with a heavy fine."); return new Decision(new DMerchantInvestigation(), Category.Personal, descString, 2, decisionDescString, outcomeDescString, d); } class DMerchantInvestigation implements Behavior { //Receive money //[TODO] Decrease approval public void AcceptDecision(District d) { d.updateBudget(d.getBudget() + 1000000); } //receive money public void IgnoreDecision(District d) { d.updateBudget(d.getBudget() + 100000); } } public Decision amazonTax (District d) { //2 decisions String descString = "Some members of your cabinet want to collect sales tax from online retailers that ship to your region."; String[] decisionDescString = packageStrings ( "Tax them. They get free shipping anyways.", "Don't tax them. You don't want to pay sales tax on that new washing machine you're buying."); String[] outcomeDescString = packageStrings ( "The tax passes. Revenue increases.", "Your washing machine arrives. Free shipping, no sales tax. How nice."); return new Decision(new DAmazonTax(), Category.Commerce, descString, 2, decisionDescString, outcomeDescString, d); } class DAmazonTax implements Behavior { //Get money //[TODO] Lower approval public void AcceptDecision(District d) { d.updateBudget(d.getBudget() + 500000); } //Nothing happens public void IgnoreDecision(District d) { } } //template /* public Decision ["NAMEOFDECISION"] (District d) { //2 decisions String descString = "[DESCRIPTION]"; String[] decisionDescString = packageStrings ( "[OPTION1]", "[OPTION2"); String[] outcomeDescString = packageStrings ( "[OUTCOME1]", "[OUTCOME2]"); return new Decision(new ["INTERFACE"](), Category.["CATEGORY"], descString, 2, decisionDescString, outcomeDescString, d); } class ["INTERFACE"] implements Behavior { //[DOCUMENTATION] public void AcceptDecision(District d) { } //[DOCUMENTATION] public void IgnoreDecision(District d) { } } */ }
8,643
0.692352
0.682633
210
40.109524
44.336079
265
false
false
0
0
0
0
0
0
0.62381
false
false
1
14f95995a037ddc197215e1743e169dd0711921e
14,748,917,750,998
2168df96bc59c074d238f708e89e3f3aa2763453
/src/main/java/toor/barrettbot/environment/sniper/sniper/main/Account.java
1c1a48a65e70db524a0154497b6176029a0a4b30
[]
no_license
superusertoor/Barrett
https://github.com/superusertoor/Barrett
28e9def0d16db809c4fa3fa784db3045435521a7
cd91be9b0cc24333464d1f14c82ae013dad17da5
refs/heads/master
2023-07-29T02:26:24.471000
2021-08-31T03:12:47
2021-08-31T03:12:47
401,499,013
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package toor.barrettbot.environment.sniper.sniper.main; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.User; import toor.barrettbot.environment.sniper.sniper.exceptions.TooLessProxiesException; import toor.barrettbot.environment.sniper.sniper.sniper.Authentication; import java.net.Proxy; import java.util.List; public class Account { private String password; private String email; private String wantedName; private Authentication authentication; private Long dropTime; private List<Proxy> proxies; private boolean useProxies; private String accessToken; private User user; private TextChannel textChannel; public Account() { } public Account setAccessToken(String token) { this.accessToken = token; return this; } public TextChannel getChannel() { return textChannel; } public void setChannel(TextChannel textChannel) { this.textChannel = textChannel; } public void setDiscordUser(User user) { this.user = user; } public User getDiscordUser() { return user; } public String getAccessToken() { return accessToken; } public void executeSnipe() { new SnipeRequest(this, getAccessToken()).start(); } public String getPassword() { return password; } public Account setPassword(String password) { this.password = password; return this; } public boolean usingProxies() { return useProxies; } public void setUseProxies(boolean useProxies) { this.useProxies = useProxies; } public String getEmail() { return email; } public Account setEmail(String email) { this.email = email; return this; } public String getWantedName() { return wantedName; } public void setWantedName(String wantedName) { this.wantedName = wantedName; } public Account setAuthentication(Authentication authentication) { this.authentication = authentication; return this; } public Authentication getAuthentication() { return authentication; } public Long getDropTime() { return dropTime; } public void setDropTime(long dropTime) { this.dropTime = dropTime; } public void setProxies(List<Proxy> proxies) throws TooLessProxiesException { //if(proxies.size() == 0) { // throw new TooLessProxiesException(); //} this.proxies = proxies; } public List<Proxy> getProxies() { return proxies; } }
UTF-8
Java
2,659
java
Account.java
Java
[]
null
[]
package toor.barrettbot.environment.sniper.sniper.main; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.User; import toor.barrettbot.environment.sniper.sniper.exceptions.TooLessProxiesException; import toor.barrettbot.environment.sniper.sniper.sniper.Authentication; import java.net.Proxy; import java.util.List; public class Account { private String password; private String email; private String wantedName; private Authentication authentication; private Long dropTime; private List<Proxy> proxies; private boolean useProxies; private String accessToken; private User user; private TextChannel textChannel; public Account() { } public Account setAccessToken(String token) { this.accessToken = token; return this; } public TextChannel getChannel() { return textChannel; } public void setChannel(TextChannel textChannel) { this.textChannel = textChannel; } public void setDiscordUser(User user) { this.user = user; } public User getDiscordUser() { return user; } public String getAccessToken() { return accessToken; } public void executeSnipe() { new SnipeRequest(this, getAccessToken()).start(); } public String getPassword() { return password; } public Account setPassword(String password) { this.password = password; return this; } public boolean usingProxies() { return useProxies; } public void setUseProxies(boolean useProxies) { this.useProxies = useProxies; } public String getEmail() { return email; } public Account setEmail(String email) { this.email = email; return this; } public String getWantedName() { return wantedName; } public void setWantedName(String wantedName) { this.wantedName = wantedName; } public Account setAuthentication(Authentication authentication) { this.authentication = authentication; return this; } public Authentication getAuthentication() { return authentication; } public Long getDropTime() { return dropTime; } public void setDropTime(long dropTime) { this.dropTime = dropTime; } public void setProxies(List<Proxy> proxies) throws TooLessProxiesException { //if(proxies.size() == 0) { // throw new TooLessProxiesException(); //} this.proxies = proxies; } public List<Proxy> getProxies() { return proxies; } }
2,659
0.651749
0.650621
120
21.166666
19.880615
84
false
false
0
0
0
0
0
0
0.366667
false
false
1
7c988a27b58ec7a1c00aea63299eab1cb8ae0a02
15,951,508,600,413
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/25/25_30d71bcddb06674c7f74ed90d5bf46debdc863ed/RegisterServiceImpl/25_30d71bcddb06674c7f74ed90d5bf46debdc863ed_RegisterServiceImpl_s.java
7ea9747befc1a79efc2b0e4ac14c16eee7288a8d
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package org.openiot.scheduler.core.api.impl.RegisterService; /** * Copyright (c) 2011-2014, OpenIoT * * This library is free software; you can redistribute it and/or * modify it either under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * (the "LGPL"). If you do not alter this * notice, a recipient may use your version of this file under the LGPL. * * You should have received a copy of the LGPL along with this library * in the file COPYING-LGPL-2.1; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY * OF ANY KIND, either express or implied. See the LGPL for * the specific language governing rights and limitations. * * Contact: OpenIoT mailto: info@openiot.eu */ import java.io.InputStream; import java.util.ArrayList; import java.util.List; import lsm.beans.User; import lsm.schema.LSMSchema; import lsm.server.LSMTripleStore; import org.openiot.commons.osdspec.model.OAMO; import org.openiot.commons.osdspec.model.OSDSpec; import org.openiot.commons.osdspec.model.OSMO; import org.openiot.commons.osdspec.model.PresentationAttr; import org.openiot.commons.osdspec.model.Widget; import org.openiot.scheduler.core.utils.lsmpa.entities.Service; import org.openiot.scheduler.core.utils.lsmpa.entities.WidgetAttributes; import org.openiot.scheduler.core.utils.lsmpa.entities.WidgetAvailable; import org.openiot.scheduler.core.utils.lsmpa.entities.WidgetPresentation; import org.openiot.scheduler.core.utils.sparql.SesameSPARQLClient; import org.openrdf.query.TupleQueryResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.ontology.OntModelSpec; /** * @author Nikos Kefalakis (nkef) e-mail: nkef@ait.edu.gr * */ public class RegisterServiceImpl { private OSDSpec osdSpec; final static Logger logger = LoggerFactory.getLogger(RegisterServiceImpl.class); private String replyMessage= "unsuccessfuly"; public RegisterServiceImpl (OSDSpec osdSpec){ this.osdSpec = osdSpec; logger.debug("Recieved OSDSpec from User with userID: " + osdSpec.getUserID()); //uncoment after test // registerService(); registerServiceTestV1(); //insertUser(); } // private void registerService() // { // for (OAMO oamo: osdSpec.getOAMO()) // { // logger.debug("OAMO Description: {} ID: {}",oamo.getDescription(), oamo.getId()); // logger.debug("OAMO Name: {}",oamo.getName()); // // for (OSMO osmo : oamo.getOSMO()) // { // logger.debug("OSMO Description: {} ID: {}",osmo.getDescription(), osmo.getId()); // logger.debug("OSMO Name: {}",osmo.getName()); // // logger.debug("Query request query{}",osmo.getQueryRequest().getQuery()); // // //List<Widget> wList = osmo.getRequestPresentation().getWidget(); // for (Widget widget : osmo.getRequestPresentation().getWidget()) // { // logger.debug("widget id: {}",widget.getWidgetID()); // for (PresentationAttr pAttr : widget.getPresentationAttr()) // { // logger.debug("pAttr id: {} --- name: {}",pAttr.getName(),pAttr.getValue()); // }//PresentationAttr // }//widget // }//osmo // }//oamo // // replyMessage= "successfuly"; // } private void registerServiceTestV1() { User user = new User(); user.setUsername("spet"); user.setPass("spetlsm"); LSMTripleStore lsmStore = new LSMTripleStore(); lsmStore.setUser(user); LSMSchema myOnt = new LSMSchema (OntModelSpec.OWL_DL_MEM); LSMSchema myOntInstance = new LSMSchema(); org.openiot.scheduler.core.utils.lsmpa.entities.User schedulerUser = new org.openiot.scheduler.core.utils.lsmpa.entities.User(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); schedulerUser.setId(osdSpec.getUserID()); // // schedulerUser.createClassIdv(); for (OAMO oamo: osdSpec.getOAMO()) { logger.debug("OAMO Description: {} ID: {}",oamo.getDescription(), oamo.getId()); logger.debug("OAMO Name: {}",oamo.getName()); Service srvc = null; for (OSMO osmo : oamo.getOSMO()) { logger.debug("OSMO ID: {}",osmo.getId()); logger.debug("OSMO Name: {}",osmo.getName()); logger.debug("OSMO Description: {}",osmo.getDescription()); logger.debug("Query request query{}",osmo.getQueryRequest().getQuery()); srvc = new Service(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); srvc.setName(osmo.getName()); srvc.setDescription(osmo.getDescription()); srvc.setQueryString(osmo.getQueryRequest().getQuery()); srvc.setUser(schedulerUser); srvc.setId(osmo.getId()); // srvc.createClassIdv(); srvc.createPserviceName(); srvc.createPserviceDescription(); srvc.createPqString(); srvc.createPUser(); // schedulerUser.addService(srvc); schedulerUser.createPuserOf(); WidgetPresentation widgetPre = null; for (Widget widget : osmo.getRequestPresentation().getWidget()) { widgetPre = new WidgetPresentation(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); widgetPre.setService(srvc); // widgetPre.createClassIdv(); widgetPre.createPwidgetPresOf(); // srvc.addWidgetPresentation(widgetPre); srvc.createPwidgetPres(); logger.debug("widget available id: {}",widget.getWidgetID()); WidgetAvailable wAvail = new WidgetAvailable(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); wAvail.setId(widget.getWidgetID()); wAvail.setWidgetPre(widgetPre); /// wAvail.createClassIdv(); wAvail.createPWidgetOf(); // widgetPre.setWidgetAvailable(wAvail); widgetPre.createPwidget(); WidgetAttributes wAttr = null; for (PresentationAttr pAttr : widget.getPresentationAttr()) { logger.debug("pAttr id: {} --- name: {}",pAttr.getName(),pAttr.getValue()); wAttr = new WidgetAttributes(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); wAttr.setDescription(pAttr.getName()); wAttr.setName(pAttr.getValue()); wAttr.setWidgetPre(widgetPre); /// wAttr.createClassIdv(); wAttr.createPdesc(); wAttr.createPname(); wAttr.createPWidgetAttrOf(); // widgetPre.addWidgetAttr(wAttr); widgetPre.createPwidgetAttr(); }//PresentationAttr }//widget }//osmo }//oamo logger.debug(myOntInstance.exportToTriples("TURTLE")); boolean ok = lsmStore.pushRDF("http://lsm.deri.ie/OpenIoT/testSchema#",myOntInstance.exportToTriples("N-TRIPLE")); if(ok) { // StringBuilder listsID = new StringBuilder(); // // SesameSPARQLClient sparqlCl = new SesameSPARQLClient(); // for(int i=0; i<schedulerUser.getServiceList().size(); i++) // { // TupleQueryResult qres = sparqlCl.sparqlToQResult(Service.Queries. // selectSrvcByUserByNameByDescByQuery( // schedulerUser, // schedulerUser.getServiceList().get(i).getName(), // schedulerUser.getServiceList().get(i).getDescription(), // schedulerUser.getServiceList().get(i).getDescription())); // ArrayList<Service> sl= Service.Queries.parseService(qres); // listsID.append(sl.get(0)); // listsID.append(","); // } // // for(int i=0; i<schedulerUser.getServiceList().size(); i++) // { // replyMessage= "added:"+listsID.toString(); // } replyMessage= "regestering successfull"; } else { replyMessage= "error regestering service"; } } /** * @return String */ public String replyMessage() { return replyMessage; } }
UTF-8
Java
8,047
java
25_30d71bcddb06674c7f74ed90d5bf46debdc863ed_RegisterServiceImpl_s.java
Java
[ { "context": " and limitations.\n *\n * Contact: OpenIoT mailto: info@openiot.eu\n */\n \n \n \n \n import java.io.InputStream;\n import", "end": 900, "score": 0.9999255537986755, "start": 885, "tag": "EMAIL", "value": "info@openiot.eu" }, { "context": "l.jena.ontology.OntModelSpec;\n \n \n /**\n * @author Nikos Kefalakis (nkef) e-mail: nkef@ait.edu.gr\n *\n */\n public c", "end": 1892, "score": 0.9998816251754761, "start": 1877, "tag": "NAME", "value": "Nikos Kefalakis" }, { "context": "tModelSpec;\n \n \n /**\n * @author Nikos Kefalakis (nkef) e-mail: nkef@ait.edu.gr\n *\n */\n public class R", "end": 1898, "score": 0.9982730746269226, "start": 1894, "tag": "USERNAME", "value": "nkef" }, { "context": "\n \n /**\n * @author Nikos Kefalakis (nkef) e-mail: nkef@ait.edu.gr\n *\n */\n public class RegisterServiceImpl {\n \t\n ", "end": 1923, "score": 0.9999355673789978, "start": 1908, "tag": "EMAIL", "value": "nkef@ait.edu.gr" }, { "context": "{\n \t\tUser user = new User();\n \t\tuser.setUsername(\"spet\");\n \t\tuser.setPass(\"spetlsm\");\n \t\t\n \t\tLSMTripleSt", "end": 3564, "score": 0.9992555379867554, "start": 3560, "tag": "USERNAME", "value": "spet" }, { "context": "();\n \t\tuser.setUsername(\"spet\");\n \t\tuser.setPass(\"spetlsm\");\n \t\t\n \t\tLSMTripleStore lsmStore = new LSMTriple", "end": 3592, "score": 0.999422013759613, "start": 3585, "tag": "PASSWORD", "value": "spetlsm" } ]
null
[]
package org.openiot.scheduler.core.api.impl.RegisterService; /** * Copyright (c) 2011-2014, OpenIoT * * This library is free software; you can redistribute it and/or * modify it either under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * (the "LGPL"). If you do not alter this * notice, a recipient may use your version of this file under the LGPL. * * You should have received a copy of the LGPL along with this library * in the file COPYING-LGPL-2.1; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY * OF ANY KIND, either express or implied. See the LGPL for * the specific language governing rights and limitations. * * Contact: OpenIoT mailto: <EMAIL> */ import java.io.InputStream; import java.util.ArrayList; import java.util.List; import lsm.beans.User; import lsm.schema.LSMSchema; import lsm.server.LSMTripleStore; import org.openiot.commons.osdspec.model.OAMO; import org.openiot.commons.osdspec.model.OSDSpec; import org.openiot.commons.osdspec.model.OSMO; import org.openiot.commons.osdspec.model.PresentationAttr; import org.openiot.commons.osdspec.model.Widget; import org.openiot.scheduler.core.utils.lsmpa.entities.Service; import org.openiot.scheduler.core.utils.lsmpa.entities.WidgetAttributes; import org.openiot.scheduler.core.utils.lsmpa.entities.WidgetAvailable; import org.openiot.scheduler.core.utils.lsmpa.entities.WidgetPresentation; import org.openiot.scheduler.core.utils.sparql.SesameSPARQLClient; import org.openrdf.query.TupleQueryResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.ontology.OntModelSpec; /** * @author <NAME> (nkef) e-mail: <EMAIL> * */ public class RegisterServiceImpl { private OSDSpec osdSpec; final static Logger logger = LoggerFactory.getLogger(RegisterServiceImpl.class); private String replyMessage= "unsuccessfuly"; public RegisterServiceImpl (OSDSpec osdSpec){ this.osdSpec = osdSpec; logger.debug("Recieved OSDSpec from User with userID: " + osdSpec.getUserID()); //uncoment after test // registerService(); registerServiceTestV1(); //insertUser(); } // private void registerService() // { // for (OAMO oamo: osdSpec.getOAMO()) // { // logger.debug("OAMO Description: {} ID: {}",oamo.getDescription(), oamo.getId()); // logger.debug("OAMO Name: {}",oamo.getName()); // // for (OSMO osmo : oamo.getOSMO()) // { // logger.debug("OSMO Description: {} ID: {}",osmo.getDescription(), osmo.getId()); // logger.debug("OSMO Name: {}",osmo.getName()); // // logger.debug("Query request query{}",osmo.getQueryRequest().getQuery()); // // //List<Widget> wList = osmo.getRequestPresentation().getWidget(); // for (Widget widget : osmo.getRequestPresentation().getWidget()) // { // logger.debug("widget id: {}",widget.getWidgetID()); // for (PresentationAttr pAttr : widget.getPresentationAttr()) // { // logger.debug("pAttr id: {} --- name: {}",pAttr.getName(),pAttr.getValue()); // }//PresentationAttr // }//widget // }//osmo // }//oamo // // replyMessage= "successfuly"; // } private void registerServiceTestV1() { User user = new User(); user.setUsername("spet"); user.setPass("<PASSWORD>"); LSMTripleStore lsmStore = new LSMTripleStore(); lsmStore.setUser(user); LSMSchema myOnt = new LSMSchema (OntModelSpec.OWL_DL_MEM); LSMSchema myOntInstance = new LSMSchema(); org.openiot.scheduler.core.utils.lsmpa.entities.User schedulerUser = new org.openiot.scheduler.core.utils.lsmpa.entities.User(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); schedulerUser.setId(osdSpec.getUserID()); // // schedulerUser.createClassIdv(); for (OAMO oamo: osdSpec.getOAMO()) { logger.debug("OAMO Description: {} ID: {}",oamo.getDescription(), oamo.getId()); logger.debug("OAMO Name: {}",oamo.getName()); Service srvc = null; for (OSMO osmo : oamo.getOSMO()) { logger.debug("OSMO ID: {}",osmo.getId()); logger.debug("OSMO Name: {}",osmo.getName()); logger.debug("OSMO Description: {}",osmo.getDescription()); logger.debug("Query request query{}",osmo.getQueryRequest().getQuery()); srvc = new Service(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); srvc.setName(osmo.getName()); srvc.setDescription(osmo.getDescription()); srvc.setQueryString(osmo.getQueryRequest().getQuery()); srvc.setUser(schedulerUser); srvc.setId(osmo.getId()); // srvc.createClassIdv(); srvc.createPserviceName(); srvc.createPserviceDescription(); srvc.createPqString(); srvc.createPUser(); // schedulerUser.addService(srvc); schedulerUser.createPuserOf(); WidgetPresentation widgetPre = null; for (Widget widget : osmo.getRequestPresentation().getWidget()) { widgetPre = new WidgetPresentation(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); widgetPre.setService(srvc); // widgetPre.createClassIdv(); widgetPre.createPwidgetPresOf(); // srvc.addWidgetPresentation(widgetPre); srvc.createPwidgetPres(); logger.debug("widget available id: {}",widget.getWidgetID()); WidgetAvailable wAvail = new WidgetAvailable(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); wAvail.setId(widget.getWidgetID()); wAvail.setWidgetPre(widgetPre); /// wAvail.createClassIdv(); wAvail.createPWidgetOf(); // widgetPre.setWidgetAvailable(wAvail); widgetPre.createPwidget(); WidgetAttributes wAttr = null; for (PresentationAttr pAttr : widget.getPresentationAttr()) { logger.debug("pAttr id: {} --- name: {}",pAttr.getName(),pAttr.getValue()); wAttr = new WidgetAttributes(myOnt, myOntInstance,"http://lsm.deri.ie/OpenIoT/testSchema#",lsmStore); wAttr.setDescription(pAttr.getName()); wAttr.setName(pAttr.getValue()); wAttr.setWidgetPre(widgetPre); /// wAttr.createClassIdv(); wAttr.createPdesc(); wAttr.createPname(); wAttr.createPWidgetAttrOf(); // widgetPre.addWidgetAttr(wAttr); widgetPre.createPwidgetAttr(); }//PresentationAttr }//widget }//osmo }//oamo logger.debug(myOntInstance.exportToTriples("TURTLE")); boolean ok = lsmStore.pushRDF("http://lsm.deri.ie/OpenIoT/testSchema#",myOntInstance.exportToTriples("N-TRIPLE")); if(ok) { // StringBuilder listsID = new StringBuilder(); // // SesameSPARQLClient sparqlCl = new SesameSPARQLClient(); // for(int i=0; i<schedulerUser.getServiceList().size(); i++) // { // TupleQueryResult qres = sparqlCl.sparqlToQResult(Service.Queries. // selectSrvcByUserByNameByDescByQuery( // schedulerUser, // schedulerUser.getServiceList().get(i).getName(), // schedulerUser.getServiceList().get(i).getDescription(), // schedulerUser.getServiceList().get(i).getDescription())); // ArrayList<Service> sl= Service.Queries.parseService(qres); // listsID.append(sl.get(0)); // listsID.append(","); // } // // for(int i=0; i<schedulerUser.getServiceList().size(); i++) // { // replyMessage= "added:"+listsID.toString(); // } replyMessage= "regestering successfull"; } else { replyMessage= "error regestering service"; } } /** * @return String */ public String replyMessage() { return replyMessage; } }
8,025
0.659252
0.655151
250
31.184
29.362665
201
false
false
0
0
0
0
0
0
3.448
false
false
1
023d4b2eafd6c80ea0cac4e15be2269f583efa4c
33,895,881,917,447
ee3bf4cc93b9a887144d359df97d3ca447b5c065
/src/main/java/com/app/config/ShiroConfig.java
1cc954ce6dce67312b2153feead243e8a23479d8
[]
no_license
1992mt/appboot
https://github.com/1992mt/appboot
28cf280c3520eba9b4a177f2713562574286e465
f46d097f68cd2e1584b533a4319962a696871540
refs/heads/master
2021-08-15T18:22:15.579000
2017-11-18T03:05:35
2017-11-18T03:06:00
110,707,992
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.config; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.Filter; import org.apache.shiro.SecurityUtils; import org.apache.shiro.mgt.DefaultSessionStorageEvaluator; import org.apache.shiro.mgt.DefaultSubjectDAO; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.DefaultSessionManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.filter.authc.AnonymousFilter; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.app.common.shiro.filter.MyAuthcFilter; import com.app.common.shiro.realm.MyAuthRealm; import com.app.service.UserService; /** * shiro配置 * @author mt * */ @Configuration public class ShiroConfig { private static final Logger logger = LoggerFactory.getLogger(ShiroConfig.class); /* @Bean public EhCacheManager getEhCacheManager() { EhCacheManager em = new EhCacheManager(); em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml"); return em; } */ @Bean public MyAuthRealm myAuthRealm(){ logger.info("ShiroConfig.myAuthRealm()"); MyAuthRealm realm = new MyAuthRealm(); // realm.setCacheManager(cacheManager); return realm; } /** * 安全管理类 * @param statelessRealm * @return */ @Bean public DefaultWebSecurityManager defaultWebSecurityManager(MyAuthRealm myAuthRealm){ logger.info("ShiroConfig.getDefaultWebSecurityManager()"); DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(myAuthRealm); // <!-- 用户授权/认证信息Cache, 采用EhCache 缓存 --> // manager.setCacheManager(getEhCacheManager()); //设置了SecurityManager采用使用SecurityUtils的静态方法 获取用户等 SecurityUtils.setSecurityManager(manager); return manager; } /** * Shiro生命周期处理 * @return */ @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){ logger.info("ShiroConfig.getLifecycleBeanPostProcessor()"); return new LifecycleBeanPostProcessor(); } /** * 身份验证过滤器 * @param manager * @param tokenManager * @return */ @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager manager){ logger.info("ShiroConfig.getShiroFilterFactoryBean()"); ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(manager); Map<String,Filter> filters = new HashMap<String,Filter>(); //无需增加 shiro默认会添加该filter //filters.put("anon", anonymousFilter()); //无状态授权过滤器 //特别注意!不能声明为bean 否则shiro无法管理该filter生命周期,该过滤器会执行其他过滤器拦截过的路径 MyAuthcFilter myAuthcFilter = myAuthcFilter(); filters.put("myAuthc", myAuthcFilter); bean.setFilters(filters); //注意是LinkedHashMap 保证有序 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); //1, 相同url规则,后面定义的会覆盖前面定义的(执行的时候只执行最后一个)。 //2, 两个url规则都可以匹配同一个url,只执行第一个 filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/img/**", "anon"); filterChainDefinitionMap.put("/js/**", "anon"); filterChainDefinitionMap.put("/fonts/**", "anon"); filterChainDefinitionMap.put("/html/**", "anon"); filterChainDefinitionMap.put("/resource/**", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/login/**", "anon"); filterChainDefinitionMap.put("/favicon.ico", "anon"); filterChainDefinitionMap.put("/index**", "anon"); filterChainDefinitionMap.put("/toRegist**", "anon"); filterChainDefinitionMap.put("/header**", "anon"); filterChainDefinitionMap.put("/footer**", "anon"); filterChainDefinitionMap.put("/regist**", "anon"); filterChainDefinitionMap.put("/logout**", "anon"); filterChainDefinitionMap.put("/**", "myAuthc");//通过myAuthcFilter过滤所有路径 bean.setFilterChainDefinitionMap(filterChainDefinitionMap); //字符串方式创建过滤链 \n换行 // String s = "/resource/**=anon\n/html/**=anon\n/login/**=anon\n/login=anon\n/**=statelessAuthc"; // bean.setFilterChainDefinitions(s); return bean; } /** * @Description: 该过滤器无需增加 shiro默认会添加该filter * @author: mt */ public AnonymousFilter anonymousFilter(){ logger.info("ShiroConfig.anonymousFilter()"); return new AnonymousFilter(); } /** * @Description: 无状态授权过滤器 注意不能声明为bean 否则shiro无法管理该filter生命周期,<br> * 该过滤器会执行其他过滤器拦截过的路径 * @author: mt */ public MyAuthcFilter myAuthcFilter(){ logger.info("ShiroConfig.statelessAuthcFilter()"); MyAuthcFilter myAuthcFilter = new MyAuthcFilter(); return myAuthcFilter; } }
UTF-8
Java
6,088
java
ShiroConfig.java
Java
[ { "context": "vice.UserService;\r\n\r\n\r\n/**\r\n * shiro配置\r\n * @author mt\r\n *\r\n */\r\n@Configuration\r\npublic class ShiroConfi", "end": 1046, "score": 0.9812197089195251, "start": 1044, "tag": "USERNAME", "value": "mt" }, { "context": "iption: 该过滤器无需增加 shiro默认会添加该filter\r\n * @author: mt\r\n */\r\n public AnonymousFilter anonymousFilte", "end": 5077, "score": 0.9941269755363464, "start": 5075, "tag": "USERNAME", "value": "mt" }, { "context": "r>\r\n * \t\t\t\t 该过滤器会执行其他过滤器拦截过的路径\r\n * @author: mt\r\n */\r\n public MyAuthcFilter myAuthcFilter(){", "end": 5366, "score": 0.9931237101554871, "start": 5364, "tag": "USERNAME", "value": "mt" } ]
null
[]
package com.app.config; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.Filter; import org.apache.shiro.SecurityUtils; import org.apache.shiro.mgt.DefaultSessionStorageEvaluator; import org.apache.shiro.mgt.DefaultSubjectDAO; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.DefaultSessionManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.filter.authc.AnonymousFilter; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.app.common.shiro.filter.MyAuthcFilter; import com.app.common.shiro.realm.MyAuthRealm; import com.app.service.UserService; /** * shiro配置 * @author mt * */ @Configuration public class ShiroConfig { private static final Logger logger = LoggerFactory.getLogger(ShiroConfig.class); /* @Bean public EhCacheManager getEhCacheManager() { EhCacheManager em = new EhCacheManager(); em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml"); return em; } */ @Bean public MyAuthRealm myAuthRealm(){ logger.info("ShiroConfig.myAuthRealm()"); MyAuthRealm realm = new MyAuthRealm(); // realm.setCacheManager(cacheManager); return realm; } /** * 安全管理类 * @param statelessRealm * @return */ @Bean public DefaultWebSecurityManager defaultWebSecurityManager(MyAuthRealm myAuthRealm){ logger.info("ShiroConfig.getDefaultWebSecurityManager()"); DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(myAuthRealm); // <!-- 用户授权/认证信息Cache, 采用EhCache 缓存 --> // manager.setCacheManager(getEhCacheManager()); //设置了SecurityManager采用使用SecurityUtils的静态方法 获取用户等 SecurityUtils.setSecurityManager(manager); return manager; } /** * Shiro生命周期处理 * @return */ @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){ logger.info("ShiroConfig.getLifecycleBeanPostProcessor()"); return new LifecycleBeanPostProcessor(); } /** * 身份验证过滤器 * @param manager * @param tokenManager * @return */ @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager manager){ logger.info("ShiroConfig.getShiroFilterFactoryBean()"); ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(manager); Map<String,Filter> filters = new HashMap<String,Filter>(); //无需增加 shiro默认会添加该filter //filters.put("anon", anonymousFilter()); //无状态授权过滤器 //特别注意!不能声明为bean 否则shiro无法管理该filter生命周期,该过滤器会执行其他过滤器拦截过的路径 MyAuthcFilter myAuthcFilter = myAuthcFilter(); filters.put("myAuthc", myAuthcFilter); bean.setFilters(filters); //注意是LinkedHashMap 保证有序 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); //1, 相同url规则,后面定义的会覆盖前面定义的(执行的时候只执行最后一个)。 //2, 两个url规则都可以匹配同一个url,只执行第一个 filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/img/**", "anon"); filterChainDefinitionMap.put("/js/**", "anon"); filterChainDefinitionMap.put("/fonts/**", "anon"); filterChainDefinitionMap.put("/html/**", "anon"); filterChainDefinitionMap.put("/resource/**", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/login/**", "anon"); filterChainDefinitionMap.put("/favicon.ico", "anon"); filterChainDefinitionMap.put("/index**", "anon"); filterChainDefinitionMap.put("/toRegist**", "anon"); filterChainDefinitionMap.put("/header**", "anon"); filterChainDefinitionMap.put("/footer**", "anon"); filterChainDefinitionMap.put("/regist**", "anon"); filterChainDefinitionMap.put("/logout**", "anon"); filterChainDefinitionMap.put("/**", "myAuthc");//通过myAuthcFilter过滤所有路径 bean.setFilterChainDefinitionMap(filterChainDefinitionMap); //字符串方式创建过滤链 \n换行 // String s = "/resource/**=anon\n/html/**=anon\n/login/**=anon\n/login=anon\n/**=statelessAuthc"; // bean.setFilterChainDefinitions(s); return bean; } /** * @Description: 该过滤器无需增加 shiro默认会添加该filter * @author: mt */ public AnonymousFilter anonymousFilter(){ logger.info("ShiroConfig.anonymousFilter()"); return new AnonymousFilter(); } /** * @Description: 无状态授权过滤器 注意不能声明为bean 否则shiro无法管理该filter生命周期,<br> * 该过滤器会执行其他过滤器拦截过的路径 * @author: mt */ public MyAuthcFilter myAuthcFilter(){ logger.info("ShiroConfig.statelessAuthcFilter()"); MyAuthcFilter myAuthcFilter = new MyAuthcFilter(); return myAuthcFilter; } }
6,088
0.635405
0.634691
157
33.656052
25.361015
105
false
false
0
0
0
0
0
0
0.630573
false
false
1
09434e959df400dee74b8a44b104a5a7a85e490b
35,923,106,485,125
e9affefd4e89b3c7e2064fee8833d7838c0e0abc
/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/GetDataQualityRuleRecommendationRunResult.java
2d8dd02f9fcf51c99d03827d439b5912f6006b34
[ "Apache-2.0" ]
permissive
aws/aws-sdk-java
https://github.com/aws/aws-sdk-java
2c6199b12b47345b5d3c50e425dabba56e279190
bab987ab604575f41a76864f755f49386e3264b4
refs/heads/master
2023-08-29T10:49:07.379000
2023-08-28T21:05:55
2023-08-28T21:05:55
574,877
3,695
3,092
Apache-2.0
false
2023-09-13T23:35:28
2010-03-22T23:34:58
2023-09-13T22:30:40
2023-09-13T21:56:58
4,866,710
3,998
2,861
114
null
false
false
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.glue.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/GetDataQualityRuleRecommendationRun" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetDataQualityRuleRecommendationRunResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The unique run identifier associated with this run. * </p> */ private String runId; /** * <p> * The data source (an Glue table) associated with this run. * </p> */ private DataSource dataSource; /** * <p> * An IAM role supplied to encrypt the results of the run. * </p> */ private String role; /** * <p> * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * </p> */ private Integer numberOfWorkers; /** * <p> * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * </p> */ private Integer timeout; /** * <p> * The status for this run. * </p> */ private String status; /** * <p> * The error strings that are associated with the run. * </p> */ private String errorString; /** * <p> * The date and time when this run started. * </p> */ private java.util.Date startedOn; /** * <p> * A timestamp. The last point in time when this data quality rule recommendation run was modified. * </p> */ private java.util.Date lastModifiedOn; /** * <p> * The date and time when this run was completed. * </p> */ private java.util.Date completedOn; /** * <p> * The amount of time (in seconds) that the run consumed resources. * </p> */ private Integer executionTime; /** * <p> * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This member * has those rules in Data Quality Definition Language (DQDL) format. * </p> */ private String recommendedRuleset; /** * <p> * The name of the ruleset that was created by the run. * </p> */ private String createdRulesetName; /** * <p> * The unique run identifier associated with this run. * </p> * * @param runId * The unique run identifier associated with this run. */ public void setRunId(String runId) { this.runId = runId; } /** * <p> * The unique run identifier associated with this run. * </p> * * @return The unique run identifier associated with this run. */ public String getRunId() { return this.runId; } /** * <p> * The unique run identifier associated with this run. * </p> * * @param runId * The unique run identifier associated with this run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withRunId(String runId) { setRunId(runId); return this; } /** * <p> * The data source (an Glue table) associated with this run. * </p> * * @param dataSource * The data source (an Glue table) associated with this run. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * <p> * The data source (an Glue table) associated with this run. * </p> * * @return The data source (an Glue table) associated with this run. */ public DataSource getDataSource() { return this.dataSource; } /** * <p> * The data source (an Glue table) associated with this run. * </p> * * @param dataSource * The data source (an Glue table) associated with this run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withDataSource(DataSource dataSource) { setDataSource(dataSource); return this; } /** * <p> * An IAM role supplied to encrypt the results of the run. * </p> * * @param role * An IAM role supplied to encrypt the results of the run. */ public void setRole(String role) { this.role = role; } /** * <p> * An IAM role supplied to encrypt the results of the run. * </p> * * @return An IAM role supplied to encrypt the results of the run. */ public String getRole() { return this.role; } /** * <p> * An IAM role supplied to encrypt the results of the run. * </p> * * @param role * An IAM role supplied to encrypt the results of the run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withRole(String role) { setRole(role); return this; } /** * <p> * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * </p> * * @param numberOfWorkers * The number of <code>G.1X</code> workers to be used in the run. The default is 5. */ public void setNumberOfWorkers(Integer numberOfWorkers) { this.numberOfWorkers = numberOfWorkers; } /** * <p> * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * </p> * * @return The number of <code>G.1X</code> workers to be used in the run. The default is 5. */ public Integer getNumberOfWorkers() { return this.numberOfWorkers; } /** * <p> * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * </p> * * @param numberOfWorkers * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withNumberOfWorkers(Integer numberOfWorkers) { setNumberOfWorkers(numberOfWorkers); return this; } /** * <p> * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * </p> * * @param timeout * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). */ public void setTimeout(Integer timeout) { this.timeout = timeout; } /** * <p> * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * </p> * * @return The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). */ public Integer getTimeout() { return this.timeout; } /** * <p> * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * </p> * * @param timeout * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withTimeout(Integer timeout) { setTimeout(timeout); return this; } /** * <p> * The status for this run. * </p> * * @param status * The status for this run. * @see TaskStatusType */ public void setStatus(String status) { this.status = status; } /** * <p> * The status for this run. * </p> * * @return The status for this run. * @see TaskStatusType */ public String getStatus() { return this.status; } /** * <p> * The status for this run. * </p> * * @param status * The status for this run. * @return Returns a reference to this object so that method calls can be chained together. * @see TaskStatusType */ public GetDataQualityRuleRecommendationRunResult withStatus(String status) { setStatus(status); return this; } /** * <p> * The status for this run. * </p> * * @param status * The status for this run. * @return Returns a reference to this object so that method calls can be chained together. * @see TaskStatusType */ public GetDataQualityRuleRecommendationRunResult withStatus(TaskStatusType status) { this.status = status.toString(); return this; } /** * <p> * The error strings that are associated with the run. * </p> * * @param errorString * The error strings that are associated with the run. */ public void setErrorString(String errorString) { this.errorString = errorString; } /** * <p> * The error strings that are associated with the run. * </p> * * @return The error strings that are associated with the run. */ public String getErrorString() { return this.errorString; } /** * <p> * The error strings that are associated with the run. * </p> * * @param errorString * The error strings that are associated with the run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withErrorString(String errorString) { setErrorString(errorString); return this; } /** * <p> * The date and time when this run started. * </p> * * @param startedOn * The date and time when this run started. */ public void setStartedOn(java.util.Date startedOn) { this.startedOn = startedOn; } /** * <p> * The date and time when this run started. * </p> * * @return The date and time when this run started. */ public java.util.Date getStartedOn() { return this.startedOn; } /** * <p> * The date and time when this run started. * </p> * * @param startedOn * The date and time when this run started. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withStartedOn(java.util.Date startedOn) { setStartedOn(startedOn); return this; } /** * <p> * A timestamp. The last point in time when this data quality rule recommendation run was modified. * </p> * * @param lastModifiedOn * A timestamp. The last point in time when this data quality rule recommendation run was modified. */ public void setLastModifiedOn(java.util.Date lastModifiedOn) { this.lastModifiedOn = lastModifiedOn; } /** * <p> * A timestamp. The last point in time when this data quality rule recommendation run was modified. * </p> * * @return A timestamp. The last point in time when this data quality rule recommendation run was modified. */ public java.util.Date getLastModifiedOn() { return this.lastModifiedOn; } /** * <p> * A timestamp. The last point in time when this data quality rule recommendation run was modified. * </p> * * @param lastModifiedOn * A timestamp. The last point in time when this data quality rule recommendation run was modified. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withLastModifiedOn(java.util.Date lastModifiedOn) { setLastModifiedOn(lastModifiedOn); return this; } /** * <p> * The date and time when this run was completed. * </p> * * @param completedOn * The date and time when this run was completed. */ public void setCompletedOn(java.util.Date completedOn) { this.completedOn = completedOn; } /** * <p> * The date and time when this run was completed. * </p> * * @return The date and time when this run was completed. */ public java.util.Date getCompletedOn() { return this.completedOn; } /** * <p> * The date and time when this run was completed. * </p> * * @param completedOn * The date and time when this run was completed. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withCompletedOn(java.util.Date completedOn) { setCompletedOn(completedOn); return this; } /** * <p> * The amount of time (in seconds) that the run consumed resources. * </p> * * @param executionTime * The amount of time (in seconds) that the run consumed resources. */ public void setExecutionTime(Integer executionTime) { this.executionTime = executionTime; } /** * <p> * The amount of time (in seconds) that the run consumed resources. * </p> * * @return The amount of time (in seconds) that the run consumed resources. */ public Integer getExecutionTime() { return this.executionTime; } /** * <p> * The amount of time (in seconds) that the run consumed resources. * </p> * * @param executionTime * The amount of time (in seconds) that the run consumed resources. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withExecutionTime(Integer executionTime) { setExecutionTime(executionTime); return this; } /** * <p> * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This member * has those rules in Data Quality Definition Language (DQDL) format. * </p> * * @param recommendedRuleset * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This * member has those rules in Data Quality Definition Language (DQDL) format. */ public void setRecommendedRuleset(String recommendedRuleset) { this.recommendedRuleset = recommendedRuleset; } /** * <p> * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This member * has those rules in Data Quality Definition Language (DQDL) format. * </p> * * @return When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This * member has those rules in Data Quality Definition Language (DQDL) format. */ public String getRecommendedRuleset() { return this.recommendedRuleset; } /** * <p> * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This member * has those rules in Data Quality Definition Language (DQDL) format. * </p> * * @param recommendedRuleset * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This * member has those rules in Data Quality Definition Language (DQDL) format. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withRecommendedRuleset(String recommendedRuleset) { setRecommendedRuleset(recommendedRuleset); return this; } /** * <p> * The name of the ruleset that was created by the run. * </p> * * @param createdRulesetName * The name of the ruleset that was created by the run. */ public void setCreatedRulesetName(String createdRulesetName) { this.createdRulesetName = createdRulesetName; } /** * <p> * The name of the ruleset that was created by the run. * </p> * * @return The name of the ruleset that was created by the run. */ public String getCreatedRulesetName() { return this.createdRulesetName; } /** * <p> * The name of the ruleset that was created by the run. * </p> * * @param createdRulesetName * The name of the ruleset that was created by the run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withCreatedRulesetName(String createdRulesetName) { setCreatedRulesetName(createdRulesetName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRunId() != null) sb.append("RunId: ").append(getRunId()).append(","); if (getDataSource() != null) sb.append("DataSource: ").append(getDataSource()).append(","); if (getRole() != null) sb.append("Role: ").append(getRole()).append(","); if (getNumberOfWorkers() != null) sb.append("NumberOfWorkers: ").append(getNumberOfWorkers()).append(","); if (getTimeout() != null) sb.append("Timeout: ").append(getTimeout()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getErrorString() != null) sb.append("ErrorString: ").append(getErrorString()).append(","); if (getStartedOn() != null) sb.append("StartedOn: ").append(getStartedOn()).append(","); if (getLastModifiedOn() != null) sb.append("LastModifiedOn: ").append(getLastModifiedOn()).append(","); if (getCompletedOn() != null) sb.append("CompletedOn: ").append(getCompletedOn()).append(","); if (getExecutionTime() != null) sb.append("ExecutionTime: ").append(getExecutionTime()).append(","); if (getRecommendedRuleset() != null) sb.append("RecommendedRuleset: ").append(getRecommendedRuleset()).append(","); if (getCreatedRulesetName() != null) sb.append("CreatedRulesetName: ").append(getCreatedRulesetName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetDataQualityRuleRecommendationRunResult == false) return false; GetDataQualityRuleRecommendationRunResult other = (GetDataQualityRuleRecommendationRunResult) obj; if (other.getRunId() == null ^ this.getRunId() == null) return false; if (other.getRunId() != null && other.getRunId().equals(this.getRunId()) == false) return false; if (other.getDataSource() == null ^ this.getDataSource() == null) return false; if (other.getDataSource() != null && other.getDataSource().equals(this.getDataSource()) == false) return false; if (other.getRole() == null ^ this.getRole() == null) return false; if (other.getRole() != null && other.getRole().equals(this.getRole()) == false) return false; if (other.getNumberOfWorkers() == null ^ this.getNumberOfWorkers() == null) return false; if (other.getNumberOfWorkers() != null && other.getNumberOfWorkers().equals(this.getNumberOfWorkers()) == false) return false; if (other.getTimeout() == null ^ this.getTimeout() == null) return false; if (other.getTimeout() != null && other.getTimeout().equals(this.getTimeout()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getErrorString() == null ^ this.getErrorString() == null) return false; if (other.getErrorString() != null && other.getErrorString().equals(this.getErrorString()) == false) return false; if (other.getStartedOn() == null ^ this.getStartedOn() == null) return false; if (other.getStartedOn() != null && other.getStartedOn().equals(this.getStartedOn()) == false) return false; if (other.getLastModifiedOn() == null ^ this.getLastModifiedOn() == null) return false; if (other.getLastModifiedOn() != null && other.getLastModifiedOn().equals(this.getLastModifiedOn()) == false) return false; if (other.getCompletedOn() == null ^ this.getCompletedOn() == null) return false; if (other.getCompletedOn() != null && other.getCompletedOn().equals(this.getCompletedOn()) == false) return false; if (other.getExecutionTime() == null ^ this.getExecutionTime() == null) return false; if (other.getExecutionTime() != null && other.getExecutionTime().equals(this.getExecutionTime()) == false) return false; if (other.getRecommendedRuleset() == null ^ this.getRecommendedRuleset() == null) return false; if (other.getRecommendedRuleset() != null && other.getRecommendedRuleset().equals(this.getRecommendedRuleset()) == false) return false; if (other.getCreatedRulesetName() == null ^ this.getCreatedRulesetName() == null) return false; if (other.getCreatedRulesetName() != null && other.getCreatedRulesetName().equals(this.getCreatedRulesetName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRunId() == null) ? 0 : getRunId().hashCode()); hashCode = prime * hashCode + ((getDataSource() == null) ? 0 : getDataSource().hashCode()); hashCode = prime * hashCode + ((getRole() == null) ? 0 : getRole().hashCode()); hashCode = prime * hashCode + ((getNumberOfWorkers() == null) ? 0 : getNumberOfWorkers().hashCode()); hashCode = prime * hashCode + ((getTimeout() == null) ? 0 : getTimeout().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getErrorString() == null) ? 0 : getErrorString().hashCode()); hashCode = prime * hashCode + ((getStartedOn() == null) ? 0 : getStartedOn().hashCode()); hashCode = prime * hashCode + ((getLastModifiedOn() == null) ? 0 : getLastModifiedOn().hashCode()); hashCode = prime * hashCode + ((getCompletedOn() == null) ? 0 : getCompletedOn().hashCode()); hashCode = prime * hashCode + ((getExecutionTime() == null) ? 0 : getExecutionTime().hashCode()); hashCode = prime * hashCode + ((getRecommendedRuleset() == null) ? 0 : getRecommendedRuleset().hashCode()); hashCode = prime * hashCode + ((getCreatedRulesetName() == null) ? 0 : getCreatedRulesetName().hashCode()); return hashCode; } @Override public GetDataQualityRuleRecommendationRunResult clone() { try { return (GetDataQualityRuleRecommendationRunResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
UTF-8
Java
26,076
java
GetDataQualityRuleRecommendationRunResult.java
Java
[]
null
[]
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.glue.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/GetDataQualityRuleRecommendationRun" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetDataQualityRuleRecommendationRunResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The unique run identifier associated with this run. * </p> */ private String runId; /** * <p> * The data source (an Glue table) associated with this run. * </p> */ private DataSource dataSource; /** * <p> * An IAM role supplied to encrypt the results of the run. * </p> */ private String role; /** * <p> * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * </p> */ private Integer numberOfWorkers; /** * <p> * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * </p> */ private Integer timeout; /** * <p> * The status for this run. * </p> */ private String status; /** * <p> * The error strings that are associated with the run. * </p> */ private String errorString; /** * <p> * The date and time when this run started. * </p> */ private java.util.Date startedOn; /** * <p> * A timestamp. The last point in time when this data quality rule recommendation run was modified. * </p> */ private java.util.Date lastModifiedOn; /** * <p> * The date and time when this run was completed. * </p> */ private java.util.Date completedOn; /** * <p> * The amount of time (in seconds) that the run consumed resources. * </p> */ private Integer executionTime; /** * <p> * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This member * has those rules in Data Quality Definition Language (DQDL) format. * </p> */ private String recommendedRuleset; /** * <p> * The name of the ruleset that was created by the run. * </p> */ private String createdRulesetName; /** * <p> * The unique run identifier associated with this run. * </p> * * @param runId * The unique run identifier associated with this run. */ public void setRunId(String runId) { this.runId = runId; } /** * <p> * The unique run identifier associated with this run. * </p> * * @return The unique run identifier associated with this run. */ public String getRunId() { return this.runId; } /** * <p> * The unique run identifier associated with this run. * </p> * * @param runId * The unique run identifier associated with this run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withRunId(String runId) { setRunId(runId); return this; } /** * <p> * The data source (an Glue table) associated with this run. * </p> * * @param dataSource * The data source (an Glue table) associated with this run. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * <p> * The data source (an Glue table) associated with this run. * </p> * * @return The data source (an Glue table) associated with this run. */ public DataSource getDataSource() { return this.dataSource; } /** * <p> * The data source (an Glue table) associated with this run. * </p> * * @param dataSource * The data source (an Glue table) associated with this run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withDataSource(DataSource dataSource) { setDataSource(dataSource); return this; } /** * <p> * An IAM role supplied to encrypt the results of the run. * </p> * * @param role * An IAM role supplied to encrypt the results of the run. */ public void setRole(String role) { this.role = role; } /** * <p> * An IAM role supplied to encrypt the results of the run. * </p> * * @return An IAM role supplied to encrypt the results of the run. */ public String getRole() { return this.role; } /** * <p> * An IAM role supplied to encrypt the results of the run. * </p> * * @param role * An IAM role supplied to encrypt the results of the run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withRole(String role) { setRole(role); return this; } /** * <p> * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * </p> * * @param numberOfWorkers * The number of <code>G.1X</code> workers to be used in the run. The default is 5. */ public void setNumberOfWorkers(Integer numberOfWorkers) { this.numberOfWorkers = numberOfWorkers; } /** * <p> * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * </p> * * @return The number of <code>G.1X</code> workers to be used in the run. The default is 5. */ public Integer getNumberOfWorkers() { return this.numberOfWorkers; } /** * <p> * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * </p> * * @param numberOfWorkers * The number of <code>G.1X</code> workers to be used in the run. The default is 5. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withNumberOfWorkers(Integer numberOfWorkers) { setNumberOfWorkers(numberOfWorkers); return this; } /** * <p> * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * </p> * * @param timeout * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). */ public void setTimeout(Integer timeout) { this.timeout = timeout; } /** * <p> * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * </p> * * @return The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). */ public Integer getTimeout() { return this.timeout; } /** * <p> * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * </p> * * @param timeout * The timeout for a run in minutes. This is the maximum time that a run can consume resources before it is * terminated and enters <code>TIMEOUT</code> status. The default is 2,880 minutes (48 hours). * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withTimeout(Integer timeout) { setTimeout(timeout); return this; } /** * <p> * The status for this run. * </p> * * @param status * The status for this run. * @see TaskStatusType */ public void setStatus(String status) { this.status = status; } /** * <p> * The status for this run. * </p> * * @return The status for this run. * @see TaskStatusType */ public String getStatus() { return this.status; } /** * <p> * The status for this run. * </p> * * @param status * The status for this run. * @return Returns a reference to this object so that method calls can be chained together. * @see TaskStatusType */ public GetDataQualityRuleRecommendationRunResult withStatus(String status) { setStatus(status); return this; } /** * <p> * The status for this run. * </p> * * @param status * The status for this run. * @return Returns a reference to this object so that method calls can be chained together. * @see TaskStatusType */ public GetDataQualityRuleRecommendationRunResult withStatus(TaskStatusType status) { this.status = status.toString(); return this; } /** * <p> * The error strings that are associated with the run. * </p> * * @param errorString * The error strings that are associated with the run. */ public void setErrorString(String errorString) { this.errorString = errorString; } /** * <p> * The error strings that are associated with the run. * </p> * * @return The error strings that are associated with the run. */ public String getErrorString() { return this.errorString; } /** * <p> * The error strings that are associated with the run. * </p> * * @param errorString * The error strings that are associated with the run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withErrorString(String errorString) { setErrorString(errorString); return this; } /** * <p> * The date and time when this run started. * </p> * * @param startedOn * The date and time when this run started. */ public void setStartedOn(java.util.Date startedOn) { this.startedOn = startedOn; } /** * <p> * The date and time when this run started. * </p> * * @return The date and time when this run started. */ public java.util.Date getStartedOn() { return this.startedOn; } /** * <p> * The date and time when this run started. * </p> * * @param startedOn * The date and time when this run started. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withStartedOn(java.util.Date startedOn) { setStartedOn(startedOn); return this; } /** * <p> * A timestamp. The last point in time when this data quality rule recommendation run was modified. * </p> * * @param lastModifiedOn * A timestamp. The last point in time when this data quality rule recommendation run was modified. */ public void setLastModifiedOn(java.util.Date lastModifiedOn) { this.lastModifiedOn = lastModifiedOn; } /** * <p> * A timestamp. The last point in time when this data quality rule recommendation run was modified. * </p> * * @return A timestamp. The last point in time when this data quality rule recommendation run was modified. */ public java.util.Date getLastModifiedOn() { return this.lastModifiedOn; } /** * <p> * A timestamp. The last point in time when this data quality rule recommendation run was modified. * </p> * * @param lastModifiedOn * A timestamp. The last point in time when this data quality rule recommendation run was modified. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withLastModifiedOn(java.util.Date lastModifiedOn) { setLastModifiedOn(lastModifiedOn); return this; } /** * <p> * The date and time when this run was completed. * </p> * * @param completedOn * The date and time when this run was completed. */ public void setCompletedOn(java.util.Date completedOn) { this.completedOn = completedOn; } /** * <p> * The date and time when this run was completed. * </p> * * @return The date and time when this run was completed. */ public java.util.Date getCompletedOn() { return this.completedOn; } /** * <p> * The date and time when this run was completed. * </p> * * @param completedOn * The date and time when this run was completed. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withCompletedOn(java.util.Date completedOn) { setCompletedOn(completedOn); return this; } /** * <p> * The amount of time (in seconds) that the run consumed resources. * </p> * * @param executionTime * The amount of time (in seconds) that the run consumed resources. */ public void setExecutionTime(Integer executionTime) { this.executionTime = executionTime; } /** * <p> * The amount of time (in seconds) that the run consumed resources. * </p> * * @return The amount of time (in seconds) that the run consumed resources. */ public Integer getExecutionTime() { return this.executionTime; } /** * <p> * The amount of time (in seconds) that the run consumed resources. * </p> * * @param executionTime * The amount of time (in seconds) that the run consumed resources. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withExecutionTime(Integer executionTime) { setExecutionTime(executionTime); return this; } /** * <p> * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This member * has those rules in Data Quality Definition Language (DQDL) format. * </p> * * @param recommendedRuleset * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This * member has those rules in Data Quality Definition Language (DQDL) format. */ public void setRecommendedRuleset(String recommendedRuleset) { this.recommendedRuleset = recommendedRuleset; } /** * <p> * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This member * has those rules in Data Quality Definition Language (DQDL) format. * </p> * * @return When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This * member has those rules in Data Quality Definition Language (DQDL) format. */ public String getRecommendedRuleset() { return this.recommendedRuleset; } /** * <p> * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This member * has those rules in Data Quality Definition Language (DQDL) format. * </p> * * @param recommendedRuleset * When a start rule recommendation run completes, it creates a recommended ruleset (a set of rules). This * member has those rules in Data Quality Definition Language (DQDL) format. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withRecommendedRuleset(String recommendedRuleset) { setRecommendedRuleset(recommendedRuleset); return this; } /** * <p> * The name of the ruleset that was created by the run. * </p> * * @param createdRulesetName * The name of the ruleset that was created by the run. */ public void setCreatedRulesetName(String createdRulesetName) { this.createdRulesetName = createdRulesetName; } /** * <p> * The name of the ruleset that was created by the run. * </p> * * @return The name of the ruleset that was created by the run. */ public String getCreatedRulesetName() { return this.createdRulesetName; } /** * <p> * The name of the ruleset that was created by the run. * </p> * * @param createdRulesetName * The name of the ruleset that was created by the run. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDataQualityRuleRecommendationRunResult withCreatedRulesetName(String createdRulesetName) { setCreatedRulesetName(createdRulesetName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRunId() != null) sb.append("RunId: ").append(getRunId()).append(","); if (getDataSource() != null) sb.append("DataSource: ").append(getDataSource()).append(","); if (getRole() != null) sb.append("Role: ").append(getRole()).append(","); if (getNumberOfWorkers() != null) sb.append("NumberOfWorkers: ").append(getNumberOfWorkers()).append(","); if (getTimeout() != null) sb.append("Timeout: ").append(getTimeout()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getErrorString() != null) sb.append("ErrorString: ").append(getErrorString()).append(","); if (getStartedOn() != null) sb.append("StartedOn: ").append(getStartedOn()).append(","); if (getLastModifiedOn() != null) sb.append("LastModifiedOn: ").append(getLastModifiedOn()).append(","); if (getCompletedOn() != null) sb.append("CompletedOn: ").append(getCompletedOn()).append(","); if (getExecutionTime() != null) sb.append("ExecutionTime: ").append(getExecutionTime()).append(","); if (getRecommendedRuleset() != null) sb.append("RecommendedRuleset: ").append(getRecommendedRuleset()).append(","); if (getCreatedRulesetName() != null) sb.append("CreatedRulesetName: ").append(getCreatedRulesetName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetDataQualityRuleRecommendationRunResult == false) return false; GetDataQualityRuleRecommendationRunResult other = (GetDataQualityRuleRecommendationRunResult) obj; if (other.getRunId() == null ^ this.getRunId() == null) return false; if (other.getRunId() != null && other.getRunId().equals(this.getRunId()) == false) return false; if (other.getDataSource() == null ^ this.getDataSource() == null) return false; if (other.getDataSource() != null && other.getDataSource().equals(this.getDataSource()) == false) return false; if (other.getRole() == null ^ this.getRole() == null) return false; if (other.getRole() != null && other.getRole().equals(this.getRole()) == false) return false; if (other.getNumberOfWorkers() == null ^ this.getNumberOfWorkers() == null) return false; if (other.getNumberOfWorkers() != null && other.getNumberOfWorkers().equals(this.getNumberOfWorkers()) == false) return false; if (other.getTimeout() == null ^ this.getTimeout() == null) return false; if (other.getTimeout() != null && other.getTimeout().equals(this.getTimeout()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getErrorString() == null ^ this.getErrorString() == null) return false; if (other.getErrorString() != null && other.getErrorString().equals(this.getErrorString()) == false) return false; if (other.getStartedOn() == null ^ this.getStartedOn() == null) return false; if (other.getStartedOn() != null && other.getStartedOn().equals(this.getStartedOn()) == false) return false; if (other.getLastModifiedOn() == null ^ this.getLastModifiedOn() == null) return false; if (other.getLastModifiedOn() != null && other.getLastModifiedOn().equals(this.getLastModifiedOn()) == false) return false; if (other.getCompletedOn() == null ^ this.getCompletedOn() == null) return false; if (other.getCompletedOn() != null && other.getCompletedOn().equals(this.getCompletedOn()) == false) return false; if (other.getExecutionTime() == null ^ this.getExecutionTime() == null) return false; if (other.getExecutionTime() != null && other.getExecutionTime().equals(this.getExecutionTime()) == false) return false; if (other.getRecommendedRuleset() == null ^ this.getRecommendedRuleset() == null) return false; if (other.getRecommendedRuleset() != null && other.getRecommendedRuleset().equals(this.getRecommendedRuleset()) == false) return false; if (other.getCreatedRulesetName() == null ^ this.getCreatedRulesetName() == null) return false; if (other.getCreatedRulesetName() != null && other.getCreatedRulesetName().equals(this.getCreatedRulesetName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRunId() == null) ? 0 : getRunId().hashCode()); hashCode = prime * hashCode + ((getDataSource() == null) ? 0 : getDataSource().hashCode()); hashCode = prime * hashCode + ((getRole() == null) ? 0 : getRole().hashCode()); hashCode = prime * hashCode + ((getNumberOfWorkers() == null) ? 0 : getNumberOfWorkers().hashCode()); hashCode = prime * hashCode + ((getTimeout() == null) ? 0 : getTimeout().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getErrorString() == null) ? 0 : getErrorString().hashCode()); hashCode = prime * hashCode + ((getStartedOn() == null) ? 0 : getStartedOn().hashCode()); hashCode = prime * hashCode + ((getLastModifiedOn() == null) ? 0 : getLastModifiedOn().hashCode()); hashCode = prime * hashCode + ((getCompletedOn() == null) ? 0 : getCompletedOn().hashCode()); hashCode = prime * hashCode + ((getExecutionTime() == null) ? 0 : getExecutionTime().hashCode()); hashCode = prime * hashCode + ((getRecommendedRuleset() == null) ? 0 : getRecommendedRuleset().hashCode()); hashCode = prime * hashCode + ((getCreatedRulesetName() == null) ? 0 : getCreatedRulesetName().hashCode()); return hashCode; } @Override public GetDataQualityRuleRecommendationRunResult clone() { try { return (GetDataQualityRuleRecommendationRunResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
26,076
0.607839
0.60431
796
31.758795
34.236645
156
false
false
0
0
0
0
0
0
0.211055
false
false
1
ea9f1237cb8d0cd83d23368a56a704f0e442bbfc
9,594,956,999,501
69f78dfb40bcb50d413020fcda9cbea3f51d1c31
/src/main/java/com/java1234/dao/ProductDao.java
b345c037cc89fd3d41abc2e0f900f0b272b45faa
[]
no_license
denggege123/TestBuy
https://github.com/denggege123/TestBuy
b587e53e64b61e649e17a11e6cc6ea2d3e252031
8534a54198c618aeade0eb07acea5ed3c405414e
refs/heads/master
2020-03-19T12:53:01.427000
2018-06-22T10:02:04
2018-06-22T10:02:04
136,547,143
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.java1234.dao; import java.util.List; import java.util.Map; import com.java1234.entity.News; import com.java1234.entity.Product; import com.java1234.entity.ProductSmallType; import com.java1234.entity.Tag; public interface ProductDao { public List<Product> findProductList(Map<String,Object> map); public Long getProductCountById(Map<String,Object> map); public List<Product> findProductListById(Map<String,Object> map); public Long getProductCountByBigType(String bigTypeId); public List<Tag> findTagList(String bigTypeId); public List<ProductSmallType> findSmallTypeLByBigTypeID(Map<String, Object> map); public Long getProductCountBySmallType(String smallTypeId); public Product getProductById(String productId); }
UTF-8
Java
781
java
ProductDao.java
Java
[]
null
[]
package com.java1234.dao; import java.util.List; import java.util.Map; import com.java1234.entity.News; import com.java1234.entity.Product; import com.java1234.entity.ProductSmallType; import com.java1234.entity.Tag; public interface ProductDao { public List<Product> findProductList(Map<String,Object> map); public Long getProductCountById(Map<String,Object> map); public List<Product> findProductListById(Map<String,Object> map); public Long getProductCountByBigType(String bigTypeId); public List<Tag> findTagList(String bigTypeId); public List<ProductSmallType> findSmallTypeLByBigTypeID(Map<String, Object> map); public Long getProductCountBySmallType(String smallTypeId); public Product getProductById(String productId); }
781
0.775928
0.75032
28
25.892857
25.715948
82
false
false
0
0
0
0
0
0
1.142857
false
false
1
80dbefc4eff2a1c11a6ae2c4c952274cd209e0bd
36,661,840,861,113
084021e2fee3710e7daccd7fec03f3e14e504907
/src/main/java/com/wsh/SpringBootMybatisApplication.java
46e481b32e3e936954e961e05f4ba4645f773cd6
[]
no_license
cckmit/springBoot-mybatis
https://github.com/cckmit/springBoot-mybatis
eeac6159d88d307d811e789b545e751302f9d921
5625b9937346c54b0198d72dedbca77de9988f24
refs/heads/master
2023-03-16T13:41:10.708000
2019-04-26T10:45:29
2019-04-26T10:45:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wsh; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.EnableTransactionManagement; import springfox.documentation.swagger2.annotations.EnableSwagger2; // Swagger2访问 http://localhost/swagger-ui.html @SpringBootApplication @MapperScan("com.wsh.zero.mapper") //扫描位置要清楚,shiro swagger2没神效都是因为扫描位置配置范围错误引起 @ComponentScan({"com.wsh.zero.controller", "com.wsh.zero.service", "com.wsh.config", "com.wsh.util"}) @EnableTransactionManagement//事务管理 @EnableSwagger2 public class SpringBootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMybatisApplication.class, args); } }
UTF-8
Java
935
java
SpringBootMybatisApplication.java
Java
[]
null
[]
package com.wsh; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.transaction.annotation.EnableTransactionManagement; import springfox.documentation.swagger2.annotations.EnableSwagger2; // Swagger2访问 http://localhost/swagger-ui.html @SpringBootApplication @MapperScan("com.wsh.zero.mapper") //扫描位置要清楚,shiro swagger2没神效都是因为扫描位置配置范围错误引起 @ComponentScan({"com.wsh.zero.controller", "com.wsh.zero.service", "com.wsh.config", "com.wsh.util"}) @EnableTransactionManagement//事务管理 @EnableSwagger2 public class SpringBootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMybatisApplication.class, args); } }
935
0.821634
0.81588
22
38.5
28.146936
101
false
false
0
0
0
0
0
0
0.545455
false
false
1
c8b70f1e6cb851b0f330561d94e247780c7bd8c8
36,155,034,731,019
6e1142ca9aa6c6300091908e07d61d94728e13a4
/app/src/main/java/com/example/android/quizapp/json/JsonParser.java
973229a3b3913be1d7dae25a65aaf4202f653735
[]
no_license
paltee13/QuizApp
https://github.com/paltee13/QuizApp
edcc5e0e8dd478c76c4609e0d934e7103143a0b4
c43fe6b51a79d47c3fa448d928e05eefc1d21a9e
refs/heads/master
2020-04-06T15:41:12.384000
2019-01-05T21:42:51
2019-01-05T21:42:51
157,588,725
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android.quizapp.json; import com.example.android.quizapp.util.Util; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class JsonParser { public String getQuote(String data){ String s=""; try{ JSONArray jsonArray=new JSONArray(data); for(int i=0; i<jsonArray.length(); i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); s = Util.getString("quote", jsonObject)+"\n - "+Util.getString("author",jsonObject); } }catch (JSONException e){ e.printStackTrace(); } return s; } }
UTF-8
Java
679
java
JsonParser.java
Java
[]
null
[]
package com.example.android.quizapp.json; import com.example.android.quizapp.util.Util; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class JsonParser { public String getQuote(String data){ String s=""; try{ JSONArray jsonArray=new JSONArray(data); for(int i=0; i<jsonArray.length(); i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); s = Util.getString("quote", jsonObject)+"\n - "+Util.getString("author",jsonObject); } }catch (JSONException e){ e.printStackTrace(); } return s; } }
679
0.600884
0.599411
32
20.21875
23.896566
100
false
false
0
0
0
0
0
0
0.46875
false
false
1
aa49de87539169082d32c917175accff405dccd3
39,290,360,824,560
78f9e15bc0b37a91806ab2f50ab51a1ee577d8b3
/src/main/java/top/vanserver/wxpublic/dao/SFoodDao.java
6dd1eb4f1acd700611235627a0bd6ac8acc61759
[]
no_license
FanFamily123/wxpublic
https://github.com/FanFamily123/wxpublic
4dee2051fe2510b1b5a870e2e491785fa520045a
c75c67addb9c73f07f697509b65517d41421620e
refs/heads/master
2020-06-12T06:46:04.774000
2019-06-28T06:55:45
2019-06-28T06:55:45
194,223,568
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package top.vanserver.wxpublic.dao; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import top.vanserver.wxpublic.bean.Food; @Mapper @Repository public interface SFoodDao { Food SelectOneFood(int mathi); }
UTF-8
Java
259
java
SFoodDao.java
Java
[]
null
[]
package top.vanserver.wxpublic.dao; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import top.vanserver.wxpublic.bean.Food; @Mapper @Repository public interface SFoodDao { Food SelectOneFood(int mathi); }
259
0.810811
0.810811
11
22.545454
18.157711
49
false
false
0
0
0
0
0
0
0.454545
false
false
1
c0183d0ee19477d15b8314d0d7f7bd0ccf9b636f
12,816,182,480,710
4ea59b5aee039e2111be8ff30c0b333f8d013e53
/src/com/youku/exranking/data/crawl/components/downloaders/HttpClientDownloader.java
a6728e1e84342c18b54ed928ef659e6aed3f4ce3
[]
no_license
CharmLynn/Spider
https://github.com/CharmLynn/Spider
666b4b547a96c93ee8703fe1b9a855acb923f600
069fe923afaaa9f43d914d26144d78fd85e14ca5
refs/heads/master
2017-05-01T00:38:24.945000
2016-09-13T02:48:00
2016-09-13T02:48:00
68,067,277
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.youku.exranking.data.crawl.components.downloaders; import java.io.IOException; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.annotation.ThreadSafe; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.youku.exranking.data.crawl.components.models.HttpConstant; import com.youku.exranking.data.crawl.components.models.Page; import com.youku.exranking.data.crawl.components.models.Request; import com.youku.exranking.utils.UrlUtils; /** * @author ariel.wang * */ @ThreadSafe public class HttpClientDownloader implements Downloader { private Logger logger = LoggerFactory.getLogger(getClass()); public static CloseableHttpClient client = HttpClients.custom() .setConnectionManager(new PoolingHttpClientConnectionManager()) .build(); @Override public Page download(Request request) { String charset = "UTF-8"; logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request); httpResponse = client.execute(httpUriRequest); Page page = handleResponse(request, charset, httpResponse); return page; } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); return null; } finally { try { if (httpResponse != null) { // ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } } public String getRequest(Request request) { String charset = "UTF-8"; String content = null; logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request); httpResponse = client.execute(httpUriRequest); content = getContent(charset, httpResponse); } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); return null; } finally { try { if (httpResponse != null) { // ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } return content; } public String postRequest(String url, String charset, String referHost, UrlEncodedFormEntity params) { String resultHtml = ""; HttpPost post = new HttpPost(url); try { post.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0"); post.setHeader("Referer", referHost); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(params); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); resultHtml = new String(EntityUtils.toString(entity, charset)); post.abort(); } catch (Exception e) { resultHtml = ""; e.printStackTrace(); } return resultHtml; } public String getRequest(String url, String charset) { String content = null; logger.info("downloading page {}", url); CloseableHttpResponse httpResponse = null; try { HttpUriRequest httpUriRequest = selectRequestMethod( HttpConstant.Method.GET).setUri(url) .build(); httpResponse = client.execute(httpUriRequest); content = getContent(charset, httpResponse); System.out.println(content); } catch (IOException e) { logger.warn("download page " + url + " error", e); return null; } finally { try { if (httpResponse != null) { // ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } return content; } @Override public void setThread(int thread) { } protected HttpUriRequest getHttpUriRequest(Request request) { RequestBuilder requestBuilder = selectRequestMethod(request).setUri( request.getUrl()); return requestBuilder.build(); } protected RequestBuilder selectRequestMethod(Request request) { String method = request.getMethod(); if (method == null || method.equalsIgnoreCase(HttpConstant.Method.GET)) { // default get return RequestBuilder.get(); } else if (method.equalsIgnoreCase(HttpConstant.Method.POST)) { RequestBuilder requestBuilder = RequestBuilder.post(); return requestBuilder; } else if (method.equalsIgnoreCase(HttpConstant.Method.HEAD)) { return RequestBuilder.head(); } else if (method.equalsIgnoreCase(HttpConstant.Method.PUT)) { return RequestBuilder.put(); } else if (method.equalsIgnoreCase(HttpConstant.Method.DELETE)) { return RequestBuilder.delete(); } else if (method.equalsIgnoreCase(HttpConstant.Method.TRACE)) { return RequestBuilder.trace(); } throw new IllegalArgumentException("Illegal HTTP Method " + method); } protected RequestBuilder selectRequestMethod(String method) { if (method == null || method.equalsIgnoreCase(HttpConstant.Method.GET)) { // default get return RequestBuilder.get(); } else if (method.equalsIgnoreCase(HttpConstant.Method.POST)) { RequestBuilder requestBuilder = RequestBuilder.post(); return requestBuilder; } else if (method.equalsIgnoreCase(HttpConstant.Method.HEAD)) { return RequestBuilder.head(); } else if (method.equalsIgnoreCase(HttpConstant.Method.PUT)) { return RequestBuilder.put(); } else if (method.equalsIgnoreCase(HttpConstant.Method.DELETE)) { return RequestBuilder.delete(); } else if (method.equalsIgnoreCase(HttpConstant.Method.TRACE)) { return RequestBuilder.trace(); } throw new IllegalArgumentException("Illegal HTTP Method " + method); } protected Page handleResponse(Request request, String charset, HttpResponse httpResponse) throws IOException { String content = getContent(charset, httpResponse); Page page = new Page(); page.setRawText(content); page.setUrl(request.getUrl()); page.setRequest(request); return page; } protected String getContent(String charset, HttpResponse httpResponse) throws IOException { if (charset == null) { byte[] contentBytes = IOUtils.toByteArray(httpResponse.getEntity() .getContent()); String htmlCharset = getHtmlCharset(httpResponse, contentBytes); if (htmlCharset != null) { return new String(contentBytes, htmlCharset); } else { logger.warn( "Charset autodetect failed, use {} as charset. Please specify charset in Site.setCharset()", Charset.defaultCharset()); return new String(contentBytes); } } else { return IOUtils.toString(httpResponse.getEntity().getContent(), charset); } } protected String getHtmlCharset(HttpResponse httpResponse, byte[] contentBytes) throws IOException { String charset; // charset // 1、encoding in http header Content-Type String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); if (StringUtils.isNotBlank(charset)) { logger.debug("Auto get charset: {}", charset); return charset; } // use default charset to decode first time Charset defaultCharset = Charset.defaultCharset(); String content = new String(contentBytes, defaultCharset.name()); // 2、charset in meta if (StringUtils.isNotEmpty(content)) { Document document = Jsoup.parse(content); Elements links = document.select("meta"); for (Element link : links) { // 2.1、html4.01 <meta http-equiv="Content-Type" // content="text/html; charset=UTF-8" /> String metaContent = link.attr("content"); String metaCharset = link.attr("charset"); if (metaContent.indexOf("charset") != -1) { metaContent = metaContent.substring( metaContent.indexOf("charset"), metaContent.length()); charset = metaContent.split("=")[1]; break; } // 2.2、html5 <meta charset="UTF-8" /> else if (StringUtils.isNotEmpty(metaCharset)) { charset = metaCharset; break; } } } logger.debug("Auto get charset: {}", charset); return charset; } public static void main(String[] args) { String url = "http://top.qidian.com/Book/TopDetail.aspx?TopType=3"; HttpClientDownloader d = new HttpClientDownloader(); d.getRequest(url, "UTF-8"); } }
UTF-8
Java
9,029
java
HttpClientDownloader.java
Java
[ { "context": "m.youku.exranking.utils.UrlUtils;\n\n\n/**\n * @author ariel.wang\n * \n */\n@ThreadSafe\npublic class HttpClientDownlo", "end": 1264, "score": 0.9923739433288574, "start": 1254, "tag": "NAME", "value": "ariel.wang" } ]
null
[]
package com.youku.exranking.data.crawl.components.downloaders; import java.io.IOException; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.annotation.ThreadSafe; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.youku.exranking.data.crawl.components.models.HttpConstant; import com.youku.exranking.data.crawl.components.models.Page; import com.youku.exranking.data.crawl.components.models.Request; import com.youku.exranking.utils.UrlUtils; /** * @author ariel.wang * */ @ThreadSafe public class HttpClientDownloader implements Downloader { private Logger logger = LoggerFactory.getLogger(getClass()); public static CloseableHttpClient client = HttpClients.custom() .setConnectionManager(new PoolingHttpClientConnectionManager()) .build(); @Override public Page download(Request request) { String charset = "UTF-8"; logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request); httpResponse = client.execute(httpUriRequest); Page page = handleResponse(request, charset, httpResponse); return page; } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); return null; } finally { try { if (httpResponse != null) { // ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } } public String getRequest(Request request) { String charset = "UTF-8"; String content = null; logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request); httpResponse = client.execute(httpUriRequest); content = getContent(charset, httpResponse); } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); return null; } finally { try { if (httpResponse != null) { // ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } return content; } public String postRequest(String url, String charset, String referHost, UrlEncodedFormEntity params) { String resultHtml = ""; HttpPost post = new HttpPost(url); try { post.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0"); post.setHeader("Referer", referHost); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(params); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); resultHtml = new String(EntityUtils.toString(entity, charset)); post.abort(); } catch (Exception e) { resultHtml = ""; e.printStackTrace(); } return resultHtml; } public String getRequest(String url, String charset) { String content = null; logger.info("downloading page {}", url); CloseableHttpResponse httpResponse = null; try { HttpUriRequest httpUriRequest = selectRequestMethod( HttpConstant.Method.GET).setUri(url) .build(); httpResponse = client.execute(httpUriRequest); content = getContent(charset, httpResponse); System.out.println(content); } catch (IOException e) { logger.warn("download page " + url + " error", e); return null; } finally { try { if (httpResponse != null) { // ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } return content; } @Override public void setThread(int thread) { } protected HttpUriRequest getHttpUriRequest(Request request) { RequestBuilder requestBuilder = selectRequestMethod(request).setUri( request.getUrl()); return requestBuilder.build(); } protected RequestBuilder selectRequestMethod(Request request) { String method = request.getMethod(); if (method == null || method.equalsIgnoreCase(HttpConstant.Method.GET)) { // default get return RequestBuilder.get(); } else if (method.equalsIgnoreCase(HttpConstant.Method.POST)) { RequestBuilder requestBuilder = RequestBuilder.post(); return requestBuilder; } else if (method.equalsIgnoreCase(HttpConstant.Method.HEAD)) { return RequestBuilder.head(); } else if (method.equalsIgnoreCase(HttpConstant.Method.PUT)) { return RequestBuilder.put(); } else if (method.equalsIgnoreCase(HttpConstant.Method.DELETE)) { return RequestBuilder.delete(); } else if (method.equalsIgnoreCase(HttpConstant.Method.TRACE)) { return RequestBuilder.trace(); } throw new IllegalArgumentException("Illegal HTTP Method " + method); } protected RequestBuilder selectRequestMethod(String method) { if (method == null || method.equalsIgnoreCase(HttpConstant.Method.GET)) { // default get return RequestBuilder.get(); } else if (method.equalsIgnoreCase(HttpConstant.Method.POST)) { RequestBuilder requestBuilder = RequestBuilder.post(); return requestBuilder; } else if (method.equalsIgnoreCase(HttpConstant.Method.HEAD)) { return RequestBuilder.head(); } else if (method.equalsIgnoreCase(HttpConstant.Method.PUT)) { return RequestBuilder.put(); } else if (method.equalsIgnoreCase(HttpConstant.Method.DELETE)) { return RequestBuilder.delete(); } else if (method.equalsIgnoreCase(HttpConstant.Method.TRACE)) { return RequestBuilder.trace(); } throw new IllegalArgumentException("Illegal HTTP Method " + method); } protected Page handleResponse(Request request, String charset, HttpResponse httpResponse) throws IOException { String content = getContent(charset, httpResponse); Page page = new Page(); page.setRawText(content); page.setUrl(request.getUrl()); page.setRequest(request); return page; } protected String getContent(String charset, HttpResponse httpResponse) throws IOException { if (charset == null) { byte[] contentBytes = IOUtils.toByteArray(httpResponse.getEntity() .getContent()); String htmlCharset = getHtmlCharset(httpResponse, contentBytes); if (htmlCharset != null) { return new String(contentBytes, htmlCharset); } else { logger.warn( "Charset autodetect failed, use {} as charset. Please specify charset in Site.setCharset()", Charset.defaultCharset()); return new String(contentBytes); } } else { return IOUtils.toString(httpResponse.getEntity().getContent(), charset); } } protected String getHtmlCharset(HttpResponse httpResponse, byte[] contentBytes) throws IOException { String charset; // charset // 1、encoding in http header Content-Type String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); if (StringUtils.isNotBlank(charset)) { logger.debug("Auto get charset: {}", charset); return charset; } // use default charset to decode first time Charset defaultCharset = Charset.defaultCharset(); String content = new String(contentBytes, defaultCharset.name()); // 2、charset in meta if (StringUtils.isNotEmpty(content)) { Document document = Jsoup.parse(content); Elements links = document.select("meta"); for (Element link : links) { // 2.1、html4.01 <meta http-equiv="Content-Type" // content="text/html; charset=UTF-8" /> String metaContent = link.attr("content"); String metaCharset = link.attr("charset"); if (metaContent.indexOf("charset") != -1) { metaContent = metaContent.substring( metaContent.indexOf("charset"), metaContent.length()); charset = metaContent.split("=")[1]; break; } // 2.2、html5 <meta charset="UTF-8" /> else if (StringUtils.isNotEmpty(metaCharset)) { charset = metaCharset; break; } } } logger.debug("Auto get charset: {}", charset); return charset; } public static void main(String[] args) { String url = "http://top.qidian.com/Book/TopDetail.aspx?TopType=3"; HttpClientDownloader d = new HttpClientDownloader(); d.getRequest(url, "UTF-8"); } }
9,029
0.722647
0.718324
273
32.043957
22.913715
98
false
false
0
0
0
0
0
0
2.769231
false
false
1
4f8ba21048db0a0cc162c912488ab3740ef472e0
21,328,807,617,613
282563a7998174c0c7c8d331137a03a7add8e9b0
/app/src/main/java/com/yiyang/cn/util/FourLieDecoration.java
2e7d1208a4db4e284c01205a517ba14d65afb06d
[]
no_license
CareyLiu/YiyangApp_0907_01
https://github.com/CareyLiu/YiyangApp_0907_01
c226a6d8965143f19bccd567ff137b1b1059c8be
d3d7e1e08ed6c3e342424bafbb8b562a1013e302
refs/heads/master
2023-08-05T06:35:43.620000
2021-09-22T03:17:43
2021-09-22T03:17:43
403,847,296
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yiyang.cn.util; import android.app.Activity; import android.graphics.Canvas; import android.graphics.Rect; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.View; import com.scwang.smartrefresh.layout.util.DensityUtil; public class FourLieDecoration extends RecyclerView.ItemDecoration { Activity activity; public FourLieDecoration(Activity activity) { this.activity = activity; } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDrawOver(c, parent, state); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); int leftSpace = 10; int rightSpace = 10; if (layoutManager instanceof GridLayoutManager) { GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager; int spanCount = gridLayoutManager.getSpanCount(); int totalSpace = 10 + 10 + 10 * (spanCount - 1); int itemNeedSpace = totalSpace / spanCount; // if (parent.getChildAdapterPosition(view) % 2 == 0) { // // 最左一条 // outRect.left = DensityUtil.dp2px(leftSpace); // outRect.right = DensityUtil.dp2px(itemNeedSpace - leftSpace); // } else if (parent.getChildAdapterPosition(view) % 2 == 1) { // // 最右一条 // outRect.left = DensityUtil.dp2px(itemNeedSpace - rightSpace); // outRect.right = DensityUtil.dp2px(rightSpace); // } // 330 dp if (parent.getChildAdapterPosition(view) % 2 == 0) { outRect.right = DensityUtil.dp2px(itemNeedSpace - leftSpace); } else if (parent.getChildAdapterPosition(view) % 2 == 1) { } else if (parent.getChildAdapterPosition(view) % 2 == 2) { } else if (parent.getChildAdapterPosition(view) % 2 == 3) { outRect.left = DensityUtil.dp2px(itemNeedSpace - rightSpace); } Log.i("spanCount", spanCount + ""); Log.i("getchildadapterposition", parent.getChildAdapterPosition(view) % 2 + "" + parent.getChildAdapterPosition(view)); } } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { super.getItemOffsets(outRect, itemPosition, parent); } }
UTF-8
Java
2,660
java
FourLieDecoration.java
Java
[]
null
[]
package com.yiyang.cn.util; import android.app.Activity; import android.graphics.Canvas; import android.graphics.Rect; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.View; import com.scwang.smartrefresh.layout.util.DensityUtil; public class FourLieDecoration extends RecyclerView.ItemDecoration { Activity activity; public FourLieDecoration(Activity activity) { this.activity = activity; } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDrawOver(c, parent, state); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); int leftSpace = 10; int rightSpace = 10; if (layoutManager instanceof GridLayoutManager) { GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager; int spanCount = gridLayoutManager.getSpanCount(); int totalSpace = 10 + 10 + 10 * (spanCount - 1); int itemNeedSpace = totalSpace / spanCount; // if (parent.getChildAdapterPosition(view) % 2 == 0) { // // 最左一条 // outRect.left = DensityUtil.dp2px(leftSpace); // outRect.right = DensityUtil.dp2px(itemNeedSpace - leftSpace); // } else if (parent.getChildAdapterPosition(view) % 2 == 1) { // // 最右一条 // outRect.left = DensityUtil.dp2px(itemNeedSpace - rightSpace); // outRect.right = DensityUtil.dp2px(rightSpace); // } // 330 dp if (parent.getChildAdapterPosition(view) % 2 == 0) { outRect.right = DensityUtil.dp2px(itemNeedSpace - leftSpace); } else if (parent.getChildAdapterPosition(view) % 2 == 1) { } else if (parent.getChildAdapterPosition(view) % 2 == 2) { } else if (parent.getChildAdapterPosition(view) % 2 == 3) { outRect.left = DensityUtil.dp2px(itemNeedSpace - rightSpace); } Log.i("spanCount", spanCount + ""); Log.i("getchildadapterposition", parent.getChildAdapterPosition(view) % 2 + "" + parent.getChildAdapterPosition(view)); } } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { super.getItemOffsets(outRect, itemPosition, parent); } }
2,660
0.647126
0.634644
69
37.31884
32.089321
131
false
false
0
0
0
0
0
0
0.652174
false
false
1
b8ec95450de49202b936e073445311e7ec40daeb
30,047,591,260,712
ec234daf08beeefba2a7098c92f5a31a1cb84153
/src/task/src/task/Config.java
a0eea556cbe9f91ee4bf47a1900658b96fed5456
[]
no_license
Pivovarov/task
https://github.com/Pivovarov/task
2f51eb9ea866331c3b105cc903178fdb1f507541
5ae98db7ada086229cb7dd0127cf1565af9971b6
refs/heads/master
2016-09-05T16:08:18.450000
2011-07-10T16:38:14
2011-07-10T16:38:14
2,026,085
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package task; /** * * @author Alexey */ public class Config { final static String WORK_DIR = "work/"; final static String CONFIG_DIR = "config/"; final static String WEBHARVEST_CONFIG_FILE = "farpost.xml"; final static String CATALOG_FILE = "catalog.xml"; final static String REPORT_FILE = "report.pdf"; final static String FONT_FILE = "tahoma.ttf"; final static String WEBHARVEST_CONFIG_PATH = CONFIG_DIR + WEBHARVEST_CONFIG_FILE; final static String CATALOG_PATH = WORK_DIR + CATALOG_FILE; final static String REPORT_PATH = WORK_DIR + REPORT_FILE; final static String FONT_PATH = CONFIG_DIR + FONT_FILE; //Минимальный размер абзаца final static int MIN_PARAGRAPH_SIZE = 5; //Коэф. совпадения, после которого объявления считаются одинаковыми final static double SAME_TEXT = 0.6; final static double SAME_FOTO = 0.6; final static double SAME_URL = 0.6; }
UTF-8
Java
1,103
java
Config.java
Java
[ { "context": "n the editor.\n */\npackage task;\n\n/**\n *\n * @author Alexey\n */\npublic class Config {\n final static String", "end": 139, "score": 0.999538779258728, "start": 133, "tag": "NAME", "value": "Alexey" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package task; /** * * @author Alexey */ public class Config { final static String WORK_DIR = "work/"; final static String CONFIG_DIR = "config/"; final static String WEBHARVEST_CONFIG_FILE = "farpost.xml"; final static String CATALOG_FILE = "catalog.xml"; final static String REPORT_FILE = "report.pdf"; final static String FONT_FILE = "tahoma.ttf"; final static String WEBHARVEST_CONFIG_PATH = CONFIG_DIR + WEBHARVEST_CONFIG_FILE; final static String CATALOG_PATH = WORK_DIR + CATALOG_FILE; final static String REPORT_PATH = WORK_DIR + REPORT_FILE; final static String FONT_PATH = CONFIG_DIR + FONT_FILE; //Минимальный размер абзаца final static int MIN_PARAGRAPH_SIZE = 5; //Коэф. совпадения, после которого объявления считаются одинаковыми final static double SAME_TEXT = 0.6; final static double SAME_FOTO = 0.6; final static double SAME_URL = 0.6; }
1,103
0.69697
0.690127
28
35.535713
24.418205
85
false
false
0
0
0
0
0
0
0.642857
false
false
1
2d69681352df85ebff6bc0adc588193df6659a6f
19,894,288,528,063
38bf7b40d5dc7d45020d7ccfccd3061ab50d49af
/src/Google/spellchecktest.java
d6a56db5d2eee508f7fe27f2ac796a3df65d1d71
[]
no_license
musan801/ACCProject-8547-Anveshan
https://github.com/musan801/ACCProject-8547-Anveshan
2b6ddf6aa8814b654f171d39c6ededa4466ba681
18fa1f2dfad36f42e39b633bf5b310d59eb5b255
refs/heads/master
2023-07-01T05:35:44.262000
2021-08-01T08:48:36
2021-08-01T08:48:36
391,573,372
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Google; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import searchtrees.Sequences; public class spellchecktest { public static String SpellCheck(String word) { int temp; BufferedReader reader; ArrayList<String> dictionary = new ArrayList(); try { reader = new BufferedReader(new FileReader("words.txt")); String line = reader.readLine(); while (line != null) { // System.out.println(line); int distance = Sequences.editDistance(line, word); if (distance <= 5 && line.startsWith(word.substring(0, 1)) && word.length()<= line.length()) { dictionary.add(line); // System.out.println(line); } line = reader.readLine(); } if (dictionary.contains(word)) { int c = 0; for (int i = 0; i < dictionary.size(); i++) { // auto complete //Collections.sort(dictionary, Collections.reverseOrder()); if (dictionary.get(i).length() > word.length() && dictionary.get(i).indexOf(word) != -1) { if (c==0) { System.out.println("*************************************"); System.out.println("Our Auto Complete Suggestion:"); } System.out.println(dictionary.get(i)); c++; if (c > 4) { break; } } } } else { for(String w:dictionary) { int Comparator=Sequences.editDistance(word, w); if (Comparator<=1) return w; } if (dictionary.size() >= 5) { // Collections.sort(dictionary); // Spell correction // System.out.println(dictionary.subList(0, 4)); Collections.sort(dictionary); //return dictionary.subList(0, 4); } else { temp=1; // System.out.println(dictionary); Collections.sort(dictionary); //return dictionary; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } return word; } public static void main(String[] args) { Scanner input = new Scanner(System.in); // String word = input.next(); String word = "apple"; // Hashtable<String, String> dictionary; // dictionary = new Hashtable<String, String>(); String a = SpellCheck("match"); System.out.println(a); } }
UTF-8
Java
2,350
java
spellchecktest.java
Java
[]
null
[]
package Google; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import searchtrees.Sequences; public class spellchecktest { public static String SpellCheck(String word) { int temp; BufferedReader reader; ArrayList<String> dictionary = new ArrayList(); try { reader = new BufferedReader(new FileReader("words.txt")); String line = reader.readLine(); while (line != null) { // System.out.println(line); int distance = Sequences.editDistance(line, word); if (distance <= 5 && line.startsWith(word.substring(0, 1)) && word.length()<= line.length()) { dictionary.add(line); // System.out.println(line); } line = reader.readLine(); } if (dictionary.contains(word)) { int c = 0; for (int i = 0; i < dictionary.size(); i++) { // auto complete //Collections.sort(dictionary, Collections.reverseOrder()); if (dictionary.get(i).length() > word.length() && dictionary.get(i).indexOf(word) != -1) { if (c==0) { System.out.println("*************************************"); System.out.println("Our Auto Complete Suggestion:"); } System.out.println(dictionary.get(i)); c++; if (c > 4) { break; } } } } else { for(String w:dictionary) { int Comparator=Sequences.editDistance(word, w); if (Comparator<=1) return w; } if (dictionary.size() >= 5) { // Collections.sort(dictionary); // Spell correction // System.out.println(dictionary.subList(0, 4)); Collections.sort(dictionary); //return dictionary.subList(0, 4); } else { temp=1; // System.out.println(dictionary); Collections.sort(dictionary); //return dictionary; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } return word; } public static void main(String[] args) { Scanner input = new Scanner(System.in); // String word = input.next(); String word = "apple"; // Hashtable<String, String> dictionary; // dictionary = new Hashtable<String, String>(); String a = SpellCheck("match"); System.out.println(a); } }
2,350
0.599149
0.592766
103
21.815535
20.340189
98
false
false
0
0
0
0
0
0
3.601942
false
false
1
21e59d05ac911a4224f29d53dff1101befca2770
15,891,379,022,523
e0066daf65bee30d48de76c1332e02971608bbba
/src/main/java/ru/energodata/PostgreProcessor.java
de6edf6d481913a5306b4bc7626f40e1afe73a17
[]
no_license
annanimous/xml2csv
https://github.com/annanimous/xml2csv
9b2495bdab5e1458b3a5233784a2555610e23a03
13d946ca2aed18c758bc7c62819e5640736dd8cf
refs/heads/master
2021-06-12T12:20:03.211000
2017-04-06T09:26:43
2017-04-06T09:26:43
69,962,169
1
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 ru.energodata; import org.postgresql.ds.PGPoolingDataSource; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; class PostgreProcessor { private Connection con; public void initialize(Config config) throws SQLException, ClassNotFoundException { Class.forName("org.postgresql.Driver"); //con = DriverManager.getConnection("jdbc:postgresql://" + postgreHost + ':' + postgrePort + '/' + databaseName, postgreUser, postgrePassword); PGPoolingDataSource source = new PGPoolingDataSource(); source.setDataSourceName(config.getPostgrePassword()); source.setServerName(config.getPostgreHost()); source.setDatabaseName(config.getPostgreDatabaseName()); source.setUser(config.getPostgreUser()); source.setPassword(config.getPostgrePassword()); source.setMaxConnections(config.getPostgreMaxConnections()); con = source.getConnection(); } public void deinitialize() throws SQLException { if (con != null) { con.close(); } } public List<String> query (String returnColumn, String table, String searchString) throws SQLException { List<String> returnString = new ArrayList<>(); Statement stmt = con.createStatement(); ResultSet rs; if (searchString.contains(" ")) { String socr = searchString.split(" ")[0]; searchString = searchString.substring(searchString.indexOf(" ")+1); rs = stmt.executeQuery("SELECT " + returnColumn + " FROM " + table + " WHERE name = '" + searchString + "' AND socr ='" + socr + "'"); } else rs = stmt.executeQuery("SELECT " + returnColumn + " FROM " + table + " WHERE name = '" + searchString + "'"); while (rs.next()) { if (rs.getString(returnColumn) != null ) returnString.add(rs.getString(returnColumn)); } return returnString; } public List<String> getBuilding(String searchString, String searchCode) throws SQLException { List<String> returnString = new ArrayList<>(); Statement stmt = con.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT index FROM street_building WHERE build_number = '" + searchString + "'" + "AND parent_code = '" + searchCode + "'"); while (rs.next()) { if (rs.getString("index") != null ) returnString.add(rs.getString("index")); } return returnString; } public String getStreetIndex(String searchString) throws SQLException { String returnString = ""; Statement stmt = con.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT index FROM street_zip WHERE code = '" + searchString + "'"); while (rs.next()) { if (Objects.equals(returnString, "")) { returnString = rs.getString("index"); } else returnString = returnString + ", " + rs.getString("index"); } return returnString; } public String getBuildingIndex(String searchString) throws SQLException { String returnString = ""; Statement stmt = con.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT index FROM street_building WHERE parent_code = '" + searchString + "'"); while (rs.next()) { if (Objects.equals(returnString, "")) { returnString = rs.getString("index"); } else if (!returnString.contains(rs.getString("index"))) returnString = returnString + ", " + rs.getString("index"); } return returnString; } }
UTF-8
Java
3,903
java
PostgreProcessor.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 ru.energodata; import org.postgresql.ds.PGPoolingDataSource; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; class PostgreProcessor { private Connection con; public void initialize(Config config) throws SQLException, ClassNotFoundException { Class.forName("org.postgresql.Driver"); //con = DriverManager.getConnection("jdbc:postgresql://" + postgreHost + ':' + postgrePort + '/' + databaseName, postgreUser, postgrePassword); PGPoolingDataSource source = new PGPoolingDataSource(); source.setDataSourceName(config.getPostgrePassword()); source.setServerName(config.getPostgreHost()); source.setDatabaseName(config.getPostgreDatabaseName()); source.setUser(config.getPostgreUser()); source.setPassword(config.getPostgrePassword()); source.setMaxConnections(config.getPostgreMaxConnections()); con = source.getConnection(); } public void deinitialize() throws SQLException { if (con != null) { con.close(); } } public List<String> query (String returnColumn, String table, String searchString) throws SQLException { List<String> returnString = new ArrayList<>(); Statement stmt = con.createStatement(); ResultSet rs; if (searchString.contains(" ")) { String socr = searchString.split(" ")[0]; searchString = searchString.substring(searchString.indexOf(" ")+1); rs = stmt.executeQuery("SELECT " + returnColumn + " FROM " + table + " WHERE name = '" + searchString + "' AND socr ='" + socr + "'"); } else rs = stmt.executeQuery("SELECT " + returnColumn + " FROM " + table + " WHERE name = '" + searchString + "'"); while (rs.next()) { if (rs.getString(returnColumn) != null ) returnString.add(rs.getString(returnColumn)); } return returnString; } public List<String> getBuilding(String searchString, String searchCode) throws SQLException { List<String> returnString = new ArrayList<>(); Statement stmt = con.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT index FROM street_building WHERE build_number = '" + searchString + "'" + "AND parent_code = '" + searchCode + "'"); while (rs.next()) { if (rs.getString("index") != null ) returnString.add(rs.getString("index")); } return returnString; } public String getStreetIndex(String searchString) throws SQLException { String returnString = ""; Statement stmt = con.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT index FROM street_zip WHERE code = '" + searchString + "'"); while (rs.next()) { if (Objects.equals(returnString, "")) { returnString = rs.getString("index"); } else returnString = returnString + ", " + rs.getString("index"); } return returnString; } public String getBuildingIndex(String searchString) throws SQLException { String returnString = ""; Statement stmt = con.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT index FROM street_building WHERE parent_code = '" + searchString + "'"); while (rs.next()) { if (Objects.equals(returnString, "")) { returnString = rs.getString("index"); } else if (!returnString.contains(rs.getString("index"))) returnString = returnString + ", " + rs.getString("index"); } return returnString; } }
3,903
0.621573
0.621061
96
39.65625
35.929279
155
false
false
0
0
0
0
0
0
0.625
false
false
1
a5a884b44a8795dd1c34dd683b283fd33e3443d9
23,072,564,341,781
84ab3c6395ec9e7dba3a40f95bf702ca9e3af831
/zyx-news-service-model/src/main/java/com/zyx/pojo/vo/ArticleDetailVO.java
0210fb387cbbc4069feed8e08e97a1e1551c23a2
[ "Apache-2.0" ]
permissive
xitinb/zyx-news-service
https://github.com/xitinb/zyx-news-service
1b85e0a6ac10c1f5f8f24f006fd71aa7322f6833
cb012c754ffb432b8f16be2d070d1d8d132e07cf
refs/heads/master
2023-07-01T10:57:36.425000
2021-07-10T23:57:11
2021-07-10T23:57:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zyx.pojo.vo; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class ArticleDetailVO { private String id; private String title; private String cover; private Integer categoryId; private String categoryName; private String publishUserId; @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date publishTime; private String content; private String publishUserName; private Integer readCounts; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getPublishUserId() { return publishUserId; } public void setPublishUserId(String publishUserId) { this.publishUserId = publishUserId; } public String getPublishUserName() { return publishUserName; } public void setPublishUserName(String publishUserName) { this.publishUserName = publishUserName; } public Date getPublishTime() { return publishTime; } public void setPublishTime(Date publishTime) { this.publishTime = publishTime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public Integer getReadCounts() { return readCounts; } public void setReadCounts(Integer readCounts) { this.readCounts = readCounts; } }
UTF-8
Java
2,106
java
ArticleDetailVO.java
Java
[]
null
[]
package com.zyx.pojo.vo; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class ArticleDetailVO { private String id; private String title; private String cover; private Integer categoryId; private String categoryName; private String publishUserId; @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date publishTime; private String content; private String publishUserName; private Integer readCounts; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getPublishUserId() { return publishUserId; } public void setPublishUserId(String publishUserId) { this.publishUserId = publishUserId; } public String getPublishUserName() { return publishUserName; } public void setPublishUserName(String publishUserName) { this.publishUserName = publishUserName; } public Date getPublishTime() { return publishTime; } public void setPublishTime(Date publishTime) { this.publishTime = publishTime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public Integer getReadCounts() { return readCounts; } public void setReadCounts(Integer readCounts) { this.readCounts = readCounts; } }
2,106
0.6415
0.641026
101
19.861385
18.083431
68
false
false
0
0
0
0
0
0
0.336634
false
false
1
aefc85b39cfe41d91222a361756a8add44ba8f2b
25,366,076,885,392
5e139a33ad8aa00db66e6589ea713a534d8cc26d
/src/test/java/com/ijmeet/base/BaseCucumber.java
c90bc74c77ede54d79b049c8827aa171b28154af
[]
no_license
dharmikmehta1112/IJmeet
https://github.com/dharmikmehta1112/IJmeet
aeec6010c0c949f9cb47ecf0887dd953b83e5f35
d3985323970cdc28d7857d65c43a5fbb6db98d46
refs/heads/master
2023-03-13T09:09:11.828000
2021-03-06T19:14:32
2021-03-06T19:14:32
343,659,668
0
0
null
false
2021-03-06T19:14:32
2021-03-02T05:44:45
2021-03-02T08:48:46
2021-03-06T19:14:32
0
0
0
0
null
false
false
package com.ijmeet.base; import com.ijmeet.main.Constants; import com.ijmeet.main.UIKeywords; import io.cucumber.java.*; public class BaseCucumber extends UIKeywords { @After public void tearDown(){ Constants.driver.quit(); } }
UTF-8
Java
237
java
BaseCucumber.java
Java
[]
null
[]
package com.ijmeet.base; import com.ijmeet.main.Constants; import com.ijmeet.main.UIKeywords; import io.cucumber.java.*; public class BaseCucumber extends UIKeywords { @After public void tearDown(){ Constants.driver.quit(); } }
237
0.755274
0.755274
14
16
15.436506
46
false
false
0
0
0
0
0
0
0.785714
false
false
1
32f380e154a7eeb6951e818ab92b459d6f4ae73c
25,864,293,059,998
c4dc34106ac473ff3dd1fbf8e4edbb8d9906fe1c
/thecaptains.domain/src/test/java/ch/kitchencaptain/model/CreateIT.java
bdbfd7d7352c9e0606869a418820e4642669fc5a
[]
no_license
engineererr/KitchenCaptain
https://github.com/engineererr/KitchenCaptain
ed2cb5519faea264c1f162c84987b3828396c822
5faa2e67886c16bad90a04290b6b3c1c579012a2
refs/heads/master
2021-05-30T19:39:33.285000
2016-01-26T21:13:16
2016-01-26T21:13:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.kitchencaptain.model; /** * Created by User on 27.10.2015. */ import org.junit.Test; import javax.persistence.EntityManager; import javax.persistence.Persistence; import java.util.ArrayList; import java.util.List; public class CreateIT { @Test public void test() { Category category = new Category(); category.setTitle("Beilage"); Ingredient ingredient = new Ingredient(); ingredient.setTitle("Spaghetti"); Ingredient ingredient2 = new Ingredient(); ingredient2.setTitle("Speck"); List<Ingredient> ingredients = new ArrayList<Ingredient>(); ingredients.add(ingredient); ingredients.add(ingredient2); category.setIngredients(ingredients); ingredient.setCategory(category); ingredient2.setCategory(category); EntityManager em = Persistence.createEntityManagerFactory( "thecaptains.domain").createEntityManager(); em.getTransaction().begin(); em.persist(ingredient); em.getTransaction().commit(); } }
UTF-8
Java
1,079
java
CreateIT.java
Java
[]
null
[]
package ch.kitchencaptain.model; /** * Created by User on 27.10.2015. */ import org.junit.Test; import javax.persistence.EntityManager; import javax.persistence.Persistence; import java.util.ArrayList; import java.util.List; public class CreateIT { @Test public void test() { Category category = new Category(); category.setTitle("Beilage"); Ingredient ingredient = new Ingredient(); ingredient.setTitle("Spaghetti"); Ingredient ingredient2 = new Ingredient(); ingredient2.setTitle("Speck"); List<Ingredient> ingredients = new ArrayList<Ingredient>(); ingredients.add(ingredient); ingredients.add(ingredient2); category.setIngredients(ingredients); ingredient.setCategory(category); ingredient2.setCategory(category); EntityManager em = Persistence.createEntityManagerFactory( "thecaptains.domain").createEntityManager(); em.getTransaction().begin(); em.persist(ingredient); em.getTransaction().commit(); } }
1,079
0.668211
0.65709
42
24.690475
20.724369
67
false
false
0
0
0
0
0
0
0.52381
false
false
1
2ccfa708978ec74d0009eb60f4d4ae13ea297503
16,544,214,029,077
48a5b8d33f061d2a5eab13d6d3dd0c1af871bc12
/src/main/java/com/example/demo/controller/CustomerController.java
79ba8b23a1854a584f2f03a01cf4aedc8dc323d3
[]
no_license
vinnunaidu/SpringGradle
https://github.com/vinnunaidu/SpringGradle
767c0c77fb09e90e2dafb9c0f60a70ba9f494dc3
d5cd8315d39d8667964d82abd27cd5dba741bf9e
refs/heads/master
2020-06-08T02:07:31.896000
2019-06-21T17:52:49
2019-06-21T17:52:49
193,138,936
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.controller; import com.example.demo.entities.Customer; import com.example.demo.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class CustomerController { @Autowired private CustomerService customerService; @GetMapping("/customer/{customerId}") public Customer getCustomer(@PathVariable("customerId") Long customerId){ return customerService.getCustomer(customerId); } @PostMapping("/customer") public void sayHello(@RequestBody Customer customer){ customerService.createCustomer(customer); } }
UTF-8
Java
687
java
CustomerController.java
Java
[]
null
[]
package com.example.demo.controller; import com.example.demo.entities.Customer; import com.example.demo.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class CustomerController { @Autowired private CustomerService customerService; @GetMapping("/customer/{customerId}") public Customer getCustomer(@PathVariable("customerId") Long customerId){ return customerService.getCustomer(customerId); } @PostMapping("/customer") public void sayHello(@RequestBody Customer customer){ customerService.createCustomer(customer); } }
687
0.765648
0.765648
25
26.48
24.250559
77
false
false
0
0
0
0
0
0
0.32
false
false
1
ea57d1902c6cac521f71fb0ac187f97530c86b34
4,973,572,154,587
a1b8170ffbaf3e94b16d496b2d9ae21b56c8329c
/utc-python/src/test/java/me/dave_karetnyk/utils/grammar/python27/UtcTest.java
380ae4aa1b99bb48fc491ca1ed94ef41ffe6a7c7
[ "MIT" ]
permissive
DaveKaretnyk/parsing-utils2
https://github.com/DaveKaretnyk/parsing-utils2
e8736d2d7946acb820b755c80ee3e6217d47c376
40085bbd399fa605f2f2a4708d385a64ffc907de
refs/heads/master
2021-09-03T06:23:14.917000
2018-01-06T11:30:21
2018-01-06T11:30:21
115,658,112
0
0
MIT
false
2018-01-05T20:15:48
2017-12-28T20:43:09
2018-01-05T13:39:07
2018-01-05T20:15:48
10,959
0
0
0
Python
false
null
// Under MIT License, Copyright (c) 2017-18 Dave Karetnyk // Full terms: see "LICENSE' file in root directory of repository: // https://github.com/DaveKaretnyk/parsing-utils2 package me.dave_karetnyk.utils.grammar.python27; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class UtcTest { private boolean printDiagnostics = true; @BeforeEach void setUp() { } @AfterEach void tearDown() { } @Test void generate_symbols_sample1_py() throws Exception { Utc utc = new Utc("samples/sample1.py"); SymbolTable symbolTable = utc.generateSymbols(); if (printDiagnostics) { System.out.printf("%s free functions detected:%n", symbolTable.freeFuncList.size()); for (String entry : symbolTable.freeFuncList) { System.out.println(" " + entry); } } List<String> expectFreeFuncs = Arrays.asList( "free_func_1", "free_func_2", "free_func_3", "free_func_4" ); assertEquals(expectFreeFuncs, symbolTable.freeFuncList); if (printDiagnostics) { System.out.printf("%s class/es with functions detected:%n", symbolTable.classMap.size()); for (String className: symbolTable.classMap.keySet()) { System.out.println("\t" + className); for (String funcName: symbolTable.classMap.get(className) ) { System.out.println("\t\t" + funcName); } } } HashMap<String, ArrayList<String>> expectedClassFuncs = new HashMap<>(); expectedClassFuncs.put("Silly1", new ArrayList<>()); expectedClassFuncs.get("Silly1").add("class_func_get1"); expectedClassFuncs.get("Silly1").add("class_func_set1"); expectedClassFuncs.put("Silly2", new ArrayList<>()); expectedClassFuncs.get("Silly2").add("class_func_get2"); expectedClassFuncs.get("Silly2").add("class_func_set2"); expectedClassFuncs.get("Silly2").add("class_func_another"); expectedClassFuncs.get("Silly2").add("class_func_another2"); expectedClassFuncs.put("Silly3", new ArrayList<>()); expectedClassFuncs.get("Silly3").add("class_func_get1"); expectedClassFuncs.get("Silly3").add("class_func_set1"); assertEquals(expectedClassFuncs.size(), symbolTable.classMap.size()); assertEquals(expectedClassFuncs.get("Silly1"), symbolTable.classMap.get("Silly1")); assertEquals(expectedClassFuncs.get("Silly2"), symbolTable.classMap.get("Silly2")); assertEquals(expectedClassFuncs.get("Silly3"), symbolTable.classMap.get("Silly3")); } @Test void render_utc_sample1() throws Exception { Utc utc = new Utc("samples/sample1.py"); SymbolTable symbolTable = utc.generateSymbols(); String result = utc.render(symbolTable); if (printDiagnostics) System.out.print("\r\n\r\n"); System.out.println(result); assertNotEquals(0, result.length()); UiSystemClipboard.CopyTo(result); String fromClipboard = UiSystemClipboard.getFrom(); assertEquals(fromClipboard, result); } }
UTF-8
Java
3,445
java
UtcTest.java
Java
[ { "context": "// Under MIT License, Copyright (c) 2017-18 Dave Karetnyk\n// Full terms: see \"LICENSE' file in root directo", "end": 57, "score": 0.9998519420623779, "start": 44, "tag": "NAME", "value": "Dave Karetnyk" }, { "context": "rectory of repository:\n// https://github.com/DaveKaretnyk/parsing-utils2\npackage me.dave_karetnyk.utils.gra", "end": 164, "score": 0.9977471828460693, "start": 152, "tag": "USERNAME", "value": "DaveKaretnyk" } ]
null
[]
// Under MIT License, Copyright (c) 2017-18 <NAME> // Full terms: see "LICENSE' file in root directory of repository: // https://github.com/DaveKaretnyk/parsing-utils2 package me.dave_karetnyk.utils.grammar.python27; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class UtcTest { private boolean printDiagnostics = true; @BeforeEach void setUp() { } @AfterEach void tearDown() { } @Test void generate_symbols_sample1_py() throws Exception { Utc utc = new Utc("samples/sample1.py"); SymbolTable symbolTable = utc.generateSymbols(); if (printDiagnostics) { System.out.printf("%s free functions detected:%n", symbolTable.freeFuncList.size()); for (String entry : symbolTable.freeFuncList) { System.out.println(" " + entry); } } List<String> expectFreeFuncs = Arrays.asList( "free_func_1", "free_func_2", "free_func_3", "free_func_4" ); assertEquals(expectFreeFuncs, symbolTable.freeFuncList); if (printDiagnostics) { System.out.printf("%s class/es with functions detected:%n", symbolTable.classMap.size()); for (String className: symbolTable.classMap.keySet()) { System.out.println("\t" + className); for (String funcName: symbolTable.classMap.get(className) ) { System.out.println("\t\t" + funcName); } } } HashMap<String, ArrayList<String>> expectedClassFuncs = new HashMap<>(); expectedClassFuncs.put("Silly1", new ArrayList<>()); expectedClassFuncs.get("Silly1").add("class_func_get1"); expectedClassFuncs.get("Silly1").add("class_func_set1"); expectedClassFuncs.put("Silly2", new ArrayList<>()); expectedClassFuncs.get("Silly2").add("class_func_get2"); expectedClassFuncs.get("Silly2").add("class_func_set2"); expectedClassFuncs.get("Silly2").add("class_func_another"); expectedClassFuncs.get("Silly2").add("class_func_another2"); expectedClassFuncs.put("Silly3", new ArrayList<>()); expectedClassFuncs.get("Silly3").add("class_func_get1"); expectedClassFuncs.get("Silly3").add("class_func_set1"); assertEquals(expectedClassFuncs.size(), symbolTable.classMap.size()); assertEquals(expectedClassFuncs.get("Silly1"), symbolTable.classMap.get("Silly1")); assertEquals(expectedClassFuncs.get("Silly2"), symbolTable.classMap.get("Silly2")); assertEquals(expectedClassFuncs.get("Silly3"), symbolTable.classMap.get("Silly3")); } @Test void render_utc_sample1() throws Exception { Utc utc = new Utc("samples/sample1.py"); SymbolTable symbolTable = utc.generateSymbols(); String result = utc.render(symbolTable); if (printDiagnostics) System.out.print("\r\n\r\n"); System.out.println(result); assertNotEquals(0, result.length()); UiSystemClipboard.CopyTo(result); String fromClipboard = UiSystemClipboard.getFrom(); assertEquals(fromClipboard, result); } }
3,438
0.636865
0.624673
92
36.445652
28.053274
96
false
false
0
0
0
0
0
0
0.663043
false
false
1
54b62414e1ed51cf83d5ec4f7a4e96e3b29fcfc0
33,088,428,084,460
733e01273f054601ac8e1f28aabb9a8d12266812
/P532-GameMaker/src/main/java/com/infrastruture/MoveType.java
b81c4b986fd425a540e3600c414c62277c7d25ff
[]
no_license
chetan253/GameMaker
https://github.com/chetan253/GameMaker
8c0c5323aebd05dcabf3ebdea9ee7a5b388f2494
56262c0f91352b001d83eea172a80f86fe075d75
refs/heads/master
2020-04-05T22:32:41.578000
2018-11-12T18:52:14
2018-11-12T18:52:14
157,256,411
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.infrastruture; public enum MoveType { FREE, FIXED, LEFTRIGHT, UPDOWN, FOURWAY }
UTF-8
Java
94
java
MoveType.java
Java
[]
null
[]
package com.infrastruture; public enum MoveType { FREE, FIXED, LEFTRIGHT, UPDOWN, FOURWAY }
94
0.765957
0.765957
5
17.799999
15.341447
40
false
false
0
0
0
0
0
0
1.2
false
false
1
e06c73f45f1b9d991b4e1c6576ad4fd16b7c304c
26,525,718,066,881
9bbf3cb4917513177b8d07f6dc45ebc6393e3ff1
/Service-Tech-Java/sam/org.st.sam.lscminer/src/lscminer/tracer/JavaMethodCallTracer.java
5998b46dd7f8a35448a18e843f750afe0e591407
[]
no_license
bakhansen/service-technology.org
https://github.com/bakhansen/service-technology.org
ff538493e3d23874dbab13b2abe128ff3ee8709c
03479bef94adc927bf824967fc91ed4b4b298ed6
refs/heads/master
2020-03-22T19:54:49.232000
2013-12-20T14:02:58
2013-12-20T14:02:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lscminer.tracer; import gov.nasa.jpf.*; import gov.nasa.jpf.jvm.*; import gov.nasa.jpf.jvm.bytecode.*; import java.util.*; import java.io.*; import lscminer.datastructure.LSCEvent; /** * This class can trace method calls from an arbitrary Java program, * given its class path and a set of test inputs. * * @author Anh Cuong Nguyen */ public class JavaMethodCallTracer extends ListenerAdapter{ boolean traceLib; LinkedList<LSCEvent> currentTrace; // global variable used to log traces String failInput; public JavaMethodCallTracer(boolean traceLib){ this.traceLib = traceLib; currentTrace = new LinkedList<LSCEvent>(); failInput = ""; } public String getFailInput(){ return failInput; } public LSCEvent[][] trace(String mainClass, String classPath, String inputFilePath){ LinkedList<LSCEvent[]> dataList = new LinkedList<LSCEvent[]>(); File inputFile = new File(inputFilePath); String input = ""; try { Scanner inputSc = new Scanner(inputFile); while (inputSc.hasNext()) { /* run the tracer with this particular input */ input = inputSc.nextLine(); String[] args = input.split(" "); String[] jpfArgs = new String[args.length + 2]; /* append args with class path and main class */ System.arraycopy(args, 0, jpfArgs, 2, args.length); jpfArgs[0] = "+classpath=lib/jpf-classes.jar;" + classPath; jpfArgs[1] = mainClass; /* run the tracer */ currentTrace = new LinkedList<LSCEvent>(); // reset the trace Config conf = JPF.createConfig(jpfArgs); JPF jpf = new JPF(conf); jpf.addListener(this); jpf.run(); dataList.add(currentTrace.toArray(new LSCEvent[currentTrace.size()])); System.out.println(currentTrace); } return dataList.toArray(new LSCEvent[dataList.size()][]); } catch (IOException e) { failInput = input; return null; } } @Override public void instructionExecuted(JVM jvm){ Instruction insn = jvm.getLastInstruction(); if (insn instanceof InvokeInstruction){ try { InvokeInstruction callInsn = (InvokeInstruction)insn; if (traceLib || !isJavaLibCall(callInsn)){ String className = callInsn.getMethodInfo().getClassName() + "&" + callInsn.getMethodInfo().getClassInfo().getClassObjectRef(); String callName = callInsn.getInvokedMethod().getReturnTypeName() + " " + callInsn.getInvokedMethod().getName(); callName += "("; String[] callArgs = callInsn.getInvokedMethod().getArgumentTypeNames(); for (int inx = 0; inx < callArgs.length; inx++){ callName += callArgs[inx]; if (inx != callArgs.length-1){ callName += ", "; } } callName += ")"; String callClassName = callInsn.getInvokedMethodClassName() + "&" + callInsn.getInvokedMethod().getClassInfo().getClassObjectRef(); LSCEvent lscEvent = new LSCEvent(className, callClassName, callName); currentTrace.add(lscEvent); } } catch (Exception e){ } } } public boolean isJavaLibCall(InvokeInstruction insn){ String callClass = insn.getInvokedMethodClassName(); if ( callClass.startsWith("java.applet") || callClass.startsWith("java.awt") || callClass.startsWith("java.beans") || callClass.startsWith("java.io") || callClass.startsWith("java.lang") || callClass.startsWith("java.math") || callClass.startsWith("java.net") || callClass.startsWith("java.nio") || callClass.startsWith("java.rmi") || callClass.startsWith("java.security") || callClass.startsWith("java.sql") || callClass.startsWith("java.text") || callClass.startsWith("java.util") || callClass.startsWith("javax.accessibility") || callClass.startsWith("javax.activity") || callClass.startsWith("javax.crypto") || callClass.startsWith("javax.imageio") || callClass.startsWith("javax.management") || callClass.startsWith("javax.naming") || callClass.startsWith("javax.net") || callClass.startsWith("javax.print") || callClass.startsWith("javax.rmi") || callClass.startsWith("javax.security") || callClass.startsWith("javax.sound") || callClass.startsWith("javax.sql") || callClass.startsWith("javax.swing") || callClass.startsWith("javax.transaction") || callClass.startsWith("javax.xml") || callClass.startsWith("sun.misc") ) return true; else return false; } // public static void main(String[] args){ // String[] jpfArgs = {"+classpath=lib/jpf-classes.jar;lib/jpf.jar","lscminer.tracer.HelloWorld"}; // Config conf = JPF.createConfig(jpfArgs); // JPF jpf = new JPF(conf); // jpf.addListener(new JavaMethodCallTracer(false)); // jpf.run(); // } }
UTF-8
Java
5,689
java
JavaMethodCallTracer.java
Java
[ { "context": "class path and a set of test inputs.\n *\n * @author Anh Cuong Nguyen\n */\npublic class JavaMethodCallTracer extends Lis", "end": 344, "score": 0.9998226761817932, "start": 328, "tag": "NAME", "value": "Anh Cuong Nguyen" } ]
null
[]
package lscminer.tracer; import gov.nasa.jpf.*; import gov.nasa.jpf.jvm.*; import gov.nasa.jpf.jvm.bytecode.*; import java.util.*; import java.io.*; import lscminer.datastructure.LSCEvent; /** * This class can trace method calls from an arbitrary Java program, * given its class path and a set of test inputs. * * @author <NAME> */ public class JavaMethodCallTracer extends ListenerAdapter{ boolean traceLib; LinkedList<LSCEvent> currentTrace; // global variable used to log traces String failInput; public JavaMethodCallTracer(boolean traceLib){ this.traceLib = traceLib; currentTrace = new LinkedList<LSCEvent>(); failInput = ""; } public String getFailInput(){ return failInput; } public LSCEvent[][] trace(String mainClass, String classPath, String inputFilePath){ LinkedList<LSCEvent[]> dataList = new LinkedList<LSCEvent[]>(); File inputFile = new File(inputFilePath); String input = ""; try { Scanner inputSc = new Scanner(inputFile); while (inputSc.hasNext()) { /* run the tracer with this particular input */ input = inputSc.nextLine(); String[] args = input.split(" "); String[] jpfArgs = new String[args.length + 2]; /* append args with class path and main class */ System.arraycopy(args, 0, jpfArgs, 2, args.length); jpfArgs[0] = "+classpath=lib/jpf-classes.jar;" + classPath; jpfArgs[1] = mainClass; /* run the tracer */ currentTrace = new LinkedList<LSCEvent>(); // reset the trace Config conf = JPF.createConfig(jpfArgs); JPF jpf = new JPF(conf); jpf.addListener(this); jpf.run(); dataList.add(currentTrace.toArray(new LSCEvent[currentTrace.size()])); System.out.println(currentTrace); } return dataList.toArray(new LSCEvent[dataList.size()][]); } catch (IOException e) { failInput = input; return null; } } @Override public void instructionExecuted(JVM jvm){ Instruction insn = jvm.getLastInstruction(); if (insn instanceof InvokeInstruction){ try { InvokeInstruction callInsn = (InvokeInstruction)insn; if (traceLib || !isJavaLibCall(callInsn)){ String className = callInsn.getMethodInfo().getClassName() + "&" + callInsn.getMethodInfo().getClassInfo().getClassObjectRef(); String callName = callInsn.getInvokedMethod().getReturnTypeName() + " " + callInsn.getInvokedMethod().getName(); callName += "("; String[] callArgs = callInsn.getInvokedMethod().getArgumentTypeNames(); for (int inx = 0; inx < callArgs.length; inx++){ callName += callArgs[inx]; if (inx != callArgs.length-1){ callName += ", "; } } callName += ")"; String callClassName = callInsn.getInvokedMethodClassName() + "&" + callInsn.getInvokedMethod().getClassInfo().getClassObjectRef(); LSCEvent lscEvent = new LSCEvent(className, callClassName, callName); currentTrace.add(lscEvent); } } catch (Exception e){ } } } public boolean isJavaLibCall(InvokeInstruction insn){ String callClass = insn.getInvokedMethodClassName(); if ( callClass.startsWith("java.applet") || callClass.startsWith("java.awt") || callClass.startsWith("java.beans") || callClass.startsWith("java.io") || callClass.startsWith("java.lang") || callClass.startsWith("java.math") || callClass.startsWith("java.net") || callClass.startsWith("java.nio") || callClass.startsWith("java.rmi") || callClass.startsWith("java.security") || callClass.startsWith("java.sql") || callClass.startsWith("java.text") || callClass.startsWith("java.util") || callClass.startsWith("javax.accessibility") || callClass.startsWith("javax.activity") || callClass.startsWith("javax.crypto") || callClass.startsWith("javax.imageio") || callClass.startsWith("javax.management") || callClass.startsWith("javax.naming") || callClass.startsWith("javax.net") || callClass.startsWith("javax.print") || callClass.startsWith("javax.rmi") || callClass.startsWith("javax.security") || callClass.startsWith("javax.sound") || callClass.startsWith("javax.sql") || callClass.startsWith("javax.swing") || callClass.startsWith("javax.transaction") || callClass.startsWith("javax.xml") || callClass.startsWith("sun.misc") ) return true; else return false; } // public static void main(String[] args){ // String[] jpfArgs = {"+classpath=lib/jpf-classes.jar;lib/jpf.jar","lscminer.tracer.HelloWorld"}; // Config conf = JPF.createConfig(jpfArgs); // JPF jpf = new JPF(conf); // jpf.addListener(new JavaMethodCallTracer(false)); // jpf.run(); // } }
5,679
0.556688
0.555458
136
40.830883
24.743258
105
false
false
0
0
0
0
0
0
0.933824
false
false
1
73427c29de83a1a32cae1062179af607946f2d87
14,302,241,098,046
372ca69a81723ae7a51e95862e3eb8c8e7d00de2
/src/test/java/seedu/address/testutil/personutil/TypicalPersonDescriptor.java
6dd17748700df3b48f03b8243ce8a80027a4aee4
[ "MIT" ]
permissive
klementtan/main
https://github.com/klementtan/main
d70dc9ea96a490bd57d572a5b9c3e868a202aeca
d4e108efb53e2d748d7a78ef3ae0118241cd12ed
refs/heads/master
2020-08-03T14:05:33.916000
2019-11-11T16:49:59
2019-11-11T16:49:59
211,779,059
1
0
NOASSERTION
true
2019-10-09T06:02:54
2019-09-30T05:04:18
2019-10-06T18:05:44
2019-10-09T06:02:53
11,842
0
0
0
Java
false
false
package seedu.address.testutil.personutil; import seedu.address.model.person.PersonDescriptor; import seedu.address.model.person.PersonList; import seedu.address.model.person.User; import seedu.address.model.person.exceptions.DuplicatePersonException; /** * Typical person descriptors. */ public class TypicalPersonDescriptor { public static final String WHITESPACE = " "; public static final PersonDescriptor ALICE = new PersonDescriptorBuilder() .withName("Alice Pauline").withAddress("123, Jurong West Ave 6, #08-111") .withEmail("alice@example.com") .withPhone("94351253") .withRemark("Alice is a loser") .withTags("friends") .build(); public static final PersonDescriptor BENSON = new PersonDescriptorBuilder() .withName("Benson Meier") .withAddress("311, Clementi Ave 2, #02-25") .withEmail("johnd@example.com") .withPhone("98765432") .withRemark("Benson is a dumbass") .withTags("owesMoney", "friends") .build(); public static final PersonDescriptor CARL = new PersonDescriptorBuilder() .withName("Carl Kurz") .withPhone("95352563") .withEmail("heinz@example.com") .withAddress("wall street") .withRemark("WTF CARL") .withTags("LALALA").build(); public static final PersonDescriptor DANIEL = new PersonDescriptorBuilder() .withName("Daniel Meier") .withPhone("87652533") .withEmail("cornelia@example.com") .withAddress("10th street") .withRemark("LOL") .withTags("friends").build(); public static final PersonDescriptor ELLE = new PersonDescriptorBuilder() .withName("Elle Meyer").withPhone("9482224") .withRemark("HDL?") .withTags("friends") .withEmail("werner@example.com") .withAddress("michegan ave") .build(); public static final PersonDescriptor FIONA = new PersonDescriptorBuilder() .withName("Fiona Kunz") .withPhone("9482427") .withRemark("BIAP") .withTags("friends") .withEmail("lydia@example.com") .withAddress("little tokyo") .build(); public static final PersonDescriptor GEORGE = new PersonDescriptorBuilder() .withName("George Best") .withPhone("9482442") .withRemark("GEORGEEEEEEE") .withTags("friends") .withEmail("anna@example.com") .withAddress("4th street") .build(); public static final PersonDescriptor ZACK = new PersonDescriptorBuilder() .withName("Zack") .withPhone("81231236") .withTags("friends") .withEmail("zack@example.com") .withAddress("loser street") .withRemark("Im not on the list") .withTags("blabla").build(); public static final PersonDescriptor USER = new PersonDescriptorBuilder() .withName("User").withPhone("99999999").withTags("friends") .withEmail("user@gmail.com").withAddress("bla bla") .withRemark("me").build(); /** * Generates a typical PersonList. * All persons will be added except ZACK. */ public static PersonList generateTypicalPersonList() { PersonList personList = new PersonList(new User(USER)); try { personList.addPerson(ALICE); personList.addPerson(BENSON); personList.addPerson(CARL); personList.addPerson(DANIEL); personList.addPerson(ELLE); personList.addPerson(FIONA); personList.addPerson(GEORGE); } catch (DuplicatePersonException e) { e.printStackTrace(); } return personList; } }
UTF-8
Java
3,933
java
TypicalPersonDescriptor.java
Java
[ { "context": "E = \" \";\n\n public static final PersonDescriptor ALICE = new PersonDescriptorBuilder()\n .with", "end": 429, "score": 0.8716132044792175, "start": 424, "tag": "NAME", "value": "ALICE" }, { "context": " PersonDescriptorBuilder()\n .withName(\"Alice Pauline\").withAddress(\"123, Jurong West Ave 6, #08-111\")\n", "end": 498, "score": 0.9998717904090881, "start": 485, "tag": "NAME", "value": "Alice Pauline" }, { "context": "ong West Ave 6, #08-111\")\n .withEmail(\"alice@example.com\")\n .withPhone(\"94351253\")\n ", "end": 589, "score": 0.9999303817749023, "start": 572, "tag": "EMAIL", "value": "alice@example.com" }, { "context": " .withPhone(\"94351253\")\n .withRemark(\"Alice is a loser\")\n .withTags(\"friends\")\n ", "end": 657, "score": 0.9997727274894714, "start": 652, "tag": "NAME", "value": "Alice" }, { "context": "build();\n\n public static final PersonDescriptor BENSON = new PersonDescriptorBuilder()\n .with", "end": 774, "score": 0.9363493323326111, "start": 768, "tag": "NAME", "value": "BENSON" }, { "context": " PersonDescriptorBuilder()\n .withName(\"Benson Meier\")\n .withAddress(\"311, Clementi Ave 2, ", "end": 842, "score": 0.9998648166656494, "start": 830, "tag": "NAME", "value": "Benson Meier" }, { "context": " Clementi Ave 2, #02-25\")\n .withEmail(\"johnd@example.com\")\n .withPhone(\"98765432\")\n ", "end": 942, "score": 0.9999265670776367, "start": 925, "tag": "EMAIL", "value": "johnd@example.com" }, { "context": " .withPhone(\"98765432\")\n .withRemark(\"Benson is a dumbass\")\n .withTags(\"owesMoney\",", "end": 1011, "score": 0.9998301863670349, "start": 1005, "tag": "NAME", "value": "Benson" }, { "context": "build();\n\n public static final PersonDescriptor CARL = new PersonDescriptorBuilder()\n .with", "end": 1141, "score": 0.903050422668457, "start": 1137, "tag": "NAME", "value": "CARL" }, { "context": " PersonDescriptorBuilder()\n .withName(\"Carl Kurz\")\n .withPhone(\"95352563\")\n ", "end": 1206, "score": 0.9998446702957153, "start": 1197, "tag": "NAME", "value": "Carl Kurz" }, { "context": " .withPhone(\"95352563\")\n .withEmail(\"heinz@example.com\")\n .withAddress(\"wall street\")\n ", "end": 1285, "score": 0.9999211430549622, "start": 1268, "tag": "EMAIL", "value": "heinz@example.com" }, { "context": "build();\n\n public static final PersonDescriptor DANIEL = new PersonDescriptorBuilder()\n .with", "end": 1453, "score": 0.9277532696723938, "start": 1447, "tag": "NAME", "value": "DANIEL" }, { "context": " PersonDescriptorBuilder()\n .withName(\"Daniel Meier\")\n .withPhone(\"87652533\")\n ", "end": 1521, "score": 0.999858021736145, "start": 1509, "tag": "NAME", "value": "Daniel Meier" }, { "context": " .withPhone(\"87652533\")\n .withEmail(\"cornelia@example.com\")\n .withAddress(\"10th street\")\n ", "end": 1603, "score": 0.9999256730079651, "start": 1583, "tag": "EMAIL", "value": "cornelia@example.com" }, { "context": "build();\n\n public static final PersonDescriptor ELLE = new PersonDescriptorBuilder()\n .with", "end": 1765, "score": 0.7202097177505493, "start": 1761, "tag": "NAME", "value": "ELLE" }, { "context": " PersonDescriptorBuilder()\n .withName(\"Elle Meyer\").withPhone(\"9482224\")\n .withRemark(\"H", "end": 1831, "score": 0.9998218417167664, "start": 1821, "tag": "NAME", "value": "Elle Meyer" }, { "context": " .withTags(\"friends\")\n .withEmail(\"werner@example.com\")\n .withAddress(\"michegan ave\")\n ", "end": 1962, "score": 0.9999263882637024, "start": 1944, "tag": "EMAIL", "value": "werner@example.com" }, { "context": "build();\n\n public static final PersonDescriptor FIONA = new PersonDescriptorBuilder()\n .wit", "end": 2074, "score": 0.9026496410369873, "start": 2070, "tag": "NAME", "value": "FION" }, { "context": " PersonDescriptorBuilder()\n .withName(\"Fiona Kunz\")\n .withPhone(\"9482427\")\n .", "end": 2141, "score": 0.9998028874397278, "start": 2131, "tag": "NAME", "value": "Fiona Kunz" }, { "context": " .withTags(\"friends\")\n .withEmail(\"lydia@example.com\")\n .withAddress(\"little tokyo\")\n ", "end": 2284, "score": 0.9999266266822815, "start": 2267, "tag": "EMAIL", "value": "lydia@example.com" }, { "context": " PersonDescriptorBuilder()\n .withName(\"George Best\")\n .withPhone(\"9482442\")\n .", "end": 2465, "score": 0.9997634887695312, "start": 2454, "tag": "NAME", "value": "George Best" }, { "context": " .withTags(\"friends\")\n .withEmail(\"anna@example.com\")\n .withAddress(\"4th street\")\n ", "end": 2615, "score": 0.9999238848686218, "start": 2599, "tag": "EMAIL", "value": "anna@example.com" }, { "context": "build();\n\n public static final PersonDescriptor ZACK = new PersonDescriptorBuilder()\n .w", "end": 2722, "score": 0.8456898927688599, "start": 2721, "tag": "NAME", "value": "Z" }, { "context": " PersonDescriptorBuilder()\n .withName(\"Zack\")\n .withPhone(\"81231236\")\n ", "end": 2785, "score": 0.9996249675750732, "start": 2781, "tag": "NAME", "value": "Zack" }, { "context": " .withTags(\"friends\")\n .withEmail(\"zack@example.com\")\n .withAddress(\"loser street\")\n ", "end": 2896, "score": 0.9999215602874756, "start": 2880, "tag": "EMAIL", "value": "zack@example.com" }, { "context": " PersonDescriptorBuilder()\n .withName(\"User\").withPhone(\"99999999\").withTags(\"friends\")\n ", "end": 3133, "score": 0.9995286464691162, "start": 3129, "tag": "NAME", "value": "User" }, { "context": "999\").withTags(\"friends\")\n .withEmail(\"user@gmail.com\").withAddress(\"bla bla\")\n .withRemark(", "end": 3216, "score": 0.9999253153800964, "start": 3202, "tag": "EMAIL", "value": "user@gmail.com" }, { "context": ");\n try {\n personList.addPerson(ALICE);\n personList.addPerson(BENSON);\n ", "end": 3558, "score": 0.9793716073036194, "start": 3553, "tag": "NAME", "value": "ALICE" }, { "context": "ddPerson(ALICE);\n personList.addPerson(BENSON);\n personList.addPerson(CARL);\n ", "end": 3600, "score": 0.9759065508842468, "start": 3594, "tag": "NAME", "value": "BENSON" }, { "context": "dPerson(BENSON);\n personList.addPerson(CARL);\n personList.addPerson(DANIEL);\n ", "end": 3640, "score": 0.9839826822280884, "start": 3636, "tag": "NAME", "value": "CARL" }, { "context": "addPerson(CARL);\n personList.addPerson(DANIEL);\n personList.addPerson(ELLE);\n ", "end": 3682, "score": 0.9911970496177673, "start": 3676, "tag": "NAME", "value": "DANIEL" }, { "context": "dPerson(DANIEL);\n personList.addPerson(ELLE);\n personList.addPerson(FIONA);\n ", "end": 3722, "score": 0.979029655456543, "start": 3718, "tag": "NAME", "value": "ELLE" }, { "context": "addPerson(ELLE);\n personList.addPerson(FIONA);\n personList.addPerson(GEORGE);\n ", "end": 3763, "score": 0.9811752438545227, "start": 3758, "tag": "NAME", "value": "FIONA" }, { "context": "ddPerson(FIONA);\n personList.addPerson(GEORGE);\n } catch (DuplicatePersonException e", "end": 3801, "score": 0.6599960327148438, "start": 3799, "tag": "NAME", "value": "GE" } ]
null
[]
package seedu.address.testutil.personutil; import seedu.address.model.person.PersonDescriptor; import seedu.address.model.person.PersonList; import seedu.address.model.person.User; import seedu.address.model.person.exceptions.DuplicatePersonException; /** * Typical person descriptors. */ public class TypicalPersonDescriptor { public static final String WHITESPACE = " "; public static final PersonDescriptor ALICE = new PersonDescriptorBuilder() .withName("<NAME>").withAddress("123, Jurong West Ave 6, #08-111") .withEmail("<EMAIL>") .withPhone("94351253") .withRemark("Alice is a loser") .withTags("friends") .build(); public static final PersonDescriptor BENSON = new PersonDescriptorBuilder() .withName("<NAME>") .withAddress("311, Clementi Ave 2, #02-25") .withEmail("<EMAIL>") .withPhone("98765432") .withRemark("Benson is a dumbass") .withTags("owesMoney", "friends") .build(); public static final PersonDescriptor CARL = new PersonDescriptorBuilder() .withName("<NAME>") .withPhone("95352563") .withEmail("<EMAIL>") .withAddress("wall street") .withRemark("WTF CARL") .withTags("LALALA").build(); public static final PersonDescriptor DANIEL = new PersonDescriptorBuilder() .withName("<NAME>") .withPhone("87652533") .withEmail("<EMAIL>") .withAddress("10th street") .withRemark("LOL") .withTags("friends").build(); public static final PersonDescriptor ELLE = new PersonDescriptorBuilder() .withName("<NAME>").withPhone("9482224") .withRemark("HDL?") .withTags("friends") .withEmail("<EMAIL>") .withAddress("michegan ave") .build(); public static final PersonDescriptor FIONA = new PersonDescriptorBuilder() .withName("<NAME>") .withPhone("9482427") .withRemark("BIAP") .withTags("friends") .withEmail("<EMAIL>") .withAddress("little tokyo") .build(); public static final PersonDescriptor GEORGE = new PersonDescriptorBuilder() .withName("<NAME>") .withPhone("9482442") .withRemark("GEORGEEEEEEE") .withTags("friends") .withEmail("<EMAIL>") .withAddress("4th street") .build(); public static final PersonDescriptor ZACK = new PersonDescriptorBuilder() .withName("Zack") .withPhone("81231236") .withTags("friends") .withEmail("<EMAIL>") .withAddress("loser street") .withRemark("Im not on the list") .withTags("blabla").build(); public static final PersonDescriptor USER = new PersonDescriptorBuilder() .withName("User").withPhone("99999999").withTags("friends") .withEmail("<EMAIL>").withAddress("bla bla") .withRemark("me").build(); /** * Generates a typical PersonList. * All persons will be added except ZACK. */ public static PersonList generateTypicalPersonList() { PersonList personList = new PersonList(new User(USER)); try { personList.addPerson(ALICE); personList.addPerson(BENSON); personList.addPerson(CARL); personList.addPerson(DANIEL); personList.addPerson(ELLE); personList.addPerson(FIONA); personList.addPerson(GEORGE); } catch (DuplicatePersonException e) { e.printStackTrace(); } return personList; } }
3,809
0.59878
0.576151
107
35.757008
21.75902
85
false
false
0
0
0
0
0
0
0.280374
false
false
1
30ea77fa07b8250ddbf57d950def649637f6f537
23,287,312,695,504
1963f999bfee40582e7849338ea772c86dfa0bcd
/user-service/src/main/java/com/ut/user/cache/ICacheService.java
45d47aa8aa4d784bcaf77d78186a7027d213e726
[]
no_license
shindoyang/admission
https://github.com/shindoyang/admission
9aa41759ca2f44e65b0751ab3680774278c15292
b50689c4928880c820b1f3f9ddf08bd60e188bd1
refs/heads/main
2023-06-12T22:38:02.162000
2021-07-02T06:34:00
2021-07-02T06:34:00
381,985,604
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ut.user.cache; public interface ICacheService { String setex(String key, String value); String setex(String key, int seconds, String value); String get(String key); }
UTF-8
Java
195
java
ICacheService.java
Java
[]
null
[]
package com.ut.user.cache; public interface ICacheService { String setex(String key, String value); String setex(String key, int seconds, String value); String get(String key); }
195
0.712821
0.712821
10
18.5
19.981241
56
true
false
0
0
0
0
0
0
0.7
false
false
1
726181d85219113d35f93ba28030fb52cd6ffd18
12,558,484,390,379
73c6071d6b99b9ac5b24655df98dbdc3d6b89dd6
/app/src/main/java/carcar/alex/cityguide/Trolley.java
263fbd71dce4f186ed9ddab3db08e9713a051d04
[]
no_license
alexcarcar/SanFranciscoCityGuide
https://github.com/alexcarcar/SanFranciscoCityGuide
06b62f50639e8bb6bcd427a8aa6b5f59a06853e6
f9114d3550cce555e00278139084ceb7d60b6b9d
refs/heads/master
2018-01-08T14:02:21.238000
2015-10-14T21:01:47
2015-10-14T21:01:47
44,276,108
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package carcar.alex.cityguide; import android.app.Activity; import android.os.Bundle; /** * Created by Local User on 10/14/2015. */ public class Trolley extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.trolley); } }
UTF-8
Java
341
java
Trolley.java
Java
[ { "context": "vity;\nimport android.os.Bundle;\n\n/**\n * Created by Local User on 10/14/2015.\n */\npublic class Trolley extends A", "end": 116, "score": 0.5530762672424316, "start": 106, "tag": "USERNAME", "value": "Local User" } ]
null
[]
package carcar.alex.cityguide; import android.app.Activity; import android.os.Bundle; /** * Created by Local User on 10/14/2015. */ public class Trolley extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.trolley); } }
341
0.715542
0.692082
15
21.733334
18.52014
56
false
false
0
0
0
0
0
0
0.333333
false
false
1
2f5d2e71aa021c9253a381c86ebeafca06cd545b
30,176,440,243,964
3cc849f555953147e8051f623b8552ac17854399
/src/com/rds/statistics/service/impl/RdsStatisticsWagesServiceImpl.java
c0ce6ede4269990b0bd40b56f8ef46947dc3fff8
[]
no_license
clownlin22/judicial-web
https://github.com/clownlin22/judicial-web
c8444b17f16ec9a567d43786efce6ff8ce0c967b
6350aa62353187dc1ee5dac5b1f6322e5c2982c8
refs/heads/master
2020-05-07T22:23:21.426000
2019-04-12T06:07:00
2019-04-12T06:07:00
180,913,232
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rds.statistics.service.impl; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.format.Colour; import jxl.format.UnderlineStyle; import jxl.write.Label; import jxl.write.Number; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.rds.code.utils.uuid.UUIDUtil; import com.rds.statistics.mapper.RdsStatisticsWagesMapper; import com.rds.statistics.model.RdsFinanceWagesModel; import com.rds.statistics.service.RdsStatisticsWagesService; @Service public class RdsStatisticsWagesServiceImpl implements RdsStatisticsWagesService { @Autowired private RdsStatisticsWagesMapper rdsStatisticsWagesMapper; @Override public List<Object> queryAllPage(Map<String, Object> params) { return rdsStatisticsWagesMapper.queryAllPage(params); } @Override public int queryAllCount(Map<String, Object> params) { return rdsStatisticsWagesMapper.queryAllCount(params); } @Override public boolean insertWages(Map<String, Object> params) { return rdsStatisticsWagesMapper.insertWages(params); } @Override public List<Object> queryAll(Map<String, Object> params) { return rdsStatisticsWagesMapper.queryAll(params); } @Override public boolean deleteWages(Map<String, Object> params) { return rdsStatisticsWagesMapper.deleteWages(params); } @Override public Map<String, Object> uploadWages(String wages_month, String attachmentPath, String userid, String attachment_id) throws Exception { String msg = "操作成功"; List<Map<String, Object>> lists = new ArrayList<>(); jxl.Workbook readwb = null; try { InputStream instream = new FileInputStream(attachmentPath); readwb = Workbook.getWorkbook(instream); // Sheet的下标是从0开始 // 获取第一张Sheet表 Sheet readsheet = readwb.getSheet(0); // 获取Sheet表中所包含的总列数 int rsColumns = readsheet.getColumns(); // 获取Sheet表中所包含的总行数 int rsRows = readsheet.getRows(); // 获取指定单元格的对象引用 for (int i = 0; i < rsRows; i++) { String id = UUIDUtil.getUUID(); String user_dept_level1 = ""; String user_dept_level2 = ""; String user_dept_level3 = ""; String wages = ""; String wages_name = ""; Map<String, Object> map = new HashMap<>(); map.put("id", id); map.put("create_per", userid); map.put("wages_month", wages_month); map.put("attachment_id", attachment_id); for (int j = 0; j < rsColumns; j++) { Cell cell = readsheet.getCell(j, i); if (j == 0) { wages_name = cell.getContents().trim(); map.put("wages_name", wages_name.trim()); } if (j == 1) { user_dept_level1 = cell.getContents().trim(); map.put("user_dept_level1", user_dept_level1.trim()); } if (j == 2) { user_dept_level2 = cell.getContents().trim(); map.put("user_dept_level2", user_dept_level2.trim()); } if (j == 3) { user_dept_level3 = cell.getContents().trim(); map.put("user_dept_level3", user_dept_level3.trim()); } if (j == 4) { wages = cell.getContents().trim(); map.put("wages", wages.trim()); } } lists.add(map); } Map<String, Object> params = new HashMap<>(); params.put("list", lists); // 插入人员成本表 if (!rdsStatisticsWagesMapper.insertWages(params)) { return setMsg(true, false, msg + "上传失败,请联系管理员"); } } catch (Exception e) { e.printStackTrace(); return setMsg(true, false, msg + "上传失败,请联系管理员"); } return setMsg(true, true, msg); } private Map<String, Object> setMsg(boolean success, boolean result, String message) { Map<String, Object> map = new HashMap<String, Object>(); map.put("success", success); map.put("result", result); map.put("message", message); return map; } @Override public List<Object> queryWagesAttachment(Map<String, Object> params) { return rdsStatisticsWagesMapper.queryWagesAttachment(params); } @Override public boolean insertWagesAttachment(Map<String, Object> params) { return rdsStatisticsWagesMapper.insertWagesAttachment(params); } @Override public boolean updateWagesAttachment(Map<String, Object> params) { return rdsStatisticsWagesMapper.updateWagesAttachment(params); } @Override public void exportWagesInfo(Map<String, Object> params, HttpServletResponse httpResponse) throws Exception { List<Object> objs = rdsStatisticsWagesMapper.queryAllPage(params); // excel表格列头 Object[] titles = { "人工成本归属划分核心部分", "", "", "", "", "", "", "发生月份", "人工成本", "", "", "", "", "", "创建人", "创建日期", "备注"}; // 表格实体 List<List<Object>> bodys = new ArrayList<List<Object>>(); List<Object> firstobject = new ArrayList<Object>(); firstobject.add("成本归属事业部"); firstobject.add("成本归属二级部门"); firstobject.add("成本归属三级部门"); firstobject.add("成本归属四级部门"); firstobject.add("成本归属五级部门"); firstobject.add("成本归属人"); firstobject.add("归属人工号"); firstobject.add(""); firstobject.add("合计"); firstobject.add("社保"); firstobject.add("公积金"); firstobject.add("月中部分(底薪)"); firstobject.add("月底部分(绩效等)"); firstobject.add("其他"); firstobject.add(""); firstobject.add(""); firstobject.add(""); bodys.add(firstobject); // 循环案例列表拼装表格一行 for (int i = 0; i < objs.size(); i++) { List<Object> objects = new ArrayList<Object>(); RdsFinanceWagesModel rdsFinanceWagesModel = (RdsFinanceWagesModel)objs .get(i); objects.add(rdsFinanceWagesModel.getUser_dept_level1()); objects.add(rdsFinanceWagesModel.getUser_dept_level2()); objects.add(rdsFinanceWagesModel.getUser_dept_level3()); objects.add(rdsFinanceWagesModel.getUser_dept_level4()); objects.add(rdsFinanceWagesModel.getUser_dept_level5()); objects.add(rdsFinanceWagesModel.getWages_name()); objects.add(rdsFinanceWagesModel.getWorkcode()); objects.add(rdsFinanceWagesModel.getWages_month()); objects.add(rdsFinanceWagesModel.getWagesTemp()); objects.add(rdsFinanceWagesModel.getWages_socialTemp()); objects.add(rdsFinanceWagesModel.getWages_accumulationTemp()); objects.add(rdsFinanceWagesModel.getWages_middleTemp()); objects.add(rdsFinanceWagesModel.getWages_endTemp()); objects.add(rdsFinanceWagesModel.getWages_otherTemp()); objects.add(rdsFinanceWagesModel.getCreate_pername()); objects.add(rdsFinanceWagesModel.getCreate_date()); objects.add(rdsFinanceWagesModel.getRemark()); bodys.add(objects); } try { OutputStream os = httpResponse.getOutputStream();// 取得输出流 httpResponse.reset();// 清空输出流 String fname = new String("人工成本明细".getBytes("gb2312"), "iso8859-1"); httpResponse.setHeader("Content-disposition", "attachment; filename=" + fname + ".xls");// 设定输出文件头 httpResponse.setContentType("application/vnd.ms-excel"); WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件 WritableSheet wsheet = wbook.createSheet("sheet1", 0); // sheet名称 for (int i = 0; i < titles.length; i++) { Label label = new Label(i, 0, String.valueOf(titles[i])); wsheet.addCell(label); } for (int i = 0; i < bodys.size(); i++) { for (int j = 0; j < bodys.get(i).size(); j++) { if (bodys.get(i).get(j) != null) { if (bodys.get(i).get(j) instanceof String) { Label label = new Label(j, i + 1, String.valueOf(bodys.get(i).get(j))); wsheet.addCell(label); } else { Number number = new Number(j, i + 1, Float.valueOf(String.valueOf(bodys.get(i) .get(j)))); wsheet.addCell(number); } } else { Label label = new Label(j, i + 1, ""); wsheet.addCell(label); } } } wsheet.mergeCells(0, 0, 6, 0); WritableCellFormat writableCellFormat = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat.setAlignment(jxl.format.Alignment.CENTRE); for (int i = 0; i < 6; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat); } wsheet.getWritableCell(6, 0).setCellFormat(writableCellFormat); for (int i = 0; i <= 6; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat); } wsheet.mergeCells(7, 0, 7, 1); WritableCellFormat writableCellFormat1 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat1.setAlignment(jxl.format.Alignment.CENTRE); writableCellFormat1 .setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); for (int i = 7; i <= 7; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat1); } for (int i = 7; i <= 7; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat1); } wsheet.mergeCells(8, 0, 13, 0); WritableCellFormat writableCellFormat2 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat2.setAlignment(jxl.format.Alignment.CENTRE); for (int i = 8; i < 13; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat2); } for (int i = 8; i <= 13; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat2); } wsheet.mergeCells(14, 0, 14, 1); WritableCellFormat writableCellFormat3 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat3.setAlignment(jxl.format.Alignment.CENTRE); writableCellFormat3.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); for (int i = 14; i <= 14; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat3); } for (int i = 14; i <= 14; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat3); } wsheet.mergeCells(15, 0, 15, 1); WritableCellFormat writableCellFormat4 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat4.setAlignment(jxl.format.Alignment.CENTRE); writableCellFormat4.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); for (int i = 15; i <= 15; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat4); } for (int i = 15; i <= 15; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat4); } wsheet.mergeCells(16, 0, 16, 1); WritableCellFormat writableCellFormat5 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat5.setAlignment(jxl.format.Alignment.CENTRE); writableCellFormat5.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); for (int i = 16; i <= 16; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat5); } for (int i = 16; i <= 164; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat5); } // 主体内容生成结束 wbook.write(); // 写入文件 wbook.close(); os.close(); // 关闭流 } catch (Exception e) { e.printStackTrace(); } // String filename = "苏博人员成本"; // List<Object> list = rdsStatisticsWagesMapper.queryAllPage(params); // Object[] titles = { "人员姓名", "月份", "一级部门", "二级部门", "三级部门", "总成本", // "公司社保", "公积金", "月中小计","月底小计","创建时间","备注" }; // List<List<Object>> bodys = new ArrayList<List<Object>>(); // for (int i = 0; i < list.size(); i++) { // List<Object> objects = new ArrayList<Object>(); // RdsFinanceWagesModel rdsFinanceWagesModel = // (RdsFinanceWagesModel)list.get(i); // objects.add(rdsFinanceWagesModel.getWages_name()); // objects.add(rdsFinanceWagesModel.getWages_month()); // objects.add(rdsFinanceWagesModel.getUser_dept_level1()); // objects.add(rdsFinanceWagesModel.getUser_dept_level2()); // objects.add(rdsFinanceWagesModel.getUser_dept_level3()); // objects.add(rdsFinanceWagesModel.getWagesTemp()); // objects.add(rdsFinanceWagesModel.getWages_accumulationTemp()); // objects.add(rdsFinanceWagesModel.getWages_socialTemp()); // objects.add(rdsFinanceWagesModel.getWages_middleTemp()); // objects.add(rdsFinanceWagesModel.getWages_endTemp()); // objects.add(rdsFinanceWagesModel.getCreate_date()); // objects.add(rdsFinanceWagesModel.getRemark()); // bodys.add(objects); // } // ExportUtils.export(response, filename, titles, bodys, "苏博人员成本"); } }
UTF-8
Java
13,639
java
RdsStatisticsWagesServiceImpl.java
Java
[]
null
[]
package com.rds.statistics.service.impl; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.format.Colour; import jxl.format.UnderlineStyle; import jxl.write.Label; import jxl.write.Number; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.rds.code.utils.uuid.UUIDUtil; import com.rds.statistics.mapper.RdsStatisticsWagesMapper; import com.rds.statistics.model.RdsFinanceWagesModel; import com.rds.statistics.service.RdsStatisticsWagesService; @Service public class RdsStatisticsWagesServiceImpl implements RdsStatisticsWagesService { @Autowired private RdsStatisticsWagesMapper rdsStatisticsWagesMapper; @Override public List<Object> queryAllPage(Map<String, Object> params) { return rdsStatisticsWagesMapper.queryAllPage(params); } @Override public int queryAllCount(Map<String, Object> params) { return rdsStatisticsWagesMapper.queryAllCount(params); } @Override public boolean insertWages(Map<String, Object> params) { return rdsStatisticsWagesMapper.insertWages(params); } @Override public List<Object> queryAll(Map<String, Object> params) { return rdsStatisticsWagesMapper.queryAll(params); } @Override public boolean deleteWages(Map<String, Object> params) { return rdsStatisticsWagesMapper.deleteWages(params); } @Override public Map<String, Object> uploadWages(String wages_month, String attachmentPath, String userid, String attachment_id) throws Exception { String msg = "操作成功"; List<Map<String, Object>> lists = new ArrayList<>(); jxl.Workbook readwb = null; try { InputStream instream = new FileInputStream(attachmentPath); readwb = Workbook.getWorkbook(instream); // Sheet的下标是从0开始 // 获取第一张Sheet表 Sheet readsheet = readwb.getSheet(0); // 获取Sheet表中所包含的总列数 int rsColumns = readsheet.getColumns(); // 获取Sheet表中所包含的总行数 int rsRows = readsheet.getRows(); // 获取指定单元格的对象引用 for (int i = 0; i < rsRows; i++) { String id = UUIDUtil.getUUID(); String user_dept_level1 = ""; String user_dept_level2 = ""; String user_dept_level3 = ""; String wages = ""; String wages_name = ""; Map<String, Object> map = new HashMap<>(); map.put("id", id); map.put("create_per", userid); map.put("wages_month", wages_month); map.put("attachment_id", attachment_id); for (int j = 0; j < rsColumns; j++) { Cell cell = readsheet.getCell(j, i); if (j == 0) { wages_name = cell.getContents().trim(); map.put("wages_name", wages_name.trim()); } if (j == 1) { user_dept_level1 = cell.getContents().trim(); map.put("user_dept_level1", user_dept_level1.trim()); } if (j == 2) { user_dept_level2 = cell.getContents().trim(); map.put("user_dept_level2", user_dept_level2.trim()); } if (j == 3) { user_dept_level3 = cell.getContents().trim(); map.put("user_dept_level3", user_dept_level3.trim()); } if (j == 4) { wages = cell.getContents().trim(); map.put("wages", wages.trim()); } } lists.add(map); } Map<String, Object> params = new HashMap<>(); params.put("list", lists); // 插入人员成本表 if (!rdsStatisticsWagesMapper.insertWages(params)) { return setMsg(true, false, msg + "上传失败,请联系管理员"); } } catch (Exception e) { e.printStackTrace(); return setMsg(true, false, msg + "上传失败,请联系管理员"); } return setMsg(true, true, msg); } private Map<String, Object> setMsg(boolean success, boolean result, String message) { Map<String, Object> map = new HashMap<String, Object>(); map.put("success", success); map.put("result", result); map.put("message", message); return map; } @Override public List<Object> queryWagesAttachment(Map<String, Object> params) { return rdsStatisticsWagesMapper.queryWagesAttachment(params); } @Override public boolean insertWagesAttachment(Map<String, Object> params) { return rdsStatisticsWagesMapper.insertWagesAttachment(params); } @Override public boolean updateWagesAttachment(Map<String, Object> params) { return rdsStatisticsWagesMapper.updateWagesAttachment(params); } @Override public void exportWagesInfo(Map<String, Object> params, HttpServletResponse httpResponse) throws Exception { List<Object> objs = rdsStatisticsWagesMapper.queryAllPage(params); // excel表格列头 Object[] titles = { "人工成本归属划分核心部分", "", "", "", "", "", "", "发生月份", "人工成本", "", "", "", "", "", "创建人", "创建日期", "备注"}; // 表格实体 List<List<Object>> bodys = new ArrayList<List<Object>>(); List<Object> firstobject = new ArrayList<Object>(); firstobject.add("成本归属事业部"); firstobject.add("成本归属二级部门"); firstobject.add("成本归属三级部门"); firstobject.add("成本归属四级部门"); firstobject.add("成本归属五级部门"); firstobject.add("成本归属人"); firstobject.add("归属人工号"); firstobject.add(""); firstobject.add("合计"); firstobject.add("社保"); firstobject.add("公积金"); firstobject.add("月中部分(底薪)"); firstobject.add("月底部分(绩效等)"); firstobject.add("其他"); firstobject.add(""); firstobject.add(""); firstobject.add(""); bodys.add(firstobject); // 循环案例列表拼装表格一行 for (int i = 0; i < objs.size(); i++) { List<Object> objects = new ArrayList<Object>(); RdsFinanceWagesModel rdsFinanceWagesModel = (RdsFinanceWagesModel)objs .get(i); objects.add(rdsFinanceWagesModel.getUser_dept_level1()); objects.add(rdsFinanceWagesModel.getUser_dept_level2()); objects.add(rdsFinanceWagesModel.getUser_dept_level3()); objects.add(rdsFinanceWagesModel.getUser_dept_level4()); objects.add(rdsFinanceWagesModel.getUser_dept_level5()); objects.add(rdsFinanceWagesModel.getWages_name()); objects.add(rdsFinanceWagesModel.getWorkcode()); objects.add(rdsFinanceWagesModel.getWages_month()); objects.add(rdsFinanceWagesModel.getWagesTemp()); objects.add(rdsFinanceWagesModel.getWages_socialTemp()); objects.add(rdsFinanceWagesModel.getWages_accumulationTemp()); objects.add(rdsFinanceWagesModel.getWages_middleTemp()); objects.add(rdsFinanceWagesModel.getWages_endTemp()); objects.add(rdsFinanceWagesModel.getWages_otherTemp()); objects.add(rdsFinanceWagesModel.getCreate_pername()); objects.add(rdsFinanceWagesModel.getCreate_date()); objects.add(rdsFinanceWagesModel.getRemark()); bodys.add(objects); } try { OutputStream os = httpResponse.getOutputStream();// 取得输出流 httpResponse.reset();// 清空输出流 String fname = new String("人工成本明细".getBytes("gb2312"), "iso8859-1"); httpResponse.setHeader("Content-disposition", "attachment; filename=" + fname + ".xls");// 设定输出文件头 httpResponse.setContentType("application/vnd.ms-excel"); WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件 WritableSheet wsheet = wbook.createSheet("sheet1", 0); // sheet名称 for (int i = 0; i < titles.length; i++) { Label label = new Label(i, 0, String.valueOf(titles[i])); wsheet.addCell(label); } for (int i = 0; i < bodys.size(); i++) { for (int j = 0; j < bodys.get(i).size(); j++) { if (bodys.get(i).get(j) != null) { if (bodys.get(i).get(j) instanceof String) { Label label = new Label(j, i + 1, String.valueOf(bodys.get(i).get(j))); wsheet.addCell(label); } else { Number number = new Number(j, i + 1, Float.valueOf(String.valueOf(bodys.get(i) .get(j)))); wsheet.addCell(number); } } else { Label label = new Label(j, i + 1, ""); wsheet.addCell(label); } } } wsheet.mergeCells(0, 0, 6, 0); WritableCellFormat writableCellFormat = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat.setAlignment(jxl.format.Alignment.CENTRE); for (int i = 0; i < 6; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat); } wsheet.getWritableCell(6, 0).setCellFormat(writableCellFormat); for (int i = 0; i <= 6; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat); } wsheet.mergeCells(7, 0, 7, 1); WritableCellFormat writableCellFormat1 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat1.setAlignment(jxl.format.Alignment.CENTRE); writableCellFormat1 .setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); for (int i = 7; i <= 7; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat1); } for (int i = 7; i <= 7; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat1); } wsheet.mergeCells(8, 0, 13, 0); WritableCellFormat writableCellFormat2 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat2.setAlignment(jxl.format.Alignment.CENTRE); for (int i = 8; i < 13; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat2); } for (int i = 8; i <= 13; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat2); } wsheet.mergeCells(14, 0, 14, 1); WritableCellFormat writableCellFormat3 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat3.setAlignment(jxl.format.Alignment.CENTRE); writableCellFormat3.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); for (int i = 14; i <= 14; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat3); } for (int i = 14; i <= 14; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat3); } wsheet.mergeCells(15, 0, 15, 1); WritableCellFormat writableCellFormat4 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat4.setAlignment(jxl.format.Alignment.CENTRE); writableCellFormat4.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); for (int i = 15; i <= 15; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat4); } for (int i = 15; i <= 15; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat4); } wsheet.mergeCells(16, 0, 16, 1); WritableCellFormat writableCellFormat5 = new WritableCellFormat( new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK)); writableCellFormat5.setAlignment(jxl.format.Alignment.CENTRE); writableCellFormat5.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); for (int i = 16; i <= 16; i++) { wsheet.mergeCells(i, 0, i, 1); wsheet.getWritableCell(i, 0).setCellFormat(writableCellFormat5); } for (int i = 16; i <= 164; i++) { wsheet.getWritableCell(i, 1).setCellFormat(writableCellFormat5); } // 主体内容生成结束 wbook.write(); // 写入文件 wbook.close(); os.close(); // 关闭流 } catch (Exception e) { e.printStackTrace(); } // String filename = "苏博人员成本"; // List<Object> list = rdsStatisticsWagesMapper.queryAllPage(params); // Object[] titles = { "人员姓名", "月份", "一级部门", "二级部门", "三级部门", "总成本", // "公司社保", "公积金", "月中小计","月底小计","创建时间","备注" }; // List<List<Object>> bodys = new ArrayList<List<Object>>(); // for (int i = 0; i < list.size(); i++) { // List<Object> objects = new ArrayList<Object>(); // RdsFinanceWagesModel rdsFinanceWagesModel = // (RdsFinanceWagesModel)list.get(i); // objects.add(rdsFinanceWagesModel.getWages_name()); // objects.add(rdsFinanceWagesModel.getWages_month()); // objects.add(rdsFinanceWagesModel.getUser_dept_level1()); // objects.add(rdsFinanceWagesModel.getUser_dept_level2()); // objects.add(rdsFinanceWagesModel.getUser_dept_level3()); // objects.add(rdsFinanceWagesModel.getWagesTemp()); // objects.add(rdsFinanceWagesModel.getWages_accumulationTemp()); // objects.add(rdsFinanceWagesModel.getWages_socialTemp()); // objects.add(rdsFinanceWagesModel.getWages_middleTemp()); // objects.add(rdsFinanceWagesModel.getWages_endTemp()); // objects.add(rdsFinanceWagesModel.getCreate_date()); // objects.add(rdsFinanceWagesModel.getRemark()); // bodys.add(objects); // } // ExportUtils.export(response, filename, titles, bodys, "苏博人员成本"); } }
13,639
0.694455
0.680574
370
34.243244
23.620199
81
false
false
0
0
0
0
0
0
3.705405
false
false
1
77e76f01dd231e05704ba39a69c965c7bf93c8c8
28,750,511,097,588
0ba37d0e41ee5a99187e3bc2d430594a1817b07c
/src/main/java/br/com/cardapiododia/model/request/CardapioDatesRequest.java
60f3213c741f9a2063234bee1aaeb1b2ac29e2b5
[]
no_license
tenazatto/cardapiododia
https://github.com/tenazatto/cardapiododia
4df90dbc58a19cefa980eb197ec00c80fa05f603
e804f386b934bb0c8531d22c2511aef95bac2466
refs/heads/master
2020-09-06T04:16:29.003000
2019-11-07T20:01:59
2019-11-07T20:01:59
220,317,993
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.cardapiododia.model.request; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.NotNull; import java.time.LocalDate; import java.util.List; @Getter @Setter public class CardapioDatesRequest { @NotNull @JsonDeserialize(contentUsing = LocalDateDeserializer.class) @JsonSerialize(contentUsing = LocalDateSerializer.class) private List<LocalDate> dates; }
UTF-8
Java
689
java
CardapioDatesRequest.java
Java
[]
null
[]
package br.com.cardapiododia.model.request; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.NotNull; import java.time.LocalDate; import java.util.List; @Getter @Setter public class CardapioDatesRequest { @NotNull @JsonDeserialize(contentUsing = LocalDateDeserializer.class) @JsonSerialize(contentUsing = LocalDateSerializer.class) private List<LocalDate> dates; }
689
0.827286
0.818578
21
31.809525
25.104769
73
false
false
0
0
0
0
0
0
0.52381
false
false
1
0af6844ca198eabe6779e9bf6d6fed87f4726281
8,607,114,521,732
7183ab01643c51f9c1fc4833dbd6eaf2625a5cb8
/src/com/upgrader/validator/PNRValidator.java
d95264dd7834d558da9d3e1f39d158d741e5ad6c
[]
no_license
sonamrasal/FlightTicketUpgrader
https://github.com/sonamrasal/FlightTicketUpgrader
a6b77d6dff8381839003069fc47a2fdce6855bc8
2a540dd8193ce9c2a8900d3b27739da7ce5e1178
refs/heads/master
2020-12-23T12:17:26.357000
2020-02-05T10:37:19
2020-02-05T10:37:19
237,148,014
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.upgrader.validator; import com.updgrader.booking.Booking; public class PNRValidator implements Validator { @Override public void validate(Booking booking) throws ValidationException { if(!booking.isPNRValid()) { throw new ValidationException("PNR Invalid"); } } }
UTF-8
Java
290
java
PNRValidator.java
Java
[]
null
[]
package com.upgrader.validator; import com.updgrader.booking.Booking; public class PNRValidator implements Validator { @Override public void validate(Booking booking) throws ValidationException { if(!booking.isPNRValid()) { throw new ValidationException("PNR Invalid"); } } }
290
0.765517
0.765517
14
19.714285
22.266016
67
false
false
0
0
0
0
0
0
0.928571
false
false
1
a1f6b7573e8c84fea115a71fd43c735ee5d2cfbe
3,650,722,268,848
9b12a4ba3644731a88052fbe9733ca10e74bf55a
/blade-service/ml-pms-gw/src/main/java/org/springblade/gw/listener/ApplicationReadyEventListener.java
5e46d2604f79048fb906340d1fb6fd7ae8d38ce1
[]
no_license
ken209/BladeX
https://github.com/ken209/BladeX
7f633f7e3ffac82783efc6b7a584cf198a2f01a1
12a518e482b4a79864e40f7d8c638082761cd1fa
refs/heads/master
2023-01-11T22:58:36.438000
2020-11-10T07:38:26
2020-11-10T07:38:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.springblade.gw.listener; import org.springblade.core.redis.cache.BladeRedisCache; import org.springblade.gw.config.SystemConfig; import org.springblade.pms.gw.feign.ITopicClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * @Auther: bond * @Date: 2020/4/22 * @Description: */ @Component public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> { @Autowired private ITopicClient iTopicClient; @Autowired private BladeRedisCache redisCache; @Autowired private SystemConfig systemConfig; @Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { // Map<String, Device> codeDeviceMap = new HashMap<>(1); // String key= RedisKeysUtil.getKey(systemConfig.getServerIdCard(), GwsubscribeConstant.DEVICE_CODE_TO_DEVICE); // codeDeviceMap=redisCache.hGetAll(key); // // if(Func.isNotEmpty(codeDeviceMap)){ // iTopicClient.addDeviceTopic(new ArrayList<>(codeDeviceMap.keySet())); // } } }
UTF-8
Java
1,188
java
ApplicationReadyEventListener.java
Java
[ { "context": "ngframework.stereotype.Component;\n\n/**\n * @Auther: bond\n * @Date: 2020/4/22\n * @Description:\n */\n@Compone", "end": 450, "score": 0.9993720650672913, "start": 446, "tag": "USERNAME", "value": "bond" } ]
null
[]
package org.springblade.gw.listener; import org.springblade.core.redis.cache.BladeRedisCache; import org.springblade.gw.config.SystemConfig; import org.springblade.pms.gw.feign.ITopicClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * @Auther: bond * @Date: 2020/4/22 * @Description: */ @Component public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> { @Autowired private ITopicClient iTopicClient; @Autowired private BladeRedisCache redisCache; @Autowired private SystemConfig systemConfig; @Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { // Map<String, Device> codeDeviceMap = new HashMap<>(1); // String key= RedisKeysUtil.getKey(systemConfig.getServerIdCard(), GwsubscribeConstant.DEVICE_CODE_TO_DEVICE); // codeDeviceMap=redisCache.hGetAll(key); // // if(Func.isNotEmpty(codeDeviceMap)){ // iTopicClient.addDeviceTopic(new ArrayList<>(codeDeviceMap.keySet())); // } } }
1,188
0.800505
0.793771
40
28.700001
29.063894
112
false
false
0
0
0
0
0
0
0.975
false
false
1
9024675fd6baabd01b5372de745ed55ba986bf23
36,704,790,534,374
4d9f783b251ed9d91421ce2aaad762c971f87793
/STSWorkspace/horse-service/src/main/java/com/oracle/service/impl/PingLunServiceImpl.java
5e0e1cd1c1e84661035b13a7d9685d360a989f72
[]
no_license
lvjunjiang/OracleStudy
https://github.com/lvjunjiang/OracleStudy
e33b7a7649cf91a3faece9cfac481a4f6a609153
8a390f161b892a2f7a9a35667eb2c667aac34f73
refs/heads/master
2020-06-02T22:08:20.074000
2019-06-11T08:37:38
2019-06-11T08:37:38
191,318,365
0
0
null
false
2020-10-13T13:50:36
2019-06-11T07:33:28
2019-06-11T08:45:11
2020-10-13T13:50:35
203,165
0
0
78
JavaScript
false
false
package com.oracle.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import com.oracle.mapper.PingLunMapper; import com.oracle.mapper.PingLunPlusMapper; import com.oracle.mapper.po.OrderNew; import com.oracle.mapper.po.PingLun; import com.oracle.mapper.po.PingLunAndPlus; import com.oracle.mapper.po.PingLunNew; import com.oracle.mapper.po.PingLunPlus; import com.oracle.service.PingLunService; import com.oracle.utils.RetMessage; public class PingLunServiceImpl implements PingLunService{ @Resource(name="pingLunMapper") private PingLunMapper pingLunMapper; @Resource(name="pingLunPlusMapper") private PingLunPlusMapper pingLunPlusMapper; public PingLunPlusMapper getPingLunPlusMapper() { return pingLunPlusMapper; } public void setPingLunPlusMapper(PingLunPlusMapper pingLunPlusMapper) { this.pingLunPlusMapper = pingLunPlusMapper; } public PingLunMapper getPingLunMapper() { return pingLunMapper; } public void setPingLunMapper(PingLunMapper pingLunMapper) { this.pingLunMapper = pingLunMapper; } public PingLunNew selectByGoodsIdAndOrderId(Integer goodsId, Integer orderId) { return this.pingLunMapper.selectByGoodsIdAndOrderId(goodsId,orderId); } public RetMessage updateByPingLun(PingLun pinglun) { RetMessage rm=new RetMessage(); try { this.pingLunMapper.updateByPrimaryKey(pinglun); rm.setCode(0); rm.setMessage("修改成功"); } catch (Exception e) { rm.setCode(1); rm.setMessage("修改失败"); } return rm; } public void insertNewPingLunPlus(PingLunPlus pingLunPlus) { this.pingLunPlusMapper.insert(pingLunPlus); } public List<PingLunAndPlus> selectPingLunAndPlusByGoodsId(Integer goodsId) { List<PingLunNew> ls=this.pingLunMapper.selectByGoodsId(goodsId); List<PingLunAndPlus> list=new ArrayList<PingLunAndPlus>(); for (PingLunNew pingLunNew : ls) { List<PingLunPlus> listPlus=this.pingLunPlusMapper.selectByPingLunId(pingLunNew.getId()); PingLunAndPlus p=new PingLunAndPlus(pingLunNew, listPlus); list.add(p); } return list; } }
UTF-8
Java
2,090
java
PingLunServiceImpl.java
Java
[]
null
[]
package com.oracle.service.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import com.oracle.mapper.PingLunMapper; import com.oracle.mapper.PingLunPlusMapper; import com.oracle.mapper.po.OrderNew; import com.oracle.mapper.po.PingLun; import com.oracle.mapper.po.PingLunAndPlus; import com.oracle.mapper.po.PingLunNew; import com.oracle.mapper.po.PingLunPlus; import com.oracle.service.PingLunService; import com.oracle.utils.RetMessage; public class PingLunServiceImpl implements PingLunService{ @Resource(name="pingLunMapper") private PingLunMapper pingLunMapper; @Resource(name="pingLunPlusMapper") private PingLunPlusMapper pingLunPlusMapper; public PingLunPlusMapper getPingLunPlusMapper() { return pingLunPlusMapper; } public void setPingLunPlusMapper(PingLunPlusMapper pingLunPlusMapper) { this.pingLunPlusMapper = pingLunPlusMapper; } public PingLunMapper getPingLunMapper() { return pingLunMapper; } public void setPingLunMapper(PingLunMapper pingLunMapper) { this.pingLunMapper = pingLunMapper; } public PingLunNew selectByGoodsIdAndOrderId(Integer goodsId, Integer orderId) { return this.pingLunMapper.selectByGoodsIdAndOrderId(goodsId,orderId); } public RetMessage updateByPingLun(PingLun pinglun) { RetMessage rm=new RetMessage(); try { this.pingLunMapper.updateByPrimaryKey(pinglun); rm.setCode(0); rm.setMessage("修改成功"); } catch (Exception e) { rm.setCode(1); rm.setMessage("修改失败"); } return rm; } public void insertNewPingLunPlus(PingLunPlus pingLunPlus) { this.pingLunPlusMapper.insert(pingLunPlus); } public List<PingLunAndPlus> selectPingLunAndPlusByGoodsId(Integer goodsId) { List<PingLunNew> ls=this.pingLunMapper.selectByGoodsId(goodsId); List<PingLunAndPlus> list=new ArrayList<PingLunAndPlus>(); for (PingLunNew pingLunNew : ls) { List<PingLunPlus> listPlus=this.pingLunPlusMapper.selectByPingLunId(pingLunNew.getId()); PingLunAndPlus p=new PingLunAndPlus(pingLunNew, listPlus); list.add(p); } return list; } }
2,090
0.788332
0.787367
75
26.653334
24.360893
91
false
false
0
0
0
0
0
0
1.573333
false
false
1
7b9ee8a3b72c4fa313ffc9e9725d0308817e2ef9
29,815,663,027,717
ed5159d056e98d6715357d0d14a9b3f20b764f89
/src/irvine/oeis/a161/A161617.java
b9c183565a3699e5103cb5fd3138eb2e55b7b3e4
[]
no_license
flywind2/joeis
https://github.com/flywind2/joeis
c5753169cf562939b04dd246f8a2958e97f74558
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
refs/heads/master
2020-09-13T18:34:35.080000
2019-11-19T05:40:55
2019-11-19T05:40:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package irvine.oeis.a161; import irvine.oeis.LinearRecurrence; /** * A161617 <code>8*n^2+20*n+1</code>. * @author Sean A. Irvine */ public class A161617 extends LinearRecurrence { /** Construct the sequence. */ public A161617() { super(new long[] {1, -3, 3}, new long[] {1, 29, 73}); } }
UTF-8
Java
304
java
A161617.java
Java
[ { "context": "*\n * A161617 <code>8*n^2+20*n+1</code>.\n * @author Sean A. Irvine\n */\npublic class A161617 extends LinearRecurrence", "end": 132, "score": 0.9998944401741028, "start": 118, "tag": "NAME", "value": "Sean A. Irvine" } ]
null
[]
package irvine.oeis.a161; import irvine.oeis.LinearRecurrence; /** * A161617 <code>8*n^2+20*n+1</code>. * @author <NAME> */ public class A161617 extends LinearRecurrence { /** Construct the sequence. */ public A161617() { super(new long[] {1, -3, 3}, new long[] {1, 29, 73}); } }
296
0.634868
0.523026
15
19.266666
18.720636
57
false
false
0
0
0
0
0
0
0.533333
false
false
1
8e0d2e171ac81b366d1bc6dc3dc58b40aeb9a8df
25,503,515,805,448
e4e32977da3acb4e58f643e6be33db834c4a301c
/interfaces-and-abstraction/src/main/java/bg/softuni/foodshortage/model/citizen/contracts/Citizen.java
58e0faf7c96bc633866f8c928ae10a0878a77827
[]
no_license
kosio197/JavaOOPAdvanced
https://github.com/kosio197/JavaOOPAdvanced
8ed57e3fbd4d0fbcc294ff0001e69d5d2a98901f
ffef480954a0898943ad98c49c79edae65f196a1
refs/heads/master
2020-09-21T08:43:05.587000
2016-08-21T10:50:49
2016-08-21T10:50:49
66,186,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bg.softuni.foodshortage.model.citizen.contracts; public interface Citizen extends Identifiable, HasName { }
UTF-8
Java
118
java
Citizen.java
Java
[]
null
[]
package bg.softuni.foodshortage.model.citizen.contracts; public interface Citizen extends Identifiable, HasName { }
118
0.822034
0.822034
5
22.6
27.27343
56
false
false
0
0
0
0
0
0
0.4
false
false
1
c3bc5e30a8dfaa5ccde947849375dc0c31013d99
27,247,272,581,451
df23470774e42ab13bcdbcd1de2da49e573c44e3
/src/main/java/com/example/demo/job/job4/NewJob.java
8fb03edcaec814344700726a10413524af54859a
[]
no_license
guangyuanlcc123/springboot-one
https://github.com/guangyuanlcc123/springboot-one
c8f3d4654b801d317e30c06dec41a8cb92d32f1d
511ff9a052b07fc710615d4c7180868a81298989
refs/heads/master
2023-02-09T20:47:19.445000
2021-01-06T02:12:23
2021-01-06T02:12:23
327,173,275
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.job.job4; import lombok.extern.slf4j.Slf4j; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import java.util.concurrent.TimeUnit; /** * 四、Quartz----Scheduler(任务的执行需自行调用方法执行) */ @Slf4j public class NewJob implements Job { @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { log.info("TestJob执行啦!"); sleep(4); log.info("TestJob结束了!"); } private void sleep(long time) { try { TimeUnit.SECONDS.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } }
UTF-8
Java
732
java
NewJob.java
Java
[]
null
[]
package com.example.demo.job.job4; import lombok.extern.slf4j.Slf4j; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import java.util.concurrent.TimeUnit; /** * 四、Quartz----Scheduler(任务的执行需自行调用方法执行) */ @Slf4j public class NewJob implements Job { @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { log.info("TestJob执行啦!"); sleep(4); log.info("TestJob结束了!"); } private void sleep(long time) { try { TimeUnit.SECONDS.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } }
732
0.660294
0.651471
31
20.935484
19.181536
80
false
false
0
0
0
0
0
0
0.354839
false
false
1
be76acd9189a0386ba126da96fe07ad1f1303fe3
33,139,967,664,143
8bfb64f3c8ab81b6ef38e5a510e44f5db3e4deed
/tvhms/3_implementation/src/com/tvhms/entity/Account.java
9d5b9d546bca5e21c9816a452d91a89123d05ead
[]
no_license
ngphloc/temp
https://github.com/ngphloc/temp
b07d66d6b99117156a9e53b5bc7b155a78a304f1
0865c7cc19996c8495f5b0229ce07b6fe9d9635e
refs/heads/master
2022-10-13T09:15:01.660000
2022-09-28T10:23:20
2022-09-28T10:23:20
138,309,054
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tvhms.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; /** * * @author Administrator2 * @version 1.0 * */ @javax.persistence.Entity @Table (name = "Account") public class Account extends Entity { /** * */ public final static int OFFICER = 1; /** * */ public final static int MANAGER = 3; /** * */ private String accountId; /** * */ private String accountPassword; /** * */ private String fullName; /** * */ private int accountRight; /** * * @param accountId * @param accountPassword * @param fullName * @param accountRight */ public Account( String accountId, String accountPassword, String fullName, int accountRight) { this.accountId = accountId; this.accountPassword = accountPassword; this.fullName = fullName; this.accountRight = accountRight; } /** * */ public Account() { } @Id @Column (name = "AccountId") public String getAccountId() { return accountId; } /** * * @param accountId */ public void setAccountId(String accountId) { this.accountId = accountId; } @Column (name = "AccountPassword") public String getAccountPassword() { return accountPassword; } /** * * @param accountPassword */ public void setAccountPassword(String accountPassword) { this.accountPassword = accountPassword; } @Column (name = "FullName") public String getFullName() { return fullName; } /** * * @param fullName */ public void setFullName(String fullName) { this.fullName = fullName; } @Column (name = "AccountRight") public int getAccountRight() { return accountRight; } /** * * @param accountRight */ public void setAccountRight(int accountRight) { this.accountRight = accountRight; } @Override public Serializable queryId() { // TODO Auto-generated method stub return getAccountId(); } /** * * @return */ public Account save2() { Serializable accountId = super.save(); if (accountId == null) return null; return (Account)load(this.getClass(), accountId); } }
UTF-8
Java
2,219
java
Account.java
Java
[ { "context": "port javax.persistence.Table;\n\n\n/**\n * \n * @author Administrator2\n * @version 1.0\n *\n */\n@javax.persistence.Entity\n", "end": 186, "score": 0.9996367692947388, "start": 172, "tag": "USERNAME", "value": "Administrator2" }, { "context": "is.accountId = accountId;\n\t\tthis.accountPassword = accountPassword;\n\t\tthis.fullName = fullName;\n\t\tthis.accou", "end": 886, "score": 0.5983005166053772, "start": 879, "tag": "PASSWORD", "value": "account" } ]
null
[]
package com.tvhms.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; /** * * @author Administrator2 * @version 1.0 * */ @javax.persistence.Entity @Table (name = "Account") public class Account extends Entity { /** * */ public final static int OFFICER = 1; /** * */ public final static int MANAGER = 3; /** * */ private String accountId; /** * */ private String accountPassword; /** * */ private String fullName; /** * */ private int accountRight; /** * * @param accountId * @param accountPassword * @param fullName * @param accountRight */ public Account( String accountId, String accountPassword, String fullName, int accountRight) { this.accountId = accountId; this.accountPassword = <PASSWORD>Password; this.fullName = fullName; this.accountRight = accountRight; } /** * */ public Account() { } @Id @Column (name = "AccountId") public String getAccountId() { return accountId; } /** * * @param accountId */ public void setAccountId(String accountId) { this.accountId = accountId; } @Column (name = "AccountPassword") public String getAccountPassword() { return accountPassword; } /** * * @param accountPassword */ public void setAccountPassword(String accountPassword) { this.accountPassword = accountPassword; } @Column (name = "FullName") public String getFullName() { return fullName; } /** * * @param fullName */ public void setFullName(String fullName) { this.fullName = fullName; } @Column (name = "AccountRight") public int getAccountRight() { return accountRight; } /** * * @param accountRight */ public void setAccountRight(int accountRight) { this.accountRight = accountRight; } @Override public Serializable queryId() { // TODO Auto-generated method stub return getAccountId(); } /** * * @return */ public Account save2() { Serializable accountId = super.save(); if (accountId == null) return null; return (Account)load(this.getClass(), accountId); } }
2,222
0.634971
0.632267
166
12.36747
13.958756
57
false
false
0
0
0
0
0
0
1.228916
false
false
1
87711ed7fb46c047724a1d95c85a465b06bbb455
33,139,967,663,086
86a08b37844d717fca3354cb9e1d7f93dfaf379a
/src/main/java/com/doodod/staffmanagement/statistic/WorkTimeLauncher.java
9c647be4b039c9f2fba13f138bbf98aaf3cedf1f
[]
no_license
yifenghi/employee_worktime
https://github.com/yifenghi/employee_worktime
f5a62b34752b88b0e0b43c5d1272d171864a381c
e629c0ec10aa3433ad3cb7036df178bc7383dfd1
refs/heads/master
2021-01-24T20:53:15.277000
2018-02-28T09:36:35
2018-02-28T09:36:35
123,261,355
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.doodod.staffmanagement.statistic; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class WorkTimeLauncher extends Configured implements Tool { public int run(String[] arg0) throws Exception { //calculate work time GenericOptionsParser options=new GenericOptionsParser(getConf(), arg0); Configuration hadoopConf = options.getConfiguration(); Job job = new Job(hadoopConf); job.setJarByClass(WorkTimeLauncher.class); job.setMapperClass(WorkTimeMapper.class); // job.setReducerClass(WorkTimerReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); job.waitForCompletion(true); return 0; } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub System.exit(ToolRunner.run(new Configuration(), new WorkTimeLauncher(), args)); } }
UTF-8
Java
1,577
java
WorkTimeLauncher.java
Java
[]
null
[]
package com.doodod.staffmanagement.statistic; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class WorkTimeLauncher extends Configured implements Tool { public int run(String[] arg0) throws Exception { //calculate work time GenericOptionsParser options=new GenericOptionsParser(getConf(), arg0); Configuration hadoopConf = options.getConfiguration(); Job job = new Job(hadoopConf); job.setJarByClass(WorkTimeLauncher.class); job.setMapperClass(WorkTimeMapper.class); // job.setReducerClass(WorkTimerReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); job.waitForCompletion(true); return 0; } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub System.exit(ToolRunner.run(new Configuration(), new WorkTimeLauncher(), args)); } }
1,577
0.790742
0.78884
46
33.282608
22.851755
73
false
false
0
0
0
0
0
0
1.804348
false
false
1
68757a6502d21a2984371af9b46b1ecec13b547d
16,449,724,759,882
68748cbfdba3f6ad6ec81016375237f84eb815a0
/BasicConcepts/callingprivatemethod/ReflectionDemo.java
431703f546214565fad3171d497cc1888f507ef6
[]
no_license
osemrt/Java
https://github.com/osemrt/Java
993232c62bee01cbb22b225d5788f75670fbc37e
d65479d7a981a0a1de9b6727061df5f7a43a95b2
refs/heads/master
2020-05-02T03:27:26.870000
2019-05-01T12:46:46
2019-05-01T12:46:46
177,729,023
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package callingprivatemethod; /* * If we can able to call private function, Why is there? * because reflection is for debugging and it is a trick. * */ import java.lang.reflect.Method; public class ReflectionDemo { public static void main(String[] args) throws Exception { Class c = Class.forName("callingprivatemethod.Test"); Test t = (Test)c.newInstance(); Method m = c.getDeclaredMethod("show", null); m.setAccessible(true); m.invoke(t, null); } }
UTF-8
Java
485
java
ReflectionDemo.java
Java
[]
null
[]
package callingprivatemethod; /* * If we can able to call private function, Why is there? * because reflection is for debugging and it is a trick. * */ import java.lang.reflect.Method; public class ReflectionDemo { public static void main(String[] args) throws Exception { Class c = Class.forName("callingprivatemethod.Test"); Test t = (Test)c.newInstance(); Method m = c.getDeclaredMethod("show", null); m.setAccessible(true); m.invoke(t, null); } }
485
0.692784
0.692784
24
19.208334
21.466988
58
false
false
0
0
0
0
0
0
1.25
false
false
1
1c9376f433d834b27df3fc9a1e94addf539df0f6
11,862,699,686,354
528e8a52d10696b9f432a2d3151a92c671f78752
/Build10/src/Build10.java
c8ff59762e7b1be0489b42d2c9698d9457601a00
[]
no_license
Robra1/Robocomp
https://github.com/Robra1/Robocomp
cb0bb3fb306590699c5d7c8b077e413951fff46b
110b74a69bedecbd006715794c52c4081dafa9e6
refs/heads/master
2020-05-18T09:00:38.847000
2015-07-25T19:15:13
2015-07-25T19:15:13
39,697,950
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import lejos.nxt.Button; import lejos.robotics.subsumption.Arbitrator; import lejos.robotics.subsumption.Behavior; public class Build10 { public static void main(String[] args) { //Erstellen des Hilfsobjektes Robot r = new Robot(); //Setzen des Ziels r.setTarget(r.winkelBestimmen()); //Abfrage vor dem Start System.out.println("Start"); Button.waitForAnyPress(); Behavior b[] = {new Fahren(r),new Ausweichen(r),new Kill(r)}; Arbitrator a = new Arbitrator(b); a.start(); } }
UTF-8
Java
520
java
Build10.java
Java
[]
null
[]
import lejos.nxt.Button; import lejos.robotics.subsumption.Arbitrator; import lejos.robotics.subsumption.Behavior; public class Build10 { public static void main(String[] args) { //Erstellen des Hilfsobjektes Robot r = new Robot(); //Setzen des Ziels r.setTarget(r.winkelBestimmen()); //Abfrage vor dem Start System.out.println("Start"); Button.waitForAnyPress(); Behavior b[] = {new Fahren(r),new Ausweichen(r),new Kill(r)}; Arbitrator a = new Arbitrator(b); a.start(); } }
520
0.686538
0.682692
20
24
17.108477
63
false
false
0
0
0
0
0
0
1.7
false
false
1
21b23f004d4ff08a9f5917328b06048cb3feb15f
11,862,699,686,443
6ef5bbd7daf1362fe42db062b834056a21519f05
/DesignPatterns/src/dp/iterator/EmployeeIterator.java
064ae8fd15ef035d4d2cc26e06ed4c4b5a20ae00
[]
no_license
gkdgithub/Dp-Repo
https://github.com/gkdgithub/Dp-Repo
f8920ed37b420d6c11f5c0b4f397c64de868e96b
821fb07d6815e66400b25b127dfe47508b0842b0
refs/heads/master
2023-05-03T05:42:00.959000
2022-07-24T18:15:07
2022-07-24T18:15:07
216,508,268
0
0
null
false
2023-04-14T17:43:12
2019-10-21T07:49:20
2022-07-24T18:15:14
2023-04-14T17:43:12
50,932
0
0
38
Java
false
false
/** * */ package dp.iterator; /** * @author DhanunjayaY * */ public interface EmployeeIterator { boolean hasNext(); Object next(); boolean hasPrevious(); Object previous(); }
UTF-8
Java
189
java
EmployeeIterator.java
Java
[ { "context": "/**\n * \n */\npackage dp.iterator;\n\n/**\n * @author DhanunjayaY\n *\n */\npublic interface EmployeeIterator {\n\n\tbool", "end": 60, "score": 0.9605536460876465, "start": 49, "tag": "NAME", "value": "DhanunjayaY" } ]
null
[]
/** * */ package dp.iterator; /** * @author DhanunjayaY * */ public interface EmployeeIterator { boolean hasNext(); Object next(); boolean hasPrevious(); Object previous(); }
189
0.640212
0.640212
17
10.117647
10.560093
35
false
false
0
0
0
0
0
0
0.588235
false
false
1
fc90be0c721ea2e1e2c167534adf12a6ffc661e0
30,803,505,465,800
17e8438486cb3e3073966ca2c14956d3ba9209ea
/dso/branches/3.6/dso-l1/src/main/java/com/tc/object/bytecode/HashtableClassAdapter.java
2a27cfcbb4cab32f0f31130f0c483322cc1e7e7b
[]
no_license
sirinath/Terracotta
https://github.com/sirinath/Terracotta
fedfc2c4f0f06c990f94b8b6c3b9c93293334345
00a7662b9cf530dfdb43f2dd821fa559e998c892
refs/heads/master
2021-01-23T05:41:52.414000
2015-07-02T15:21:54
2015-07-02T15:21:54
38,613,711
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright * notice. All rights reserved. */ package com.tc.object.bytecode; import com.tc.asm.Label; import com.tc.asm.Opcodes; import com.tc.asm.tree.MethodNode; import com.tc.util.runtime.Vm; public class HashtableClassAdapter implements Opcodes { /** * Creates the following method code * * For Sun JRE: * * <pre> * protected Map.Entry __tc_getEntry(Object obj) { * Entry aentry[] = table; * int i = obj.hashCode(); * int j = (i &amp; 0x7fffffff) % aentry.length; * for (Entry entry = aentry[j]; entry != null; entry = entry.next) { * if (entry.hash == i &amp;&amp; entry.key.equals(obj)) { return (Entry) entry; } * } * return null; * } * </pre> * * For IBM JRE: * * <pre> * protected Map.Entry __tc_getEntry(Object obj) { * return getEntry(); * } * </pre> * */ private static MethodNode __tc_getEntryMethod() { MethodNode mv = new MethodNode(ACC_PROTECTED, // "__tc_getEntry", // "(Ljava/lang/Object;)Ljava/util/Map$Entry;", null, null); mv.visitCode(); if (Vm.isIBM()) { mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/util/Hashtable", "getEntry", "(Ljava/lang/Object;)Ljava/util/Hashtable$Entry;"); } else { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "table", "[Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I"); mv.visitVarInsn(ISTORE, 3); mv.visitVarInsn(ILOAD, 3); mv.visitLdcInsn(Integer.valueOf(2147483647)); mv.visitInsn(IAND); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(ARRAYLENGTH); mv.visitInsn(IREM); mv.visitVarInsn(ISTORE, 4); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ILOAD, 4); mv.visitInsn(AALOAD); mv.visitVarInsn(ASTORE, 5); Label l4 = new Label(); mv.visitLabel(l4); mv.visitVarInsn(ALOAD, 5); Label l5 = new Label(); mv.visitJumpInsn(IFNULL, l5); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "hash", "I"); mv.visitVarInsn(ILOAD, 3); Label l7 = new Label(); mv.visitJumpInsn(IF_ICMPNE, l7); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "key", "Ljava/lang/Object;"); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z"); mv.visitJumpInsn(IFEQ, l7); mv.visitVarInsn(ALOAD, 5); mv.visitTypeInsn(CHECKCAST, "java/util/Hashtable$Entry"); mv.visitInsn(ARETURN); mv.visitLabel(l7); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 5); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l5); mv.visitInsn(ACONST_NULL); } mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); return mv; } /** * Just like Hashtable.remove(Object) except that it returns the entry (or null) * * <pre> * protected synchronized Entry __tc_removeEntryForKey(Object key) { * Entry tab[] = table; * int hash = key.hashCode(); * int index = (hash &amp; 0x7FFFFFFF) % tab.length; * for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.next) { * if ((e.hash == hash) &amp;&amp; e.key.equals(key)) { * modCount++; * if (prev != null) { * prev.next = e.next; * } else { * tab[index] = e.next; * } * count--; * return e; * } * } * return null; * } * */ private static MethodNode __tc_removeEntryForKeyMethodSun() { MethodNode mv = new MethodNode(ACC_PROTECTED + ACC_SYNCHRONIZED, "__tc_removeEntryForKey", "(Ljava/lang/Object;)Ljava/util/Map$Entry;", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "table", "[Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I"); mv.visitVarInsn(ISTORE, 3); mv.visitVarInsn(ILOAD, 3); mv.visitLdcInsn(Integer.valueOf(2147483647)); mv.visitInsn(IAND); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(ARRAYLENGTH); mv.visitInsn(IREM); mv.visitVarInsn(ISTORE, 4); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ILOAD, 4); mv.visitInsn(AALOAD); mv.visitVarInsn(ASTORE, 5); mv.visitInsn(ACONST_NULL); mv.visitVarInsn(ASTORE, 6); Label l4 = new Label(); mv.visitLabel(l4); mv.visitVarInsn(ALOAD, 5); Label l5 = new Label(); mv.visitJumpInsn(IFNULL, l5); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "hash", "I"); mv.visitVarInsn(ILOAD, 3); Label l7 = new Label(); mv.visitJumpInsn(IF_ICMPNE, l7); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "key", "Ljava/lang/Object;"); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z"); mv.visitJumpInsn(IFEQ, l7); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "modCount", "I"); mv.visitInsn(ICONST_1); mv.visitInsn(IADD); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable", "modCount", "I"); mv.visitVarInsn(ALOAD, 6); Label l10 = new Label(); mv.visitJumpInsn(IFNULL, l10); mv.visitVarInsn(ALOAD, 6); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); Label l12 = new Label(); mv.visitJumpInsn(GOTO, l12); mv.visitLabel(l10); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ILOAD, 4); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitInsn(AASTORE); mv.visitLabel(l12); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "count", "I"); mv.visitInsn(ICONST_1); mv.visitInsn(ISUB); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable", "count", "I"); mv.visitVarInsn(ALOAD, 5); mv.visitInsn(ARETURN); mv.visitLabel(l7); mv.visitVarInsn(ALOAD, 5); mv.visitVarInsn(ASTORE, 6); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 5); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l5); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); return mv; } private static MethodNode __tc_removeEntryForKeyMethodIBM() { MethodNode mv = new MethodNode(ACC_PROTECTED + ACC_SYNCHRONIZED, "__tc_removeEntryForKey", "(Ljava/lang/Object;)Ljava/util/Map$Entry;", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I"); mv.visitVarInsn(ISTORE, 2); mv.visitVarInsn(ILOAD, 2); mv.visitLdcInsn(Integer.valueOf(2147483647)); mv.visitInsn(IAND); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "elementData", "[Ljava/util/Hashtable$Entry;"); mv.visitInsn(ARRAYLENGTH); mv.visitInsn(IREM); mv.visitVarInsn(ISTORE, 3); mv.visitInsn(ACONST_NULL); mv.visitVarInsn(ASTORE, 4); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "elementData", "[Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ILOAD, 3); mv.visitInsn(AALOAD); mv.visitVarInsn(ASTORE, 5); Label l4 = new Label(); mv.visitLabel(l4); mv.visitVarInsn(ALOAD, 5); Label l5 = new Label(); mv.visitJumpInsn(IFNULL, l5); mv.visitVarInsn(ALOAD, 5); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ILOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, "java/util/Hashtable$Entry", "equalsKey", "(Ljava/lang/Object;I)Z"); mv.visitJumpInsn(IFNE, l5); mv.visitVarInsn(ALOAD, 5); mv.visitVarInsn(ASTORE, 4); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 5); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l5); mv.visitVarInsn(ALOAD, 5); Label l9 = new Label(); mv.visitJumpInsn(IFNULL, l9); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "modCount", "I"); mv.visitInsn(ICONST_1); mv.visitInsn(IADD); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable", "modCount", "I"); mv.visitVarInsn(ALOAD, 4); Label l12 = new Label(); mv.visitJumpInsn(IFNONNULL, l12); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "elementData", "[Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ILOAD, 3); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitInsn(AASTORE); Label l13 = new Label(); mv.visitJumpInsn(GOTO, l13); mv.visitLabel(l12); mv.visitVarInsn(ALOAD, 4); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitLabel(l13); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "elementCount", "I"); mv.visitInsn(ICONST_1); mv.visitInsn(ISUB); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable", "elementCount", "I"); mv.visitVarInsn(ALOAD, 5); mv.visitInsn(ARETURN); mv.visitLabel(l9); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); return mv; } public static MethodNode[] getMethods() { return new MethodNode[] { __tc_getEntryMethod(), Vm.isIBM() ? __tc_removeEntryForKeyMethodIBM() : __tc_removeEntryForKeyMethodSun() }; } }
UTF-8
Java
10,797
java
HashtableClassAdapter.java
Java
[]
null
[]
/* * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright * notice. All rights reserved. */ package com.tc.object.bytecode; import com.tc.asm.Label; import com.tc.asm.Opcodes; import com.tc.asm.tree.MethodNode; import com.tc.util.runtime.Vm; public class HashtableClassAdapter implements Opcodes { /** * Creates the following method code * * For Sun JRE: * * <pre> * protected Map.Entry __tc_getEntry(Object obj) { * Entry aentry[] = table; * int i = obj.hashCode(); * int j = (i &amp; 0x7fffffff) % aentry.length; * for (Entry entry = aentry[j]; entry != null; entry = entry.next) { * if (entry.hash == i &amp;&amp; entry.key.equals(obj)) { return (Entry) entry; } * } * return null; * } * </pre> * * For IBM JRE: * * <pre> * protected Map.Entry __tc_getEntry(Object obj) { * return getEntry(); * } * </pre> * */ private static MethodNode __tc_getEntryMethod() { MethodNode mv = new MethodNode(ACC_PROTECTED, // "__tc_getEntry", // "(Ljava/lang/Object;)Ljava/util/Map$Entry;", null, null); mv.visitCode(); if (Vm.isIBM()) { mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/util/Hashtable", "getEntry", "(Ljava/lang/Object;)Ljava/util/Hashtable$Entry;"); } else { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "table", "[Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I"); mv.visitVarInsn(ISTORE, 3); mv.visitVarInsn(ILOAD, 3); mv.visitLdcInsn(Integer.valueOf(2147483647)); mv.visitInsn(IAND); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(ARRAYLENGTH); mv.visitInsn(IREM); mv.visitVarInsn(ISTORE, 4); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ILOAD, 4); mv.visitInsn(AALOAD); mv.visitVarInsn(ASTORE, 5); Label l4 = new Label(); mv.visitLabel(l4); mv.visitVarInsn(ALOAD, 5); Label l5 = new Label(); mv.visitJumpInsn(IFNULL, l5); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "hash", "I"); mv.visitVarInsn(ILOAD, 3); Label l7 = new Label(); mv.visitJumpInsn(IF_ICMPNE, l7); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "key", "Ljava/lang/Object;"); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z"); mv.visitJumpInsn(IFEQ, l7); mv.visitVarInsn(ALOAD, 5); mv.visitTypeInsn(CHECKCAST, "java/util/Hashtable$Entry"); mv.visitInsn(ARETURN); mv.visitLabel(l7); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 5); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l5); mv.visitInsn(ACONST_NULL); } mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); return mv; } /** * Just like Hashtable.remove(Object) except that it returns the entry (or null) * * <pre> * protected synchronized Entry __tc_removeEntryForKey(Object key) { * Entry tab[] = table; * int hash = key.hashCode(); * int index = (hash &amp; 0x7FFFFFFF) % tab.length; * for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.next) { * if ((e.hash == hash) &amp;&amp; e.key.equals(key)) { * modCount++; * if (prev != null) { * prev.next = e.next; * } else { * tab[index] = e.next; * } * count--; * return e; * } * } * return null; * } * */ private static MethodNode __tc_removeEntryForKeyMethodSun() { MethodNode mv = new MethodNode(ACC_PROTECTED + ACC_SYNCHRONIZED, "__tc_removeEntryForKey", "(Ljava/lang/Object;)Ljava/util/Map$Entry;", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "table", "[Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I"); mv.visitVarInsn(ISTORE, 3); mv.visitVarInsn(ILOAD, 3); mv.visitLdcInsn(Integer.valueOf(2147483647)); mv.visitInsn(IAND); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(ARRAYLENGTH); mv.visitInsn(IREM); mv.visitVarInsn(ISTORE, 4); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ILOAD, 4); mv.visitInsn(AALOAD); mv.visitVarInsn(ASTORE, 5); mv.visitInsn(ACONST_NULL); mv.visitVarInsn(ASTORE, 6); Label l4 = new Label(); mv.visitLabel(l4); mv.visitVarInsn(ALOAD, 5); Label l5 = new Label(); mv.visitJumpInsn(IFNULL, l5); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "hash", "I"); mv.visitVarInsn(ILOAD, 3); Label l7 = new Label(); mv.visitJumpInsn(IF_ICMPNE, l7); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "key", "Ljava/lang/Object;"); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z"); mv.visitJumpInsn(IFEQ, l7); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "modCount", "I"); mv.visitInsn(ICONST_1); mv.visitInsn(IADD); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable", "modCount", "I"); mv.visitVarInsn(ALOAD, 6); Label l10 = new Label(); mv.visitJumpInsn(IFNULL, l10); mv.visitVarInsn(ALOAD, 6); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); Label l12 = new Label(); mv.visitJumpInsn(GOTO, l12); mv.visitLabel(l10); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ILOAD, 4); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitInsn(AASTORE); mv.visitLabel(l12); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "count", "I"); mv.visitInsn(ICONST_1); mv.visitInsn(ISUB); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable", "count", "I"); mv.visitVarInsn(ALOAD, 5); mv.visitInsn(ARETURN); mv.visitLabel(l7); mv.visitVarInsn(ALOAD, 5); mv.visitVarInsn(ASTORE, 6); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 5); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l5); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); return mv; } private static MethodNode __tc_removeEntryForKeyMethodIBM() { MethodNode mv = new MethodNode(ACC_PROTECTED + ACC_SYNCHRONIZED, "__tc_removeEntryForKey", "(Ljava/lang/Object;)Ljava/util/Map$Entry;", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I"); mv.visitVarInsn(ISTORE, 2); mv.visitVarInsn(ILOAD, 2); mv.visitLdcInsn(Integer.valueOf(2147483647)); mv.visitInsn(IAND); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "elementData", "[Ljava/util/Hashtable$Entry;"); mv.visitInsn(ARRAYLENGTH); mv.visitInsn(IREM); mv.visitVarInsn(ISTORE, 3); mv.visitInsn(ACONST_NULL); mv.visitVarInsn(ASTORE, 4); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "elementData", "[Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ILOAD, 3); mv.visitInsn(AALOAD); mv.visitVarInsn(ASTORE, 5); Label l4 = new Label(); mv.visitLabel(l4); mv.visitVarInsn(ALOAD, 5); Label l5 = new Label(); mv.visitJumpInsn(IFNULL, l5); mv.visitVarInsn(ALOAD, 5); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ILOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, "java/util/Hashtable$Entry", "equalsKey", "(Ljava/lang/Object;I)Z"); mv.visitJumpInsn(IFNE, l5); mv.visitVarInsn(ALOAD, 5); mv.visitVarInsn(ASTORE, 4); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ASTORE, 5); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l5); mv.visitVarInsn(ALOAD, 5); Label l9 = new Label(); mv.visitJumpInsn(IFNULL, l9); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "modCount", "I"); mv.visitInsn(ICONST_1); mv.visitInsn(IADD); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable", "modCount", "I"); mv.visitVarInsn(ALOAD, 4); Label l12 = new Label(); mv.visitJumpInsn(IFNONNULL, l12); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "elementData", "[Ljava/util/Hashtable$Entry;"); mv.visitVarInsn(ILOAD, 3); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitInsn(AASTORE); Label l13 = new Label(); mv.visitJumpInsn(GOTO, l13); mv.visitLabel(l12); mv.visitVarInsn(ALOAD, 4); mv.visitVarInsn(ALOAD, 5); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable$Entry", "next", "Ljava/util/Hashtable$Entry;"); mv.visitLabel(l13); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(GETFIELD, "java/util/Hashtable", "elementCount", "I"); mv.visitInsn(ICONST_1); mv.visitInsn(ISUB); mv.visitFieldInsn(PUTFIELD, "java/util/Hashtable", "elementCount", "I"); mv.visitVarInsn(ALOAD, 5); mv.visitInsn(ARETURN); mv.visitLabel(l9); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); return mv; } public static MethodNode[] getMethods() { return new MethodNode[] { __tc_getEntryMethod(), Vm.isIBM() ? __tc_removeEntryForKeyMethodIBM() : __tc_removeEntryForKeyMethodSun() }; } }
10,797
0.633139
0.616282
297
35.353535
25.80501
113
false
false
0
0
0
0
0
0
1.606061
false
false
1
aa769e9d181d5b793099a74dd0bda4ad1f32671a
13,357,348,312,589
11bb59cf93b085875f31fa8e9add749f15fd565f
/src/main/java/NeatSnake/World/World.java
0e6f35cbca6c0b4aaceb6b2af9a789d0509cf67d
[ "MIT" ]
permissive
DirkGehlich/NeatSnake
https://github.com/DirkGehlich/NeatSnake
2de51e3cb43e57738b06adbccb67ca9cc5a318dc
f8ab0a39852c2aeed30f89e66e6215eef393ce19
refs/heads/master
2022-11-28T23:21:07.482000
2019-05-25T08:57:36
2019-05-25T08:57:36
175,991,973
1
0
MIT
false
2022-11-16T12:23:53
2019-03-16T15:49:57
2019-05-25T08:57:39
2022-11-16T12:23:50
235
1
0
3
Java
false
false
package NeatSnake.World; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ThreadLocalRandom; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class World extends JFrame implements KeyListener { /** * */ private static final long serialVersionUID = 1L; final int BOARDSIZE = 11; final int MARGIN = 50; final int FIELD_SIZE = 50; final int FRAME_WIDTH = 800; final int FRAME_HEIGHT = 600; final int POPULATIONSIZE = 500; final int MOVETIME_MS = 100; boolean worldRunning = false; Timer timer = null; Snake enemySnake; private Population population = null; PlayArea playArea; JPanel container = new JPanel(); private JFreeChart chart = null; private XYSeries seriesLifetime = null; private XYSeries seriesSnakeLength = null; public static void main(String[] args) { World world = new World(); world.setVisible(true); // world.runWorld(); } public World() { int playAreaSize = BOARDSIZE * FIELD_SIZE + MARGIN; setSize(playAreaSize + 1000, playAreaSize + 250); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setFocusable(true); addKeyListener(this); container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); playArea = new PlayArea(BOARDSIZE, FIELD_SIZE, MARGIN); container.add(playArea); seriesLifetime = new XYSeries("# Moves"); seriesSnakeLength = new XYSeries("Snake length"); // series.add(1.0, 400); // series.add(2.0, 200); final XYSeriesCollection data = new XYSeriesCollection(seriesLifetime); data.addSeries(seriesSnakeLength); chart = ChartFactory.createXYLineChart("Highest Number moves per generation", "Generation", "# Moves", data, PlotOrientation.VERTICAL, true, true, false); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(900, 500)); chartPanel.setMaximumSize(new Dimension(900, 500)); container.add(chartPanel); add(container); createEnemySnake(); } private void createEnemySnake() { enemySnake = new Snake(); enemySnake.head = new Point(9, 6); enemySnake.tail.add(new Point(9, 1)); enemySnake.tail.add(new Point(9, 2)); enemySnake.tail.add(new Point(9, 3)); enemySnake.tail.add(new Point(9, 4)); enemySnake.tail.add(new Point(9, 5)); } public void runWorld() { if (timer != null) { return; } if (population == null) { population = new Population(POPULATIONSIZE, BOARDSIZE); } worldRunning = true; timer = new Timer(true); timer.scheduleAtFixedRate(new MoveTask(this), 0, MOVETIME_MS); } protected void update() { playArea.update(); } private List<Point> getEnemySnakesCoords() { List<Point> snakeCoords = new ArrayList<Point>(); // TODO: replace by snake array snakeCoords.add(enemySnake.head); snakeCoords.addAll(enemySnake.tail); return snakeCoords; } public void keyReleased(KeyEvent arg0) { if (arg0.getKeyCode() == KeyEvent.VK_ESCAPE) { dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (arg0.getKeyCode() == KeyEvent.VK_SPACE) { population.setTraining(!population.isTraining()); } else if (arg0.getKeyChar() == 's') { population.getBestSnake().brain.save("savednn.txt"); } else if (arg0.getKeyChar() == 'l') { population = new Population("savednn.txt", POPULATIONSIZE, BOARDSIZE); } else if (arg0.getKeyCode() == KeyEvent.VK_ENTER) { runWorld(); } } public void moveEnemySnakeRandomly() { Point direction = getRandomDirection(); int deadlockCnt = 0; while (deadlockCnt < 20 && enemySnake.wouldDie(direction, BOARDSIZE)) { direction = getRandomDirection(); deadlockCnt++; } if (deadlockCnt == 20) { createEnemySnake(); } enemySnake.move(direction); } private Point getRandomDirection() { int x = ThreadLocalRandom.current().nextInt(-1, 2); int y = ThreadLocalRandom.current().nextInt(-1, 2); return new Point(x, y); } class MoveTask extends TimerTask { private World world; public MoveTask(World world) { this.world = world; } @Override public void run() { world.moveEnemySnakeRandomly(); // TODO: pass population as parameter to ctor? if (population.isPopulationDead()) { population.createNewGeneration(); createEnemySnake(); } else { population.moveSnakes(getEnemySnakesCoords()); } world.update(); } } class PlayArea extends JPanel { /** * */ private static final long serialVersionUID = 1L; int boardSize; int fieldSize; int margin; String logMsg = new String(); public PlayArea(int boardSize, int fieldSize, int margin) { this.boardSize = boardSize; this.fieldSize = fieldSize; this.margin = margin; } public void update() { validate(); repaint(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // Draw Board g.setColor(Color.BLACK); for (int rowIdx = 0; rowIdx < BOARDSIZE; ++rowIdx) { for (int colIdx = 0; colIdx < BOARDSIZE; ++colIdx) { g.drawRect(MARGIN + rowIdx * fieldSize, MARGIN + colIdx * fieldSize, fieldSize, fieldSize); } } if (!worldRunning) { return; } if (population.isTraining()) { // Draw Food // for (GoodSnake snake : population.getSnakes()) { // // // Food // if (!snake.isDead() ) { // g.setColor(Color.BLUE); // for (Point food : snake.getFood()) { // g.fillRect(MARGIN + food.x * FIELD_SIZE, MARGIN + food.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); // } // //// break; // } // } // Draw Snakes for (GoodSnake snake : population.getSnakes()) { if (!snake.isDead()) { if (snake.isDead()) { g.setColor(Color.GRAY); } else { g.setColor(Color.BLACK); } for (Point tail : snake.tail) { g.fillRect(MARGIN + tail.x * FIELD_SIZE, MARGIN + tail.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } if (snake.isDead()) { g.setColor(Color.GRAY); } else { g.setColor(Color.GREEN); } g.fillRect(MARGIN + snake.head.x * FIELD_SIZE, MARGIN + snake.head.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); // break; } } } else { GoodSnake bestSnake = population.getDemonstrationSnake(); // Draw Food g.setColor(Color.BLUE); for (Point food : bestSnake.getFood()) { g.fillRect(MARGIN + food.x * FIELD_SIZE, MARGIN + food.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } if (bestSnake.isDead()) { g.setColor(Color.GRAY); } else { g.setColor(Color.BLACK); } for (Point tail : bestSnake.tail) { g.fillRect(MARGIN + tail.x * FIELD_SIZE, MARGIN + tail.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } if (bestSnake.isDead()) { g.setColor(Color.GRAY); } else { g.setColor(Color.GREEN); } g.fillRect(MARGIN + bestSnake.head.x * FIELD_SIZE, MARGIN + bestSnake.head.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } // Draw Enemy Snake g.setColor(Color.BLACK); for (Point tail : enemySnake.tail) { g.fillRect(MARGIN + tail.x * FIELD_SIZE, MARGIN + tail.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } g.setColor(Color.RED); g.fillRect(MARGIN + enemySnake.head.x * FIELD_SIZE, MARGIN + enemySnake.head.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); // Draw Logging g.setColor(Color.BLACK); g.drawString("# Populations: " + Integer.toString(population.getGenerationNo()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN); GoodSnake bestSnake = population.getBestSnake(); if (bestSnake != null) { g.drawString("Current Best Snakes Fitness: " + Double.toString(bestSnake.getFitness()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 20); g.drawString("Current Best Snakes Lifetime: " + Double.toString(population.getLocalMostMoves()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 40); g.drawString("Current Best Snakes Length: " + Double.toString(population.getLocalBiggestLength()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 60); g.drawString("Global Best Snakes Fitness: " + Double.toString(population.getGlobalBestFitness()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 80); g.drawString("Global Best Snakes Lifetime: " + Double.toString(population.getGlobalMostMoves()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 100); g.drawString("Global Best Snakes Length: " + Double.toString(population.getGlobalBiggestLength()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 120); } if (bestSnake != null) { if (population.getLifetimeHistory().size() > seriesLifetime.getItemCount()) { seriesLifetime.add(seriesLifetime.getItemCount() + 1, population.getLifetimeHistory().get(population.getLifetimeHistory().size()-1)); } if (population.getSnakeLengthHistory().size() > seriesSnakeLength.getItemCount()) { seriesSnakeLength.add(seriesSnakeLength.getItemCount() + 1, population.getSnakeLengthHistory().get(population.getSnakeLengthHistory().size()-1)); } } } } public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }
UTF-8
Java
9,890
java
World.java
Java
[]
null
[]
package NeatSnake.World; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ThreadLocalRandom; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class World extends JFrame implements KeyListener { /** * */ private static final long serialVersionUID = 1L; final int BOARDSIZE = 11; final int MARGIN = 50; final int FIELD_SIZE = 50; final int FRAME_WIDTH = 800; final int FRAME_HEIGHT = 600; final int POPULATIONSIZE = 500; final int MOVETIME_MS = 100; boolean worldRunning = false; Timer timer = null; Snake enemySnake; private Population population = null; PlayArea playArea; JPanel container = new JPanel(); private JFreeChart chart = null; private XYSeries seriesLifetime = null; private XYSeries seriesSnakeLength = null; public static void main(String[] args) { World world = new World(); world.setVisible(true); // world.runWorld(); } public World() { int playAreaSize = BOARDSIZE * FIELD_SIZE + MARGIN; setSize(playAreaSize + 1000, playAreaSize + 250); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setFocusable(true); addKeyListener(this); container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); playArea = new PlayArea(BOARDSIZE, FIELD_SIZE, MARGIN); container.add(playArea); seriesLifetime = new XYSeries("# Moves"); seriesSnakeLength = new XYSeries("Snake length"); // series.add(1.0, 400); // series.add(2.0, 200); final XYSeriesCollection data = new XYSeriesCollection(seriesLifetime); data.addSeries(seriesSnakeLength); chart = ChartFactory.createXYLineChart("Highest Number moves per generation", "Generation", "# Moves", data, PlotOrientation.VERTICAL, true, true, false); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(900, 500)); chartPanel.setMaximumSize(new Dimension(900, 500)); container.add(chartPanel); add(container); createEnemySnake(); } private void createEnemySnake() { enemySnake = new Snake(); enemySnake.head = new Point(9, 6); enemySnake.tail.add(new Point(9, 1)); enemySnake.tail.add(new Point(9, 2)); enemySnake.tail.add(new Point(9, 3)); enemySnake.tail.add(new Point(9, 4)); enemySnake.tail.add(new Point(9, 5)); } public void runWorld() { if (timer != null) { return; } if (population == null) { population = new Population(POPULATIONSIZE, BOARDSIZE); } worldRunning = true; timer = new Timer(true); timer.scheduleAtFixedRate(new MoveTask(this), 0, MOVETIME_MS); } protected void update() { playArea.update(); } private List<Point> getEnemySnakesCoords() { List<Point> snakeCoords = new ArrayList<Point>(); // TODO: replace by snake array snakeCoords.add(enemySnake.head); snakeCoords.addAll(enemySnake.tail); return snakeCoords; } public void keyReleased(KeyEvent arg0) { if (arg0.getKeyCode() == KeyEvent.VK_ESCAPE) { dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (arg0.getKeyCode() == KeyEvent.VK_SPACE) { population.setTraining(!population.isTraining()); } else if (arg0.getKeyChar() == 's') { population.getBestSnake().brain.save("savednn.txt"); } else if (arg0.getKeyChar() == 'l') { population = new Population("savednn.txt", POPULATIONSIZE, BOARDSIZE); } else if (arg0.getKeyCode() == KeyEvent.VK_ENTER) { runWorld(); } } public void moveEnemySnakeRandomly() { Point direction = getRandomDirection(); int deadlockCnt = 0; while (deadlockCnt < 20 && enemySnake.wouldDie(direction, BOARDSIZE)) { direction = getRandomDirection(); deadlockCnt++; } if (deadlockCnt == 20) { createEnemySnake(); } enemySnake.move(direction); } private Point getRandomDirection() { int x = ThreadLocalRandom.current().nextInt(-1, 2); int y = ThreadLocalRandom.current().nextInt(-1, 2); return new Point(x, y); } class MoveTask extends TimerTask { private World world; public MoveTask(World world) { this.world = world; } @Override public void run() { world.moveEnemySnakeRandomly(); // TODO: pass population as parameter to ctor? if (population.isPopulationDead()) { population.createNewGeneration(); createEnemySnake(); } else { population.moveSnakes(getEnemySnakesCoords()); } world.update(); } } class PlayArea extends JPanel { /** * */ private static final long serialVersionUID = 1L; int boardSize; int fieldSize; int margin; String logMsg = new String(); public PlayArea(int boardSize, int fieldSize, int margin) { this.boardSize = boardSize; this.fieldSize = fieldSize; this.margin = margin; } public void update() { validate(); repaint(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // Draw Board g.setColor(Color.BLACK); for (int rowIdx = 0; rowIdx < BOARDSIZE; ++rowIdx) { for (int colIdx = 0; colIdx < BOARDSIZE; ++colIdx) { g.drawRect(MARGIN + rowIdx * fieldSize, MARGIN + colIdx * fieldSize, fieldSize, fieldSize); } } if (!worldRunning) { return; } if (population.isTraining()) { // Draw Food // for (GoodSnake snake : population.getSnakes()) { // // // Food // if (!snake.isDead() ) { // g.setColor(Color.BLUE); // for (Point food : snake.getFood()) { // g.fillRect(MARGIN + food.x * FIELD_SIZE, MARGIN + food.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); // } // //// break; // } // } // Draw Snakes for (GoodSnake snake : population.getSnakes()) { if (!snake.isDead()) { if (snake.isDead()) { g.setColor(Color.GRAY); } else { g.setColor(Color.BLACK); } for (Point tail : snake.tail) { g.fillRect(MARGIN + tail.x * FIELD_SIZE, MARGIN + tail.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } if (snake.isDead()) { g.setColor(Color.GRAY); } else { g.setColor(Color.GREEN); } g.fillRect(MARGIN + snake.head.x * FIELD_SIZE, MARGIN + snake.head.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); // break; } } } else { GoodSnake bestSnake = population.getDemonstrationSnake(); // Draw Food g.setColor(Color.BLUE); for (Point food : bestSnake.getFood()) { g.fillRect(MARGIN + food.x * FIELD_SIZE, MARGIN + food.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } if (bestSnake.isDead()) { g.setColor(Color.GRAY); } else { g.setColor(Color.BLACK); } for (Point tail : bestSnake.tail) { g.fillRect(MARGIN + tail.x * FIELD_SIZE, MARGIN + tail.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } if (bestSnake.isDead()) { g.setColor(Color.GRAY); } else { g.setColor(Color.GREEN); } g.fillRect(MARGIN + bestSnake.head.x * FIELD_SIZE, MARGIN + bestSnake.head.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } // Draw Enemy Snake g.setColor(Color.BLACK); for (Point tail : enemySnake.tail) { g.fillRect(MARGIN + tail.x * FIELD_SIZE, MARGIN + tail.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); } g.setColor(Color.RED); g.fillRect(MARGIN + enemySnake.head.x * FIELD_SIZE, MARGIN + enemySnake.head.y * FIELD_SIZE, FIELD_SIZE, FIELD_SIZE); // Draw Logging g.setColor(Color.BLACK); g.drawString("# Populations: " + Integer.toString(population.getGenerationNo()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN); GoodSnake bestSnake = population.getBestSnake(); if (bestSnake != null) { g.drawString("Current Best Snakes Fitness: " + Double.toString(bestSnake.getFitness()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 20); g.drawString("Current Best Snakes Lifetime: " + Double.toString(population.getLocalMostMoves()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 40); g.drawString("Current Best Snakes Length: " + Double.toString(population.getLocalBiggestLength()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 60); g.drawString("Global Best Snakes Fitness: " + Double.toString(population.getGlobalBestFitness()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 80); g.drawString("Global Best Snakes Lifetime: " + Double.toString(population.getGlobalMostMoves()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 100); g.drawString("Global Best Snakes Length: " + Double.toString(population.getGlobalBiggestLength()), MARGIN, MARGIN + BOARDSIZE * FIELD_SIZE + MARGIN + 120); } if (bestSnake != null) { if (population.getLifetimeHistory().size() > seriesLifetime.getItemCount()) { seriesLifetime.add(seriesLifetime.getItemCount() + 1, population.getLifetimeHistory().get(population.getLifetimeHistory().size()-1)); } if (population.getSnakeLengthHistory().size() > seriesSnakeLength.getItemCount()) { seriesSnakeLength.add(seriesSnakeLength.getItemCount() + 1, population.getSnakeLengthHistory().get(population.getSnakeLengthHistory().size()-1)); } } } } public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }
9,890
0.667947
0.657937
356
26.77528
30.944042
159
false
false
0
0
0
0
0
0
3.160112
false
false
1
cf4903f8ebbc18bc7e12f01f44b5c25d45f3fb8e
27,736,898,810,842
edf009b7ae29106f87d3b8596e0a60992160a48a
/Shoping/src/system/servlet/loginFilter.java
828eb37a9f7447e1fdc8a0dabaeb334fe9e40fb1
[]
no_license
JunqiFu/more_web
https://github.com/JunqiFu/more_web
d6b610b7cdc465bd4c891f837bf6a68e78be9e08
aa81fd0fac9c0d3ddcdbaeda4ecee1073fe2e20c
refs/heads/master
2021-09-29T01:12:27.564000
2018-11-22T06:06:52
2018-11-22T06:06:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package system.servlet; /*<filter> <filter-name>loginFilter</filter-name> <filter-class>system.servlet.loginFilter</filter-class> <init-param> <param-name>include</param-name> <param-value>manageUserinfo,addAddrinfo</param-value> </init-param> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>*/ import java.io.IOException; import system.bean.Userinfo; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class loginFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpSession session = ((HttpServletRequest)request).getSession(); //获取HttpSession Userinfo user = (Userinfo)session.getAttribute("Username"); //获取用户信息(登陆用户才有) if(user==null){ String path = ((HttpServletRequest)request).getContextPath(); ((HttpServletResponse)response).sendRedirect(path+"/index.jsp"); return; } filterChain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
GB18030
Java
1,693
java
loginFilter.java
Java
[]
null
[]
package system.servlet; /*<filter> <filter-name>loginFilter</filter-name> <filter-class>system.servlet.loginFilter</filter-class> <init-param> <param-name>include</param-name> <param-value>manageUserinfo,addAddrinfo</param-value> </init-param> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>*/ import java.io.IOException; import system.bean.Userinfo; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class loginFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpSession session = ((HttpServletRequest)request).getSession(); //获取HttpSession Userinfo user = (Userinfo)session.getAttribute("Username"); //获取用户信息(登陆用户才有) if(user==null){ String path = ((HttpServletRequest)request).getContextPath(); ((HttpServletResponse)response).sendRedirect(path+"/index.jsp"); return; } filterChain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
1,693
0.72065
0.720048
58
26.637932
23.479042
83
false
false
0
0
0
0
0
0
1.327586
false
false
1
0b48c78cf803234ba8278a8c4fb013e470d4c928
3,968,549,800,677
232cb52812c1351a9b2ed2db4d55d217fd118cce
/src/com/training/srs/dao/IdGeneratorAnnotation.java
8e64dfe4af568572ed444acc1d43e5ab7250a63d
[]
no_license
shamalsd/ship-reservation-system
https://github.com/shamalsd/ship-reservation-system
442f82d5bb6400c974d050ed899ffd0bed282935
c0cfe883541cc2aa0049d3c04894cfeed7e577d1
refs/heads/master
2023-03-28T04:15:33.962000
2021-03-06T07:43:17
2021-03-06T07:43:17
345,035,211
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.training.srs.dao; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy=IdGeneratorClass.class) public @interface IdGeneratorAnnotation { String message() default "Name should start with capital letter"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default{}; }
UTF-8
Java
577
java
IdGeneratorAnnotation.java
Java
[]
null
[]
package com.training.srs.dao; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy=IdGeneratorClass.class) public @interface IdGeneratorAnnotation { String message() default "Name should start with capital letter"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default{}; }
577
0.786828
0.786828
21
26.476191
19.599852
66
false
false
0
0
0
0
0
0
0.904762
false
false
1
bece4267b7377e0bba20283cab6a97237548f106
12,283,606,488,670
e89b6be272f1c70fd93f80285a552b1d80e40705
/src/main/java/com/hello/suripu/service/resources/RegisterResource.java
d008b8bd894cfe87374d2cfd3a4231ff0c529ef2
[]
no_license
hello/suripu-service
https://github.com/hello/suripu-service
ec6b9c5f3109c49092b7d628f829f1f07f14baf0
981fe38a0fb157d63b04b4278af52048fdc846c7
refs/heads/master
2021-03-30T17:48:37.303000
2017-05-03T22:11:18
2017-05-03T22:11:18
45,714,188
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hello.suripu.service.resources; import com.codahale.metrics.annotation.Timed; import com.google.common.base.Optional; import com.hello.dropwizard.mikkusu.helpers.AdditionalMediaTypes; import com.hello.suripu.api.ble.SenseCommandProtos; import com.hello.suripu.api.ble.SenseCommandProtos.MorpheusCommand; import com.hello.suripu.api.logging.LoggingProtos; import com.hello.suripu.core.configuration.QueueName; import com.hello.suripu.core.db.DeviceDAO; import com.hello.suripu.core.db.KeyStore; import com.hello.suripu.core.db.KeyStoreDynamoDB; import com.hello.suripu.core.flipper.FeatureFlipper; import com.hello.suripu.core.flipper.GroupFlipper; import com.hello.suripu.core.logging.DataLogger; import com.hello.suripu.core.logging.KinesisLoggerFactory; import com.hello.suripu.core.models.DeviceAccountPair; import com.hello.suripu.core.oauth.ClientCredentials; import com.hello.suripu.core.oauth.ClientDetails; import com.hello.suripu.core.oauth.MissingRequiredScopeException; import com.hello.suripu.core.oauth.OAuthScope; import com.hello.suripu.core.oauth.stores.OAuthTokenStore; import com.hello.suripu.core.util.HelloHttpHeader; import com.hello.suripu.core.util.PairAction; import com.hello.suripu.coredropwizard.oauth.AccessToken; import com.hello.suripu.service.SignedMessage; import com.hello.suripu.service.pairing.PairingAttempt; import com.hello.suripu.service.pairing.PairingManager; import com.hello.suripu.service.pairing.PairingResult; import com.hello.suripu.service.utils.KinesisRegistrationLogger; import com.hello.suripu.service.utils.ServiceFeatureFlipper; import com.librato.rollout.RolloutClient; import org.apache.commons.codec.binary.Hex; import org.joda.time.DateTime; import org.skife.jdbi.v2.exceptions.DBIException; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by pangwu on 10/10/14. */ @Path("/register") public class RegisterResource extends BaseResource { private static final Pattern PG_UNIQ_PATTERN = Pattern.compile("ERROR: duplicate key value violates unique constraint \"(\\w+)\""); private static int PROTOBUF_VERSION = 0; private static final Logger LOGGER = LoggerFactory.getLogger(RegisterResource.class); private final DeviceDAO deviceDAO; final OAuthTokenStore<AccessToken, ClientDetails, ClientCredentials> tokenStore; private final KinesisLoggerFactory kinesisLoggerFactory; private final KeyStore senseKeyStore; private final static String UNKNOWN_SENSE_ID = "UNKNOWN"; private final PairingManager pairingManager; @Context HttpServletRequest request; @Inject RolloutClient featureFlipper; private final GroupFlipper groupFlipper; public RegisterResource(final DeviceDAO deviceDAO, final OAuthTokenStore<AccessToken, ClientDetails, ClientCredentials> tokenStore, final KinesisLoggerFactory kinesisLoggerFactory, final KeyStore senseKeyStore, final GroupFlipper groupFlipper, final PairingManager pairingManager){ this.deviceDAO = deviceDAO; this.tokenStore = tokenStore; this.kinesisLoggerFactory = kinesisLoggerFactory; this.senseKeyStore = senseKeyStore; this.groupFlipper = groupFlipper; this.pairingManager = pairingManager; } protected final boolean checkCommandType(final MorpheusCommand morpheusCommand, final PairAction action){ switch (action){ case PAIR_PILL: return morpheusCommand.getType() == MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_PILL; case PAIR_MORPHEUS: return morpheusCommand.getType() == MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE; default: return false; } } private boolean isPillPairingDebugMode(final String senseId) { final List<String> groups = groupFlipper.getGroups(senseId); return featureFlipper.deviceFeatureActive(FeatureFlipper.DEBUG_MODE_PILL_PAIRING, senseId, groups); } private boolean notifyOnConflict(final Long accountId) { final List<String> groups = groupFlipper.getGroups(accountId); return featureFlipper.userFeatureActive(ServiceFeatureFlipper.NOTIFY_ON_PAIRING_CONFLICT.getFeatureName(), accountId, groups); } private final Optional<AccessToken> getClientDetailsByToken(final ClientCredentials credentials, final DateTime now) { try { return this.tokenStore.getTokenByClientCredentials(credentials, now); } catch (MissingRequiredScopeException e) { return Optional.absent(); } } protected final MorpheusCommand.Builder pair(final String senseIdFromHeader, final byte[] encryptedRequest, final KeyStore keyStore, final PairAction action, final String ipAddress) { // Mutable until this is re-architected. MorpheusCommand.Builder builder = MorpheusCommand.newBuilder() .setVersion(PROTOBUF_VERSION); final DataLogger registrationLogger = kinesisLoggerFactory.get(QueueName.LOGS); // onboarding logger should be accessed through PairingManger.logger() final PairingManager pairer = pairingManager.withLogger( KinesisRegistrationLogger.create(senseIdFromHeader, action, ipAddress, registrationLogger) ); MorpheusCommand morpheusCommand = MorpheusCommand.getDefaultInstance(); SignedMessage signedMessage = null; try { signedMessage = SignedMessage.parse(encryptedRequest); // This call will throw morpheusCommand = MorpheusCommand.parseFrom(signedMessage.body); } catch (IOException exception) { final String errorMessage = String.format("Failed parsing protobuf: %s", exception.getMessage()); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.absent(), errorMessage); // We can't return a proper error because we can't decode the protobuf throwPlainTextError(Response.Status.BAD_REQUEST, ""); } catch (RuntimeException rtEx){ final String errorMessage = String.format("Failed parsing input: %s", rtEx.getMessage()); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.absent(), errorMessage); // We can't return a proper error because we can't decode the protobuf throwPlainTextError(Response.Status.BAD_REQUEST, ""); } final String deviceId = morpheusCommand.getDeviceId(); builder.setDeviceId(deviceId); String senseId = ""; String pillId = ""; final String token = morpheusCommand.getAccountId(); LOGGER.debug("deviceId = {}", deviceId); LOGGER.debug("token = {}", token); final Optional<AccessToken> accessTokenOptional = getClientDetailsByToken( new ClientCredentials(new OAuthScope[]{OAuthScope.AUTH}, token), DateTime.now()); if(!accessTokenOptional.isPresent()) { builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_OPERATION_FAILED); final String logMessage = String.format("Token not found %s for device Id %s", token, deviceId); LOGGER.error(logMessage); pairer.logger().logFailure(Optional.<String>absent(), logMessage); pairer.logger().commit(); return builder; } final Long accountId = accessTokenOptional.get().accountId; pairer.logger().setAccountId(accountId); final String logMessage = String.format("AccountId from protobuf = %d", accountId); LOGGER.debug(logMessage); pairer.logger().logProgress(Optional.<String>absent(), logMessage); // this is only needed for devices with 000... in the header // MUST BE CLEARED when the buffer is returned to Sense builder.setAccountId(token); switch (action) { case PAIR_MORPHEUS: senseId = deviceId; pairer.logger().setSenseId(senseId); // We need this until the provision problem got fixed. break; case PAIR_PILL: pillId = deviceId; final List<DeviceAccountPair> deviceAccountPairs = this.deviceDAO.getSensesForAccountId(accountId); if(deviceAccountPairs.isEmpty()){ final String errorMessage = String.format("No sense paired with account %d when pill %s tries to register", accountId, pillId); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_DATA_ERROR); pairer.logger().commit(); return builder; } senseId = deviceAccountPairs.get(0).externalDeviceId; break; } final Optional<byte[]> keyBytesOptional = keyStore.get(senseId); if(!keyBytesOptional.isPresent()) { final String errorMessage = String.format("Missing AES key for device = %s", senseId); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); throwPlainTextError(Response.Status.UNAUTHORIZED, "no key"); } final Optional<SignedMessage.Error> error = signedMessage.validateWithKey(keyBytesOptional.get()); if(error.isPresent()) { final String errorMessage = String.format("Fail to validate signature %s", error.get().message); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); throwPlainTextError(Response.Status.UNAUTHORIZED, "invalid signature"); } if(!checkCommandType(morpheusCommand, action)){ builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_DATA_ERROR); final String errorMessage = String.format("Wrong request command type %s", morpheusCommand.getType().toString()); LOGGER.error(errorMessage); LOGGER.error("error=wrong-request-command-type sense_id={}", senseId); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); pairer.logger().commit(); return builder; } try { switch (action){ case PAIR_MORPHEUS: { final PairingAttempt sensePairingAttempt = PairingAttempt.sense(builder, senseId,accountId, false, ipAddress); final PairingResult result = pairer.pairSense(sensePairingAttempt); builder = result.builder; break; } case PAIR_PILL: { final boolean pillPairingDebugMode = isPillPairingDebugMode(senseId); final boolean notifyOnConflict = notifyOnConflict(accountId); final PairingAttempt pillPairingAttempt = PairingAttempt.pill(builder, senseId, accountId, deviceId, pillPairingDebugMode, ipAddress, notifyOnConflict); final PairingResult result = pairer.pairPill(pillPairingAttempt); builder = result.builder; break; } } //builder.setAccountId(morpheusCommand.getAccountId()); } catch (UnableToExecuteStatementException sqlExp){ final Matcher matcher = PG_UNIQ_PATTERN.matcher(sqlExp.getMessage()); if (!matcher.find()) { final String errorMessage = String.format("SQL error %s", sqlExp.getMessage()); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_OPERATION_FAILED); }else { LOGGER.error(sqlExp.getMessage()); pairer.logger().logFailure(Optional.fromNullable(pillId), sqlExp.getMessage()); //TODO: enforce the constraint LOGGER.warn("Account {} tries to pair a paired device {} ", accountId, deviceId); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.DEVICE_ALREADY_PAIRED); } } catch (DBIException e) { LOGGER.error("action={} error=db-fail sense_id={} message={}", action, senseId, e.getMessage()); LOGGER.error("error=db-down message={}", e.getMessage()); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.SERVER_CONNECTION_TIMEOUT); } catch (Exception e) { LOGGER.error("action={} error=register-fail sense_id={} message={}", action, senseId, e.getMessage()); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_OPERATION_FAILED); } try { final String ip = request.getHeader("X-Forwarded-For"); final DataLogger dataLogger = kinesisLoggerFactory.get(QueueName.REGISTRATIONS); final LoggingProtos.Registration.Builder registration = LoggingProtos.Registration.newBuilder().setAccountId(accountId) .setDeviceId(deviceId) .setTimestamp(DateTime.now().getMillis()); if (ip != null) { registration.setIpAddress(ip); } dataLogger.put(accountId.toString(), registration.build().toByteArray()); } catch (Exception e) { LOGGER.error("error=failed-registration-insert-kinesis message={}", e.getMessage()); } pairer.logger().commit(); return builder; } private byte[] signAndSend(final String senseId, final MorpheusCommand.Builder morpheusCommandBuilder, final KeyStore keyStore) { final Optional<byte[]> keyBytesOptional = keyStore.get(senseId); if(!keyBytesOptional.isPresent()) { LOGGER.error("error=missing-aes-key sense_id={}", senseId); return plainTextError(Response.Status.INTERNAL_SERVER_ERROR, ""); } LOGGER.trace("Key used to sign device {} : {}", senseId, Hex.encodeHexString(keyBytesOptional.get())); final Optional<byte[]> signedResponse = SignedMessage.sign(morpheusCommandBuilder.build().toByteArray(), keyBytesOptional.get()); if(!signedResponse.isPresent()) { LOGGER.error("Failed signing message for deviceId = {}", senseId); return plainTextError(Response.Status.INTERNAL_SERVER_ERROR, ""); } return signedResponse.get(); } @POST @Path("/morpheus") @Consumes(AdditionalMediaTypes.APPLICATION_PROTOBUF) @Produces(MediaType.APPLICATION_OCTET_STREAM) @Deprecated @Timed public byte[] registerMorpheus(final byte[] body) { final String senseIdFromHeader = this.request.getHeader(HelloHttpHeader.SENSE_ID); if(senseIdFromHeader != null){ LOGGER.info("Sense Id from http header {}", senseIdFromHeader); } final MorpheusCommand.Builder builder = pair(senseIdFromHeader, body, senseKeyStore, PairAction.PAIR_MORPHEUS, getIpAddress(request)); builder.clearAccountId(); if(senseIdFromHeader != null && senseIdFromHeader.equals(KeyStoreDynamoDB.DEFAULT_FACTORY_DEVICE_ID)){ senseKeyStore.put(builder.getDeviceId(), Hex.encodeHexString(KeyStoreDynamoDB.DEFAULT_AES_KEY)); LOGGER.error("Key for device {} has been automatically generated", builder.getDeviceId()); } return signAndSend(builder.getDeviceId(), builder, senseKeyStore); } @POST @Path("/sense") @Consumes(AdditionalMediaTypes.APPLICATION_PROTOBUF) @Produces(MediaType.APPLICATION_OCTET_STREAM) @Timed public byte[] registerSense(final byte[] body) { final String senseIdFromHeader = this.request.getHeader(HelloHttpHeader.SENSE_ID); final String senseId = (senseIdFromHeader != null) ? senseIdFromHeader : UNKNOWN_SENSE_ID; final String middleFW = getFirmwareVersion(request, HelloHttpHeader.MIDDLE_FW_VERSION); final String topFW = getFirmwareVersion(request, HelloHttpHeader.TOP_FW_VERSION); final String ipAddress = getIpAddress(request); LOGGER.info("action=pair-sense sense_id={} ip_address={} fw_version={}, top_fw_version={}", senseId, ipAddress, middleFW, topFW); final MorpheusCommand.Builder builder = pair(senseIdFromHeader, body, senseKeyStore, PairAction.PAIR_MORPHEUS, ipAddress); if(senseIdFromHeader != null){ return signAndSend(senseIdFromHeader, builder, senseKeyStore); } return signAndSend(builder.getDeviceId(), builder, senseKeyStore); } @POST @Path("/pill") @Consumes(AdditionalMediaTypes.APPLICATION_PROTOBUF) @Produces(MediaType.APPLICATION_OCTET_STREAM) @Timed public byte[] registerPill(final byte[] body) { final String senseIdFromHeader = this.request.getHeader(HelloHttpHeader.SENSE_ID); final String senseId = (senseIdFromHeader != null) ? senseIdFromHeader : UNKNOWN_SENSE_ID; final String middleFW = getFirmwareVersion(request, HelloHttpHeader.MIDDLE_FW_VERSION); final String topFW = getFirmwareVersion(request, HelloHttpHeader.TOP_FW_VERSION); final String ipAddress = getIpAddress(request); LOGGER.info("action=pair-pill sense_id={} ip_address={} fw_version={}, top_fw_version={}", senseId, ipAddress, middleFW, topFW); final MorpheusCommand.Builder builder = pair(senseIdFromHeader, body, senseKeyStore, PairAction.PAIR_PILL, ipAddress); final String token = builder.getAccountId(); // WARNING: never return the account id, it will overflow buffer for old versions builder.clearAccountId(); if(senseIdFromHeader != null && !senseIdFromHeader.equals(KeyStoreDynamoDB.DEFAULT_FACTORY_DEVICE_ID)){ LOGGER.info("Sense Id from http header {}", senseIdFromHeader); return signAndSend(senseIdFromHeader, builder, senseKeyStore); } LOGGER.warn("action=pair-pill-token-lookup sense_id={} ip_address={} fw_version={}, top_fw_version={}", senseId, ipAddress, middleFW, topFW); // TODO: Remove this and get sense id from header after the firmware is fixed. final Optional<AccessToken> accessTokenOptional = getClientDetailsByToken( new ClientCredentials(new OAuthScope[]{OAuthScope.AUTH}, token), DateTime.now()); if(!accessTokenOptional.isPresent()) { LOGGER.error("Did not find accessToken {}", token); return plainTextError(Response.Status.BAD_REQUEST, ""); } final Long accountId = accessTokenOptional.get().accountId; final List<DeviceAccountPair> deviceAccountPairs = this.deviceDAO.getSensesForAccountId(accountId); if(deviceAccountPairs.isEmpty()) { return plainTextError(Response.Status.BAD_REQUEST, ""); } final String senseIdFromDB = deviceAccountPairs.get(0).externalDeviceId; return signAndSend(senseIdFromDB, builder, senseKeyStore); } // TODO: move this in base resource private static String getFirmwareVersion(final HttpServletRequest request, final String board) { final String fwVersion = (request.getHeader(board) != null) ? request.getHeader(board) : "0"; return fwVersion; } }
UTF-8
Java
20,793
java
RegisterResource.java
Java
[ { "context": "mport java.util.regex.Pattern;\n\n\n/**\n * Created by pangwu on 10/10/14.\n */\n@Path(\"/register\")\npublic class ", "end": 2316, "score": 0.9995675086975098, "start": 2310, "tag": "USERNAME", "value": "pangwu" } ]
null
[]
package com.hello.suripu.service.resources; import com.codahale.metrics.annotation.Timed; import com.google.common.base.Optional; import com.hello.dropwizard.mikkusu.helpers.AdditionalMediaTypes; import com.hello.suripu.api.ble.SenseCommandProtos; import com.hello.suripu.api.ble.SenseCommandProtos.MorpheusCommand; import com.hello.suripu.api.logging.LoggingProtos; import com.hello.suripu.core.configuration.QueueName; import com.hello.suripu.core.db.DeviceDAO; import com.hello.suripu.core.db.KeyStore; import com.hello.suripu.core.db.KeyStoreDynamoDB; import com.hello.suripu.core.flipper.FeatureFlipper; import com.hello.suripu.core.flipper.GroupFlipper; import com.hello.suripu.core.logging.DataLogger; import com.hello.suripu.core.logging.KinesisLoggerFactory; import com.hello.suripu.core.models.DeviceAccountPair; import com.hello.suripu.core.oauth.ClientCredentials; import com.hello.suripu.core.oauth.ClientDetails; import com.hello.suripu.core.oauth.MissingRequiredScopeException; import com.hello.suripu.core.oauth.OAuthScope; import com.hello.suripu.core.oauth.stores.OAuthTokenStore; import com.hello.suripu.core.util.HelloHttpHeader; import com.hello.suripu.core.util.PairAction; import com.hello.suripu.coredropwizard.oauth.AccessToken; import com.hello.suripu.service.SignedMessage; import com.hello.suripu.service.pairing.PairingAttempt; import com.hello.suripu.service.pairing.PairingManager; import com.hello.suripu.service.pairing.PairingResult; import com.hello.suripu.service.utils.KinesisRegistrationLogger; import com.hello.suripu.service.utils.ServiceFeatureFlipper; import com.librato.rollout.RolloutClient; import org.apache.commons.codec.binary.Hex; import org.joda.time.DateTime; import org.skife.jdbi.v2.exceptions.DBIException; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by pangwu on 10/10/14. */ @Path("/register") public class RegisterResource extends BaseResource { private static final Pattern PG_UNIQ_PATTERN = Pattern.compile("ERROR: duplicate key value violates unique constraint \"(\\w+)\""); private static int PROTOBUF_VERSION = 0; private static final Logger LOGGER = LoggerFactory.getLogger(RegisterResource.class); private final DeviceDAO deviceDAO; final OAuthTokenStore<AccessToken, ClientDetails, ClientCredentials> tokenStore; private final KinesisLoggerFactory kinesisLoggerFactory; private final KeyStore senseKeyStore; private final static String UNKNOWN_SENSE_ID = "UNKNOWN"; private final PairingManager pairingManager; @Context HttpServletRequest request; @Inject RolloutClient featureFlipper; private final GroupFlipper groupFlipper; public RegisterResource(final DeviceDAO deviceDAO, final OAuthTokenStore<AccessToken, ClientDetails, ClientCredentials> tokenStore, final KinesisLoggerFactory kinesisLoggerFactory, final KeyStore senseKeyStore, final GroupFlipper groupFlipper, final PairingManager pairingManager){ this.deviceDAO = deviceDAO; this.tokenStore = tokenStore; this.kinesisLoggerFactory = kinesisLoggerFactory; this.senseKeyStore = senseKeyStore; this.groupFlipper = groupFlipper; this.pairingManager = pairingManager; } protected final boolean checkCommandType(final MorpheusCommand morpheusCommand, final PairAction action){ switch (action){ case PAIR_PILL: return morpheusCommand.getType() == MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_PILL; case PAIR_MORPHEUS: return morpheusCommand.getType() == MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE; default: return false; } } private boolean isPillPairingDebugMode(final String senseId) { final List<String> groups = groupFlipper.getGroups(senseId); return featureFlipper.deviceFeatureActive(FeatureFlipper.DEBUG_MODE_PILL_PAIRING, senseId, groups); } private boolean notifyOnConflict(final Long accountId) { final List<String> groups = groupFlipper.getGroups(accountId); return featureFlipper.userFeatureActive(ServiceFeatureFlipper.NOTIFY_ON_PAIRING_CONFLICT.getFeatureName(), accountId, groups); } private final Optional<AccessToken> getClientDetailsByToken(final ClientCredentials credentials, final DateTime now) { try { return this.tokenStore.getTokenByClientCredentials(credentials, now); } catch (MissingRequiredScopeException e) { return Optional.absent(); } } protected final MorpheusCommand.Builder pair(final String senseIdFromHeader, final byte[] encryptedRequest, final KeyStore keyStore, final PairAction action, final String ipAddress) { // Mutable until this is re-architected. MorpheusCommand.Builder builder = MorpheusCommand.newBuilder() .setVersion(PROTOBUF_VERSION); final DataLogger registrationLogger = kinesisLoggerFactory.get(QueueName.LOGS); // onboarding logger should be accessed through PairingManger.logger() final PairingManager pairer = pairingManager.withLogger( KinesisRegistrationLogger.create(senseIdFromHeader, action, ipAddress, registrationLogger) ); MorpheusCommand morpheusCommand = MorpheusCommand.getDefaultInstance(); SignedMessage signedMessage = null; try { signedMessage = SignedMessage.parse(encryptedRequest); // This call will throw morpheusCommand = MorpheusCommand.parseFrom(signedMessage.body); } catch (IOException exception) { final String errorMessage = String.format("Failed parsing protobuf: %s", exception.getMessage()); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.absent(), errorMessage); // We can't return a proper error because we can't decode the protobuf throwPlainTextError(Response.Status.BAD_REQUEST, ""); } catch (RuntimeException rtEx){ final String errorMessage = String.format("Failed parsing input: %s", rtEx.getMessage()); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.absent(), errorMessage); // We can't return a proper error because we can't decode the protobuf throwPlainTextError(Response.Status.BAD_REQUEST, ""); } final String deviceId = morpheusCommand.getDeviceId(); builder.setDeviceId(deviceId); String senseId = ""; String pillId = ""; final String token = morpheusCommand.getAccountId(); LOGGER.debug("deviceId = {}", deviceId); LOGGER.debug("token = {}", token); final Optional<AccessToken> accessTokenOptional = getClientDetailsByToken( new ClientCredentials(new OAuthScope[]{OAuthScope.AUTH}, token), DateTime.now()); if(!accessTokenOptional.isPresent()) { builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_OPERATION_FAILED); final String logMessage = String.format("Token not found %s for device Id %s", token, deviceId); LOGGER.error(logMessage); pairer.logger().logFailure(Optional.<String>absent(), logMessage); pairer.logger().commit(); return builder; } final Long accountId = accessTokenOptional.get().accountId; pairer.logger().setAccountId(accountId); final String logMessage = String.format("AccountId from protobuf = %d", accountId); LOGGER.debug(logMessage); pairer.logger().logProgress(Optional.<String>absent(), logMessage); // this is only needed for devices with 000... in the header // MUST BE CLEARED when the buffer is returned to Sense builder.setAccountId(token); switch (action) { case PAIR_MORPHEUS: senseId = deviceId; pairer.logger().setSenseId(senseId); // We need this until the provision problem got fixed. break; case PAIR_PILL: pillId = deviceId; final List<DeviceAccountPair> deviceAccountPairs = this.deviceDAO.getSensesForAccountId(accountId); if(deviceAccountPairs.isEmpty()){ final String errorMessage = String.format("No sense paired with account %d when pill %s tries to register", accountId, pillId); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_DATA_ERROR); pairer.logger().commit(); return builder; } senseId = deviceAccountPairs.get(0).externalDeviceId; break; } final Optional<byte[]> keyBytesOptional = keyStore.get(senseId); if(!keyBytesOptional.isPresent()) { final String errorMessage = String.format("Missing AES key for device = %s", senseId); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); throwPlainTextError(Response.Status.UNAUTHORIZED, "no key"); } final Optional<SignedMessage.Error> error = signedMessage.validateWithKey(keyBytesOptional.get()); if(error.isPresent()) { final String errorMessage = String.format("Fail to validate signature %s", error.get().message); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); throwPlainTextError(Response.Status.UNAUTHORIZED, "invalid signature"); } if(!checkCommandType(morpheusCommand, action)){ builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_DATA_ERROR); final String errorMessage = String.format("Wrong request command type %s", morpheusCommand.getType().toString()); LOGGER.error(errorMessage); LOGGER.error("error=wrong-request-command-type sense_id={}", senseId); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); pairer.logger().commit(); return builder; } try { switch (action){ case PAIR_MORPHEUS: { final PairingAttempt sensePairingAttempt = PairingAttempt.sense(builder, senseId,accountId, false, ipAddress); final PairingResult result = pairer.pairSense(sensePairingAttempt); builder = result.builder; break; } case PAIR_PILL: { final boolean pillPairingDebugMode = isPillPairingDebugMode(senseId); final boolean notifyOnConflict = notifyOnConflict(accountId); final PairingAttempt pillPairingAttempt = PairingAttempt.pill(builder, senseId, accountId, deviceId, pillPairingDebugMode, ipAddress, notifyOnConflict); final PairingResult result = pairer.pairPill(pillPairingAttempt); builder = result.builder; break; } } //builder.setAccountId(morpheusCommand.getAccountId()); } catch (UnableToExecuteStatementException sqlExp){ final Matcher matcher = PG_UNIQ_PATTERN.matcher(sqlExp.getMessage()); if (!matcher.find()) { final String errorMessage = String.format("SQL error %s", sqlExp.getMessage()); LOGGER.error(errorMessage); pairer.logger().logFailure(Optional.fromNullable(pillId), errorMessage); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_OPERATION_FAILED); }else { LOGGER.error(sqlExp.getMessage()); pairer.logger().logFailure(Optional.fromNullable(pillId), sqlExp.getMessage()); //TODO: enforce the constraint LOGGER.warn("Account {} tries to pair a paired device {} ", accountId, deviceId); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.DEVICE_ALREADY_PAIRED); } } catch (DBIException e) { LOGGER.error("action={} error=db-fail sense_id={} message={}", action, senseId, e.getMessage()); LOGGER.error("error=db-down message={}", e.getMessage()); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.SERVER_CONNECTION_TIMEOUT); } catch (Exception e) { LOGGER.error("action={} error=register-fail sense_id={} message={}", action, senseId, e.getMessage()); builder.setType(MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR); builder.setError(SenseCommandProtos.ErrorType.INTERNAL_OPERATION_FAILED); } try { final String ip = request.getHeader("X-Forwarded-For"); final DataLogger dataLogger = kinesisLoggerFactory.get(QueueName.REGISTRATIONS); final LoggingProtos.Registration.Builder registration = LoggingProtos.Registration.newBuilder().setAccountId(accountId) .setDeviceId(deviceId) .setTimestamp(DateTime.now().getMillis()); if (ip != null) { registration.setIpAddress(ip); } dataLogger.put(accountId.toString(), registration.build().toByteArray()); } catch (Exception e) { LOGGER.error("error=failed-registration-insert-kinesis message={}", e.getMessage()); } pairer.logger().commit(); return builder; } private byte[] signAndSend(final String senseId, final MorpheusCommand.Builder morpheusCommandBuilder, final KeyStore keyStore) { final Optional<byte[]> keyBytesOptional = keyStore.get(senseId); if(!keyBytesOptional.isPresent()) { LOGGER.error("error=missing-aes-key sense_id={}", senseId); return plainTextError(Response.Status.INTERNAL_SERVER_ERROR, ""); } LOGGER.trace("Key used to sign device {} : {}", senseId, Hex.encodeHexString(keyBytesOptional.get())); final Optional<byte[]> signedResponse = SignedMessage.sign(morpheusCommandBuilder.build().toByteArray(), keyBytesOptional.get()); if(!signedResponse.isPresent()) { LOGGER.error("Failed signing message for deviceId = {}", senseId); return plainTextError(Response.Status.INTERNAL_SERVER_ERROR, ""); } return signedResponse.get(); } @POST @Path("/morpheus") @Consumes(AdditionalMediaTypes.APPLICATION_PROTOBUF) @Produces(MediaType.APPLICATION_OCTET_STREAM) @Deprecated @Timed public byte[] registerMorpheus(final byte[] body) { final String senseIdFromHeader = this.request.getHeader(HelloHttpHeader.SENSE_ID); if(senseIdFromHeader != null){ LOGGER.info("Sense Id from http header {}", senseIdFromHeader); } final MorpheusCommand.Builder builder = pair(senseIdFromHeader, body, senseKeyStore, PairAction.PAIR_MORPHEUS, getIpAddress(request)); builder.clearAccountId(); if(senseIdFromHeader != null && senseIdFromHeader.equals(KeyStoreDynamoDB.DEFAULT_FACTORY_DEVICE_ID)){ senseKeyStore.put(builder.getDeviceId(), Hex.encodeHexString(KeyStoreDynamoDB.DEFAULT_AES_KEY)); LOGGER.error("Key for device {} has been automatically generated", builder.getDeviceId()); } return signAndSend(builder.getDeviceId(), builder, senseKeyStore); } @POST @Path("/sense") @Consumes(AdditionalMediaTypes.APPLICATION_PROTOBUF) @Produces(MediaType.APPLICATION_OCTET_STREAM) @Timed public byte[] registerSense(final byte[] body) { final String senseIdFromHeader = this.request.getHeader(HelloHttpHeader.SENSE_ID); final String senseId = (senseIdFromHeader != null) ? senseIdFromHeader : UNKNOWN_SENSE_ID; final String middleFW = getFirmwareVersion(request, HelloHttpHeader.MIDDLE_FW_VERSION); final String topFW = getFirmwareVersion(request, HelloHttpHeader.TOP_FW_VERSION); final String ipAddress = getIpAddress(request); LOGGER.info("action=pair-sense sense_id={} ip_address={} fw_version={}, top_fw_version={}", senseId, ipAddress, middleFW, topFW); final MorpheusCommand.Builder builder = pair(senseIdFromHeader, body, senseKeyStore, PairAction.PAIR_MORPHEUS, ipAddress); if(senseIdFromHeader != null){ return signAndSend(senseIdFromHeader, builder, senseKeyStore); } return signAndSend(builder.getDeviceId(), builder, senseKeyStore); } @POST @Path("/pill") @Consumes(AdditionalMediaTypes.APPLICATION_PROTOBUF) @Produces(MediaType.APPLICATION_OCTET_STREAM) @Timed public byte[] registerPill(final byte[] body) { final String senseIdFromHeader = this.request.getHeader(HelloHttpHeader.SENSE_ID); final String senseId = (senseIdFromHeader != null) ? senseIdFromHeader : UNKNOWN_SENSE_ID; final String middleFW = getFirmwareVersion(request, HelloHttpHeader.MIDDLE_FW_VERSION); final String topFW = getFirmwareVersion(request, HelloHttpHeader.TOP_FW_VERSION); final String ipAddress = getIpAddress(request); LOGGER.info("action=pair-pill sense_id={} ip_address={} fw_version={}, top_fw_version={}", senseId, ipAddress, middleFW, topFW); final MorpheusCommand.Builder builder = pair(senseIdFromHeader, body, senseKeyStore, PairAction.PAIR_PILL, ipAddress); final String token = builder.getAccountId(); // WARNING: never return the account id, it will overflow buffer for old versions builder.clearAccountId(); if(senseIdFromHeader != null && !senseIdFromHeader.equals(KeyStoreDynamoDB.DEFAULT_FACTORY_DEVICE_ID)){ LOGGER.info("Sense Id from http header {}", senseIdFromHeader); return signAndSend(senseIdFromHeader, builder, senseKeyStore); } LOGGER.warn("action=pair-pill-token-lookup sense_id={} ip_address={} fw_version={}, top_fw_version={}", senseId, ipAddress, middleFW, topFW); // TODO: Remove this and get sense id from header after the firmware is fixed. final Optional<AccessToken> accessTokenOptional = getClientDetailsByToken( new ClientCredentials(new OAuthScope[]{OAuthScope.AUTH}, token), DateTime.now()); if(!accessTokenOptional.isPresent()) { LOGGER.error("Did not find accessToken {}", token); return plainTextError(Response.Status.BAD_REQUEST, ""); } final Long accountId = accessTokenOptional.get().accountId; final List<DeviceAccountPair> deviceAccountPairs = this.deviceDAO.getSensesForAccountId(accountId); if(deviceAccountPairs.isEmpty()) { return plainTextError(Response.Status.BAD_REQUEST, ""); } final String senseIdFromDB = deviceAccountPairs.get(0).externalDeviceId; return signAndSend(senseIdFromDB, builder, senseKeyStore); } // TODO: move this in base resource private static String getFirmwareVersion(final HttpServletRequest request, final String board) { final String fwVersion = (request.getHeader(board) != null) ? request.getHeader(board) : "0"; return fwVersion; } }
20,793
0.67441
0.673592
447
45.516777
37.217712
187
false
false
0
0
0
0
0
0
0.814318
false
false
1
5671632c0734c5149d0569259d90b86cee898d36
35,794,257,479,524
459805e61f3b1fea89dd5eff4a2b7fb51eb4b36d
/modules/gateway/management/src/main/java/com/l7tech/server/management/api/monitoring/NodeStatus.java
ff3992362af6de43f0659d78ec4e5222ccf103aa
[]
no_license
neelam-007/gateway
https://github.com/neelam-007/gateway
9ae2d04eda96ce510ad7034f4d72efa034f973cd
60e0a4138746803a14d8de070d3319b028fcffe4
refs/heads/master
2023-04-29T01:19:08.369000
2018-11-08T20:03:09
2018-11-08T20:03:09
368,039,344
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2009 Layer 7 Technologies Inc. */ package com.l7tech.server.management.api.monitoring; import com.l7tech.server.management.NodeStateType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; @XmlRootElement public class NodeStatus { private NodeStateType type; private Date startTime; private Date lastObservedTime; @Deprecated public NodeStatus() { } public NodeStatus(NodeStateType type, Date startTime, Date lastObservedTime) { this.type = type; this.startTime = startTime; this.lastObservedTime = lastObservedTime; } @XmlAttribute public NodeStateType getType() { return type; } @XmlAttribute public Date getStartTime() { return startTime; } @XmlAttribute public Date getLastObservedTime() { return lastObservedTime; } @Deprecated protected void setType(NodeStateType type) { this.type = type; } @Deprecated protected void setStartTime(Date startTime) { this.startTime = startTime; } @Deprecated protected void setLastObservedTime(Date lastObservedTime) { this.lastObservedTime = lastObservedTime; } }
UTF-8
Java
1,276
java
NodeStatus.java
Java
[]
null
[]
/* * Copyright (C) 2009 Layer 7 Technologies Inc. */ package com.l7tech.server.management.api.monitoring; import com.l7tech.server.management.NodeStateType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; @XmlRootElement public class NodeStatus { private NodeStateType type; private Date startTime; private Date lastObservedTime; @Deprecated public NodeStatus() { } public NodeStatus(NodeStateType type, Date startTime, Date lastObservedTime) { this.type = type; this.startTime = startTime; this.lastObservedTime = lastObservedTime; } @XmlAttribute public NodeStateType getType() { return type; } @XmlAttribute public Date getStartTime() { return startTime; } @XmlAttribute public Date getLastObservedTime() { return lastObservedTime; } @Deprecated protected void setType(NodeStateType type) { this.type = type; } @Deprecated protected void setStartTime(Date startTime) { this.startTime = startTime; } @Deprecated protected void setLastObservedTime(Date lastObservedTime) { this.lastObservedTime = lastObservedTime; } }
1,276
0.688872
0.683386
56
21.785715
19.779783
82
false
false
0
0
0
0
0
0
0.339286
false
false
1
0bba698c1d064adef58ab1da314ee534b9518947
32,083,405,758,703
2b5ba1c267ccf7b740cb6ba01628ec9302ae1f05
/java-project/src/main/java/com/sapient/week4/Matrix.java
6d43df9313aafbc2d6691a3d379a6a3e148f638e
[]
no_license
mohitvyas9265/JavaFirstProject
https://github.com/mohitvyas9265/JavaFirstProject
0d7d6926ebf1473a5252c20d95d5a427a9f48203
713f07406057c46eab64588e8cd0240eaf4c7d36
refs/heads/master
2022-12-21T19:33:10.253000
2020-06-05T18:52:18
2020-06-05T18:52:18
254,365,940
0
0
null
false
2022-12-16T04:24:16
2020-04-09T12:31:43
2020-06-05T18:52:21
2022-12-16T04:24:16
92
0
0
11
Java
false
false
package com.sapient.week4; import java.util.Arrays; import java.util.Scanner; public class Matrix { int arr[][]; public Matrix(int m,int n) { arr=new int[m][n]; } public Matrix() { arr=new int[3][3]; } public Matrix(int arr1[][]) { arr=new int[arr1.length][arr1[0].length]; for(int i=0;i<arr1.length;i++) { for(int j=0;j<arr1[0].length;j++) arr[i][j]=arr1[i][j]; } } public Matrix(Matrix obj) { arr=obj.arr; } public void readMatrix() { Scanner sc=new Scanner(System.in); int m=sc.nextInt(); int n=sc.nextInt(); arr=new int[m][n]; for(int i=0;i<m;i++) for(int j=0;j<n;j++) arr[i][j]=sc.nextInt(); } public void display() { for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[0].length;j++) System.out.print(arr[i][j]+" "); System.out.println(""); } } public int[][] add(int arr1[][]) { for(int i=0;i<arr1.length;i++) { for(int j=0;j<arr1[0].length;j++) arr[i][j]+=arr1[i][j]; } return arr; } public void scalar() { int result=arr[0][0]; for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[0].length;j++) { result=gcd(result,arr[i][j]); } } if(result!=1) System.out.println(" Matrix is Scalar "); else System.out.println(" Matrix is not Scalar "); } public int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public int[][] multiply(int arr1[][]) { int arr2[][] = new int[arr.length][arr1[0].length]; for(int i = 0; i < arr.length; i++) { for (int j = 0; j < arr1[0].length; j++) { for (int k = 0; k < arr[0].length; k++) { arr2[i][j] += arr[i][k] * arr1[k][j]; } } } return arr2; } }
UTF-8
Java
1,789
java
Matrix.java
Java
[]
null
[]
package com.sapient.week4; import java.util.Arrays; import java.util.Scanner; public class Matrix { int arr[][]; public Matrix(int m,int n) { arr=new int[m][n]; } public Matrix() { arr=new int[3][3]; } public Matrix(int arr1[][]) { arr=new int[arr1.length][arr1[0].length]; for(int i=0;i<arr1.length;i++) { for(int j=0;j<arr1[0].length;j++) arr[i][j]=arr1[i][j]; } } public Matrix(Matrix obj) { arr=obj.arr; } public void readMatrix() { Scanner sc=new Scanner(System.in); int m=sc.nextInt(); int n=sc.nextInt(); arr=new int[m][n]; for(int i=0;i<m;i++) for(int j=0;j<n;j++) arr[i][j]=sc.nextInt(); } public void display() { for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[0].length;j++) System.out.print(arr[i][j]+" "); System.out.println(""); } } public int[][] add(int arr1[][]) { for(int i=0;i<arr1.length;i++) { for(int j=0;j<arr1[0].length;j++) arr[i][j]+=arr1[i][j]; } return arr; } public void scalar() { int result=arr[0][0]; for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[0].length;j++) { result=gcd(result,arr[i][j]); } } if(result!=1) System.out.println(" Matrix is Scalar "); else System.out.println(" Matrix is not Scalar "); } public int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public int[][] multiply(int arr1[][]) { int arr2[][] = new int[arr.length][arr1[0].length]; for(int i = 0; i < arr.length; i++) { for (int j = 0; j < arr1[0].length; j++) { for (int k = 0; k < arr[0].length; k++) { arr2[i][j] += arr[i][k] * arr1[k][j]; } } } return arr2; } }
1,789
0.5109
0.485746
96
17.625
15.163175
57
false
false
0
0
0
0
0
0
2.145833
false
false
1
1f4825b1fab8c1444dfec0b1a1b0ee99e296f1aa
34,711,925,725,288
f3210f323645b6bc1007942720faeb858327de97
/distribuidora/src/modmantenimiento/util/BusquedaTipoPago.java
7afa6a36d28015ffb6ec8c48c6704b6ce4f6a4f5
[]
no_license
santiagoaisa/distribuidora
https://github.com/santiagoaisa/distribuidora
da1e0c16334742fa5e13a8acba09fb8f64de5bc7
ddff291604e8290e3d3a792a2285994474593163
refs/heads/master
2018-01-07T12:02:43.997000
2014-09-04T01:11:11
2014-09-04T01:11:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package modmantenimiento.util; import com.zarcillo.service.TipoCuentaBancariaService; import javax.naming.NamingException; import org.zkoss.zk.ui.HtmlMacroComponent; import org.zkoss.zk.ui.Path; import org.zkoss.zk.ui.select.SelectorComposer; import org.zkoss.zk.ui.select.annotation.Listen; import org.zkoss.zk.ui.select.annotation.VariableResolver; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zk.ui.select.annotation.WireVariable; import org.zkoss.zul.ListModelList; import org.zkoss.zul.Listbox; import org.zkoss.zul.Window; @VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class) public class BusquedaTipoPago extends SelectorComposer { @Wire private Listbox lstTipopago; @Wire private Window WinBtipopago; @WireVariable TipoCuentaBancariaService tipoCuentaBancariaService; private MenuResultado menuresultado; private ListModelList modeloTipopago; @Listen("onCreate=window#WinBtipopago") public void onCreate() throws NamingException { HtmlMacroComponent macro = (HtmlMacroComponent) WinBtipopago.getFellow("mresultado"); menuresultado = (MenuResultado) macro.getChildren().get(0); initComponets(); } public void initComponets(){ modeloTipopago=new ListModelList(tipoCuentaBancariaService.listaGeneral()); lstTipopago.setModel(modeloTipopago); lstTipopago.onInitRender(); menuresultado.setSize(modeloTipopago.getSize()); } }
UTF-8
Java
1,518
java
BusquedaTipoPago.java
Java
[]
null
[]
package modmantenimiento.util; import com.zarcillo.service.TipoCuentaBancariaService; import javax.naming.NamingException; import org.zkoss.zk.ui.HtmlMacroComponent; import org.zkoss.zk.ui.Path; import org.zkoss.zk.ui.select.SelectorComposer; import org.zkoss.zk.ui.select.annotation.Listen; import org.zkoss.zk.ui.select.annotation.VariableResolver; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zk.ui.select.annotation.WireVariable; import org.zkoss.zul.ListModelList; import org.zkoss.zul.Listbox; import org.zkoss.zul.Window; @VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class) public class BusquedaTipoPago extends SelectorComposer { @Wire private Listbox lstTipopago; @Wire private Window WinBtipopago; @WireVariable TipoCuentaBancariaService tipoCuentaBancariaService; private MenuResultado menuresultado; private ListModelList modeloTipopago; @Listen("onCreate=window#WinBtipopago") public void onCreate() throws NamingException { HtmlMacroComponent macro = (HtmlMacroComponent) WinBtipopago.getFellow("mresultado"); menuresultado = (MenuResultado) macro.getChildren().get(0); initComponets(); } public void initComponets(){ modeloTipopago=new ListModelList(tipoCuentaBancariaService.listaGeneral()); lstTipopago.setModel(modeloTipopago); lstTipopago.onInitRender(); menuresultado.setSize(modeloTipopago.getSize()); } }
1,518
0.757576
0.756917
43
34.325581
23.370346
93
false
false
0
0
0
0
0
0
0.581395
false
false
1
8c7b4c5159a535b2a46f178f390bf9b8f0527d73
38,723,425,186,459
030b82cf0ed7f341e3464403d44c58ef650f1f96
/examsys/src/main/java/com/hainan/cs/dao/NewTestDaoImp.java
a7a9062d4e05b8d61648e15402d1f138ea988397
[]
no_license
ChenJingS/examination_system
https://github.com/ChenJingS/examination_system
27570e443a3ff601c03f2c9adc351c8db4479e82
d8b7feb35289f3e7d6fbe3524e00b2cf4b5b0949
refs/heads/master
2021-06-10T19:41:28.464000
2017-02-18T15:18:47
2017-02-18T15:18:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hainan.cs.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.hainan.cs.bean.NewTest; import com.hainan.cs.bean.TestBean; public class NewTestDaoImp implements NewTestDao { private SessionFactory sessionfactory; public SessionFactory getSessionfactory() { return sessionfactory; } public void setSessionfactory(SessionFactory sessionfactory) { this.sessionfactory = sessionfactory; } @Override public NewTest getNewTest(String id){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); session.close(); return test; } @Override public List<NewTest> queryExamineeId(String examineeid){ Session session=sessionfactory.openSession(); session.beginTransaction(); String str="from NewTest newtest where newtest.examineeid='"+examineeid+"'"; Query query=session.createQuery(str); List<NewTest> nlist=query.list(); session.close(); return nlist; } @Override public List<NewTest> queryPaperId(String paperid){ Session session=sessionfactory.openSession(); session.beginTransaction(); String str="from NewTest newtest where newtest.paperid='"+paperid+"'"; Query query=session.createQuery(str); List<NewTest> nlist=query.list(); session.close(); return nlist; } @Override public void insert(NewTest test){ Session session=sessionfactory.openSession(); session.beginTransaction(); session.save(test); session.getTransaction().commit(); session.close(); } @Override public void delete(String id){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest tb=(NewTest) session.get(NewTest.class,id); session.delete(tb); session.getTransaction().commit(); session.close(); } @Override public List<NewTest> queryPaperIdAndExamineeId(String paperid, String Examineeid){ Session session=sessionfactory.openSession(); session.beginTransaction(); String str="from NewTest tb where tb.examineeid='"+Examineeid+"' and tb.paperid='"+paperid+"'"; Query query=session.createQuery(str); List<NewTest> tlist=query.list(); session.close(); return tlist; } @Override public void updateScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setScore(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateSingleScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setSingle(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateMultipleScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setMultiple(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateJudgeScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setJudge(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateEssayScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setEssay(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateTeacherScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setTeacherscore(score); session.update(test); session.getTransaction().commit(); session.close(); } }
UTF-8
Java
4,228
java
NewTestDaoImp.java
Java
[]
null
[]
package com.hainan.cs.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.hainan.cs.bean.NewTest; import com.hainan.cs.bean.TestBean; public class NewTestDaoImp implements NewTestDao { private SessionFactory sessionfactory; public SessionFactory getSessionfactory() { return sessionfactory; } public void setSessionfactory(SessionFactory sessionfactory) { this.sessionfactory = sessionfactory; } @Override public NewTest getNewTest(String id){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); session.close(); return test; } @Override public List<NewTest> queryExamineeId(String examineeid){ Session session=sessionfactory.openSession(); session.beginTransaction(); String str="from NewTest newtest where newtest.examineeid='"+examineeid+"'"; Query query=session.createQuery(str); List<NewTest> nlist=query.list(); session.close(); return nlist; } @Override public List<NewTest> queryPaperId(String paperid){ Session session=sessionfactory.openSession(); session.beginTransaction(); String str="from NewTest newtest where newtest.paperid='"+paperid+"'"; Query query=session.createQuery(str); List<NewTest> nlist=query.list(); session.close(); return nlist; } @Override public void insert(NewTest test){ Session session=sessionfactory.openSession(); session.beginTransaction(); session.save(test); session.getTransaction().commit(); session.close(); } @Override public void delete(String id){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest tb=(NewTest) session.get(NewTest.class,id); session.delete(tb); session.getTransaction().commit(); session.close(); } @Override public List<NewTest> queryPaperIdAndExamineeId(String paperid, String Examineeid){ Session session=sessionfactory.openSession(); session.beginTransaction(); String str="from NewTest tb where tb.examineeid='"+Examineeid+"' and tb.paperid='"+paperid+"'"; Query query=session.createQuery(str); List<NewTest> tlist=query.list(); session.close(); return tlist; } @Override public void updateScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setScore(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateSingleScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setSingle(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateMultipleScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setMultiple(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateJudgeScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setJudge(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateEssayScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setEssay(score); session.update(test); session.getTransaction().commit(); session.close(); } @Override public void updateTeacherScore(String id,String score){ Session session=sessionfactory.openSession(); session.beginTransaction(); NewTest test=(NewTest) session.get(NewTest.class,id); test.setTeacherscore(score); session.update(test); session.getTransaction().commit(); session.close(); } }
4,228
0.729186
0.729186
140
28.200001
19.769817
97
false
false
0
0
0
0
0
0
2.2
false
false
1
f593f49e54ec2511b2024796dcd2aa5a90a45e97
36,275,293,814,442
40cd4da5514eb920e6a6889e82590e48720c3d38
/desktop/applis/apps/core/common/expressionlanguage/src/main/java/code/expressionlanguage/analyze/AnaApplyCoreMethodUtil.java
b6bab60ea5e2bc5c069555d18611c49b16ce846f
[]
no_license
Cardman/projects
https://github.com/Cardman/projects
02704237e81868f8cb614abb37468cebb4ef4b31
23a9477dd736795c3af10bccccb3cdfa10c8123c
refs/heads/master
2023-08-17T11:27:41.999000
2023-08-15T07:09:28
2023-08-15T07:09:28
34,724,613
4
0
null
false
2020-10-13T08:08:38
2015-04-28T10:39:03
2020-10-12T21:02:20
2020-10-13T08:08:37
44,842
1
0
0
Java
false
false
package code.expressionlanguage.analyze; import code.expressionlanguage.Argument; import code.expressionlanguage.analyze.stds.AnaStdCaller; import code.expressionlanguage.exec.util.ArgumentListCall; import code.expressionlanguage.stds.StandardConstructor; import code.expressionlanguage.stds.StandardMethod; import code.expressionlanguage.stds.StandardType; import code.expressionlanguage.stds.StdCaller; import code.expressionlanguage.structs.*; import code.util.core.IndexConstants; public final class AnaApplyCoreMethodUtil { private AnaApplyCoreMethodUtil() { } public static Struct invokeAnalyzisStdMethod(StandardMethod _std, Struct _struct, AnalyzedPageEl _page, Argument... _args) { StdCaller caller_ = _std.getCaller(); Struct[] args_ = getObjects(_args); if (caller_ instanceof AnaStdCaller) { return ((AnaStdCaller)caller_).call(_page,_struct,args_); } return null; } public static Struct newAnalyzisInstanceStd(StandardConstructor _constructor, AnalyzedPageEl _page, Argument... _args) { Struct[] args_ = getObjects(_args); StdCaller stdCaller_ = StandardType.caller(_constructor, null); AnaStdCaller anaStdCaller_; if (stdCaller_ instanceof AnaStdCaller) { anaStdCaller_ = (AnaStdCaller)stdCaller_; } else { anaStdCaller_ = null; } if (anaStdCaller_ != null) { return anaStdCaller_.call(_page,NullStruct.NULL_VALUE,args_); } return null; } private static Struct[] getObjects(Argument... _args) { int len_ = _args.length; Struct[] classes_ = new Struct[len_]; for (int i = IndexConstants.FIRST_INDEX; i < len_; i++) { classes_[i] = _args[i].getStruct(); } return classes_; } private static AnaDisplayableStruct getAnaDisplayable(Struct _value) { if (_value instanceof AnaDisplayableStruct) { return (AnaDisplayableStruct) _value; } return null; } public static String getString(Struct _value, AnalyzedPageEl _page) { AnaDisplayableStruct dis_ = getAnaDisplayable(_value); if (dis_ == null) { return _page.getCharSeq().getAliasReplacement(); } return dis_.getDisplayedString(_page).getInstance(); } public static Argument localSumDiff(Argument _a, Argument _b, AnalyzedPageEl _page) { StringBuilder str_ = new StringBuilder(); str_.append(getString(ArgumentListCall.toStr(_a), _page)); str_.append(getString(ArgumentListCall.toStr(_b), _page)); return new Argument(new StringStruct(str_.toString())); } }
UTF-8
Java
2,705
java
AnaApplyCoreMethodUtil.java
Java
[]
null
[]
package code.expressionlanguage.analyze; import code.expressionlanguage.Argument; import code.expressionlanguage.analyze.stds.AnaStdCaller; import code.expressionlanguage.exec.util.ArgumentListCall; import code.expressionlanguage.stds.StandardConstructor; import code.expressionlanguage.stds.StandardMethod; import code.expressionlanguage.stds.StandardType; import code.expressionlanguage.stds.StdCaller; import code.expressionlanguage.structs.*; import code.util.core.IndexConstants; public final class AnaApplyCoreMethodUtil { private AnaApplyCoreMethodUtil() { } public static Struct invokeAnalyzisStdMethod(StandardMethod _std, Struct _struct, AnalyzedPageEl _page, Argument... _args) { StdCaller caller_ = _std.getCaller(); Struct[] args_ = getObjects(_args); if (caller_ instanceof AnaStdCaller) { return ((AnaStdCaller)caller_).call(_page,_struct,args_); } return null; } public static Struct newAnalyzisInstanceStd(StandardConstructor _constructor, AnalyzedPageEl _page, Argument... _args) { Struct[] args_ = getObjects(_args); StdCaller stdCaller_ = StandardType.caller(_constructor, null); AnaStdCaller anaStdCaller_; if (stdCaller_ instanceof AnaStdCaller) { anaStdCaller_ = (AnaStdCaller)stdCaller_; } else { anaStdCaller_ = null; } if (anaStdCaller_ != null) { return anaStdCaller_.call(_page,NullStruct.NULL_VALUE,args_); } return null; } private static Struct[] getObjects(Argument... _args) { int len_ = _args.length; Struct[] classes_ = new Struct[len_]; for (int i = IndexConstants.FIRST_INDEX; i < len_; i++) { classes_[i] = _args[i].getStruct(); } return classes_; } private static AnaDisplayableStruct getAnaDisplayable(Struct _value) { if (_value instanceof AnaDisplayableStruct) { return (AnaDisplayableStruct) _value; } return null; } public static String getString(Struct _value, AnalyzedPageEl _page) { AnaDisplayableStruct dis_ = getAnaDisplayable(_value); if (dis_ == null) { return _page.getCharSeq().getAliasReplacement(); } return dis_.getDisplayedString(_page).getInstance(); } public static Argument localSumDiff(Argument _a, Argument _b, AnalyzedPageEl _page) { StringBuilder str_ = new StringBuilder(); str_.append(getString(ArgumentListCall.toStr(_a), _page)); str_.append(getString(ArgumentListCall.toStr(_b), _page)); return new Argument(new StringStruct(str_.toString())); } }
2,705
0.665434
0.665434
72
36.569443
28.896763
128
false
false
0
0
0
0
0
0
0.708333
false
false
1
3e061e1dd06aae7b1831977d67bb1cbf8f34dda5
34,720,515,666,984
f1103f4c1d6df2446aa656dd307ff2a58aee874d
/src/main/java/com/j/utils/GPS.java
f2171e89f9018d3826221083a2452a249f1d9161
[]
no_license
kwy904/Middleware
https://github.com/kwy904/Middleware
11fc067444adf59f45469c51ac30af40a0971e3e
a2c7fc8b14c6e6130250d6ed3828ce7e3358b934
refs/heads/master
2016-09-09T21:07:38.271000
2015-07-02T08:04:04
2015-07-02T08:04:04
38,419,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.j.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.provider.Settings; import android.widget.Toast; import com.j.log.FLog; public class GPS { private static final String TAG = GPS.class.getSimpleName(); public static void openGPSSettings(Activity context, int requestCode) { LocationManager alm = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) { FLog.i(TAG, "GPS is OK"); return; } Toast.makeText(context, "Open GPS please!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); context.startActivityForResult(intent, requestCode); } public static Location getLocation(Context context) { // 获取位置管理服务 LocationManager locationManager; String serviceName = Context.LOCATION_SERVICE; locationManager = (LocationManager) context .getSystemService(serviceName); // 查找到服务信息 Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度 criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗 String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息 return locationManager.getLastKnownLocation(provider); // 通过GPS获取位置 } }
UTF-8
Java
1,663
java
GPS.java
Java
[]
null
[]
package com.j.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.provider.Settings; import android.widget.Toast; import com.j.log.FLog; public class GPS { private static final String TAG = GPS.class.getSimpleName(); public static void openGPSSettings(Activity context, int requestCode) { LocationManager alm = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) { FLog.i(TAG, "GPS is OK"); return; } Toast.makeText(context, "Open GPS please!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS); context.startActivityForResult(intent, requestCode); } public static Location getLocation(Context context) { // 获取位置管理服务 LocationManager locationManager; String serviceName = Context.LOCATION_SERVICE; locationManager = (LocationManager) context .getSystemService(serviceName); // 查找到服务信息 Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度 criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗 String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息 return locationManager.getLastKnownLocation(provider); // 通过GPS获取位置 } }
1,663
0.755153
0.755153
48
31.354166
23.946547
79
false
false
0
0
0
0
0
0
1.895833
false
false
1
d7e68543ca42c35180be08847deb641fc797a5d1
34,720,515,669,794
66ee2edf9980ee676e8f483116e95ee321ef64ef
/Proyecto1/src/java/blagtunez/MatrixManager.java
d08121ea623994354ede9615e09cf93ce38e7f53
[]
no_license
tian2992/blagtunez
https://github.com/tian2992/blagtunez
50a88cece9a89785321955348a5da257eee1942c
8db95a77125dad50ff9469cd3919147dba4255bc
refs/heads/master
2016-09-05T09:02:31.193000
2010-03-08T08:10:17
2010-03-08T08:10:17
33,006,010
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package blagtunez; /** * La clase que abstrae la matriz * @author tian */ public class MatrixManager implements java.io.Serializable { static matriz matrix; public MatrixManager(){ } void setup(){ if (matrix == null) matrix = new matriz(); else return; } public void vaciarMatriz(){ matrix = new matriz(); } public boolean reemplazarArtista(artista art1, artista art2, Boolean sano){ UserManager.log("<h2>Se reemplaza "+art1+" por "+art2+"</h2>"); art2.setLisCan(art1.getLisCan()); borrarArtista(art1,sano); return agregarArtista(art2,sano); } public boolean reemplazarArtista(artista art1, artista art2){ return reemplazarArtista(art1,art2,false); } public boolean agregarArtista(artista arti){ return agregarArtista(arti, false); } public boolean agregarArtista(artista arti, boolean sano){ setup(); if (!sano){ arti.setNombre(stringFixer.toUTF8(arti.getNombre())); arti.setGenero(stringFixer.toUTF8(arti.getGenero())); } nodoEl let = new nodoEl(arti.getNombre().trim().charAt(0),arti.getGenero()); try{ let = (nodoEl)matrix.agregarNodo(let); UserManager.log("<h1>Se agrega el artista "+arti+"</h1>"); return let.getPayload().add(arti); } catch (Exception e){ return false; } //return agregarArtista(a.getNombre(), a.getNacionalidad(),a.getImagen()); } public boolean borrarArtista(artista arti){ return borrarArtista(arti, false); } public boolean borrarArtista(artista arti, boolean sano){ //TODO: Hacer algo con el nodo que nos retorna la matrix if (!sano){ arti.setNombre(stringFixer.toUTF8(arti.getNombre())); arti.setGenero(stringFixer.toUTF8(arti.getGenero())); } try { nodoEl nodel = (nodoEl)matrix.buscarNodo(arti.getNombre().charAt(0), arti.getGenero()); if (nodel==null){ return false; } liston<artista> listu = (liston<artista>)nodel.getPayload(); artista temp = null; for (artista ar:listu){ //forma no eficiente de hacer las cosas if (ar.getNombre().equalsIgnoreCase(arti.getNombre())&&(ar.getGenero().equalsIgnoreCase(arti.getGenero()))){ temp = ar; break; } } if (temp == null) return false; listu.remove(temp); if (listu.isEmpty()){ matrix.borrarNodo(nodel); } UserManager.log("<h1>Se Borra el artista "+arti+"</h1>"); return true; } catch (Exception e){ return false; } } public boolean borrarGenero(String s){ UserManager.log("<h1>Se borra el genero "+s+"</h1>"); //no funcio... nodoCol coli = matrix.buscarColumna(s); if (coli==null) return false; matrix.borrarColumna(coli); return true; } public java.util.List<String> listarGeneros(){ return matrix.getGeneros(); } public java.util.List<artista> listarArtistas(){ setup(); return matrix.getArtistas(); } public java.util.List<artista> listarArtistas(String gen){ setup(); return matrix.getArtistasPorGenero(gen); } /** * agrega cancion a lo Ranger, a.k.a no sano * @param songi * @return el true si funcio, false si no */ public boolean agregarCancion(cancion songi){ return agregarCancion(songi, false); } public boolean agregarCancion(String nomSon, String anio, String art, String gen){ return agregarCancion(nomSon,anio,art,gen,false); } public boolean agregarCancion(String nomSon, String anio, String art, String gen, boolean sano){ try { int año = Integer.parseInt(anio); if (!sano){ nomSon = stringFixer.toUTF8(nomSon); art = stringFixer.toUTF8(art); gen = stringFixer.toUTF8(gen); } artista arti = buscarArtista(new artista(art,gen),true); if (arti == null) return false; cancion songi = new cancion(nomSon,año,arti); if (songi==null) return false; return agregarCancion(songi,arti,true); //return true; } catch (Exception e){ return false; } } public java.util.List<cancion> buscarCancion(String s){ java.util.List<artista> ar = listarArtistas(); java.util.List<cancion> temp = new liston(); for (artista a: ar){ for (cancion c: a.getLisCan()){ if (c.getNombre().equalsIgnoreCase(s)){ temp.add(c); } } } return temp; } public boolean agregarCancion(cancion songi, boolean sano){ if (songi==null) return false; if (songi.getNombre()==null || songi.getInterprete()==null) return false; artista artuditu; if (sano) artuditu = buscarArtista(songi.getInterprete(), true); else artuditu = buscarArtista(songi.getInterprete()); /* boolean artexis = false; if (artuditu == null) artexis = agregarArtista(artuditu); if (!artexis){ if (sano) artuditu = buscarArtista(songi.getInterprete(), true); else artuditu = buscarArtista(songi.getInterprete()); } */ if (artuditu==null) //lo intente... return false; if (!sano){ songi.setNombre(stringFixer.toUTF8(songi.getNombre())); songi.getInterprete().setGenero(stringFixer.toUTF8(songi.getInterprete().getGenero())); songi.getInterprete().setNombre(stringFixer.toUTF8(songi.getInterprete().getNombre())); } UserManager.log("Se agregó "+songi); return artuditu.getLisCan().add(songi); //lo metemos ya sanitizado //return true; } public boolean agregarCancion(cancion songi, artista arti, boolean sano){ //solo si ya estan ambos if (!sano) songi.setNombre(songi.getNombre()); songi.setInterprete(arti); arti.getLisCan().add(songi); UserManager.log("Se agregó "+songi); return true; } /** * retorna las canciones del artista, ya sanitizada * @param arti * @return el artista o null si no ta */ public java.util.List<cancion> getCancionesArtista(String art, String gen){ //envio las strings ya sanitizadas, :D UTF8 FTW artista artuditu = buscarArtista(new artista(art,gen), true); if (artuditu==null) return null; //java.util.List<cancion> listolon = new liston<cancion>(); return artuditu.getLisCan(); //return null; } /** * busca los artistas a lo Ranger, a.k.a no sano * @param arti * @return el artista o null si no ta */ public artista buscarArtista(artista arti){ // si lo envio a lo ranger, no estan sanitizadas return buscarArtista(arti, false); } /** * busca los artistas civilizadamente, sano decide si ya estan en UTF-8 * @param arti el artista a buscar * @param sano true si estan sanitizadas * @return el artista, o null si no ta */ public artista buscarArtista(artista arti, Boolean sano){ if (arti==null) return null; if (arti.getNombre()==null || arti.getGenero()==null) return null; if (!sano){ //sano decide si estan sanas o no arti.setNombre(stringFixer.toUTF8(arti.getNombre())); arti.setGenero(stringFixer.toUTF8(arti.getGenero())); } nodoEl nodista = (nodoEl)matrix.buscarNodo(arti.getNombre().charAt(0),arti.getGenero()); if (nodista == null) return null; java.util.List<artista> listin = nodista.getPayload(); if (listin==null) return null; if (!listin.isEmpty()){ for (artista R2D2: listin){ if (R2D2.getNombre().equalsIgnoreCase(arti.getNombre()) && R2D2.getGenero().equalsIgnoreCase(arti.getGenero())){ return R2D2; //esto deberia de funcionar... } } } else { return null; } return null; } public artista buscarArtista(String s){ return matrix.getArtista(s); } public boolean borrarCancion(String artiString, String genString, String rola, boolean sano){ if (!sano){ rola = stringFixer.toUTF8(rola); } artista artuditu = this.buscarArtista(new artista(artiString,genString),false); //Si sano es verdad, si si no no if (artuditu==null) return false; cancion tempRola = null; //Terriblemente ineficiente, pero que se le hace... for (cancion s: artuditu.getLisCan()){ if (s.getNombre().equalsIgnoreCase(rola)){ tempRola = s; break; } } if (tempRola == null) return false; UserManager.log("Se borro "+tempRola); return artuditu.getLisCan().remove(tempRola); // se que lo recorre dos veces, es ineficiente... } public boolean borrarCancion(String a, String g, String r){ return borrarCancion(a,g,r,false); } public boolean agregarArtista(String art, String gen){ return agregarArtista(new artista(art,gen)); } public boolean esVacia(){ return matrix.esVacia(); } public String estadoDeMatriz(){ setup(); if (matrix.esVacia()) return "No hay artistas registrados, Porque no <a href='agregaArtista.jsp'>Añades uno</a>"; else{ return "Hay "+matrix.contarArtistas()+" artistas en "+matrix.contarColumnas()+ " generos"; } } }
UTF-8
Java
10,330
java
MatrixManager.java
Java
[ { "context": "\n\n/**\n * La clase que abstrae la matriz\n * @author tian\n */\npublic class MatrixManager implements java.io", "end": 73, "score": 0.8894993662834167, "start": 69, "tag": "USERNAME", "value": "tian" } ]
null
[]
package blagtunez; /** * La clase que abstrae la matriz * @author tian */ public class MatrixManager implements java.io.Serializable { static matriz matrix; public MatrixManager(){ } void setup(){ if (matrix == null) matrix = new matriz(); else return; } public void vaciarMatriz(){ matrix = new matriz(); } public boolean reemplazarArtista(artista art1, artista art2, Boolean sano){ UserManager.log("<h2>Se reemplaza "+art1+" por "+art2+"</h2>"); art2.setLisCan(art1.getLisCan()); borrarArtista(art1,sano); return agregarArtista(art2,sano); } public boolean reemplazarArtista(artista art1, artista art2){ return reemplazarArtista(art1,art2,false); } public boolean agregarArtista(artista arti){ return agregarArtista(arti, false); } public boolean agregarArtista(artista arti, boolean sano){ setup(); if (!sano){ arti.setNombre(stringFixer.toUTF8(arti.getNombre())); arti.setGenero(stringFixer.toUTF8(arti.getGenero())); } nodoEl let = new nodoEl(arti.getNombre().trim().charAt(0),arti.getGenero()); try{ let = (nodoEl)matrix.agregarNodo(let); UserManager.log("<h1>Se agrega el artista "+arti+"</h1>"); return let.getPayload().add(arti); } catch (Exception e){ return false; } //return agregarArtista(a.getNombre(), a.getNacionalidad(),a.getImagen()); } public boolean borrarArtista(artista arti){ return borrarArtista(arti, false); } public boolean borrarArtista(artista arti, boolean sano){ //TODO: Hacer algo con el nodo que nos retorna la matrix if (!sano){ arti.setNombre(stringFixer.toUTF8(arti.getNombre())); arti.setGenero(stringFixer.toUTF8(arti.getGenero())); } try { nodoEl nodel = (nodoEl)matrix.buscarNodo(arti.getNombre().charAt(0), arti.getGenero()); if (nodel==null){ return false; } liston<artista> listu = (liston<artista>)nodel.getPayload(); artista temp = null; for (artista ar:listu){ //forma no eficiente de hacer las cosas if (ar.getNombre().equalsIgnoreCase(arti.getNombre())&&(ar.getGenero().equalsIgnoreCase(arti.getGenero()))){ temp = ar; break; } } if (temp == null) return false; listu.remove(temp); if (listu.isEmpty()){ matrix.borrarNodo(nodel); } UserManager.log("<h1>Se Borra el artista "+arti+"</h1>"); return true; } catch (Exception e){ return false; } } public boolean borrarGenero(String s){ UserManager.log("<h1>Se borra el genero "+s+"</h1>"); //no funcio... nodoCol coli = matrix.buscarColumna(s); if (coli==null) return false; matrix.borrarColumna(coli); return true; } public java.util.List<String> listarGeneros(){ return matrix.getGeneros(); } public java.util.List<artista> listarArtistas(){ setup(); return matrix.getArtistas(); } public java.util.List<artista> listarArtistas(String gen){ setup(); return matrix.getArtistasPorGenero(gen); } /** * agrega cancion a lo Ranger, a.k.a no sano * @param songi * @return el true si funcio, false si no */ public boolean agregarCancion(cancion songi){ return agregarCancion(songi, false); } public boolean agregarCancion(String nomSon, String anio, String art, String gen){ return agregarCancion(nomSon,anio,art,gen,false); } public boolean agregarCancion(String nomSon, String anio, String art, String gen, boolean sano){ try { int año = Integer.parseInt(anio); if (!sano){ nomSon = stringFixer.toUTF8(nomSon); art = stringFixer.toUTF8(art); gen = stringFixer.toUTF8(gen); } artista arti = buscarArtista(new artista(art,gen),true); if (arti == null) return false; cancion songi = new cancion(nomSon,año,arti); if (songi==null) return false; return agregarCancion(songi,arti,true); //return true; } catch (Exception e){ return false; } } public java.util.List<cancion> buscarCancion(String s){ java.util.List<artista> ar = listarArtistas(); java.util.List<cancion> temp = new liston(); for (artista a: ar){ for (cancion c: a.getLisCan()){ if (c.getNombre().equalsIgnoreCase(s)){ temp.add(c); } } } return temp; } public boolean agregarCancion(cancion songi, boolean sano){ if (songi==null) return false; if (songi.getNombre()==null || songi.getInterprete()==null) return false; artista artuditu; if (sano) artuditu = buscarArtista(songi.getInterprete(), true); else artuditu = buscarArtista(songi.getInterprete()); /* boolean artexis = false; if (artuditu == null) artexis = agregarArtista(artuditu); if (!artexis){ if (sano) artuditu = buscarArtista(songi.getInterprete(), true); else artuditu = buscarArtista(songi.getInterprete()); } */ if (artuditu==null) //lo intente... return false; if (!sano){ songi.setNombre(stringFixer.toUTF8(songi.getNombre())); songi.getInterprete().setGenero(stringFixer.toUTF8(songi.getInterprete().getGenero())); songi.getInterprete().setNombre(stringFixer.toUTF8(songi.getInterprete().getNombre())); } UserManager.log("Se agregó "+songi); return artuditu.getLisCan().add(songi); //lo metemos ya sanitizado //return true; } public boolean agregarCancion(cancion songi, artista arti, boolean sano){ //solo si ya estan ambos if (!sano) songi.setNombre(songi.getNombre()); songi.setInterprete(arti); arti.getLisCan().add(songi); UserManager.log("Se agregó "+songi); return true; } /** * retorna las canciones del artista, ya sanitizada * @param arti * @return el artista o null si no ta */ public java.util.List<cancion> getCancionesArtista(String art, String gen){ //envio las strings ya sanitizadas, :D UTF8 FTW artista artuditu = buscarArtista(new artista(art,gen), true); if (artuditu==null) return null; //java.util.List<cancion> listolon = new liston<cancion>(); return artuditu.getLisCan(); //return null; } /** * busca los artistas a lo Ranger, a.k.a no sano * @param arti * @return el artista o null si no ta */ public artista buscarArtista(artista arti){ // si lo envio a lo ranger, no estan sanitizadas return buscarArtista(arti, false); } /** * busca los artistas civilizadamente, sano decide si ya estan en UTF-8 * @param arti el artista a buscar * @param sano true si estan sanitizadas * @return el artista, o null si no ta */ public artista buscarArtista(artista arti, Boolean sano){ if (arti==null) return null; if (arti.getNombre()==null || arti.getGenero()==null) return null; if (!sano){ //sano decide si estan sanas o no arti.setNombre(stringFixer.toUTF8(arti.getNombre())); arti.setGenero(stringFixer.toUTF8(arti.getGenero())); } nodoEl nodista = (nodoEl)matrix.buscarNodo(arti.getNombre().charAt(0),arti.getGenero()); if (nodista == null) return null; java.util.List<artista> listin = nodista.getPayload(); if (listin==null) return null; if (!listin.isEmpty()){ for (artista R2D2: listin){ if (R2D2.getNombre().equalsIgnoreCase(arti.getNombre()) && R2D2.getGenero().equalsIgnoreCase(arti.getGenero())){ return R2D2; //esto deberia de funcionar... } } } else { return null; } return null; } public artista buscarArtista(String s){ return matrix.getArtista(s); } public boolean borrarCancion(String artiString, String genString, String rola, boolean sano){ if (!sano){ rola = stringFixer.toUTF8(rola); } artista artuditu = this.buscarArtista(new artista(artiString,genString),false); //Si sano es verdad, si si no no if (artuditu==null) return false; cancion tempRola = null; //Terriblemente ineficiente, pero que se le hace... for (cancion s: artuditu.getLisCan()){ if (s.getNombre().equalsIgnoreCase(rola)){ tempRola = s; break; } } if (tempRola == null) return false; UserManager.log("Se borro "+tempRola); return artuditu.getLisCan().remove(tempRola); // se que lo recorre dos veces, es ineficiente... } public boolean borrarCancion(String a, String g, String r){ return borrarCancion(a,g,r,false); } public boolean agregarArtista(String art, String gen){ return agregarArtista(new artista(art,gen)); } public boolean esVacia(){ return matrix.esVacia(); } public String estadoDeMatriz(){ setup(); if (matrix.esVacia()) return "No hay artistas registrados, Porque no <a href='agregaArtista.jsp'>Añades uno</a>"; else{ return "Hay "+matrix.contarArtistas()+" artistas en "+matrix.contarColumnas()+ " generos"; } } }
10,330
0.564165
0.559709
349
28.584528
27.455864
128
false
false
0
0
0
0
0
0
0.538682
false
false
1
9ba53fac9293c90d32e5ddb7ea0bc0302834367d
37,340,445,698,830
b094598e9333afc23621a7fd112d6729d7bfbaf3
/src/main/java/com/druppel/api/model/Measurement.java
712448bd0dc3ce71f516922a47b76e87b74cb195
[ "MIT" ]
permissive
De-Druppel/DruppelAPI
https://github.com/De-Druppel/DruppelAPI
222c57226c0cb0dd895908aa00cc663f31c814ae
309efb2cf8e8ecc7eb213d24e910bf6decdaf19b
refs/heads/master
2023-02-02T11:27:28.582000
2020-12-17T18:04:25
2020-12-17T18:04:25
291,798,914
1
0
MIT
false
2020-12-17T18:04:26
2020-08-31T18:54:02
2020-12-16T21:43:45
2020-12-17T18:04:26
38,217
1
0
0
Java
false
false
package com.druppel.api.model; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "measurement") public class Measurement { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "date_created") private Date date; @Column(name = "type") private String type; @Column(name = "value") private Float value; @JoinColumn(name = "client_id") @ManyToOne() private Plant plant; public Measurement() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Float getValue() { return value; } public void setValue(Float value) { this.value = value; } public Plant getPlant() { return plant; } public void setPlant(Plant plant) { this.plant = plant; } }
UTF-8
Java
1,139
java
Measurement.java
Java
[]
null
[]
package com.druppel.api.model; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "measurement") public class Measurement { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "date_created") private Date date; @Column(name = "type") private String type; @Column(name = "value") private Float value; @JoinColumn(name = "client_id") @ManyToOne() private Plant plant; public Measurement() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Float getValue() { return value; } public void setValue(Float value) { this.value = value; } public Plant getPlant() { return plant; } public void setPlant(Plant plant) { this.plant = plant; } }
1,139
0.590869
0.590869
65
16.507692
15.23167
61
false
false
0
0
0
0
0
0
0.276923
false
false
1
2c20c2c0f6f243de358aa1734e4110e625fcdb0a
37,134,287,267,496
703dad4be855a57de562e3ae88a042b80bad9f3d
/app/src/main/java/micro/com/microblog/manager/RxSubscriber.java
c938603002991c26d26356472055501d4248fab2
[]
no_license
Microhx/MicroBlog
https://github.com/Microhx/MicroBlog
47ee0f3f519b6d5259c9cfe738e34a65deae1842
c3ddc57ee89cdccc0a1696aab46635fc00920265
refs/heads/master
2021-01-10T23:45:41.766000
2016-12-04T04:00:00
2016-12-04T04:00:00
70,405,841
8
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package micro.com.microblog.manager; import android.app.Activity; import android.content.Context; import micro.com.microblog.R; import micro.com.microblog.utils.DialogUtils; import micro.com.microblog.utils.LogUtils; import micro.com.microblog.utils.NetWorkUtils; import micro.com.microblog.utils.UIUtils; import rx.Subscriber; /** * author : micro_hx * desc : * email: javainstalling@163.com * date : 2016/10/28 - 17:44 */ public abstract class RxSubscriber<T> extends Subscriber<T> { private Context mContext; private String msg; private boolean showDialog = true; public RxSubscriber(Context mContext, String msg, boolean showDialog) { this.mContext = mContext; this.msg = msg; this.showDialog = showDialog; } public RxSubscriber(Context mContext) { this(mContext, UIUtils.getString(R.string.str_loading), true); } public RxSubscriber(Context mContext, boolean showDialog) { this(mContext, UIUtils.getString(R.string.str_loading), showDialog); } @Override public void onStart() { super.onStart(); if (showDialog) { try { DialogUtils.showDialog((Activity) mContext, msg, false); } catch (Exception e) { e.printStackTrace(); } } } @Override public void onNext(T t) { _onNext(t); } @Override public void onError(Throwable e) { if (showDialog) DialogUtils.hideDialog(); LogUtils.d("the error : " + e); if (NetWorkUtils.isNetConnected(UIUtils.getAppContext())) { _onError(UIUtils.getString(R.string.str_network_error)); } else { _onError(UIUtils.getString(R.string.str_other_error)); } } @Override public void onCompleted() { if (showDialog) { DialogUtils.hideDialog(); } } public abstract void _onNext(T t); public abstract void _onError(String msg); }
UTF-8
Java
2,011
java
RxSubscriber.java
Java
[ { "context": "ls.UIUtils;\nimport rx.Subscriber;\n\n/**\n * author : micro_hx\n * desc :\n * email: javainstalling@163.com\n * dat", "end": 355, "score": 0.9996440410614014, "start": 347, "tag": "USERNAME", "value": "micro_hx" }, { "context": "ber;\n\n/**\n * author : micro_hx\n * desc :\n * email: javainstalling@163.com\n * date : 2016/10/28 - 17:44\n */\npublic abstract ", "end": 398, "score": 0.9999224543571472, "start": 376, "tag": "EMAIL", "value": "javainstalling@163.com" } ]
null
[]
package micro.com.microblog.manager; import android.app.Activity; import android.content.Context; import micro.com.microblog.R; import micro.com.microblog.utils.DialogUtils; import micro.com.microblog.utils.LogUtils; import micro.com.microblog.utils.NetWorkUtils; import micro.com.microblog.utils.UIUtils; import rx.Subscriber; /** * author : micro_hx * desc : * email: <EMAIL> * date : 2016/10/28 - 17:44 */ public abstract class RxSubscriber<T> extends Subscriber<T> { private Context mContext; private String msg; private boolean showDialog = true; public RxSubscriber(Context mContext, String msg, boolean showDialog) { this.mContext = mContext; this.msg = msg; this.showDialog = showDialog; } public RxSubscriber(Context mContext) { this(mContext, UIUtils.getString(R.string.str_loading), true); } public RxSubscriber(Context mContext, boolean showDialog) { this(mContext, UIUtils.getString(R.string.str_loading), showDialog); } @Override public void onStart() { super.onStart(); if (showDialog) { try { DialogUtils.showDialog((Activity) mContext, msg, false); } catch (Exception e) { e.printStackTrace(); } } } @Override public void onNext(T t) { _onNext(t); } @Override public void onError(Throwable e) { if (showDialog) DialogUtils.hideDialog(); LogUtils.d("the error : " + e); if (NetWorkUtils.isNetConnected(UIUtils.getAppContext())) { _onError(UIUtils.getString(R.string.str_network_error)); } else { _onError(UIUtils.getString(R.string.str_other_error)); } } @Override public void onCompleted() { if (showDialog) { DialogUtils.hideDialog(); } } public abstract void _onNext(T t); public abstract void _onError(String msg); }
1,996
0.625062
0.617603
83
23.228916
21.555378
76
false
false
0
0
0
0
0
0
0.445783
false
false
1
f678da7aca4704b381cde8fab532d36b9bcbb20f
36,395,552,907,394
f5f311a7d010c4ec724d00d9b9ad4fbb7ed5c3d6
/eclipse代码/elemeServlet/src/bean/Order.java
e67b4e4f8a730fd1011fb0c25a8db00568e48607
[]
no_license
fenghong97/Green-Hat
https://github.com/fenghong97/Green-Hat
1c5694daf929b99d947484db1fcc5d14a9897a65
b8fbf3dbe1e4186be824ea3d50708ee732b1681e
refs/heads/master
2020-04-25T03:02:46.500000
2019-06-16T14:48:21
2019-06-16T14:48:21
172,462,423
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bean; import java.sql.ResultSet; import java.sql.SQLException; public class Order { public String go(String username) { ResultSet rs = null; Sql sql = new Sql(); sql.link("ysw", "123456", "eleme"); sql.runq ("select ord.O_Id,commodity.Name,commodity.Imagename,ord.Time,ord.U_Id,ord.IfAccept,commodity.Price,ord.Number " + "from commodity,ord,users " + "where users.Username =\""+username+"\" and ord.U_Id=users.U_Id and commodity.C_Id=ord.C_Id"); System.out.println("select order.O_Id,commodity.Name,commodity.Imagename,order.Number,order.Time,order.U_Id,order.IfAccept,commodity.Price " + "from commodity,order,users " + "where users.Name =\""+username+"\" and order.U_Id=users.U_Id and commodity.C_Id=order.C_Id"); rs = sql.getRs(); String data = new String(""); try { while(rs.next()) { data += "&O_Id="+rs.getString("O_Id"); data += "&Name="+rs.getString("Name"); data += "&Imagename="+rs.getString("Imagename"); data += "&Number="+rs.getString("Number"); data += "&Time="+rs.getString("Time"); data += "&IfAccept="+rs.getString("IfAccept"); data += "&U_Id="+rs.getString("U_Id"); data += "&Price="+rs.getDouble("Price")*rs.getInt("Number"); data += "\n"; } System.out.println(data); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } sql.close(); return data; } }
UTF-8
Java
1,408
java
Order.java
Java
[ { "context": "dity,ord,users \"\n\t\t\t\t+ \"where users.Username =\\\"\"+username+\"\\\" and ord.U_Id=users.U_Id and commodity.C_Id=or", "end": 416, "score": 0.936259925365448, "start": 408, "tag": "USERNAME", "value": "username" }, { "context": "modity,order,users \"\n\t\t\t\t+ \"where users.Name =\\\"\"+username+\"\\\" and order.U_Id=users.U_Id and commodity.C_Id=", "end": 692, "score": 0.9629867672920227, "start": 684, "tag": "USERNAME", "value": "username" } ]
null
[]
package bean; import java.sql.ResultSet; import java.sql.SQLException; public class Order { public String go(String username) { ResultSet rs = null; Sql sql = new Sql(); sql.link("ysw", "123456", "eleme"); sql.runq ("select ord.O_Id,commodity.Name,commodity.Imagename,ord.Time,ord.U_Id,ord.IfAccept,commodity.Price,ord.Number " + "from commodity,ord,users " + "where users.Username =\""+username+"\" and ord.U_Id=users.U_Id and commodity.C_Id=ord.C_Id"); System.out.println("select order.O_Id,commodity.Name,commodity.Imagename,order.Number,order.Time,order.U_Id,order.IfAccept,commodity.Price " + "from commodity,order,users " + "where users.Name =\""+username+"\" and order.U_Id=users.U_Id and commodity.C_Id=order.C_Id"); rs = sql.getRs(); String data = new String(""); try { while(rs.next()) { data += "&O_Id="+rs.getString("O_Id"); data += "&Name="+rs.getString("Name"); data += "&Imagename="+rs.getString("Imagename"); data += "&Number="+rs.getString("Number"); data += "&Time="+rs.getString("Time"); data += "&IfAccept="+rs.getString("IfAccept"); data += "&U_Id="+rs.getString("U_Id"); data += "&Price="+rs.getDouble("Price")*rs.getInt("Number"); data += "\n"; } System.out.println(data); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } sql.close(); return data; } }
1,408
0.639205
0.634943
40
34.200001
31.212337
142
false
false
0
0
0
0
0
0
3.45
false
false
1
50eb1d45205a4b51f251149fe5d97e254c667516
20,882,131,027,559
c95ccb221c184c8b226cb49792b17640c9678994
/app/src/main/java/gst/trainingcourse/quanlikhachsan/model/Floor.java
0c03a7244ab99c90a943085e97ace5c3acb101d9
[]
no_license
xuantrung231997/QuanliKhachSan
https://github.com/xuantrung231997/QuanliKhachSan
ac1f6d2dc3810cf447b49ec45fb3319ac6ba26e5
592728b36426b5c2357032805ee27998070711bc
refs/heads/master
2020-12-02T08:45:48.656000
2019-12-30T16:31:39
2019-12-30T16:31:39
230,947,074
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gst.trainingcourse.quanlikhachsan.model; public class Floor { private int mId; private String mName; private String mDescription; public int getId() { return mId; } public void setId(int mId) { this.mId = mId; } public String getName() { return mName; } public void setName(String mName) { this.mName = mName; } public String getDescription() { return mDescription; } public void setDescription(String mDescription) { this.mDescription = mDescription; } }
UTF-8
Java
579
java
Floor.java
Java
[]
null
[]
package gst.trainingcourse.quanlikhachsan.model; public class Floor { private int mId; private String mName; private String mDescription; public int getId() { return mId; } public void setId(int mId) { this.mId = mId; } public String getName() { return mName; } public void setName(String mName) { this.mName = mName; } public String getDescription() { return mDescription; } public void setDescription(String mDescription) { this.mDescription = mDescription; } }
579
0.613126
0.613126
31
17.67742
15.87123
53
false
false
0
0
0
0
0
0
0.322581
false
false
1
a77b140cc0fe508880a1fc6c9d318822b7142cca
21,732,534,563,378
69ee20ba7471e66ffa42ab5b29472ce7b6c02a52
/src/main/java/top/godder/homework/service/DiscussionService.java
08cea1dbf8031b25a259cf9cff070c058067b629
[]
no_license
WangGodder/Homework-System-V2.1
https://github.com/WangGodder/Homework-System-V2.1
88134071e4cd9a37c3a336e64d97714b1193ee59
7643b3ae52abe14cc463c66f67a8c6f8ecd468a0
refs/heads/master
2022-06-24T07:49:26.229000
2020-05-22T14:34:11
2020-05-22T14:34:11
185,955,408
0
0
null
false
2022-06-21T01:07:14
2019-05-10T09:00:39
2020-05-22T14:34:20
2022-06-21T01:07:11
28,917
0
0
2
Java
false
false
package top.godder.homework.service; import top.godder.homework.domain.Discussion; import top.godder.homework.domain.Student; /** * @author: godder * @date: 2019/5/8 */ public interface DiscussionService { Student getStudent(Discussion discussion); boolean createDiscussion(Discussion discussion); }
UTF-8
Java
314
java
DiscussionService.java
Java
[ { "context": "p.godder.homework.domain.Student;\n\n/**\n * @author: godder\n * @date: 2019/5/8\n */\npublic interface Discussio", "end": 150, "score": 0.9996205568313599, "start": 144, "tag": "USERNAME", "value": "godder" } ]
null
[]
package top.godder.homework.service; import top.godder.homework.domain.Discussion; import top.godder.homework.domain.Student; /** * @author: godder * @date: 2019/5/8 */ public interface DiscussionService { Student getStudent(Discussion discussion); boolean createDiscussion(Discussion discussion); }
314
0.764331
0.745223
14
21.428572
19.71118
52
false
false
0
0
0
0
0
0
0.357143
false
false
1
a8c4c8b5dee10e602e9b4652bfc38b82ffbacaf4
18,081,812,356,915
b90244e8d0f7bc182cb4eebf8e743b274322cc78
/src/main/java/uk/ac/ebi/lipidhome/service/result/model/IsomerSummary.java
af12eaddfdb16249a30a8577f1577f5984de0175
[]
no_license
EBI-Metabolights/lipidhome-web
https://github.com/EBI-Metabolights/lipidhome-web
8182782cdeb65bf66cfeb9d4893e61918abd9f5c
d2924175b9f1c141ea517ce982c0b21f85277963
refs/heads/master
2022-08-04T08:39:49.317000
2021-01-15T07:28:06
2021-01-15T07:28:06
52,377,277
1
3
null
false
2022-06-29T16:43:56
2016-02-23T17:19:38
2021-01-15T07:28:09
2022-06-29T16:43:54
34,457
1
3
4
JavaScript
false
false
package uk.ac.ebi.lipidhome.service.result.model; import uk.ac.ebi.lipidhome.core.model.CrossReference; import uk.ac.ebi.lipidhome.core.model.Isomer; import uk.ac.ebi.lipidhome.core.model.Paper; import java.util.ArrayList; import java.util.List; /** * @author Antonio Fabregat <fabregat@ebi.ac.uk> */ public class IsomerSummary extends ResultObject { private String smile = ""; private String systematicName; private boolean identified; List<CrossReference> xrefs = new ArrayList<CrossReference>(); List<Paper> papers = new ArrayList<Paper>(); public IsomerSummary(Isomer isomer) { super(isomer); setSmile(isomer.getSmile()); setSystematicName(isomer.getSystematicName()); setIdentified(true); } public String getSmile() { return smile; } public void setSmile(String smile) { this.smile = smile; } public String getSystematicName() { return systematicName; } public void setSystematicName(String systematicName) { this.systematicName = systematicName; } public boolean isIdentified() { return identified; } public void setIdentified(boolean identified) { this.identified = identified; } public List<CrossReference> getXrefs() { return xrefs; } public void setXrefs(List<CrossReference> xrefs) { this.xrefs = xrefs; } public List<Paper> getPapers() { return papers; } public void setPapers(List<Paper> papers) { this.papers = papers; } }
UTF-8
Java
1,578
java
IsomerSummary.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author Antonio Fabregat <fabregat@ebi.ac.uk>\n */\npublic class IsomerSumma", "end": 280, "score": 0.999880313873291, "start": 264, "tag": "NAME", "value": "Antonio Fabregat" }, { "context": "java.util.List;\n\n/**\n * @author Antonio Fabregat <fabregat@ebi.ac.uk>\n */\npublic class IsomerSummary extends ResultObj", "end": 300, "score": 0.9999332427978516, "start": 282, "tag": "EMAIL", "value": "fabregat@ebi.ac.uk" } ]
null
[]
package uk.ac.ebi.lipidhome.service.result.model; import uk.ac.ebi.lipidhome.core.model.CrossReference; import uk.ac.ebi.lipidhome.core.model.Isomer; import uk.ac.ebi.lipidhome.core.model.Paper; import java.util.ArrayList; import java.util.List; /** * @author <NAME> <<EMAIL>> */ public class IsomerSummary extends ResultObject { private String smile = ""; private String systematicName; private boolean identified; List<CrossReference> xrefs = new ArrayList<CrossReference>(); List<Paper> papers = new ArrayList<Paper>(); public IsomerSummary(Isomer isomer) { super(isomer); setSmile(isomer.getSmile()); setSystematicName(isomer.getSystematicName()); setIdentified(true); } public String getSmile() { return smile; } public void setSmile(String smile) { this.smile = smile; } public String getSystematicName() { return systematicName; } public void setSystematicName(String systematicName) { this.systematicName = systematicName; } public boolean isIdentified() { return identified; } public void setIdentified(boolean identified) { this.identified = identified; } public List<CrossReference> getXrefs() { return xrefs; } public void setXrefs(List<CrossReference> xrefs) { this.xrefs = xrefs; } public List<Paper> getPapers() { return papers; } public void setPapers(List<Paper> papers) { this.papers = papers; } }
1,557
0.659696
0.659696
71
21.225351
19.967012
65
false
false
0
0
0
0
0
0
0.352113
false
false
1
42073a272db89f93b6f5f4b15ac494e8a07efc81
18,081,812,355,010
d9281aa8c5679e618fefcf23e03122224937e4d1
/src/main/java/it/polito/tdp/quadrato/model/RisolviQuadrato.java
87464c20a3aa12f622d75a0432c0b1e7e803fb3b
[]
no_license
MartaProla/QuadratoMagico
https://github.com/MartaProla/QuadratoMagico
870e8ebf6fc8b6df83b4cc5357600c62b5933111
e4f599e7c6efce086f9cbe9d0e28ac707f76f056
refs/heads/master
2022-11-06T20:36:33.744000
2020-07-07T13:27:52
2020-07-07T13:27:52
277,812,931
0
0
null
true
2020-07-07T12:40:36
2020-07-07T12:40:35
2020-04-16T17:46:04
2020-04-16T17:39:50
8
0
0
0
null
false
false
package it.polito.tdp.quadrato.model; import java.util.ArrayList; import java.util.List; public class RisolviQuadrato { private int N ; // lato del quadrato private int N2 ; // numero di caselle (N^2) private int magica ; // costante magica private List<List<Integer>>soluzioni; public RisolviQuadrato(int N) { this.N=N; // n lato this.N2=N*N; // n*n numero celle this.magica= N*(N2+1)/2; } public List<List<Integer>> quadrati() { List<Integer>parziale=new ArrayList<>(); int livello=0; this.soluzioni=new ArrayList<List<Integer>>(); cerca(parziale, livello); return this.soluzioni; } //struttura ricorsiva(privata) private void cerca(List<Integer>parziale, int livello) { if(livello==N2) { //caso terminale--> ho un quadrato non so se è quello ottimale if(controlla(parziale)) { System.out.println(parziale); //this.soluzioni.add(parziale);// attenzione non va bene --> parziale può cambiare this.soluzioni.add(new ArrayList<>(parziale)); } return; } //controlli intermedi, quando livello è multiplo di N(righe complete) if(livello%N==0 && livello!=0) { if(!controllaRiga(parziale,livello/N-1)) return; //potatura dell'albero di ricerca--> non nasce nulla di buono } //caso intermedio for(int valore=1; valore<=N2;valore ++) { if(!parziale.contains(valore)) { //prova valore parziale.add(valore); cerca(parziale,livello+1); parziale.remove(parziale.size()-1); } } } /** * Verifica se una soluzione rispetta tutte le somme * @param parziale * @return */ private boolean controlla(List<Integer> parziale) { if(parziale.size()!=this.N*this.N) throw new IllegalArgumentException("Numero di elementi insufficiente") ; // Fai la somma delle righe for(int riga=0; riga<this.N; riga++) { int somma = 0 ; for(int col=0; col<this.N; col++) { somma += parziale.get(riga*this.N+col) ; } if(somma!=this.magica) return false ; } // Fai la somma delle colonne for(int col=0; col<this.N; col++) { int somma = 0 ; for(int riga=0; riga<this.N; riga++) { somma += parziale.get(riga*this.N+col) ; } if(somma!=this.magica) return false ; } // diagonale principale int somma = 0; for(int riga=0; riga<this.N; riga++) { somma += parziale.get(riga*this.N+riga) ; } if(somma!=this.magica) return false ; // diagonale inversa somma = 0; for(int riga=0; riga<this.N; riga++) { somma += parziale.get(riga*this.N+(this.N-1-riga)) ; } if(somma!=this.magica) return false ; return true ; } private boolean controllaRiga(List<Integer>parziale, int riga) { int somma=0; for(int col=0;col<N;col++) somma+=parziale.get(riga*N+col); return somma==magica; //return true } }
UTF-8
Java
2,806
java
RisolviQuadrato.java
Java
[]
null
[]
package it.polito.tdp.quadrato.model; import java.util.ArrayList; import java.util.List; public class RisolviQuadrato { private int N ; // lato del quadrato private int N2 ; // numero di caselle (N^2) private int magica ; // costante magica private List<List<Integer>>soluzioni; public RisolviQuadrato(int N) { this.N=N; // n lato this.N2=N*N; // n*n numero celle this.magica= N*(N2+1)/2; } public List<List<Integer>> quadrati() { List<Integer>parziale=new ArrayList<>(); int livello=0; this.soluzioni=new ArrayList<List<Integer>>(); cerca(parziale, livello); return this.soluzioni; } //struttura ricorsiva(privata) private void cerca(List<Integer>parziale, int livello) { if(livello==N2) { //caso terminale--> ho un quadrato non so se è quello ottimale if(controlla(parziale)) { System.out.println(parziale); //this.soluzioni.add(parziale);// attenzione non va bene --> parziale può cambiare this.soluzioni.add(new ArrayList<>(parziale)); } return; } //controlli intermedi, quando livello è multiplo di N(righe complete) if(livello%N==0 && livello!=0) { if(!controllaRiga(parziale,livello/N-1)) return; //potatura dell'albero di ricerca--> non nasce nulla di buono } //caso intermedio for(int valore=1; valore<=N2;valore ++) { if(!parziale.contains(valore)) { //prova valore parziale.add(valore); cerca(parziale,livello+1); parziale.remove(parziale.size()-1); } } } /** * Verifica se una soluzione rispetta tutte le somme * @param parziale * @return */ private boolean controlla(List<Integer> parziale) { if(parziale.size()!=this.N*this.N) throw new IllegalArgumentException("Numero di elementi insufficiente") ; // Fai la somma delle righe for(int riga=0; riga<this.N; riga++) { int somma = 0 ; for(int col=0; col<this.N; col++) { somma += parziale.get(riga*this.N+col) ; } if(somma!=this.magica) return false ; } // Fai la somma delle colonne for(int col=0; col<this.N; col++) { int somma = 0 ; for(int riga=0; riga<this.N; riga++) { somma += parziale.get(riga*this.N+col) ; } if(somma!=this.magica) return false ; } // diagonale principale int somma = 0; for(int riga=0; riga<this.N; riga++) { somma += parziale.get(riga*this.N+riga) ; } if(somma!=this.magica) return false ; // diagonale inversa somma = 0; for(int riga=0; riga<this.N; riga++) { somma += parziale.get(riga*this.N+(this.N-1-riga)) ; } if(somma!=this.magica) return false ; return true ; } private boolean controllaRiga(List<Integer>parziale, int riga) { int somma=0; for(int col=0;col<N;col++) somma+=parziale.get(riga*N+col); return somma==magica; //return true } }
2,806
0.647877
0.637888
118
22.754238
20.005482
87
false
false
0
0
0
0
0
0
2.525424
false
false
1
25ee0127c581affe965126ccde1733f84a634583
14,130,442,446,846
ca68103108124e16b1d62309cf5fb87f2849622a
/201712/study/src/main/java/study/produceconsumer/StorageWithReentrantLock.java
81dc327321867370ffe04cbc3a69664b25006e46
[]
no_license
clairewu2017/java_demo
https://github.com/clairewu2017/java_demo
28cb5529b27da71d4d7532c14e7142c2c3ddf1d0
7115cd5091d3220495ee4d9dca729da87fca3349
refs/heads/master
2021-09-05T09:26:18.723000
2018-01-26T02:25:47
2018-01-26T02:25:47
115,076,902
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package study.produceconsumer; import java.util.LinkedList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * Created by chunmei on 12/28/2017. */ public class StorageWithReentrantLock { private LinkedList<Object> list = new LinkedList<Object>(); ReentrantLock lock = new ReentrantLock(); Condition condition = lock.newCondition(); public void Produce(int num) throws InterruptedException { lock.lock(); while(list.size() + num > 100) { System.out.println("Full"); condition.await(); } for(int i = 0; i < num; i++) { list.add(new Object()); } condition.signalAll(); System.out.println("Now " + list.size()); lock.unlock(); } public void Consume(int num) throws InterruptedException { lock.lock(); while(list.size() < num) { System.out.println("Empty"); condition.await(); } for (int i = 0 ; i < num; i ++) { list.pop(); } condition.signalAll(); lock.unlock(); System.out.println("Now " + list.size()); } }
UTF-8
Java
1,280
java
StorageWithReentrantLock.java
Java
[ { "context": "current.locks.ReentrantLock;\r\n\r\n/**\r\n * Created by chunmei on 12/28/2017.\r\n */\r\npublic class StorageWithReen", "end": 188, "score": 0.9996545314788818, "start": 181, "tag": "USERNAME", "value": "chunmei" } ]
null
[]
package study.produceconsumer; import java.util.LinkedList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * Created by chunmei on 12/28/2017. */ public class StorageWithReentrantLock { private LinkedList<Object> list = new LinkedList<Object>(); ReentrantLock lock = new ReentrantLock(); Condition condition = lock.newCondition(); public void Produce(int num) throws InterruptedException { lock.lock(); while(list.size() + num > 100) { System.out.println("Full"); condition.await(); } for(int i = 0; i < num; i++) { list.add(new Object()); } condition.signalAll(); System.out.println("Now " + list.size()); lock.unlock(); } public void Consume(int num) throws InterruptedException { lock.lock(); while(list.size() < num) { System.out.println("Empty"); condition.await(); } for (int i = 0 ; i < num; i ++) { list.pop(); } condition.signalAll(); lock.unlock(); System.out.println("Now " + list.size()); } }
1,280
0.532812
0.522656
52
22.615385
19.110161
63
false
false
0
0
0
0
0
0
0.480769
false
false
1
0cb37ccaca05dea2c770157d558f1937654f2386
1,125,281,469,457
c161b47c9bf8fb1b526a6e6b623da917685144da
/src/se/lth/cs/trajgen/CartesianSystem.java
52df43e2b13a6b515fec73400010327cdcb8f800
[]
no_license
RTSYork/flexpicker-rtsj
https://github.com/RTSYork/flexpicker-rtsj
c181989480c7eded1bb76facb0fc0cb4d5cd2465
176d264281e704d15ecc6c8a2da868b9f9d608e1
refs/heads/master
2019-01-14T05:33:15.497000
2013-05-10T13:59:43
2013-05-10T13:59:43
73,935,531
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * CartesianSystem.java * * Created on den 23 april 2007, 21:12 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package se.lth.cs.trajgen; /** * * @author mathias */ public class CartesianSystem { /** Creates a new instance of CartesianSystem */ public CartesianSystem( CartesianCoordinate O, CartesianCoordinate X, CartesianCoordinate Y, CartesianCoordinate Z) { Ox = O.getX(); Oy = O.getY(); Oz = O.getZ(); XOx = X.getX() - O.getX(); XOy = X.getY() - O.getY(); XOz = X.getZ() - O.getZ(); YOx = Y.getX() - O.getX(); YOy = Y.getY() - O.getY(); YOz = Y.getZ() - O.getZ(); ZOx = Z.getX() - O.getX(); ZOy = Z.getY() - O.getY(); ZOz = Z.getZ() - O.getZ(); } public CartesianPath transform(PaperPath pt) { CartesianPath ct = new CartesianPath(pt.getSize()); for (int i=0; i<pt.getSize(); i++) { ct.set(i, transform(pt.get(i))); } return ct; } public CartesianPath transform(CartesianPath pt) { CartesianPath ct = new CartesianPath(pt.getSize()); for (int i=0; i<pt.getSize(); i++) { ct.set(i, transform(pt.get(i))); } return ct; } public CartesianCoordinate transform(PaperCoordinate pc) { // cc = pc.x*(X-O) + pc.y*(Y-O) + pc.z*(Z-O) + O double x = pc.getX(); double y = pc.getY(); double z = pc.getZ(); double v = pc.getV(); return new CartesianCoordinate( x*XOx + y*YOx + z*ZOx + Ox, x*XOy + y*YOy + z*ZOy + Oy, x*XOz + y*YOz + z*ZOz + Oz, v); } public CartesianCoordinate transform(CartesianCoordinate pc) { // cc = pc.x*(X-O) + pc.y*(Y-O) + pc.z*(Z-O) + O double x = pc.getX(); double y = pc.getY(); double z = pc.getZ(); double v = pc.getV(); return new CartesianCoordinate( x*XOx + y*YOx + z*ZOx + Ox, x*XOy + y*YOy + z*ZOy + Oy, x*XOz + y*YOz + z*ZOz + Oz, v); } private double Ox; private double Oy; private double Oz; private double XOx; private double XOy; private double XOz; private double YOx; private double YOy; private double YOz; private double ZOx; private double ZOy; private double ZOz; }
UTF-8
Java
2,642
java
CartesianSystem.java
Java
[ { "context": "\npackage se.lth.cs.trajgen;\r\n\r\n/**\r\n *\r\n * @author mathias\r\n */\r\npublic class CartesianSystem {\r\n \r\n /", "end": 243, "score": 0.9640315771102905, "start": 236, "tag": "USERNAME", "value": "mathias" } ]
null
[]
/* * CartesianSystem.java * * Created on den 23 april 2007, 21:12 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package se.lth.cs.trajgen; /** * * @author mathias */ public class CartesianSystem { /** Creates a new instance of CartesianSystem */ public CartesianSystem( CartesianCoordinate O, CartesianCoordinate X, CartesianCoordinate Y, CartesianCoordinate Z) { Ox = O.getX(); Oy = O.getY(); Oz = O.getZ(); XOx = X.getX() - O.getX(); XOy = X.getY() - O.getY(); XOz = X.getZ() - O.getZ(); YOx = Y.getX() - O.getX(); YOy = Y.getY() - O.getY(); YOz = Y.getZ() - O.getZ(); ZOx = Z.getX() - O.getX(); ZOy = Z.getY() - O.getY(); ZOz = Z.getZ() - O.getZ(); } public CartesianPath transform(PaperPath pt) { CartesianPath ct = new CartesianPath(pt.getSize()); for (int i=0; i<pt.getSize(); i++) { ct.set(i, transform(pt.get(i))); } return ct; } public CartesianPath transform(CartesianPath pt) { CartesianPath ct = new CartesianPath(pt.getSize()); for (int i=0; i<pt.getSize(); i++) { ct.set(i, transform(pt.get(i))); } return ct; } public CartesianCoordinate transform(PaperCoordinate pc) { // cc = pc.x*(X-O) + pc.y*(Y-O) + pc.z*(Z-O) + O double x = pc.getX(); double y = pc.getY(); double z = pc.getZ(); double v = pc.getV(); return new CartesianCoordinate( x*XOx + y*YOx + z*ZOx + Ox, x*XOy + y*YOy + z*ZOy + Oy, x*XOz + y*YOz + z*ZOz + Oz, v); } public CartesianCoordinate transform(CartesianCoordinate pc) { // cc = pc.x*(X-O) + pc.y*(Y-O) + pc.z*(Z-O) + O double x = pc.getX(); double y = pc.getY(); double z = pc.getZ(); double v = pc.getV(); return new CartesianCoordinate( x*XOx + y*YOx + z*ZOx + Ox, x*XOy + y*YOy + z*ZOy + Oy, x*XOz + y*YOz + z*ZOz + Oz, v); } private double Ox; private double Oy; private double Oz; private double XOx; private double XOy; private double XOz; private double YOx; private double YOy; private double YOz; private double ZOx; private double ZOy; private double ZOz; }
2,642
0.488645
0.484103
92
26.717392
17.082489
66
false
false
0
0
0
0
0
0
0.641304
false
false
1
8eaa3eb4634f450109dbddc0064e65382be48b59
2,095,944,099,803
0427519685c949ddf0e6b7c37f5440b8f3510a57
/src/main/java/juuxel/thisandthat/mixin/client/WorldMixin.java
04b0df6eeb6154e0351364ef7bb5c76ea4edeace
[ "MIT" ]
permissive
immortalcatz/ThisAndThat
https://github.com/immortalcatz/ThisAndThat
44e9eb287e6cfcbc6ab0624c25ae4c97db3cd9e7
b58fbfc4d20f2363ef4cb0de73546659ff44b77f
refs/heads/master
2020-05-02T11:38:49.736000
2019-02-09T11:46:19
2019-02-09T11:46:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* This file is a part of the This & That project * by Juuxel, licensed under the MIT license. * Full code and license: https://github.com/Juuxel/ThisAndThat */ package juuxel.thisandthat.mixin.client; import juuxel.thisandthat.lib.ModConfig; import juuxel.thisandthat.util.CloudColorMode; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(World.class) public class WorldMixin { @Inject(method = "getCloudColor", at = @At("RETURN"), cancellable = true) private void getCloudColor(float float_1, CallbackInfoReturnable<Vec3d> info) { ModConfig.Tweaks tweaks = ModConfig.getInstance().tweaks; if (tweaks.cloudColorMode == CloudColorMode.Modify) { Vec3d original = info.getReturnValue(); info.setReturnValue(new Vec3d( MathHelper.clamp(original.x + tweaks.cloudRedModifier, 0, 1), MathHelper.clamp(original.y + tweaks.cloudGreenModifier, 0, 1), MathHelper.clamp(original.z + tweaks.cloudBlueModifier, 0, 1) )); } else if (tweaks.cloudColorMode == CloudColorMode.Replace) { info.setReturnValue(new Vec3d( MathHelper.clamp(tweaks.cloudRedModifier, 0, 1), MathHelper.clamp(tweaks.cloudGreenModifier, 0, 1), MathHelper.clamp(tweaks.cloudBlueModifier, 0, 1) )); } } }
UTF-8
Java
1,684
java
WorldMixin.java
Java
[ { "context": "is file is a part of the This & That project\n * by Juuxel, licensed under the MIT license.\n * Full cod", "end": 57, "score": 0.7491092085838318, "start": 56, "tag": "USERNAME", "value": "J" }, { "context": " file is a part of the This & That project\n * by Juuxel, licensed under the MIT license.\n * Full code", "end": 58, "score": 0.5134180784225464, "start": 57, "tag": "NAME", "value": "u" }, { "context": "file is a part of the This & That project\n * by Juuxel, licensed under the MIT license.\n * Full code a", "end": 60, "score": 0.6764403581619263, "start": 58, "tag": "USERNAME", "value": "ux" }, { "context": "le is a part of the This & That project\n * by Juuxel, licensed under the MIT license.\n * Full code and", "end": 62, "score": 0.463296502828598, "start": 60, "tag": "NAME", "value": "el" }, { "context": "nse.\n * Full code and license: https://github.com/Juuxel/ThisAndThat\n */\npackage juuxel.thisandthat.mixin.", "end": 147, "score": 0.9997373223304749, "start": 141, "tag": "USERNAME", "value": "Juuxel" } ]
null
[]
/* This file is a part of the This & That project * by Juuxel, licensed under the MIT license. * Full code and license: https://github.com/Juuxel/ThisAndThat */ package juuxel.thisandthat.mixin.client; import juuxel.thisandthat.lib.ModConfig; import juuxel.thisandthat.util.CloudColorMode; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(World.class) public class WorldMixin { @Inject(method = "getCloudColor", at = @At("RETURN"), cancellable = true) private void getCloudColor(float float_1, CallbackInfoReturnable<Vec3d> info) { ModConfig.Tweaks tweaks = ModConfig.getInstance().tweaks; if (tweaks.cloudColorMode == CloudColorMode.Modify) { Vec3d original = info.getReturnValue(); info.setReturnValue(new Vec3d( MathHelper.clamp(original.x + tweaks.cloudRedModifier, 0, 1), MathHelper.clamp(original.y + tweaks.cloudGreenModifier, 0, 1), MathHelper.clamp(original.z + tweaks.cloudBlueModifier, 0, 1) )); } else if (tweaks.cloudColorMode == CloudColorMode.Replace) { info.setReturnValue(new Vec3d( MathHelper.clamp(tweaks.cloudRedModifier, 0, 1), MathHelper.clamp(tweaks.cloudGreenModifier, 0, 1), MathHelper.clamp(tweaks.cloudBlueModifier, 0, 1) )); } } }
1,684
0.684085
0.673397
38
43.315788
26.466568
83
false
false
0
0
0
0
0
0
0.894737
false
false
1
56166258588552c8b717a723cbb942cbb626dad6
30,803,505,491,078
b6b3ca8229fc9aa228c75f080ec46bb63b7a3f51
/apps/owl/src/java/org/hypergraphdb/app/owl/versioning/distributed/ClientCentralizedOntology.java
9e133c4081796ba08ff6e247b869aa5a3ab1a896
[]
no_license
xingh/hypergraphdb
https://github.com/xingh/hypergraphdb
533229be26323d693c84268cfc92f0ece0f0abd7
e8ae87743a916d90d039fcefe393824dee13ed9c
refs/heads/master
2019-01-02T04:02:06.217000
2015-03-20T03:06:36
2015-03-20T03:06:36
32,645,146
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.hypergraphdb.app.owl.versioning.distributed; import org.hypergraphdb.HGHandle; import org.hypergraphdb.peer.HGPeerIdentity; /** * ClientCentralizedOntology. * * @author Thomas Hilpold (CIAO/Miami-Dade County) * @created Aug 23, 2012 */ public class ClientCentralizedOntology extends DistributedOntology { private HGPeerIdentity serverPeer; public ClientCentralizedOntology() { } public ClientCentralizedOntology(HGHandle versionedOntologyHandle, HGPeerIdentity serverPeer) { super(versionedOntologyHandle); setServerPeer(serverPeer); } public ClientCentralizedOntology(HGHandle... args) { super(args); } public HGPeerIdentity getServerPeer() { return serverPeer; } public void setServerPeer(HGPeerIdentity server) { serverPeer = server; } public String toString() { if (getVersionedOntology() != null) { return getVersionedOntology().toString() + " (Client of " + getServerPeer() + ")"; } else { return super.toString(); } } }
UTF-8
Java
1,052
java
ClientCentralizedOntology.java
Java
[ { "context": "**\r\n * ClientCentralizedOntology.\r\n * \r\n * @author Thomas Hilpold (CIAO/Miami-Dade County)\r\n * @created Aug 23, 201", "end": 209, "score": 0.9998796582221985, "start": 195, "tag": "NAME", "value": "Thomas Hilpold" } ]
null
[]
package org.hypergraphdb.app.owl.versioning.distributed; import org.hypergraphdb.HGHandle; import org.hypergraphdb.peer.HGPeerIdentity; /** * ClientCentralizedOntology. * * @author <NAME> (CIAO/Miami-Dade County) * @created Aug 23, 2012 */ public class ClientCentralizedOntology extends DistributedOntology { private HGPeerIdentity serverPeer; public ClientCentralizedOntology() { } public ClientCentralizedOntology(HGHandle versionedOntologyHandle, HGPeerIdentity serverPeer) { super(versionedOntologyHandle); setServerPeer(serverPeer); } public ClientCentralizedOntology(HGHandle... args) { super(args); } public HGPeerIdentity getServerPeer() { return serverPeer; } public void setServerPeer(HGPeerIdentity server) { serverPeer = server; } public String toString() { if (getVersionedOntology() != null) { return getVersionedOntology().toString() + " (Client of " + getServerPeer() + ")"; } else { return super.toString(); } } }
1,044
0.704373
0.698669
52
18.23077
23.17709
94
false
false
0
0
0
0
0
0
1.153846
false
false
1
15aec3ebdac7c292797e9396ba53b96653aebc50
17,832,704,250,916
538adfb2f148a5f399e6308a042cf99daff4521c
/app/src/main/java/com/daniel/ottograf/services/OttografQSTileService.java
1be5599759a73333874185d258b39fcd1743dc1c
[]
no_license
Daninator1/Ottograf
https://github.com/Daninator1/Ottograf
d09052731d8a073f9c8a6810b115bf2137880160
654711086cefea90a78b89c8749a1035674be573
refs/heads/master
2018-02-07T17:51:31.919000
2018-02-05T16:28:31
2018-02-05T16:28:31
95,960,854
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.daniel.ottograf.services; import android.annotation.TargetApi; import android.media.MediaPlayer; import android.service.quicksettings.TileService; import com.daniel.ottograf.R; @TargetApi(24) public class OttografQSTileService extends TileService { @Override public void onClick() { MediaPlayer mediaPlayer; MediaPlayer.OnCompletionListener playerCompletionListener = new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer player) { player.release(); } }; mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.otto5); mediaPlayer.setOnCompletionListener(playerCompletionListener); mediaPlayer.start(); } }
UTF-8
Java
757
java
OttografQSTileService.java
Java
[]
null
[]
package com.daniel.ottograf.services; import android.annotation.TargetApi; import android.media.MediaPlayer; import android.service.quicksettings.TileService; import com.daniel.ottograf.R; @TargetApi(24) public class OttografQSTileService extends TileService { @Override public void onClick() { MediaPlayer mediaPlayer; MediaPlayer.OnCompletionListener playerCompletionListener = new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer player) { player.release(); } }; mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.otto5); mediaPlayer.setOnCompletionListener(playerCompletionListener); mediaPlayer.start(); } }
757
0.715984
0.712021
26
28.115385
27.759027
108
false
false
0
0
0
0
0
0
0.461538
false
false
1
f7fa78e4cf9171ef6d08a2320c01e4b4a9eb08e3
25,220,048,029,374
7b030039b1b2b68515c0bd82e2a7938a5a551588
/app/src/main/java/com/example/softwarepatternsca2/AdminFeatures/WelcomeAdmin.java
e700928b336d8e46a085006cfb375b00369a6ac8
[]
no_license
adamd500/SoftwarePatternsCA2
https://github.com/adamd500/SoftwarePatternsCA2
1bdf5cc04a6673d2fac3913ec87ab8f26ee2642a
777fbc186c5bbdbf122e7aad8f46ff8d4c7b4cf1
refs/heads/master
2023-04-08T01:15:36.707000
2021-04-18T19:08:33
2021-04-18T19:08:33
351,845,494
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.softwarepatternsca2.AdminFeatures; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.example.softwarepatternsca2.R; public class WelcomeAdmin extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome_admin2); } public void createItem(View view) { Intent intent = new Intent(getApplicationContext(),AddStockItem.class); startActivity(intent); } public void viewAllItems(View view) { Intent intent = new Intent(getApplicationContext(),ViewStockedItems.class); startActivity(intent); } public void viewCustomers(View view) { Intent intent = new Intent(getApplicationContext(),ViewCustomers.class); startActivity(intent); } }
UTF-8
Java
952
java
WelcomeAdmin.java
Java
[]
null
[]
package com.example.softwarepatternsca2.AdminFeatures; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.example.softwarepatternsca2.R; public class WelcomeAdmin extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome_admin2); } public void createItem(View view) { Intent intent = new Intent(getApplicationContext(),AddStockItem.class); startActivity(intent); } public void viewAllItems(View view) { Intent intent = new Intent(getApplicationContext(),ViewStockedItems.class); startActivity(intent); } public void viewCustomers(View view) { Intent intent = new Intent(getApplicationContext(),ViewCustomers.class); startActivity(intent); } }
952
0.732143
0.728992
33
27.878788
25.767912
83
false
false
0
0
0
0
0
0
0.515152
false
false
1
abf69bb367948b3576e16c4a8a68eb6048f4867f
36,928,128,853,259
95e00656ad8d5897f4d94ee066fb5966ba9ab77d
/UI Prototypes/ColorPicker/ColorPicker.java
11ea95ebbb06bad25de2236aeec59036d4670c01
[]
no_license
avalon-dev-j120/lab-3-AntNaz
https://github.com/avalon-dev-j120/lab-3-AntNaz
ee57ea40663625aa473a6b6b7c739f5a187b9d00
537ab63468159f2ee0c3d07116fb7de97f06b53b
refs/heads/master
2020-09-21T19:17:59.207000
2019-12-27T16:30:20
2019-12-27T16:30:20
224,896,787
0
0
null
false
2019-12-27T16:30:22
2019-11-29T17:27:09
2019-12-07T15:07:33
2019-12-27T16:30:21
122
0
0
0
Java
false
false
package ColorPicker; import java.awt.*; import static java.awt.BorderLayout.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class ColorPicker extends JFrame { final int width = 600; final int height = 300; private JSlider sliderRed = new JSlider(0, 255, 125); private JSlider sliderGreen = new JSlider(0, 255, 125); private JSlider sliderBlue = new JSlider(0, 255, 125); int[] rgb = new int[3]; int r = 125; int g = 125; int b = 125; public ColorPicker() { setTitle("ColorPicker"); setLocationByPlatform(true); setSize(width, height); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); this.setMinimumSize(new Dimension(500, 300)); JPanel panel1 = new JPanel(new GridBagLayout()); JPanel panel2 = new JPanel(new GridLayout()); panel1.setPreferredSize(new Dimension(width/3,height)); //panel2.setPreferredSize(new Dimension(WIDTH*2/3,height)); this.add(panel1,WEST); this.add(panel2, CENTER); panel1.setBackground(Color.LIGHT_GRAY); JPanel square = new JPanel(); square.setBackground(new Color(r,g,b)); String redHex = Integer.toHexString(r); String greenHex = Integer.toHexString(g); String blueHex = Integer.toHexString(b); String hexColor = "#" + redHex + greenHex + blueHex; square.setToolTipText(hexColor); StringSelection stringSelection = new StringSelection(hexColor); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); JPanel colorChange = new JPanel(new GridLayout(7,1)); ChangeListener onColorsChange = new ChangeListener() { @Override public void stateChanged(ChangeEvent evt) { r = sliderRed.getValue(); g = sliderGreen.getValue(); b = sliderBlue.getValue(); square.setBackground(new Color(r,g,b)); String redHex = Integer.toHexString(r); String greenHex = Integer.toHexString(g); String blueHex = Integer.toHexString(b); if (r<17) redHex = "0" + redHex; if (g<17) greenHex = "0" + greenHex; if (b<17) blueHex = "0" + blueHex; String hexColor = "#" + redHex + greenHex + blueHex; square.setToolTipText(hexColor); StringSelection stringSelection = new StringSelection(hexColor); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); } }; sliderRed.addChangeListener(onColorsChange); sliderGreen.addChangeListener(onColorsChange); sliderBlue.addChangeListener(onColorsChange); panel2.add(colorChange); colorChange.setPreferredSize(new Dimension(300, 200)); square.setPreferredSize(new Dimension(150, 150)); panel1.add(square); sliderRed.setPaintLabels(true); sliderRed.setPaintTicks(true); sliderRed.setSnapToTicks(true); sliderRed.setMajorTickSpacing(25); sliderRed.setMajorTickSpacing(5); sliderGreen.setPaintLabels(true); sliderGreen.setPaintTicks(true); sliderGreen.setSnapToTicks(true); sliderGreen.setMajorTickSpacing(25); sliderGreen.setMajorTickSpacing(5); sliderBlue.setPaintLabels(true); sliderBlue.setPaintTicks(true); sliderBlue.setSnapToTicks(true); sliderBlue.setMajorTickSpacing(25); sliderBlue.setMajorTickSpacing(5); JLabel textRed = new JLabel("RED"); colorChange.add(textRed); colorChange.add(sliderRed); JLabel textGreen = new JLabel("GREEN"); colorChange.add(textGreen); colorChange.add(sliderGreen); JLabel textBlue = new JLabel("BLUE"); colorChange.add(textBlue); colorChange.add(sliderBlue); textRed.setHorizontalAlignment(JLabel.CENTER); textGreen.setHorizontalAlignment(JLabel.CENTER); textBlue.setHorizontalAlignment(JLabel.CENTER); } }
UTF-8
Java
4,603
java
ColorPicker.java
Java
[]
null
[]
package ColorPicker; import java.awt.*; import static java.awt.BorderLayout.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class ColorPicker extends JFrame { final int width = 600; final int height = 300; private JSlider sliderRed = new JSlider(0, 255, 125); private JSlider sliderGreen = new JSlider(0, 255, 125); private JSlider sliderBlue = new JSlider(0, 255, 125); int[] rgb = new int[3]; int r = 125; int g = 125; int b = 125; public ColorPicker() { setTitle("ColorPicker"); setLocationByPlatform(true); setSize(width, height); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); this.setMinimumSize(new Dimension(500, 300)); JPanel panel1 = new JPanel(new GridBagLayout()); JPanel panel2 = new JPanel(new GridLayout()); panel1.setPreferredSize(new Dimension(width/3,height)); //panel2.setPreferredSize(new Dimension(WIDTH*2/3,height)); this.add(panel1,WEST); this.add(panel2, CENTER); panel1.setBackground(Color.LIGHT_GRAY); JPanel square = new JPanel(); square.setBackground(new Color(r,g,b)); String redHex = Integer.toHexString(r); String greenHex = Integer.toHexString(g); String blueHex = Integer.toHexString(b); String hexColor = "#" + redHex + greenHex + blueHex; square.setToolTipText(hexColor); StringSelection stringSelection = new StringSelection(hexColor); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); JPanel colorChange = new JPanel(new GridLayout(7,1)); ChangeListener onColorsChange = new ChangeListener() { @Override public void stateChanged(ChangeEvent evt) { r = sliderRed.getValue(); g = sliderGreen.getValue(); b = sliderBlue.getValue(); square.setBackground(new Color(r,g,b)); String redHex = Integer.toHexString(r); String greenHex = Integer.toHexString(g); String blueHex = Integer.toHexString(b); if (r<17) redHex = "0" + redHex; if (g<17) greenHex = "0" + greenHex; if (b<17) blueHex = "0" + blueHex; String hexColor = "#" + redHex + greenHex + blueHex; square.setToolTipText(hexColor); StringSelection stringSelection = new StringSelection(hexColor); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); } }; sliderRed.addChangeListener(onColorsChange); sliderGreen.addChangeListener(onColorsChange); sliderBlue.addChangeListener(onColorsChange); panel2.add(colorChange); colorChange.setPreferredSize(new Dimension(300, 200)); square.setPreferredSize(new Dimension(150, 150)); panel1.add(square); sliderRed.setPaintLabels(true); sliderRed.setPaintTicks(true); sliderRed.setSnapToTicks(true); sliderRed.setMajorTickSpacing(25); sliderRed.setMajorTickSpacing(5); sliderGreen.setPaintLabels(true); sliderGreen.setPaintTicks(true); sliderGreen.setSnapToTicks(true); sliderGreen.setMajorTickSpacing(25); sliderGreen.setMajorTickSpacing(5); sliderBlue.setPaintLabels(true); sliderBlue.setPaintTicks(true); sliderBlue.setSnapToTicks(true); sliderBlue.setMajorTickSpacing(25); sliderBlue.setMajorTickSpacing(5); JLabel textRed = new JLabel("RED"); colorChange.add(textRed); colorChange.add(sliderRed); JLabel textGreen = new JLabel("GREEN"); colorChange.add(textGreen); colorChange.add(sliderGreen); JLabel textBlue = new JLabel("BLUE"); colorChange.add(textBlue); colorChange.add(sliderBlue); textRed.setHorizontalAlignment(JLabel.CENTER); textGreen.setHorizontalAlignment(JLabel.CENTER); textBlue.setHorizontalAlignment(JLabel.CENTER); } }
4,603
0.617858
0.598957
112
39.080357
18.719326
87
false
false
0
0
0
0
0
0
1.008929
false
false
1
4a2c4240ba3084dc9a6718e2aafa81cd104c0fca
38,250,978,767,535
ccb9dc8450af48aa38f29b3386d8f3e84e264020
/weatherSystem/src/main/java/com/kycoo/persistence/WeatherDao.java
282a84ca7683c96253bcc62202e20e3c932f574c
[]
no_license
kycoo/kycoo
https://github.com/kycoo/kycoo
15771c2d533b36ab4ad665f3bf1d281bc946f88a
9184a7a5d57d34b2d68f7eef5c196f143b38292f
refs/heads/master
2021-01-25T01:16:07.370000
2017-06-25T07:42:38
2017-06-25T07:42:38
94,743,462
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kycoo.persistence; import java.util.Date; import java.util.List; import com.kycoo.domain.City; import com.kycoo.domain.Weather; public interface WeatherDao extends BaseDao<Weather, Integer> { List<Weather> getWeather(City city,Date date,boolean isDay,int count); }
UTF-8
Java
282
java
WeatherDao.java
Java
[]
null
[]
package com.kycoo.persistence; import java.util.Date; import java.util.List; import com.kycoo.domain.City; import com.kycoo.domain.Weather; public interface WeatherDao extends BaseDao<Weather, Integer> { List<Weather> getWeather(City city,Date date,boolean isDay,int count); }
282
0.79078
0.79078
12
22.5
23.57435
71
false
false
0
0
0
0
0
0
0.916667
false
false
1
ca1d1b7f070798fb3bf53a48a7b514f131cc640d
34,608,846,528,049
a96f5db76b23175170ef26ade3974d0bee8cee72
/xinqushi-common/src/main/java/com/xinqushi/entity/Admin.java
281020ed9b4e060f83fbded37e040ae58121541a
[]
no_license
chuanSir123/member
https://github.com/chuanSir123/member
6e930af48e65692371d112ccefd96701ddcbe950
8ca0b5212f866147da3b02fc7c937edf92704505
refs/heads/master
2021-01-25T13:11:04.571000
2018-03-02T11:42:56
2018-03-02T11:42:56
123,536,076
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xinqushi.entity; public class Admin { private Integer id; private String name; private String pwd; private String salt; private Integer authority; private String realname; private Integer cauthority; private String phone; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd == null ? null : pwd.trim(); } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt == null ? null : salt.trim(); } public Integer getAuthority() { return authority; } public void setAuthority(Integer authority) { this.authority = authority; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname == null ? null : realname.trim(); } public Integer getCauthority() { return cauthority; } public void setCauthority(Integer cauthority) { this.cauthority = cauthority; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } }
UTF-8
Java
1,630
java
Admin.java
Java
[]
null
[]
package com.xinqushi.entity; public class Admin { private Integer id; private String name; private String pwd; private String salt; private Integer authority; private String realname; private Integer cauthority; private String phone; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd == null ? null : pwd.trim(); } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt == null ? null : salt.trim(); } public Integer getAuthority() { return authority; } public void setAuthority(Integer authority) { this.authority = authority; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname == null ? null : realname.trim(); } public Integer getCauthority() { return cauthority; } public void setCauthority(Integer cauthority) { this.cauthority = cauthority; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } }
1,630
0.554601
0.554601
83
17.662651
17.676666
66
false
false
0
0
0
0
0
0
0.301205
false
false
1
2252452eb5a15ac4f9b9e28fab0cc6e928c9be73
35,356,170,831,696
4cc1e4d1a371252634ac7de9eb4fae16634958c0
/src/main/java/com/fennec/gestioncinema/service/cinemaInitServiceImp.java
3ecfc981761c8fe108edcd3a347172fc3fdff16e
[]
no_license
houcine95/gestioncinema
https://github.com/houcine95/gestioncinema
4c65e66babbb0b51bc2dccde45e9f987a51276cf
0a4b2eeb4b81d3cf87a41238c318fe8ceffa4ea8
refs/heads/master
2022-07-10T04:03:20.111000
2020-05-12T16:58:01
2020-05-12T16:58:01
263,095,656
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fennec.gestioncinema.service; import com.fennec.gestioncinema.dao.*; import com.fennec.gestioncinema.entities.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import java.util.Date; import java.util.stream.Stream; //@Bean public class cinemaInitServiceImp implements ICinemaInitService { @Autowired CategorieRepository categorieRepository; @Autowired CinemaRepository cinemaRepository; @Autowired FilmRepository filmRepository; @Autowired PlaceRepository placeRepository; @Autowired ProjectionFilmRepository projectionFilmRepository; @Autowired SalleRepository salleRepository; @Autowired SeanceRepository seanceRepository; @Autowired TicketRepository ticketRepository; @Autowired VilleRepository villeRepository; @Autowired @Override public void initCategories() { Stream.of("Action", "Aventure", "Drama").forEach(c ->{ Categorie cat = new Categorie(); cat.setName(c); categorieRepository.save(cat); }); } @Override public void initCinemas() { villeRepository.findAll().forEach(v ->{ Stream.of("Kawakib", "EL Falah", "Megarama").forEach(c ->{ Cinema cinm = new Cinema(); cinm.setName(c); cinm.setNombreSalle(3+(int)(Math.random()*9)); cinm.setVille(v); cinemaRepository.save(cinm); }); }); } @Override public void initFilms() { Categorie c1 = categorieRepository.findAll().get(0); Film f1 = new Film(); f1.setCategorie(c1); f1.setDuree(2.32); f1.setRealisateur("Christopher Nolan"); f1.setTitre("Dark Knight"); filmRepository.save(f1); } @Override public void initPlaces() { salleRepository.findAll().forEach(s ->{ Stream.of(1,2,3,4,5,6,7).forEach(p->{ Place place = new Place(); place.setNumero(p); place.setSalle(s); placeRepository.save(place); }); }); } @Override public void initProjectionFilms() { Film film = filmRepository.findAll().get(0); Salle salle = salleRepository.findAll().get(0); Seance seance = seanceRepository.findAll().get(0); ProjectionFilm projectionFilm = new ProjectionFilm(); projectionFilm.setDateProjection(seance.getHeureDebut()); projectionFilm.setFilm(film); projectionFilm.setSalle(salle); projectionFilm.setSeance(seance); projectionFilmRepository.save(projectionFilm); } @Override public void initSalles() { cinemaRepository.findAll().forEach(c ->{ Salle salle = new Salle(); salle.setCinema(c); salle.setNombrePlace(c.getNombreSalle()); salle.setName("S1"); salle.setNombrePlace(50); salleRepository.save(salle); }); } @Override public void initSeances() { Seance seance = new Seance(); seance.setHeureDebut(new Date()); seanceRepository.save(seance); } @Override public void initTickets() { ProjectionFilm projectionFilm = projectionFilmRepository.findAll().get(0); Place place = placeRepository.findAll().get(0); Ticket ticket = new Ticket(); ticket.setNomClient("ELHOUCINE MARIAMI"); ticket.setPrix(30.00); ticket.setCodePayement((int)Math.random()*10000); ticket.setPlace(place); ticket.setProjectionFilm(projectionFilm); ticketRepository.save(ticket); } @Override public void initvilles() { Stream.of("Casablanca", "Rabat", "Tanger").forEach(v ->{ Ville ville = new Ville(); ville.setName(v); villeRepository.save(ville); }); } }
UTF-8
Java
3,989
java
cinemaInitServiceImp.java
Java
[ { "context": " f1.setDuree(2.32);\n f1.setRealisateur(\"Christopher Nolan\");\n f1.setTitre(\"Dark Knight\");\n fi", "end": 1788, "score": 0.9998696446418762, "start": 1771, "tag": "NAME", "value": "Christopher Nolan" }, { "context": "cket = new Ticket();\n ticket.setNomClient(\"ELHOUCINE MARIAMI\");\n ticket.setPrix(30.00);\n ticket.", "end": 3528, "score": 0.9998509883880615, "start": 3511, "tag": "NAME", "value": "ELHOUCINE MARIAMI" } ]
null
[]
package com.fennec.gestioncinema.service; import com.fennec.gestioncinema.dao.*; import com.fennec.gestioncinema.entities.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import java.util.Date; import java.util.stream.Stream; //@Bean public class cinemaInitServiceImp implements ICinemaInitService { @Autowired CategorieRepository categorieRepository; @Autowired CinemaRepository cinemaRepository; @Autowired FilmRepository filmRepository; @Autowired PlaceRepository placeRepository; @Autowired ProjectionFilmRepository projectionFilmRepository; @Autowired SalleRepository salleRepository; @Autowired SeanceRepository seanceRepository; @Autowired TicketRepository ticketRepository; @Autowired VilleRepository villeRepository; @Autowired @Override public void initCategories() { Stream.of("Action", "Aventure", "Drama").forEach(c ->{ Categorie cat = new Categorie(); cat.setName(c); categorieRepository.save(cat); }); } @Override public void initCinemas() { villeRepository.findAll().forEach(v ->{ Stream.of("Kawakib", "EL Falah", "Megarama").forEach(c ->{ Cinema cinm = new Cinema(); cinm.setName(c); cinm.setNombreSalle(3+(int)(Math.random()*9)); cinm.setVille(v); cinemaRepository.save(cinm); }); }); } @Override public void initFilms() { Categorie c1 = categorieRepository.findAll().get(0); Film f1 = new Film(); f1.setCategorie(c1); f1.setDuree(2.32); f1.setRealisateur("<NAME>"); f1.setTitre("Dark Knight"); filmRepository.save(f1); } @Override public void initPlaces() { salleRepository.findAll().forEach(s ->{ Stream.of(1,2,3,4,5,6,7).forEach(p->{ Place place = new Place(); place.setNumero(p); place.setSalle(s); placeRepository.save(place); }); }); } @Override public void initProjectionFilms() { Film film = filmRepository.findAll().get(0); Salle salle = salleRepository.findAll().get(0); Seance seance = seanceRepository.findAll().get(0); ProjectionFilm projectionFilm = new ProjectionFilm(); projectionFilm.setDateProjection(seance.getHeureDebut()); projectionFilm.setFilm(film); projectionFilm.setSalle(salle); projectionFilm.setSeance(seance); projectionFilmRepository.save(projectionFilm); } @Override public void initSalles() { cinemaRepository.findAll().forEach(c ->{ Salle salle = new Salle(); salle.setCinema(c); salle.setNombrePlace(c.getNombreSalle()); salle.setName("S1"); salle.setNombrePlace(50); salleRepository.save(salle); }); } @Override public void initSeances() { Seance seance = new Seance(); seance.setHeureDebut(new Date()); seanceRepository.save(seance); } @Override public void initTickets() { ProjectionFilm projectionFilm = projectionFilmRepository.findAll().get(0); Place place = placeRepository.findAll().get(0); Ticket ticket = new Ticket(); ticket.setNomClient("<NAME>"); ticket.setPrix(30.00); ticket.setCodePayement((int)Math.random()*10000); ticket.setPlace(place); ticket.setProjectionFilm(projectionFilm); ticketRepository.save(ticket); } @Override public void initvilles() { Stream.of("Casablanca", "Rabat", "Tanger").forEach(v ->{ Ville ville = new Ville(); ville.setName(v); villeRepository.save(ville); }); } }
3,967
0.61444
0.604914
132
29.219696
19.401779
82
false
false
0
0
0
0
0
0
0.636364
false
false
1
b2ec6cc800bd0318c88c98f0573123b983a1966b
8,211,977,474,121
c019fcfdc9d44ac35840c7edaa141677e5aedeb1
/Dominio/src/dominio/Cliente.java
406be761a93abc00e94fa11e58d0ee890010ffe7
[]
no_license
Skye41/projetolivros
https://github.com/Skye41/projetolivros
a0d4546eb9cff4ce7985cfb7a06d738a3e6eb83c
3be7d7208571d1677a370bcb44ab9a71ac65c970
refs/heads/master
2020-03-23T04:19:51.332000
2018-07-16T02:27:47
2018-07-16T02:27:47
141,070,804
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dominio; import java.util.Date; import java.util.List; public class Cliente extends EntidadeDominio { private boolean status; private List<Endereco> enderecos; private List<Cartao> cartoes; private Usuario usuario; private Genero genero; private String nome; private Date dtNascimento; private String CPF; private List<Telefone> telefones; private int ranking; private List<Cupom> cupons; public Cliente(){} public Cliente(int id) { this.setId(id); } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public List<Endereco> getEnderecos() { return enderecos; } public void setEnderecos(List<Endereco> enderecos) { this.enderecos = enderecos; } public List<Cartao> getCartoes() { return cartoes; } public void setCartoes(List<Cartao> cartoes) { this.cartoes = cartoes; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Genero getGenero() { return genero; } public void setGenero(Genero genero) { this.genero = genero; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Date getDtNascimento() { return dtNascimento; } public void setDtNascimento(Date dtNascimento) { this.dtNascimento = dtNascimento; } public String getCPF() { return CPF; } public void setCPF(String cPF) { CPF = cPF; } public List<Telefone> getTelefones() { return telefones; } public void setTelefones(List<Telefone> telefone) { this.telefones = telefone; } public int getRanking() { return ranking; } public void setRanking(int ranking) { this.ranking = ranking; } public void addTelefone(Telefone telefone) { this.telefones.add(telefone); } public void addCartao(Cartao cartao) { this.cartoes.add(cartao); } public void addEndereco(Endereco endereco) { this.enderecos.add(endereco); } public List<Cupom> getCupons() { return cupons; } public void setCupons(List<Cupom> cupons) { this.cupons = cupons; } }
UTF-8
Java
2,532
java
Cliente.java
Java
[]
null
[]
package dominio; import java.util.Date; import java.util.List; public class Cliente extends EntidadeDominio { private boolean status; private List<Endereco> enderecos; private List<Cartao> cartoes; private Usuario usuario; private Genero genero; private String nome; private Date dtNascimento; private String CPF; private List<Telefone> telefones; private int ranking; private List<Cupom> cupons; public Cliente(){} public Cliente(int id) { this.setId(id); } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public List<Endereco> getEnderecos() { return enderecos; } public void setEnderecos(List<Endereco> enderecos) { this.enderecos = enderecos; } public List<Cartao> getCartoes() { return cartoes; } public void setCartoes(List<Cartao> cartoes) { this.cartoes = cartoes; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Genero getGenero() { return genero; } public void setGenero(Genero genero) { this.genero = genero; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Date getDtNascimento() { return dtNascimento; } public void setDtNascimento(Date dtNascimento) { this.dtNascimento = dtNascimento; } public String getCPF() { return CPF; } public void setCPF(String cPF) { CPF = cPF; } public List<Telefone> getTelefones() { return telefones; } public void setTelefones(List<Telefone> telefone) { this.telefones = telefone; } public int getRanking() { return ranking; } public void setRanking(int ranking) { this.ranking = ranking; } public void addTelefone(Telefone telefone) { this.telefones.add(telefone); } public void addCartao(Cartao cartao) { this.cartoes.add(cartao); } public void addEndereco(Endereco endereco) { this.enderecos.add(endereco); } public List<Cupom> getCupons() { return cupons; } public void setCupons(List<Cupom> cupons) { this.cupons = cupons; } }
2,532
0.594392
0.594392
128
18.78125
14.812335
54
false
false
0
0
0
0
0
0
0.34375
false
false
1
692df2f891f1c18eba38f98c24331c37d6bebeb9
9,698,036,175,505
4d9c11e6d569010159c7da225a47c282260e6310
/service-management-front/src/main/java/fr/orange/ddr/sympa/controllers/NameNodeController.java
bc745ebcc698a47dd1535cb565d896cee2980bc5
[]
no_license
Zouhairhajji/hypervision-bigdata
https://github.com/Zouhairhajji/hypervision-bigdata
0c37c696ced3d98455fe67e3ba894541e8fad6a2
87e72120937effe61f3569d550abb1ecb2305b03
refs/heads/master
2020-03-29T05:39:01.712000
2018-09-13T14:01:25
2018-09-13T14:01:25
136,483,459
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fr.orange.ddr.sympa.controllers; import com.fasterxml.jackson.core.type.TypeReference; import com.jcraft.jsch.JSchException; import fr.orange.ddr.sympa.abstractClasses.AbstractController; import fr.orange.ddr.sympa.models.agent.dtos.CommandResult; import fr.orange.ddr.sympa.models.namenode.dtos.NameNode; import fr.orange.ddr.sympa.remotes.ServiceManagementNnRemote; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.xml.sax.SAXException; /** * * @author fqlh0717 */ @Controller @RequestMapping("namenode") public class NameNodeController extends AbstractController { private final static Logger logger = Logger.getLogger(NameNodeController.class); @Autowired private ServiceManagementNnRemote serviceManagementNnRemote; /** * */ public NameNodeController() { super("namenode_views"); } /** * * @param model * @return * @throws IOException * @throws FileNotFoundException * @throws JSchException * @throws InterruptedException * @throws SAXException * @throws ParserConfigurationException * @throws Exception */ @RequestMapping(value = "showdetail", method = RequestMethod.GET) public String getNameNodeDetail(Model model) throws IOException, FileNotFoundException, JSchException, InterruptedException, SAXException, ParserConfigurationException, Exception { this.init("namenode_detail", "Détails name node", model); logger.info("VUE DETAIL NAMENODE"); List<NameNode> nns = mapper.readValue(this.serviceManagementNnRemote.getNameNodeDetail(), new TypeReference<List<NameNode>>() { }); model.addAttribute("all_nns", nns); return super.getViewPath(); } /** @RequestMapping(value = {"failover", "failover/"}, method = RequestMethod.GET) public String failOver(Model model) throws IOException, FileNotFoundException, JSchException, InterruptedException, SAXException, ParserConfigurationException, Exception { logger.info("FAILOVER"); ResponseEntity<CommandResult> result = this.serviceManagementNnRemote.failOver(getAuthentication().getName()); logger.info("FAILOVER EXECUTED by " + getAuthentication().getName() + " RESULT:" + result); model.addAttribute("failover_result", result.getBody()); return getNameNodeDetail(model); } **/ }
UTF-8
Java
3,101
java
NameNodeController.java
Java
[ { "context": "t org.xml.sax.SAXException;\r\n\r\n/**\r\n *\r\n * @author fqlh0717\r\n */\r\n@Controller\r\n@RequestMapping(\"namenode\")\r\np", "end": 1149, "score": 0.999620258808136, "start": 1141, "tag": "USERNAME", "value": "fqlh0717" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fr.orange.ddr.sympa.controllers; import com.fasterxml.jackson.core.type.TypeReference; import com.jcraft.jsch.JSchException; import fr.orange.ddr.sympa.abstractClasses.AbstractController; import fr.orange.ddr.sympa.models.agent.dtos.CommandResult; import fr.orange.ddr.sympa.models.namenode.dtos.NameNode; import fr.orange.ddr.sympa.remotes.ServiceManagementNnRemote; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.xml.sax.SAXException; /** * * @author fqlh0717 */ @Controller @RequestMapping("namenode") public class NameNodeController extends AbstractController { private final static Logger logger = Logger.getLogger(NameNodeController.class); @Autowired private ServiceManagementNnRemote serviceManagementNnRemote; /** * */ public NameNodeController() { super("namenode_views"); } /** * * @param model * @return * @throws IOException * @throws FileNotFoundException * @throws JSchException * @throws InterruptedException * @throws SAXException * @throws ParserConfigurationException * @throws Exception */ @RequestMapping(value = "showdetail", method = RequestMethod.GET) public String getNameNodeDetail(Model model) throws IOException, FileNotFoundException, JSchException, InterruptedException, SAXException, ParserConfigurationException, Exception { this.init("namenode_detail", "Détails name node", model); logger.info("VUE DETAIL NAMENODE"); List<NameNode> nns = mapper.readValue(this.serviceManagementNnRemote.getNameNodeDetail(), new TypeReference<List<NameNode>>() { }); model.addAttribute("all_nns", nns); return super.getViewPath(); } /** @RequestMapping(value = {"failover", "failover/"}, method = RequestMethod.GET) public String failOver(Model model) throws IOException, FileNotFoundException, JSchException, InterruptedException, SAXException, ParserConfigurationException, Exception { logger.info("FAILOVER"); ResponseEntity<CommandResult> result = this.serviceManagementNnRemote.failOver(getAuthentication().getName()); logger.info("FAILOVER EXECUTED by " + getAuthentication().getName() + " RESULT:" + result); model.addAttribute("failover_result", result.getBody()); return getNameNodeDetail(model); } **/ }
3,101
0.724839
0.723226
81
36.271606
36.794731
184
false
false
0
0
0
0
0
0
0.679012
false
false
1
fea38e3e976abc0a2bd2a73b0795eb7de9612968
1,735,166,839,804
1ce1fc7b663e6949e77888e2c8894d5b1471962f
/Restore IP Addresses.java
516574a8a772f61108d7e1c662b12f2cb0354741
[]
no_license
Onewayr9/Leetcode
https://github.com/Onewayr9/Leetcode
ed148f72f2e5b7e9a0aeeec1eeb895b89bb29866
97c7b4781f295c5a4752fdc9086192d64ec72ed5
refs/heads/master
2016-09-02T02:07:45.208000
2016-01-26T22:59:18
2016-01-26T22:59:18
40,700,950
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { public List<String> restoreIpAddresses(String s) { List<String> ans = new ArrayList<String>(); String IP = ""; backtracking(0,s,IP,ans); return ans; } public boolean backtracking(int layer, String sub, String IP, List<String> tempans){ if(layer==3){ if(sub.charAt(0)=='0'){ if(sub.length()==1){ tempans.add(IP+sub); return true; }else return false;} else{ int num = Integer.parseInt(sub); if(num<=255){ tempans.add(IP+sub); return true; } else return false; } }else{ if(sub.length()==0) return false; else if(sub.length()<4-layer||sub.length()>3*(4-layer)) return false; else{ if(sub.length()>1){ backtracking(layer+1,sub.substring(1),IP+sub.substring(0,1)+".",tempans); } if(sub.length()>2&&sub.charAt(0)!='0'){ backtracking(layer+1,sub.substring(2),IP+sub.substring(0,2)+".",tempans); } if(sub.length()>3&&sub.charAt(0)!='0'&&Integer.parseInt(sub.substring(0,3))<=255){ backtracking(layer+1,sub.substring(3),IP+sub.substring(0,3)+".",tempans); } } } return true; } }
UTF-8
Java
1,520
java
Restore IP Addresses.java
Java
[]
null
[]
public class Solution { public List<String> restoreIpAddresses(String s) { List<String> ans = new ArrayList<String>(); String IP = ""; backtracking(0,s,IP,ans); return ans; } public boolean backtracking(int layer, String sub, String IP, List<String> tempans){ if(layer==3){ if(sub.charAt(0)=='0'){ if(sub.length()==1){ tempans.add(IP+sub); return true; }else return false;} else{ int num = Integer.parseInt(sub); if(num<=255){ tempans.add(IP+sub); return true; } else return false; } }else{ if(sub.length()==0) return false; else if(sub.length()<4-layer||sub.length()>3*(4-layer)) return false; else{ if(sub.length()>1){ backtracking(layer+1,sub.substring(1),IP+sub.substring(0,1)+".",tempans); } if(sub.length()>2&&sub.charAt(0)!='0'){ backtracking(layer+1,sub.substring(2),IP+sub.substring(0,2)+".",tempans); } if(sub.length()>3&&sub.charAt(0)!='0'&&Integer.parseInt(sub.substring(0,3))<=255){ backtracking(layer+1,sub.substring(3),IP+sub.substring(0,3)+".",tempans); } } } return true; } }
1,520
0.45
0.426316
42
35.214287
25.461021
98
false
false
0
0
0
0
0
0
0.904762
false
false
1
c6522ccefbbc74750323f649659b6c339db49273
24,223,615,580,924
e7340b19ff001016f486183271c4baeeb3bc081a
/src/main/java/com/nachiket/vo/ResponseVO.java
4c07cffd9b560c40629c0fab499b992d5e85c8ae
[]
no_license
Nachiketsingh90/batch-service
https://github.com/Nachiketsingh90/batch-service
4679e0e1bfc386cd5bc3468d18c761a8936d2f7e
2ce73eb1ab52ee6b8369889a36df3a128bf8a332
refs/heads/main
2023-06-06T21:06:49.884000
2021-06-28T08:42:20
2021-06-28T08:42:20
380,963,639
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nachiket.vo; import com.nachiket.model.Batch; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Data @AllArgsConstructor @NoArgsConstructor @Setter @Getter public class ResponseVO { private Batch batch; private Faculty faculty; }
UTF-8
Java
337
java
ResponseVO.java
Java
[]
null
[]
package com.nachiket.vo; import com.nachiket.model.Batch; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Data @AllArgsConstructor @NoArgsConstructor @Setter @Getter public class ResponseVO { private Batch batch; private Faculty faculty; }
337
0.795252
0.795252
26
11.923077
12.025368
33
false
false
0
0
0
0
0
0
0.423077
false
false
1
66dc8ed85743a52cd38959c8bbdb1bb437f95da3
24,446,953,877,880
5d17886fe46d075a6db402373c94a7957544d535
/Course 5 Recommendation System/MovieRunnerAverage.java
ba8c9caa4e0218730e6c4977947f504eb3960865
[]
no_license
nigel-f-wilson/movieRecommendationEngine
https://github.com/nigel-f-wilson/movieRecommendationEngine
6b1fa2157ae472fcbdada06ccdf3378eb134bc17
e5ea95a5bf8a382e872cf074c33feb5adecaddda
refs/heads/master
2022-06-16T22:02:05.216000
2019-10-14T18:17:13
2019-10-14T18:17:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Write a description of MovieRunnerAverage here. * * @author (your name) * @version (a version number or a date) */ import java.util.Collections; import java.util.ArrayList; public class MovieRunnerAverage { public void printAverageRatings() throws java.io.IOException { /* * TEST FILENAME PARAMETERS */ //String moviesFilename = "ratedmovies_short.csv"; // size should be 5. // String moviesFilename = "ratedmovies.csv"; // size should be 3143. String moviesFilename = "ratedmoviesfull.csv"; // String ratingsFilename = "ratings_short.csv"; // There should be 5 raters. String ratingsFilename = "ratings.csv"; // There should be 1048 raters. SecondRatings sr = new SecondRatings(moviesFilename, ratingsFilename); System.out.println("The number of movies in the " + moviesFilename + " was " + sr.getMovieSize()); System.out.println("The number of movies in the " + ratingsFilename + " was " + sr.getRaterSize()); /* * TEST SPECIFY MINIMUM NUMBER OF RATERS */ int minRaters = 12; // Returns an unsorted ArrayList, already filtering out any movie with too few ratings. ArrayList<Rating> list = sr.getAverageRatings(minRaters); Collections.sort(list); // Collections.reverse(list); // Since the Rating class implements the Comparable interface (has method compareTo()) we can here use the AL.sort method. for (Rating r : list) { System.out.println("\"" + sr.getTitle(r.getItem()) + "\" had avg rating: " + r.getValue()); } // Using the files ratedmoviesfull.csv and ratings.csv, what is the rating of the movie “Moneyball”? String title = "Moneyball"; String id = sr.getID(title); double avg = sr.getAverageRatingByMovieID(id, minRaters); System.out.println(title + " got an avg rating of " + avg + "\r\n"); title = "Vacation"; id = sr.getID(title); avg = sr.getAverageRatingByMovieID(id, minRaters); System.out.println(title + " got an avg rating of " + avg + "\r\n"); title = "The Maze Runner"; id = sr.getID(title); avg = sr.getAverageRatingByMovieID(id, minRaters); System.out.println(title + " got an avg rating of " + avg + "\r\n"); } }
UTF-8
Java
2,468
java
MovieRunnerAverage.java
Java
[]
null
[]
/** * Write a description of MovieRunnerAverage here. * * @author (your name) * @version (a version number or a date) */ import java.util.Collections; import java.util.ArrayList; public class MovieRunnerAverage { public void printAverageRatings() throws java.io.IOException { /* * TEST FILENAME PARAMETERS */ //String moviesFilename = "ratedmovies_short.csv"; // size should be 5. // String moviesFilename = "ratedmovies.csv"; // size should be 3143. String moviesFilename = "ratedmoviesfull.csv"; // String ratingsFilename = "ratings_short.csv"; // There should be 5 raters. String ratingsFilename = "ratings.csv"; // There should be 1048 raters. SecondRatings sr = new SecondRatings(moviesFilename, ratingsFilename); System.out.println("The number of movies in the " + moviesFilename + " was " + sr.getMovieSize()); System.out.println("The number of movies in the " + ratingsFilename + " was " + sr.getRaterSize()); /* * TEST SPECIFY MINIMUM NUMBER OF RATERS */ int minRaters = 12; // Returns an unsorted ArrayList, already filtering out any movie with too few ratings. ArrayList<Rating> list = sr.getAverageRatings(minRaters); Collections.sort(list); // Collections.reverse(list); // Since the Rating class implements the Comparable interface (has method compareTo()) we can here use the AL.sort method. for (Rating r : list) { System.out.println("\"" + sr.getTitle(r.getItem()) + "\" had avg rating: " + r.getValue()); } // Using the files ratedmoviesfull.csv and ratings.csv, what is the rating of the movie “Moneyball”? String title = "Moneyball"; String id = sr.getID(title); double avg = sr.getAverageRatingByMovieID(id, minRaters); System.out.println(title + " got an avg rating of " + avg + "\r\n"); title = "Vacation"; id = sr.getID(title); avg = sr.getAverageRatingByMovieID(id, minRaters); System.out.println(title + " got an avg rating of " + avg + "\r\n"); title = "The Maze Runner"; id = sr.getID(title); avg = sr.getAverageRatingByMovieID(id, minRaters); System.out.println(title + " got an avg rating of " + avg + "\r\n"); } }
2,468
0.602273
0.597403
61
39.377048
34.337364
130
false
false
0
0
0
0
0
0
0.540984
false
false
1