blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cd8c991b2790dc6037ba333bf4123cdb6d70e6a9 | 3,178,275,859,329 | ff884f6be46b7f550a725ed56748b914e27bf85d | /jdbc/src/test/java/com/becomejavasenior/dao/jdbc/impl/TagDaoImplTest.java | 81cf91127d244bd89831928ee1c4be9f8a6ed46a | [] | no_license | borntowinn/CRM | https://github.com/borntowinn/CRM | 79f5f3e69e81dcca44fd79690447c9f416ff277c | ddc1493c1aa9b8cea309cde60def328508defda2 | refs/heads/master | 2021-01-10T14:17:46.140000 | 2016-03-28T12:13:22 | 2016-03-28T12:13:22 | 53,863,709 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.becomejavasenior.dao.jdbc.impl;
import com.becomejavasenior.Tag;
import com.becomejavasenior.dao.TagDao;
import com.becomejavasenior.dao.exception.PersistException;
import com.becomejavasenior.dao.jdbc.factory.DaoFactory;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
public class TagDaoImplTest {
private static Tag tag;
private List<Tag> tags;
private static TagDao<Tag> tagDao;
@BeforeClass
public static void setupAndConnection()
{
tagDao = DaoFactory.getTagDao();
tag = new Tag();
tag.setTag("one");
}
@Test
public void createDbEntry_Phase_PhaseFromDb()
{
Assert.assertEquals(tag.getTag(), tagDao.create(tag).getTag());
}
@Test
public void getRecordByPK()
{
//when
Integer id = tagDao.create(tag).getId();
//then
Assert.assertEquals(tag.getTag(), tagDao.getByPK(id).getTag());
tagDao.delete(id);
}
@Test
public void getAllRecordsTest()
{
//when
tags = tagDao.getAll();
//then
Assert.assertNotNull(tags);
Assert.assertTrue(tags.size() > 0);
}
@Test(expected=PersistException.class)
public void deleteRecord()
{
//when
Integer id = tagDao.create(tag).getId();
tagDao.delete(id);
//then -> exception must be thrown == the record was successfully deleted and can't be accessed anymore
tagDao.getByPK(id);
}
} | UTF-8 | Java | 1,531 | java | TagDaoImplTest.java | Java | [] | null | [] | package com.becomejavasenior.dao.jdbc.impl;
import com.becomejavasenior.Tag;
import com.becomejavasenior.dao.TagDao;
import com.becomejavasenior.dao.exception.PersistException;
import com.becomejavasenior.dao.jdbc.factory.DaoFactory;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
public class TagDaoImplTest {
private static Tag tag;
private List<Tag> tags;
private static TagDao<Tag> tagDao;
@BeforeClass
public static void setupAndConnection()
{
tagDao = DaoFactory.getTagDao();
tag = new Tag();
tag.setTag("one");
}
@Test
public void createDbEntry_Phase_PhaseFromDb()
{
Assert.assertEquals(tag.getTag(), tagDao.create(tag).getTag());
}
@Test
public void getRecordByPK()
{
//when
Integer id = tagDao.create(tag).getId();
//then
Assert.assertEquals(tag.getTag(), tagDao.getByPK(id).getTag());
tagDao.delete(id);
}
@Test
public void getAllRecordsTest()
{
//when
tags = tagDao.getAll();
//then
Assert.assertNotNull(tags);
Assert.assertTrue(tags.size() > 0);
}
@Test(expected=PersistException.class)
public void deleteRecord()
{
//when
Integer id = tagDao.create(tag).getId();
tagDao.delete(id);
//then -> exception must be thrown == the record was successfully deleted and can't be accessed anymore
tagDao.getByPK(id);
}
} | 1,531 | 0.640105 | 0.639451 | 64 | 22.9375 | 21.74991 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421875 | false | false | 0 |
37ce4dc494a2cb01992d8e729c1cda909e5fb60e | 6,871,947,716,920 | 0b1ce1b4b75af68e3b67dbac8d31e71dbcec8c86 | /src/com/xinzhe/contest/weekly/season04/weekly194/Leetcode_weekly_19403.java | 2763c32517b79697b770cf8f072539245ecddee7 | [] | no_license | JasonZ2z/LeetCode | https://github.com/JasonZ2z/LeetCode | cc37bb8715cb52ab3069d2270fd9903958065149 | 20adb4583633c68491a1baa194985af56e8ab62d | refs/heads/master | 2023-02-17T22:07:38.351000 | 2023-02-14T03:21:08 | 2023-02-14T03:21:08 | 237,776,424 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xinzhe.contest.weekly.season04.weekly194;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
/**
* @author Xin
* @date 2020/6/21
* Title : 1488. 避免洪水泛滥
* Description : 你的国家有无数个湖泊,所有湖泊一开始都是空的。当第 n 个湖泊下雨的时候,如果第 n 个湖泊是空的,那么它就会装满水,否则这个湖泊会发生洪水。你的目标是避免任意一个湖泊发生洪水。
* link : https://leetcode-cn.com/problems/avoid-flood-in-the-city
* Level : Medium
* Comment 194周赛03
*/
public class Leetcode_weekly_19403 {
public static void main(String[] args) {
int[] arr = {69,0,0,0,69};
System.out.println(Arrays.toString(avoidFlood(arr)));
System.out.println(Arrays.toString(avoidFlood3(arr)));
}
//todo need to review
public static int[] avoidFlood(int[] rains) {
int n = rains.length;
int[] res = new int[n];
int[] next = new int[n];
Arrays.fill(next, n+1);
Map<Integer, Integer> map = new HashMap<>();
for (int i = rains.length - 1; i >= 0; i--) {
int r = rains[i];
if(r > 0) {
if(map.containsKey(r)) {
next[i] = map.get(r);
}
map.put(r, i);
}
}
Map<Integer, Boolean> rmap = new HashMap<>();
PriorityQueue<Node> queue = new PriorityQueue<>(n, Comparator.comparingInt(a -> a.day));
for (int i = 0; i < n; i++) {
if(rains[i] > 0) {
if(rmap.containsKey(i) && rmap.get(i)) return new int[0];
rmap.put(i, true);
queue.offer(new Node(i, next[i]));
res[i] = -1;
} else{
if(queue.isEmpty()) {
res[i] = 1;
}else {
Node node = queue.remove();
res[i] = rains[node.index];
rmap.put(node.index, false);
}
}
if(!queue.isEmpty() && queue.peek().day <= i) {
return new int[0];
}
}
return res;
}
static class Node {
int index;
int day;
public Node(int index, int day) {
this.index = index;
this.day = day;
}
}
public static int[] avoidFlood3(int[] rains) {
int n = rains.length;
Map<Integer, Integer> registries = new HashMap<>(n);
int[] next = new int[n];
for (int i = n - 1; i >= 0; i--) {
next[i] = registries.getOrDefault(rains[i], n);
registries.put(rains[i], i);
}
int[] ans = new int[n];
PriorityQueue<Node> pq = new PriorityQueue<>(n, Comparator.comparingInt(a -> a.day));
for (int i = 0; i < n; i++) {
if (rains[i] == 0) {
if (!pq.isEmpty()) {
ans[i] = pq.remove().index;
}else{
ans[i] = 1;
}
} else {
Node rain = new Node(rains[i], next[i]);
pq.add(rain);
ans[i] = -1;
}
if (!pq.isEmpty() && pq.peek().day <= i) {
return new int[0];
}
}
return ans;
}
}
| UTF-8 | Java | 3,424 | java | Leetcode_weekly_19403.java | Java | [
{
"context": "p;\nimport java.util.PriorityQueue;\n\n/**\n * @author Xin\n * @date 2020/6/21\n * Title : 1488. 避免洪水泛滥\n * Des",
"end": 208,
"score": 0.9974726438522339,
"start": 205,
"tag": "NAME",
"value": "Xin"
}
] | null | [] | package com.xinzhe.contest.weekly.season04.weekly194;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
/**
* @author Xin
* @date 2020/6/21
* Title : 1488. 避免洪水泛滥
* Description : 你的国家有无数个湖泊,所有湖泊一开始都是空的。当第 n 个湖泊下雨的时候,如果第 n 个湖泊是空的,那么它就会装满水,否则这个湖泊会发生洪水。你的目标是避免任意一个湖泊发生洪水。
* link : https://leetcode-cn.com/problems/avoid-flood-in-the-city
* Level : Medium
* Comment 194周赛03
*/
public class Leetcode_weekly_19403 {
public static void main(String[] args) {
int[] arr = {69,0,0,0,69};
System.out.println(Arrays.toString(avoidFlood(arr)));
System.out.println(Arrays.toString(avoidFlood3(arr)));
}
//todo need to review
public static int[] avoidFlood(int[] rains) {
int n = rains.length;
int[] res = new int[n];
int[] next = new int[n];
Arrays.fill(next, n+1);
Map<Integer, Integer> map = new HashMap<>();
for (int i = rains.length - 1; i >= 0; i--) {
int r = rains[i];
if(r > 0) {
if(map.containsKey(r)) {
next[i] = map.get(r);
}
map.put(r, i);
}
}
Map<Integer, Boolean> rmap = new HashMap<>();
PriorityQueue<Node> queue = new PriorityQueue<>(n, Comparator.comparingInt(a -> a.day));
for (int i = 0; i < n; i++) {
if(rains[i] > 0) {
if(rmap.containsKey(i) && rmap.get(i)) return new int[0];
rmap.put(i, true);
queue.offer(new Node(i, next[i]));
res[i] = -1;
} else{
if(queue.isEmpty()) {
res[i] = 1;
}else {
Node node = queue.remove();
res[i] = rains[node.index];
rmap.put(node.index, false);
}
}
if(!queue.isEmpty() && queue.peek().day <= i) {
return new int[0];
}
}
return res;
}
static class Node {
int index;
int day;
public Node(int index, int day) {
this.index = index;
this.day = day;
}
}
public static int[] avoidFlood3(int[] rains) {
int n = rains.length;
Map<Integer, Integer> registries = new HashMap<>(n);
int[] next = new int[n];
for (int i = n - 1; i >= 0; i--) {
next[i] = registries.getOrDefault(rains[i], n);
registries.put(rains[i], i);
}
int[] ans = new int[n];
PriorityQueue<Node> pq = new PriorityQueue<>(n, Comparator.comparingInt(a -> a.day));
for (int i = 0; i < n; i++) {
if (rains[i] == 0) {
if (!pq.isEmpty()) {
ans[i] = pq.remove().index;
}else{
ans[i] = 1;
}
} else {
Node rain = new Node(rains[i], next[i]);
pq.add(rain);
ans[i] = -1;
}
if (!pq.isEmpty() && pq.peek().day <= i) {
return new int[0];
}
}
return ans;
}
}
| 3,424 | 0.467921 | 0.451882 | 106 | 29.584906 | 21.185999 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.688679 | false | false | 0 |
60b9ea8665cb8561c69bae23fc490f4c3248938a | 21,577,915,734,913 | d66a8ceb5cecbb3f3109588151dd583131ebae87 | /src/com/company/Main.java | f648a91880575e27b2cdfface49674e19b36bc06 | [] | no_license | megatron028/task3.2 | https://github.com/megatron028/task3.2 | 8bd07e9a37f0af2ad4928d138fb15fe151037d42 | ae29e4db4d531b365d91c4b6d35ae937a25b9be9 | refs/heads/master | 2021-08-17T05:36:13.458000 | 2017-11-20T20:32:36 | 2017-11-20T20:32:36 | 111,458,054 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
//Создать класс Художник и его подклассы Пейзажист, Баталист, Портретист. Класс художник имеет свойство "имя" и метод рисовать(),
// который выводит на экран фразу "Я не художник, я только учусь".В дочерних классах переопределить метод рисовать()
// таким образом чтобы он выводил на экран имя и направление художника (например, "Художник Пётр - отличный баталист").
public class Main {
public static void main(String[] args) {
Landscapes landscapes = new Landscapes();
landscapes.setName("mett");
landscapes.paint();
}
}
| UTF-8 | Java | 857 | java | Main.java | Java | [] | null | [] | package com.company;
//Создать класс Художник и его подклассы Пейзажист, Баталист, Портретист. Класс художник имеет свойство "имя" и метод рисовать(),
// который выводит на экран фразу "Я не художник, я только учусь".В дочерних классах переопределить метод рисовать()
// таким образом чтобы он выводил на экран имя и направление художника (например, "Художник Пётр - отличный баталист").
public class Main {
public static void main(String[] args) {
Landscapes landscapes = new Landscapes();
landscapes.setName("mett");
landscapes.paint();
}
}
| 857 | 0.73638 | 0.73638 | 12 | 46.416668 | 47.839069 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 0 |
9fef28d21b4de63b8103a7b113c0184bf82be1ea | 25,288,767,441,816 | aeefa2902ddde987dfd45c2c38e68c515ae5c6a3 | /consumerdemo/src/main/java/goal/money/consumerdemo/testAop/Aop.java | 2493b2bf7630dbe513854dd6fc0cf808a9c06b12 | [] | no_license | 392983220/pomdemo | https://github.com/392983220/pomdemo | 9e19174954baa891bb4e6303a784c6ed59160f4c | 73df0218896e6c99894fc36b12f49636e9e0748e | refs/heads/master | 2021-06-21T23:42:36.886000 | 2020-03-22T03:22:04 | 2020-03-22T03:22:04 | 215,520,001 | 3 | 1 | null | false | 2021-06-04T02:14:49 | 2019-10-16T10:22:56 | 2020-12-16T05:10:50 | 2021-06-04T02:14:48 | 39,929 | 0 | 0 | 2 | Java | false | false | package goal.money.consumerdemo.testAop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Aspect
@Component
public class Aop {
@AfterReturning(pointcut = "execution(public * login(..))",returning = "returningValue")
public void testAop(JoinPoint joinPoint,Object returningValue) {
System.out.println("目标对象:" + joinPoint.getTarget() + "方法名:" + joinPoint.getSignature().getName() + "参数列表:" + Arrays.toString(joinPoint.getArgs())
+"返回值:"+returningValue);
}
}
| UTF-8 | Java | 675 | java | Aop.java | Java | [] | null | [] | package goal.money.consumerdemo.testAop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Aspect
@Component
public class Aop {
@AfterReturning(pointcut = "execution(public * login(..))",returning = "returningValue")
public void testAop(JoinPoint joinPoint,Object returningValue) {
System.out.println("目标对象:" + joinPoint.getTarget() + "方法名:" + joinPoint.getSignature().getName() + "参数列表:" + Arrays.toString(joinPoint.getArgs())
+"返回值:"+returningValue);
}
}
| 675 | 0.74028 | 0.74028 | 19 | 32.842106 | 37.993439 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 0 |
ea67c6315b4a3545c9d7fb9796569c7c114c5d8a | 25,288,767,443,214 | 46c952efe33da9870cfba15f8a2973da50e03395 | /src/main/java/com/ats/webapi/model/logistics/VehicalType.java | 8ed6d44b0e9d72ed3fb84b8d261ab5cfc9357783 | [] | no_license | Aaryatech/MonginisAhemadabadApi | https://github.com/Aaryatech/MonginisAhemadabadApi | 1d29f69b24ffe3d1931734c7e10a770e38fc528b | 78535291e962c333b9c62579f769ea86f59f699d | refs/heads/master | 2021-06-24T05:44:05.085000 | 2021-02-10T10:50:02 | 2021-02-10T10:50:02 | 196,930,151 | 0 | 1 | null | false | 2021-01-14T20:43:39 | 2019-07-15T05:30:36 | 2021-01-04T13:49:58 | 2021-01-14T20:43:37 | 1,866 | 0 | 1 | 2 | Java | false | false | package com.ats.webapi.model.logistics;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "m_logis_vehtype")
public class VehicalType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "vehi_type_id")
private int vehiTypeId;
@Column(name = "veh_type_name")
private String vehTypeName;
@Column(name = "make_id")
private int makeId;
@Column(name = "del_status")
private int delStatus;
public int getVehiTypeId() {
return vehiTypeId;
}
public void setVehiTypeId(int vehiTypeId) {
this.vehiTypeId = vehiTypeId;
}
public String getVehTypeName() {
return vehTypeName;
}
public void setVehTypeName(String vehTypeName) {
this.vehTypeName = vehTypeName;
}
public int getMakeId() {
return makeId;
}
public void setMakeId(int makeId) {
this.makeId = makeId;
}
public int getDelStatus() {
return delStatus;
}
public void setDelStatus(int delStatus) {
this.delStatus = delStatus;
}
@Override
public String toString() {
return "VehicalType [vehiTypeId=" + vehiTypeId + ", vehTypeName=" + vehTypeName + ", makeId=" + makeId
+ ", delStatus=" + delStatus + "]";
}
}
| UTF-8 | Java | 1,393 | java | VehicalType.java | Java | [] | null | [] | package com.ats.webapi.model.logistics;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "m_logis_vehtype")
public class VehicalType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "vehi_type_id")
private int vehiTypeId;
@Column(name = "veh_type_name")
private String vehTypeName;
@Column(name = "make_id")
private int makeId;
@Column(name = "del_status")
private int delStatus;
public int getVehiTypeId() {
return vehiTypeId;
}
public void setVehiTypeId(int vehiTypeId) {
this.vehiTypeId = vehiTypeId;
}
public String getVehTypeName() {
return vehTypeName;
}
public void setVehTypeName(String vehTypeName) {
this.vehTypeName = vehTypeName;
}
public int getMakeId() {
return makeId;
}
public void setMakeId(int makeId) {
this.makeId = makeId;
}
public int getDelStatus() {
return delStatus;
}
public void setDelStatus(int delStatus) {
this.delStatus = delStatus;
}
@Override
public String toString() {
return "VehicalType [vehiTypeId=" + vehiTypeId + ", vehTypeName=" + vehTypeName + ", makeId=" + makeId
+ ", delStatus=" + delStatus + "]";
}
}
| 1,393 | 0.681981 | 0.681981 | 68 | 18.485294 | 18.823088 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.161765 | false | false | 0 |
76ae35894a1c988287fbbdf5995a5ed4c389b526 | 30,296,699,341,326 | 2c63aada74f9212036c7ec0c693c5122cf559a21 | /src/main/java/dmv/spring/demo/rest/controller/RoleRestController.java | 7a5a944ad67dc7d3f0309ae0fde7cec013087933 | [] | no_license | Valery-Dm/restjdbc | https://github.com/Valery-Dm/restjdbc | a2f321e9c513cff90671cef3712ece3e43202485 | b296c59056290af4505a2aef462516dcb32c3d79 | refs/heads/master | 2021-01-19T00:23:30.297000 | 2017-05-04T20:21:04 | 2017-05-04T20:21:04 | 87,165,225 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dmv.spring.demo.rest.controller;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import dmv.spring.demo.model.entity.Role;
import dmv.spring.demo.model.entity.User;
import dmv.spring.demo.model.repository.RoleRepository;
import dmv.spring.demo.rest.controller.apidocs.RoleRestApiDocs;
import dmv.spring.demo.rest.representation.RoleDTO;
import dmv.spring.demo.rest.representation.UserLinkResource;
import dmv.spring.demo.rest.representation.assembler.RoleDTOAsm;
import dmv.spring.demo.rest.representation.assembler.UserLinkResourceAsm;
/**
* {@link RoleRepository} Restful endpoints.
* @author dmv
*/
@RestController
@RequestMapping(path="/rest/roles", produces=APPLICATION_JSON_UTF8_VALUE)
public class RoleRestController implements RoleRestApiDocs {
private final RoleRepository roleRepository;
private final RoleDTOAsm roleDTOAsm;
private final UserLinkResourceAsm userLinkAsm;
@Autowired
public RoleRestController(RoleRepository roleRepository,
RoleDTOAsm roleDTOAsm,
UserLinkResourceAsm userLinkAsm) {
this.roleRepository = roleRepository;
this.roleDTOAsm = roleDTOAsm;
this.userLinkAsm = userLinkAsm;
}
@Override
@RequestMapping(path="/{shortName}", method = GET)
public ResponseEntity<RoleDTO> getRole(@PathVariable String shortName) {
Role role = roleRepository.findByShortName(shortName);
return ResponseEntity.ok(roleDTOAsm.toResource(role));
}
@Override
@RequestMapping(path="/{shortName}/users", method = GET)
public ResponseEntity<Resources<UserLinkResource>> getUsers(
@PathVariable String shortName,
HttpServletRequest request) {
Role role = roleRepository.findByShortName(shortName);
Set<User> users = roleRepository.getUsers(role);
if (users.isEmpty())
return ResponseEntity.noContent().build();
List<UserLinkResource> userLinks = users.stream()
.map(user -> userLinkAsm.toResource(user))
.collect(Collectors.toList());
Link link = new Link(request.getRequestURL().toString());
Resources<UserLinkResource> resources = new Resources<>(userLinks, link);
return ResponseEntity.ok(resources);
}
}
| UTF-8 | Java | 2,798 | java | RoleRestController.java | Java | [
{
"context": "link RoleRepository} Restful endpoints.\n * @author dmv\n */\n@RestController\n@RequestMapping(path=\"/rest/r",
"end": 1229,
"score": 0.9992626905441284,
"start": 1226,
"tag": "USERNAME",
"value": "dmv"
}
] | null | [] | package dmv.spring.demo.rest.controller;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import dmv.spring.demo.model.entity.Role;
import dmv.spring.demo.model.entity.User;
import dmv.spring.demo.model.repository.RoleRepository;
import dmv.spring.demo.rest.controller.apidocs.RoleRestApiDocs;
import dmv.spring.demo.rest.representation.RoleDTO;
import dmv.spring.demo.rest.representation.UserLinkResource;
import dmv.spring.demo.rest.representation.assembler.RoleDTOAsm;
import dmv.spring.demo.rest.representation.assembler.UserLinkResourceAsm;
/**
* {@link RoleRepository} Restful endpoints.
* @author dmv
*/
@RestController
@RequestMapping(path="/rest/roles", produces=APPLICATION_JSON_UTF8_VALUE)
public class RoleRestController implements RoleRestApiDocs {
private final RoleRepository roleRepository;
private final RoleDTOAsm roleDTOAsm;
private final UserLinkResourceAsm userLinkAsm;
@Autowired
public RoleRestController(RoleRepository roleRepository,
RoleDTOAsm roleDTOAsm,
UserLinkResourceAsm userLinkAsm) {
this.roleRepository = roleRepository;
this.roleDTOAsm = roleDTOAsm;
this.userLinkAsm = userLinkAsm;
}
@Override
@RequestMapping(path="/{shortName}", method = GET)
public ResponseEntity<RoleDTO> getRole(@PathVariable String shortName) {
Role role = roleRepository.findByShortName(shortName);
return ResponseEntity.ok(roleDTOAsm.toResource(role));
}
@Override
@RequestMapping(path="/{shortName}/users", method = GET)
public ResponseEntity<Resources<UserLinkResource>> getUsers(
@PathVariable String shortName,
HttpServletRequest request) {
Role role = roleRepository.findByShortName(shortName);
Set<User> users = roleRepository.getUsers(role);
if (users.isEmpty())
return ResponseEntity.noContent().build();
List<UserLinkResource> userLinks = users.stream()
.map(user -> userLinkAsm.toResource(user))
.collect(Collectors.toList());
Link link = new Link(request.getRequestURL().toString());
Resources<UserLinkResource> resources = new Resources<>(userLinks, link);
return ResponseEntity.ok(resources);
}
}
| 2,798 | 0.779485 | 0.778771 | 81 | 33.543209 | 25.698177 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.296296 | false | false | 0 |
ff3736ae50231f6c03663f4d757e6170567303a0 | 14,620,068,727,499 | 61e1cd21cb55df3d406ea9450c1fa42de95589ae | /5-java/workspace/07-inhertitance/src/abstract_class/Member.java | 12bc43aad46b058915fc5cdfc3faa415fcd7fcf9 | [] | no_license | jintolPark/git2021-working | https://github.com/jintolPark/git2021-working | 5d66287436de578574376be4b1079ec2728309ae | f47d1e054eb6009dbfc3e499fe285976b65cb00a | refs/heads/master | 2023-08-31T20:47:26.539000 | 2021-10-22T00:33:58 | 2021-10-22T00:33:58 | 390,923,673 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package abstract_class;
// 사용자 중에서도 멤버십이 있는 사용자(쿠팡 멤버십)
public class Member extends User {
private int point;
// 메서드 오버라이딩(override) - 메서드를 재정의한다.
// 메서드 시그니처(signature): 메서드명+매개변수(타입,순서,개수)
// 부모의 메서드와 메서드 시그니처는 동일해야함
// 웬만하면 @Override를 써주는게 좋음, 그래야 재정의한건지 알 수 있음
@Override
public void printUserInfo() {
// 구현 내용은 다름
// 1. 직접 새로 구현
System.out.println(this.getName() + ", " + this.getPhone() + " - 포인트: " + this.point);
// // 2. 부모 메서드를 재활용
// super.printUserInfo();
// System.out.print(" - 포인트: " + this.point);
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
} | UTF-8 | Java | 906 | java | Member.java | Java | [] | null | [] | package abstract_class;
// 사용자 중에서도 멤버십이 있는 사용자(쿠팡 멤버십)
public class Member extends User {
private int point;
// 메서드 오버라이딩(override) - 메서드를 재정의한다.
// 메서드 시그니처(signature): 메서드명+매개변수(타입,순서,개수)
// 부모의 메서드와 메서드 시그니처는 동일해야함
// 웬만하면 @Override를 써주는게 좋음, 그래야 재정의한건지 알 수 있음
@Override
public void printUserInfo() {
// 구현 내용은 다름
// 1. 직접 새로 구현
System.out.println(this.getName() + ", " + this.getPhone() + " - 포인트: " + this.point);
// // 2. 부모 메서드를 재활용
// super.printUserInfo();
// System.out.print(" - 포인트: " + this.point);
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
} | 906 | 0.635093 | 0.631988 | 31 | 19.806452 | 19.585083 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.258065 | false | false | 0 |
68b403a879a01f704029cc0c77146267c20b56eb | 32,538,672,283,652 | cd8ecb33478ff8beb38a88a9afc35c55e368a37e | /app/src/main/java/com/example/myapplication4/WeatherApi.java | d2c815f8e16f3144bd62c948437fed9c7c757eeb | [] | no_license | MuhammedAgibaev/Weather4 | https://github.com/MuhammedAgibaev/Weather4 | 7b0a61f4f1ae63ced87d4ef38aa300e9ea85bc9c | 963c1b93cd2a0330ffd0069d7dcfc59d97d1b31d | refs/heads/master | 2020-06-23T17:26:44.035000 | 2019-07-24T19:18:11 | 2019-07-24T19:18:11 | 198,696,224 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.myapplication4;
import com.example.myapplication4.dataWeather.Weather;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface WeatherApi {
@GET("{PlaceID}")
Call<Weather> GetWeatherData(@Path("PlaceID") String url, @Query("apikey") String apiKey);
}
| UTF-8 | Java | 349 | java | WeatherApi.java | Java | [] | null | [] | package com.example.myapplication4;
import com.example.myapplication4.dataWeather.Weather;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface WeatherApi {
@GET("{PlaceID}")
Call<Weather> GetWeatherData(@Path("PlaceID") String url, @Query("apikey") String apiKey);
}
| 349 | 0.773639 | 0.756447 | 12 | 28.083334 | 24.948141 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 0 |
2e165bb0e9885760ed68b33f7aa5b70281def20c | 36,464,272,384,882 | 467a9bddfb0878d459584dafb4014e08499e250c | /proj2/src/RandomizedQueue.java | 13c55a0455da099fcdb5572088ede136c4938ce1 | [] | no_license | ThoundsN/Algorithm-PrincetionCourse | https://github.com/ThoundsN/Algorithm-PrincetionCourse | ac4da5f2659cc70d79c5bc64d0a6b47c15580ab5 | 3b55e04a200bec6297a96bbc2818a1df1bc1cfed | refs/heads/master | 2020-04-16T19:00:54.758000 | 2019-01-15T12:03:21 | 2019-01-15T12:03:21 | 165,843,541 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Iterator;
import edu.princeton.cs.algs4.StdRandom;
public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] array;
private int size;
private int capacity;
public RandomizedQueue(){
size = 0 ;
capacity = 1;
update();
} // construct an empty randomized queue
public boolean isEmpty(){
return size == 0;
} // is the randomized queue empty?
public int size(){
return size;
} // return the number of items on the randomized queue
public void enqueue(Item item){
if(item == null){
throw new java.lang.IllegalArgumentException();
}
if (size == capacity){
capacity = capacity* 2 ;
update();
}
array[size++] = item;
} // add the item
public Item dequeue(){
if (isEmpty()){
throw new java.util.NoSuchElementException();
}
if (size == capacity/4){
capacity = capacity/2;
update();
}
int random = StdRandom.uniform(size);
Item item = array[random];
array[random] = array[--size];
array[size] = null;
return item;
} // remove and return a random item
public Item sample(){
if (isEmpty()){
throw new java.util.NoSuchElementException();
}
int id = StdRandom.uniform(size);
return array[id];
}
// return a random item (but do not remove it)
private void update(){
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < size; i++) {
temp[i] = array[i];
}
for (int i = size; i < capacity; i++){
temp[i] = null;
}
array = temp;
}
public Iterator<Item> iterator(){
return new RandomizedQueueIterator();
}
// return an independent iterator over items in random order
private class RandomizedQueueIterator implements Iterator<Item>{
private int[] random;
private int current;
public RandomizedQueueIterator(){
random = new int[size];
for (int i = 0; i < size; i++){
random[i] = i;
}
StdRandom.shuffle(random);
current = 0;
}
public Item next(){
if (!hasNext()){
throw new java.util.NoSuchElementException();
}
return array[random[current++]];
}
public boolean hasNext(){
return current!= size;
}
public void remove(){
throw new java.lang.UnsupportedOperationException();
}
}
// public static void main(String[] args) // unit testing (optional)
} | UTF-8 | Java | 2,842 | java | RandomizedQueue.java | Java | [] | null | [] | import java.util.Iterator;
import edu.princeton.cs.algs4.StdRandom;
public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] array;
private int size;
private int capacity;
public RandomizedQueue(){
size = 0 ;
capacity = 1;
update();
} // construct an empty randomized queue
public boolean isEmpty(){
return size == 0;
} // is the randomized queue empty?
public int size(){
return size;
} // return the number of items on the randomized queue
public void enqueue(Item item){
if(item == null){
throw new java.lang.IllegalArgumentException();
}
if (size == capacity){
capacity = capacity* 2 ;
update();
}
array[size++] = item;
} // add the item
public Item dequeue(){
if (isEmpty()){
throw new java.util.NoSuchElementException();
}
if (size == capacity/4){
capacity = capacity/2;
update();
}
int random = StdRandom.uniform(size);
Item item = array[random];
array[random] = array[--size];
array[size] = null;
return item;
} // remove and return a random item
public Item sample(){
if (isEmpty()){
throw new java.util.NoSuchElementException();
}
int id = StdRandom.uniform(size);
return array[id];
}
// return a random item (but do not remove it)
private void update(){
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < size; i++) {
temp[i] = array[i];
}
for (int i = size; i < capacity; i++){
temp[i] = null;
}
array = temp;
}
public Iterator<Item> iterator(){
return new RandomizedQueueIterator();
}
// return an independent iterator over items in random order
private class RandomizedQueueIterator implements Iterator<Item>{
private int[] random;
private int current;
public RandomizedQueueIterator(){
random = new int[size];
for (int i = 0; i < size; i++){
random[i] = i;
}
StdRandom.shuffle(random);
current = 0;
}
public Item next(){
if (!hasNext()){
throw new java.util.NoSuchElementException();
}
return array[random[current++]];
}
public boolean hasNext(){
return current!= size;
}
public void remove(){
throw new java.lang.UnsupportedOperationException();
}
}
// public static void main(String[] args) // unit testing (optional)
} | 2,842 | 0.518297 | 0.514778 | 98 | 28.010204 | 19.032461 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469388 | false | false | 0 |
10f133af5381914d306ce60d394ad055c6539ce5 | 36,464,272,384,330 | ffe8d4a82b07965a9efd3269fd8f001395087e56 | /proj1/enigma/Main.java | 3db98f9785ab82d4dfb327c57eca8dacaf70e384 | [] | no_license | celinapan/cs61b-data-structures | https://github.com/celinapan/cs61b-data-structures | b264a8ac664332feae74cdb63891b6081e12c046 | d52a4ec5998af67a6b3ace8867d19021f0dcfd5b | refs/heads/master | 2023-03-19T22:33:11.357000 | 2021-03-23T19:17:24 | 2021-03-23T19:17:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package enigma;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
import static enigma.EnigmaException.*;
/** Enigma simulator.
* @author Trang Van
*/
public final class Main {
/** Process a sequence of encryptions and decryptions, as
* specified by ARGS, where 1 <= ARGS.length <= 3.
* ARGS[0] is the name of a configuration file.
* ARGS[1] is optional; when present, it names an input file
* containing messages. Otherwise, input comes from the standard
* input. ARGS[2] is optional; when present, it names an output
* file for processed messages. Otherwise, output goes to the
* standard output. Exits normally if there are no errors in the input;
* otherwise with code 1. */
public static void main(String... args) {
try {
new Main(args).process();
return;
} catch (EnigmaException excp) {
System.err.printf("Error: %s%n", excp.getMessage());
}
System.exit(1);
}
/** Check ARGS and open the necessary files (see comment on main). */
Main(String[] args) {
if (args.length < 1 || args.length > 3) {
throw error("Only 1, 2, or 3 command-line arguments allowed");
}
_config = getInput(args[0]);
if (args.length > 1) {
_input = getInput(args[1]);
} else {
_input = new Scanner(System.in);
}
if (args.length > 2) {
_output = getOutput(args[2]);
} else {
_output = System.out;
}
}
/** Return a Scanner reading from the file named NAME. */
private Scanner getInput(String name) {
try {
return new Scanner(new File(name));
} catch (IOException excp) {
throw error("could not open %s", name);
}
}
/** Return a PrintStream writing to the file named NAME. */
private PrintStream getOutput(String name) {
try {
return new PrintStream(new File(name));
} catch (IOException excp) {
throw error("could not open %s", name);
}
}
/** Configure an Enigma machine from the contents of configuration
* file _config and apply it to the messages in _input, sending the
* results to _output.
* Source: StackOverflow, splicing array with range*/
private void process() {
Machine m = readConfig();
String s = "";
if (_input.hasNextLine()) {
s = _input.nextLine();
if (s.length() > 0 && s.charAt(0) == '*') {
setUp(m, s);
} else {
throw error("Need input configuration");
}
}
while (_input.hasNextLine()) {
s = _input.nextLine();
if (s.length() == 0) {
printMessageLine("");
} else if (s.charAt(0) == '*') {
setUp(m, s);
} else {
printMessageLine(m.convert(s));
}
}
}
/** Return an Enigma machine configured from the contents of configuration
* file _config.
* Source: GeeksForGeeks (Convert Char to Int)*/
private Machine readConfig() {
try {
_alphabet = new Alphabet(_config.nextLine().trim());
Integer numRotors = _config.nextInt();
Integer numPawls = _config.nextInt();
_config.nextLine();
ArrayList<Rotor> allRotors = new ArrayList<>();
while (_config.hasNextLine() && _config.hasNext()) {
allRotors.add(readRotor());
}
return new Machine(_alphabet, numRotors, numPawls, allRotors);
} catch (NoSuchElementException excp) {
throw error("configuration file truncated");
}
}
/** Return a rotor, reading its description from _config. */
private Rotor readRotor() {
try {
String name = _config.next();
String type = _config.next();
String cycles = "";
while (_config.hasNext(Pattern.compile("\\(.+"))) {
cycles += _config.nextLine();
}
Permutation p = new Permutation(cycles, _alphabet);
if (type.length() == 1) {
if (type.charAt(0) == 'N') {
return new FixedRotor(name, p);
} else if (type.charAt(0) == 'R') {
return new Reflector(name, p);
}
}
return new MovingRotor(name, p, type.substring(1));
} catch (NoSuchElementException excp) {
throw error("bad rotor description");
}
}
/** Set M according to the specification given on SETTINGS,
* which must have the format specified in the assignment. */
private void setUp(Machine M, String settings) {
String[] s = settings.substring(2).split("\\s+");
String[] rotorNames = Arrays.copyOfRange(s, 0, M.numRotors());
String[] mSetting = Arrays.copyOfRange(s, M.numRotors(), s.length);
String[] plugboard;
String ringSetting = "";
String cycles = "";
if (rotorNames.length != M.numRotors()) {
throw EnigmaException.error("Wrong number of rotors defined");
}
if (mSetting.length != 0) {
String setting = mSetting[0].trim();
if (mSetting.length > 1 && mSetting[1].trim().charAt(0) != '(') {
ringSetting = mSetting[1];
plugboard = Arrays.copyOfRange(mSetting, 2, mSetting.length);
} else {
plugboard = Arrays.copyOfRange(mSetting, 1, mSetting.length);
}
for (String plug: plugboard) {
cycles += plug.trim();
}
M.setPlugboard(new Permutation(cycles, _alphabet));
M.insertRotors(rotorNames);
M.setRotors(setting);
if (ringSetting.length() > 0) {
M.setRing(ringSetting);
}
} else {
throw EnigmaException.error("No initial settings");
}
}
/** Print MSG in groups of five (except that the last group may
* have fewer letters). */
private void printMessageLine(String msg) {
while (msg.length() > 5) {
_output.print(msg.substring(0, 5) + " ");
msg = msg.substring(5);
}
_output.println(msg.trim());
}
/** Alphabet used in this machine. */
private Alphabet _alphabet;
/** Source of input messages. */
private Scanner _input;
/** Source of machine configuration. */
private Scanner _config;
/** File for encoded/decoded messages. */
private PrintStream _output;
}
| UTF-8 | Java | 6,911 | java | Main.java | Java | [
{
"context": "gmaException.*;\n\n/** Enigma simulator.\n * @author Trang Van\n */\npublic final class Main {\n\n /** Process a ",
"end": 332,
"score": 0.9995947480201721,
"start": 323,
"tag": "NAME",
"value": "Trang Van"
}
] | null | [] | package enigma;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
import static enigma.EnigmaException.*;
/** Enigma simulator.
* @author <NAME>
*/
public final class Main {
/** Process a sequence of encryptions and decryptions, as
* specified by ARGS, where 1 <= ARGS.length <= 3.
* ARGS[0] is the name of a configuration file.
* ARGS[1] is optional; when present, it names an input file
* containing messages. Otherwise, input comes from the standard
* input. ARGS[2] is optional; when present, it names an output
* file for processed messages. Otherwise, output goes to the
* standard output. Exits normally if there are no errors in the input;
* otherwise with code 1. */
public static void main(String... args) {
try {
new Main(args).process();
return;
} catch (EnigmaException excp) {
System.err.printf("Error: %s%n", excp.getMessage());
}
System.exit(1);
}
/** Check ARGS and open the necessary files (see comment on main). */
Main(String[] args) {
if (args.length < 1 || args.length > 3) {
throw error("Only 1, 2, or 3 command-line arguments allowed");
}
_config = getInput(args[0]);
if (args.length > 1) {
_input = getInput(args[1]);
} else {
_input = new Scanner(System.in);
}
if (args.length > 2) {
_output = getOutput(args[2]);
} else {
_output = System.out;
}
}
/** Return a Scanner reading from the file named NAME. */
private Scanner getInput(String name) {
try {
return new Scanner(new File(name));
} catch (IOException excp) {
throw error("could not open %s", name);
}
}
/** Return a PrintStream writing to the file named NAME. */
private PrintStream getOutput(String name) {
try {
return new PrintStream(new File(name));
} catch (IOException excp) {
throw error("could not open %s", name);
}
}
/** Configure an Enigma machine from the contents of configuration
* file _config and apply it to the messages in _input, sending the
* results to _output.
* Source: StackOverflow, splicing array with range*/
private void process() {
Machine m = readConfig();
String s = "";
if (_input.hasNextLine()) {
s = _input.nextLine();
if (s.length() > 0 && s.charAt(0) == '*') {
setUp(m, s);
} else {
throw error("Need input configuration");
}
}
while (_input.hasNextLine()) {
s = _input.nextLine();
if (s.length() == 0) {
printMessageLine("");
} else if (s.charAt(0) == '*') {
setUp(m, s);
} else {
printMessageLine(m.convert(s));
}
}
}
/** Return an Enigma machine configured from the contents of configuration
* file _config.
* Source: GeeksForGeeks (Convert Char to Int)*/
private Machine readConfig() {
try {
_alphabet = new Alphabet(_config.nextLine().trim());
Integer numRotors = _config.nextInt();
Integer numPawls = _config.nextInt();
_config.nextLine();
ArrayList<Rotor> allRotors = new ArrayList<>();
while (_config.hasNextLine() && _config.hasNext()) {
allRotors.add(readRotor());
}
return new Machine(_alphabet, numRotors, numPawls, allRotors);
} catch (NoSuchElementException excp) {
throw error("configuration file truncated");
}
}
/** Return a rotor, reading its description from _config. */
private Rotor readRotor() {
try {
String name = _config.next();
String type = _config.next();
String cycles = "";
while (_config.hasNext(Pattern.compile("\\(.+"))) {
cycles += _config.nextLine();
}
Permutation p = new Permutation(cycles, _alphabet);
if (type.length() == 1) {
if (type.charAt(0) == 'N') {
return new FixedRotor(name, p);
} else if (type.charAt(0) == 'R') {
return new Reflector(name, p);
}
}
return new MovingRotor(name, p, type.substring(1));
} catch (NoSuchElementException excp) {
throw error("bad rotor description");
}
}
/** Set M according to the specification given on SETTINGS,
* which must have the format specified in the assignment. */
private void setUp(Machine M, String settings) {
String[] s = settings.substring(2).split("\\s+");
String[] rotorNames = Arrays.copyOfRange(s, 0, M.numRotors());
String[] mSetting = Arrays.copyOfRange(s, M.numRotors(), s.length);
String[] plugboard;
String ringSetting = "";
String cycles = "";
if (rotorNames.length != M.numRotors()) {
throw EnigmaException.error("Wrong number of rotors defined");
}
if (mSetting.length != 0) {
String setting = mSetting[0].trim();
if (mSetting.length > 1 && mSetting[1].trim().charAt(0) != '(') {
ringSetting = mSetting[1];
plugboard = Arrays.copyOfRange(mSetting, 2, mSetting.length);
} else {
plugboard = Arrays.copyOfRange(mSetting, 1, mSetting.length);
}
for (String plug: plugboard) {
cycles += plug.trim();
}
M.setPlugboard(new Permutation(cycles, _alphabet));
M.insertRotors(rotorNames);
M.setRotors(setting);
if (ringSetting.length() > 0) {
M.setRing(ringSetting);
}
} else {
throw EnigmaException.error("No initial settings");
}
}
/** Print MSG in groups of five (except that the last group may
* have fewer letters). */
private void printMessageLine(String msg) {
while (msg.length() > 5) {
_output.print(msg.substring(0, 5) + " ");
msg = msg.substring(5);
}
_output.println(msg.trim());
}
/** Alphabet used in this machine. */
private Alphabet _alphabet;
/** Source of input messages. */
private Scanner _input;
/** Source of machine configuration. */
private Scanner _config;
/** File for encoded/decoded messages. */
private PrintStream _output;
}
| 6,908 | 0.54435 | 0.538562 | 204 | 32.877453 | 22.416067 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.563725 | false | false | 0 |
b0d494f6aca1487458e44a6adaedca6bee75f0e0 | 39,548,058,869,320 | 7b3a2fe51f110d2310c44e1182c615003588e90d | /string/ModifySequence.java | 5a082817597d576f72ea1ce90f908c0deeadb840 | [] | no_license | allwinsr/DataStructure | https://github.com/allwinsr/DataStructure | c72d0f8e6f35f536da4c812b69d55fead5ac50c6 | aec7d0decd9bfc649988e4d28d091cb99aa9d457 | refs/heads/master | 2021-01-19T04:12:57.739000 | 2016-04-05T07:57:01 | 2016-04-05T07:57:01 | 16,336,734 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package string;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
* @author allwin.raj
*
*/
public class ModifySequence {
/**
*
*/
public ModifySequence() {
// TODO Auto-generated constructor stub
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
line = br.readLine();
int[] nos = new int[100];
for (int i = 0; i < N; i++) {
nos[i] = Integer.parseInt(line, br.read());
System.out.println(line);
}
}
}
| UTF-8 | Java | 778 | java | ModifySequence.java | Java | [
{
"context": "mReader;\nimport java.util.Scanner;\n\n/**\n * @author allwin.raj\n *\n */\npublic class ModifySequence {\n\n\t/**\n\t * \n\t",
"end": 174,
"score": 0.9557287096977234,
"start": 164,
"tag": "NAME",
"value": "allwin.raj"
}
] | null | [] | /**
*
*/
package string;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
* @author allwin.raj
*
*/
public class ModifySequence {
/**
*
*/
public ModifySequence() {
// TODO Auto-generated constructor stub
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
line = br.readLine();
int[] nos = new int[100];
for (int i = 0; i < N; i++) {
nos[i] = Integer.parseInt(line, br.read());
System.out.println(line);
}
}
}
| 778 | 0.604113 | 0.598972 | 41 | 17.975609 | 18.738884 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.804878 | false | false | 0 |
9f718cdb791e739cd599160339eaae5d980d90f8 | 30,193,620,136,137 | fdf2feb79d1ff1d1a53bfc9d8d5e4e89dc0c41e4 | /turkalman-hackbot/src/main/java/com/arcelikglobal/hackbot/turkalman/utilities/DBConnection.java | b032cdf6ca1bedd1e3e881f6681134b4fda371fa | [] | no_license | batikanor/arcelik_hackbot_turk-alman | https://github.com/batikanor/arcelik_hackbot_turk-alman | 5cfa2d4bddb0046b19218aaaa22143e1e6f04e6d | 2c2e5d25729fb022b471c4de63c71d194baa22b4 | refs/heads/master | 2022-11-19T21:35:35.447000 | 2020-07-24T10:19:06 | 2020-07-24T10:19:06 | 281,613,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.arcelikglobal.hackbot.turkalman.utilities;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//import com.arcelikglobal.hackbot.turkalman.bot.hackbot;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
public class DBConnection {
private static final String Driver = "org.hsqldb.jdbcDriver";
private static final String user = "DBArcelikSorular";
private static final String pwd = "temp";
private static final String dbPath = "~/ArcelikHackbotDB";
//private static final String dbPath = "~/dbImplicaspection";
private static final String url = "jdbc:hsqldb:file:" + dbPath;
public static Connection connect() {
try {
System.out.println("Veritabanı'na bağlanmaya çalışılınıyor");
Class.forName(Driver);
Connection con = DriverManager.getConnection(url, user, pwd);
return con;
}catch(ClassNotFoundException e) {
System.out.println("E002: Veritabanı klası bulunamadı");
e.printStackTrace();
return null;
}catch(SQLException e) {
System.out.println("E002: Veritabanı klası bulundu, ama bağlantı kurulamadı");
return null;
}
}
public static boolean addQuestion(int messageID, String question) {
Connection con = connect();
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO QUESTIONS VALUES(?, ?)");
ps.setInt(1, messageID);
ps.setString(2, question);
ps.executeUpdate();
con.commit();
con.close();
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static boolean addAnswer(int messageID, String answer) {
Connection con = connect();
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO ANSWERS(QUESTIONID, ANSWER) VALUES(?, ?)");
ps.setInt(1, messageID);
ps.setString(2, answer);
ps.executeUpdate();
con.commit();
con.close();
return true;
} catch (SQLException e) {
System.out.println("Cevap veritabanina eklenemedi"); ///< Normalde loglanir, henuz logging ile ugrasmadik
e.printStackTrace();
return false;
}
}
public static boolean addTag(int messageID, String tag) {
Connection con = connect();
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO TAGS(QUESTIONID, TAG) VALUES(?, ?)");
ps.setInt(1, messageID);
ps.setString(2, tag);
ps.executeUpdate();
con.commit();
con.close();
return true;
} catch (SQLException e) {
System.out.println("Tag veritabanina eklenemedi"); ///< Normalde loglanir, henuz logging ile ugrasmadik
e.printStackTrace();
return false;
}
}
public static HashMap<String, Integer> getTags() {
Connection con = connect();
ResultSet rs;
try {
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM TAGS");
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (rs.next()) {
map.put(rs.getString("TAG"), rs.getInt("QUESTIONID"));
}
;
con.close();
return map;
} catch (SQLException e) {
System.out.println("Tag veritabanina eklenemedi"); ///< Normalde loglanir, henuz logging ile ugrasmadik
e.printStackTrace();
}
return null;
}
public static ArrayList<String> getAnswerFromQuestionId(int qid){
Connection con = connect();
ResultSet rs;
PreparedStatement ps;
try {
ps = con.prepareStatement("SELECT ANSWER FROM ANSWERS WHERE QUESTIONID = ?");
ps.setInt(1, qid);
rs = ps.executeQuery();
ArrayList<String> ans = new ArrayList<String>();
while (rs.next()) {
ans.add(rs.getString("ANSWER"));
}
con.close();
return ans;
} catch (SQLException e) {
System.out.println("Tag veritabanina eklenemedi"); ///< Normalde loglanir, henuz logging ile ugrasmadik
e.printStackTrace();
}
return null;
}
}
| UTF-8 | Java | 4,130 | java | DBConnection.java | Java | [
{
"context": "cDriver\";\n private static final String user = \"DBArcelikSorular\";\n private static final String pwd = \"temp\";\n ",
"end": 494,
"score": 0.998937726020813,
"start": 478,
"tag": "USERNAME",
"value": "DBArcelikSorular"
},
{
"context": "kSorular\";\n private ... | null | [] | package com.arcelikglobal.hackbot.turkalman.utilities;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//import com.arcelikglobal.hackbot.turkalman.bot.hackbot;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
public class DBConnection {
private static final String Driver = "org.hsqldb.jdbcDriver";
private static final String user = "DBArcelikSorular";
private static final String pwd = "<PASSWORD>";
private static final String dbPath = "~/ArcelikHackbotDB";
//private static final String dbPath = "~/dbImplicaspection";
private static final String url = "jdbc:hsqldb:file:" + dbPath;
public static Connection connect() {
try {
System.out.println("Veritabanı'na bağlanmaya çalışılınıyor");
Class.forName(Driver);
Connection con = DriverManager.getConnection(url, user, pwd);
return con;
}catch(ClassNotFoundException e) {
System.out.println("E002: Veritabanı klası bulunamadı");
e.printStackTrace();
return null;
}catch(SQLException e) {
System.out.println("E002: Veritabanı klası bulundu, ama bağlantı kurulamadı");
return null;
}
}
public static boolean addQuestion(int messageID, String question) {
Connection con = connect();
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO QUESTIONS VALUES(?, ?)");
ps.setInt(1, messageID);
ps.setString(2, question);
ps.executeUpdate();
con.commit();
con.close();
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static boolean addAnswer(int messageID, String answer) {
Connection con = connect();
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO ANSWERS(QUESTIONID, ANSWER) VALUES(?, ?)");
ps.setInt(1, messageID);
ps.setString(2, answer);
ps.executeUpdate();
con.commit();
con.close();
return true;
} catch (SQLException e) {
System.out.println("Cevap veritabanina eklenemedi"); ///< Normalde loglanir, henuz logging ile ugrasmadik
e.printStackTrace();
return false;
}
}
public static boolean addTag(int messageID, String tag) {
Connection con = connect();
PreparedStatement ps;
try {
ps = con.prepareStatement("INSERT INTO TAGS(QUESTIONID, TAG) VALUES(?, ?)");
ps.setInt(1, messageID);
ps.setString(2, tag);
ps.executeUpdate();
con.commit();
con.close();
return true;
} catch (SQLException e) {
System.out.println("Tag veritabanina eklenemedi"); ///< Normalde loglanir, henuz logging ile ugrasmadik
e.printStackTrace();
return false;
}
}
public static HashMap<String, Integer> getTags() {
Connection con = connect();
ResultSet rs;
try {
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM TAGS");
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (rs.next()) {
map.put(rs.getString("TAG"), rs.getInt("QUESTIONID"));
}
;
con.close();
return map;
} catch (SQLException e) {
System.out.println("Tag veritabanina eklenemedi"); ///< Normalde loglanir, henuz logging ile ugrasmadik
e.printStackTrace();
}
return null;
}
public static ArrayList<String> getAnswerFromQuestionId(int qid){
Connection con = connect();
ResultSet rs;
PreparedStatement ps;
try {
ps = con.prepareStatement("SELECT ANSWER FROM ANSWERS WHERE QUESTIONID = ?");
ps.setInt(1, qid);
rs = ps.executeQuery();
ArrayList<String> ans = new ArrayList<String>();
while (rs.next()) {
ans.add(rs.getString("ANSWER"));
}
con.close();
return ans;
} catch (SQLException e) {
System.out.println("Tag veritabanina eklenemedi"); ///< Normalde loglanir, henuz logging ile ugrasmadik
e.printStackTrace();
}
return null;
}
}
| 4,136 | 0.65824 | 0.65508 | 192 | 20.427084 | 24.062092 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.473958 | false | false | 0 |
42e715ee5417cb7efff6610722d049847cff0c55 | 14,817,637,214,611 | 97865d45c521b23d700a1c7888ea1051b745891f | /pig-modules/caih-iscs-service/src/main/java/com/caih/cloud/iscs/charge/scoket/DeviceHandler.java | 62ee82c42537b78fc03b10aaf1c3fbc317fac317 | [
"MIT"
] | permissive | Eagle919/jenkinsTest | https://github.com/Eagle919/jenkinsTest | e54a1272b09266c946741889920b03f9c49c2fd1 | c42a9630cfe21d1eef66c646be5a06a8348ba384 | refs/heads/master | 2022-08-08T08:08:13.331000 | 2020-03-05T07:35:53 | 2020-03-05T07:35:53 | 245,089,242 | 0 | 0 | MIT | false | 2022-06-29T15:59:17 | 2020-03-05T06:46:15 | 2020-03-05T07:36:17 | 2022-06-29T15:59:14 | 4,945 | 0 | 0 | 2 | JavaScript | false | false | package com.caih.cloud.iscs.charge.scoket;
import com.caih.cloud.iscs.charge.scoket.Util.BCDUtil;
import com.caih.cloud.iscs.charge.scoket.Util.HexUtil;
import com.caih.cloud.iscs.charge.scoket.Util.MianCore;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* 设备操作助手
*/
public class DeviceHandler {
private static final String startChar = "FAF5"; // 起始字符
private static final String versionChar = "0100";// 版本号
private static final String cRCChar = "9CA9";// CRC编码
private static final String endChar = "16";// 结束字符
private static final Logger logger = LoggerFactory.getLogger(DeviceHandler.class);
private static MianCore mianCore = new MianCore();
/**
* 根据设备号 返回设备端口状态
*
* @param deviceCode
* @return
*/
public static List<DeviceStatus> getDeviceStatusByCode(String deviceCode) {
List<DeviceStatus> deviceStatusList = MessageHandler.deviceMap.get(deviceCode);
logger.info("[设备{}状态->{}]",deviceCode,deviceStatusList);
return deviceStatusList;
}
/**
* 通过设备号,给设备发送充电指令信息
*
* @param deviceCode 设备编号 如10002998
* @param time 充电时长 单位:分钟
* @param port 充电端口 0~9
*/
public static void sendStartChargeMessage(String deviceCode, int time, int port) throws Exception {
String length = "16";// 帧长度
String chargeHeader = "57";
String chargeTime = Integer.toHexString(time);
String deviceCodeHexString = HexUtil.string2HexStringNotSpace(deviceCode);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(startChar);
stringBuilder.append(length);
stringBuilder.append(versionChar);
stringBuilder.append("04");// 帧序列号
stringBuilder.append(deviceCodeHexString);
stringBuilder.append(chargeHeader);
stringBuilder.append("02");// 启动模式以及启动源
stringBuilder.append(chargeTime + "00");// 充电时长数据包
stringBuilder.append("0" + port);// 端口
stringBuilder.append(cRCChar);
stringBuilder.append(endChar);
String output = HexUtil.formateString(stringBuilder.toString());
IoSession session = MessageHandler.sessionMap.get(deviceCode);
if (null == session) {
throw new Exception("设备暂未连接");
}
mianCore.sendMsg(output, session);
logger.info("[向设备:{}下发充电指令->:{}]", deviceCode, output);
}
/**
* 根据充电桩编号、端口号停止充电
*
* @param deviceCode 充电桩编号
* @param port 端口号
*/
public static void sendStopChargeMessage(String deviceCode, int port) throws Exception {
String length = "13";// 帧长度
String stopChargeHeader = "5B";
String deviceCodeHexString = HexUtil.string2HexStringNotSpace(deviceCode);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(startChar);
stringBuilder.append(length);
stringBuilder.append(versionChar);
stringBuilder.append("00");// 帧序列号
stringBuilder.append(deviceCodeHexString);
stringBuilder.append(stopChargeHeader);
stringBuilder.append("0" + port);// 端口
stringBuilder.append(cRCChar);
stringBuilder.append(endChar);
String output = HexUtil.formateString(stringBuilder.toString());
IoSession session = MessageHandler.sessionMap.get(deviceCode);
if (null == session) {
throw new Exception("设备暂未连接");
}
mianCore.sendMsg(output, session);
logger.info("[向设备:{}下发停止充电指令->:{}]", deviceCode, output);
}
/**
* 给签到的设备同步时间 年月日时分秒
*
* @param deviceCode
*/
public static void timeSynchronization(String deviceCode) throws Exception {
Calendar now = Calendar.getInstance();
String year = String.valueOf(now.get(Calendar.YEAR)).substring(2, 4);
String month = String.valueOf(now.get(Calendar.MONTH) + 1);
String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
String hour = String.valueOf(now.get(Calendar.HOUR_OF_DAY));
String minute = String.valueOf(now.get(Calendar.MINUTE));
String srcond = String.valueOf(now.get(Calendar.SECOND));
if (minute.length() == 1) {
minute += "0" + minute;
}
if (srcond.length() == 1) {
srcond += "0" + srcond;
}
String dateStr = year + month + day + hour + minute + srcond;
String length = "18";// 帧长度
String stopChargeHeader = "50";
String deviceCodeHexString = HexUtil.string2HexStringNotSpace(deviceCode);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(startChar);
stringBuilder.append(length);
stringBuilder.append(versionChar);
stringBuilder.append("00");// 帧序列号
stringBuilder.append(deviceCodeHexString);
stringBuilder.append(stopChargeHeader);
stringBuilder.append(dateStr);// 同步时间
stringBuilder.append(cRCChar);
stringBuilder.append(endChar);
String output = HexUtil.formateString(stringBuilder.toString());
IoSession session = MessageHandler.sessionMap.get(deviceCode);
if (null == session) {
throw new Exception("设备暂未连接");
}
mianCore.sendMsg(output, session);
logger.info("[向设备:{}下发同步时间指令->:{}]", deviceCode, output);
}
public static void main(String[] args) throws Exception {
// sendStartChargeMessage("10002998", 60, 0);
// sendStopChargeMessage("10002998", 0);
// System.out.println("2019".substring(2, 4));
timeSynchronization("10002998");
}
}
| UTF-8 | Java | 6,261 | java | DeviceHandler.java | Java | [] | null | [] | package com.caih.cloud.iscs.charge.scoket;
import com.caih.cloud.iscs.charge.scoket.Util.BCDUtil;
import com.caih.cloud.iscs.charge.scoket.Util.HexUtil;
import com.caih.cloud.iscs.charge.scoket.Util.MianCore;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* 设备操作助手
*/
public class DeviceHandler {
private static final String startChar = "FAF5"; // 起始字符
private static final String versionChar = "0100";// 版本号
private static final String cRCChar = "9CA9";// CRC编码
private static final String endChar = "16";// 结束字符
private static final Logger logger = LoggerFactory.getLogger(DeviceHandler.class);
private static MianCore mianCore = new MianCore();
/**
* 根据设备号 返回设备端口状态
*
* @param deviceCode
* @return
*/
public static List<DeviceStatus> getDeviceStatusByCode(String deviceCode) {
List<DeviceStatus> deviceStatusList = MessageHandler.deviceMap.get(deviceCode);
logger.info("[设备{}状态->{}]",deviceCode,deviceStatusList);
return deviceStatusList;
}
/**
* 通过设备号,给设备发送充电指令信息
*
* @param deviceCode 设备编号 如10002998
* @param time 充电时长 单位:分钟
* @param port 充电端口 0~9
*/
public static void sendStartChargeMessage(String deviceCode, int time, int port) throws Exception {
String length = "16";// 帧长度
String chargeHeader = "57";
String chargeTime = Integer.toHexString(time);
String deviceCodeHexString = HexUtil.string2HexStringNotSpace(deviceCode);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(startChar);
stringBuilder.append(length);
stringBuilder.append(versionChar);
stringBuilder.append("04");// 帧序列号
stringBuilder.append(deviceCodeHexString);
stringBuilder.append(chargeHeader);
stringBuilder.append("02");// 启动模式以及启动源
stringBuilder.append(chargeTime + "00");// 充电时长数据包
stringBuilder.append("0" + port);// 端口
stringBuilder.append(cRCChar);
stringBuilder.append(endChar);
String output = HexUtil.formateString(stringBuilder.toString());
IoSession session = MessageHandler.sessionMap.get(deviceCode);
if (null == session) {
throw new Exception("设备暂未连接");
}
mianCore.sendMsg(output, session);
logger.info("[向设备:{}下发充电指令->:{}]", deviceCode, output);
}
/**
* 根据充电桩编号、端口号停止充电
*
* @param deviceCode 充电桩编号
* @param port 端口号
*/
public static void sendStopChargeMessage(String deviceCode, int port) throws Exception {
String length = "13";// 帧长度
String stopChargeHeader = "5B";
String deviceCodeHexString = HexUtil.string2HexStringNotSpace(deviceCode);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(startChar);
stringBuilder.append(length);
stringBuilder.append(versionChar);
stringBuilder.append("00");// 帧序列号
stringBuilder.append(deviceCodeHexString);
stringBuilder.append(stopChargeHeader);
stringBuilder.append("0" + port);// 端口
stringBuilder.append(cRCChar);
stringBuilder.append(endChar);
String output = HexUtil.formateString(stringBuilder.toString());
IoSession session = MessageHandler.sessionMap.get(deviceCode);
if (null == session) {
throw new Exception("设备暂未连接");
}
mianCore.sendMsg(output, session);
logger.info("[向设备:{}下发停止充电指令->:{}]", deviceCode, output);
}
/**
* 给签到的设备同步时间 年月日时分秒
*
* @param deviceCode
*/
public static void timeSynchronization(String deviceCode) throws Exception {
Calendar now = Calendar.getInstance();
String year = String.valueOf(now.get(Calendar.YEAR)).substring(2, 4);
String month = String.valueOf(now.get(Calendar.MONTH) + 1);
String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
String hour = String.valueOf(now.get(Calendar.HOUR_OF_DAY));
String minute = String.valueOf(now.get(Calendar.MINUTE));
String srcond = String.valueOf(now.get(Calendar.SECOND));
if (minute.length() == 1) {
minute += "0" + minute;
}
if (srcond.length() == 1) {
srcond += "0" + srcond;
}
String dateStr = year + month + day + hour + minute + srcond;
String length = "18";// 帧长度
String stopChargeHeader = "50";
String deviceCodeHexString = HexUtil.string2HexStringNotSpace(deviceCode);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(startChar);
stringBuilder.append(length);
stringBuilder.append(versionChar);
stringBuilder.append("00");// 帧序列号
stringBuilder.append(deviceCodeHexString);
stringBuilder.append(stopChargeHeader);
stringBuilder.append(dateStr);// 同步时间
stringBuilder.append(cRCChar);
stringBuilder.append(endChar);
String output = HexUtil.formateString(stringBuilder.toString());
IoSession session = MessageHandler.sessionMap.get(deviceCode);
if (null == session) {
throw new Exception("设备暂未连接");
}
mianCore.sendMsg(output, session);
logger.info("[向设备:{}下发同步时间指令->:{}]", deviceCode, output);
}
public static void main(String[] args) throws Exception {
// sendStartChargeMessage("10002998", 60, 0);
// sendStopChargeMessage("10002998", 0);
// System.out.println("2019".substring(2, 4));
timeSynchronization("10002998");
}
}
| 6,261 | 0.650316 | 0.635276 | 166 | 34.246986 | 25.381769 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.668675 | false | false | 0 |
8443b39c65c54a0c1240480119c50bd328a31530 | 9,749,575,806,492 | d4603bd55d0a0cd614f80e5ff7da60ad17cdb86a | /JavaBackup/AllProjects/src/games/generic/view/dataProviders/ObjLocatedProviderObjFiltering.java | 8404f9d4a1ea3a79631616f5638465f48de32926 | [] | no_license | lonevetad/PrivateBackups | https://github.com/lonevetad/PrivateBackups | 56d97736020048075ff6f3180d3111ebabe94603 | eabb3c3040c0f913218a3d473c99c2737b54912b | refs/heads/master | 2020-08-14T00:59:46.131000 | 2020-07-19T11:14:45 | 2020-07-19T11:14:45 | 215,067,721 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package games.generic.view.dataProviders;
import java.awt.Point;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import games.generic.controlModel.GModality;
import games.generic.controlModel.GObjectsInSpaceManager;
import games.generic.view.GameView;
import geometry.AbstractShape2D;
import geometry.ObjectLocated;
import geometry.ObjectShaped;
import geometry.ProviderShapesIntersectionDetector;
/**
* Iterates over ALL object held into {@link GObjectsInSpaceManager} (obtained
* through {@link GModality#getGObjectInSpaceManager()}) and, if they are inside
* the given area, provide them.<br>
* No repetitions should be provided (it depends on
* {@link GObjectsInSpaceManager#forEach(Consumer)} implementation).
*/
public class ObjLocatedProviderObjFiltering extends ObjLocatedProvider {
public ObjLocatedProviderObjFiltering(GameView gameView) { super(gameView); }
@Override
public void forEachObjInArea(GObjectsInSpaceManager goism, AbstractShape2D shape,
BiConsumer<Point, ObjectLocated> action) {
ProviderShapesIntersectionDetector psid;
// InSpaceObjectsManager<Double> isom;
psid = goism.getProviderShapesIntersectionDetector();
if (psid == null)
return;
goism.forEach(owid -> {
ObjectLocated ol;
if (owid instanceof ObjectLocated) {
ol = (ObjectLocated) owid;
if (ol instanceof ObjectShaped) {
if (psid.areIntersecting(shape, ((ObjectShaped) ol).getShape()))
action.accept(ol.getLocation(), ol);
} else if (shape.contains(ol.getLocation())) { action.accept(ol.getLocation(), ol); }
}
});
}
}
| UTF-8 | Java | 1,592 | java | ObjLocatedProviderObjFiltering.java | Java | [] | null | [] | package games.generic.view.dataProviders;
import java.awt.Point;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import games.generic.controlModel.GModality;
import games.generic.controlModel.GObjectsInSpaceManager;
import games.generic.view.GameView;
import geometry.AbstractShape2D;
import geometry.ObjectLocated;
import geometry.ObjectShaped;
import geometry.ProviderShapesIntersectionDetector;
/**
* Iterates over ALL object held into {@link GObjectsInSpaceManager} (obtained
* through {@link GModality#getGObjectInSpaceManager()}) and, if they are inside
* the given area, provide them.<br>
* No repetitions should be provided (it depends on
* {@link GObjectsInSpaceManager#forEach(Consumer)} implementation).
*/
public class ObjLocatedProviderObjFiltering extends ObjLocatedProvider {
public ObjLocatedProviderObjFiltering(GameView gameView) { super(gameView); }
@Override
public void forEachObjInArea(GObjectsInSpaceManager goism, AbstractShape2D shape,
BiConsumer<Point, ObjectLocated> action) {
ProviderShapesIntersectionDetector psid;
// InSpaceObjectsManager<Double> isom;
psid = goism.getProviderShapesIntersectionDetector();
if (psid == null)
return;
goism.forEach(owid -> {
ObjectLocated ol;
if (owid instanceof ObjectLocated) {
ol = (ObjectLocated) owid;
if (ol instanceof ObjectShaped) {
if (psid.areIntersecting(shape, ((ObjectShaped) ol).getShape()))
action.accept(ol.getLocation(), ol);
} else if (shape.contains(ol.getLocation())) { action.accept(ol.getLocation(), ol); }
}
});
}
}
| 1,592 | 0.771357 | 0.7701 | 45 | 34.377777 | 26.06427 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.844444 | false | false | 0 |
cd6e262b14cfab55e4e4927a3b61fde589bee247 | 22,479,858,831,100 | dbd011345dac0e2777ab565d7ef49db64951f72f | /Go9-bieunghi/app/src/main/java/travel/uittrser/go9/go9/View/TrangChu/chitietdiadiem.java | 6ad09d19e9ac912b1a899f587feb03989326787a | [] | no_license | vutuanhai237/Go9 | https://github.com/vutuanhai237/Go9 | 470cd321132f90ee6c74daf4ba45d815a77e7bb8 | 9cc7015262c475ecbdeeca2be07a2deecc064124 | refs/heads/master | 2020-04-01T06:08:54.200000 | 2018-10-14T03:17:29 | 2018-10-14T03:17:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package travel.uittrser.go9.go9.View.TrangChu;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import travel.uittrser.go9.go9.R;
public class chitietdiadiem extends AppCompatActivity {
public ImageButton btn_vitri;
public ImageButton btn_phanhoi;
public ImageButton btn_timkiem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chitietdiadiem);
btn_vitri = (ImageButton) findViewById(R.id.vi_tri);
btn_vitri.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent(chitietdiadiem.this, vitri.class);
startActivity(in);
}
});
btn_phanhoi = (ImageButton) findViewById(R.id.phan_hoi);
btn_phanhoi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent(chitietdiadiem.this, phanhoi.class);
startActivity(in);
}
});
btn_timkiem = (ImageButton) findViewById(R.id.tim_kiem);
btn_timkiem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent(chitietdiadiem.this, TrangChuActivity.class);
startActivity(in);
}
});
}
}
| UTF-8 | Java | 1,631 | java | chitietdiadiem.java | Java | [] | null | [] | package travel.uittrser.go9.go9.View.TrangChu;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import travel.uittrser.go9.go9.R;
public class chitietdiadiem extends AppCompatActivity {
public ImageButton btn_vitri;
public ImageButton btn_phanhoi;
public ImageButton btn_timkiem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chitietdiadiem);
btn_vitri = (ImageButton) findViewById(R.id.vi_tri);
btn_vitri.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent(chitietdiadiem.this, vitri.class);
startActivity(in);
}
});
btn_phanhoi = (ImageButton) findViewById(R.id.phan_hoi);
btn_phanhoi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent(chitietdiadiem.this, phanhoi.class);
startActivity(in);
}
});
btn_timkiem = (ImageButton) findViewById(R.id.tim_kiem);
btn_timkiem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent(chitietdiadiem.this, TrangChuActivity.class);
startActivity(in);
}
});
}
}
| 1,631 | 0.638872 | 0.635806 | 49 | 32.285713 | 23.59609 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 0 |
87d8979e919e6db8c5c7f07c53a8c988b7acd830 | 26,998,164,467,246 | 77b6383bf4c9d118ab9ddf437ecf82fb005ee5bc | /src/main/java/uz/pdp/appnews/controller/AuthController.java | 5d6a29d68048b83950df96d31232af4218a895a5 | [] | no_license | tokhirsam/news | https://github.com/tokhirsam/news | a363956f4d41ab3e0d565f2228ee604cd178e6dc | 98780c915ba9be6f41bc90ec95a201b7b26701bd | refs/heads/master | 2023-04-23T19:49:35.741000 | 2021-04-29T07:46:34 | 2021-04-29T07:46:34 | 362,713,995 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uz.pdp.appnews.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import uz.pdp.appnews.entity.User;
import uz.pdp.appnews.payload.ApiResponse;
import uz.pdp.appnews.payload.LoginDto;
import uz.pdp.appnews.payload.RegisterDto;
import uz.pdp.appnews.security.JwtProvider;
import uz.pdp.appnews.service.AuthService;
import javax.validation.Valid;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
AuthService service;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
JwtProvider jwtProvider;
@PostMapping("/register")
public HttpEntity<?> registerUser(@Valid @RequestBody RegisterDto dto){
ApiResponse apiResponse = service.registerUser(dto);
return ResponseEntity.status(apiResponse.isSuccess()?200:409).body(apiResponse);
}
@PostMapping("/login")
public HttpEntity<?> loginUser(@Valid @RequestBody LoginDto dto){
Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword()));
User user = (User) authenticate.getPrincipal();
String token = jwtProvider.generateToken(user.getUsername(), user.getRole());
return ResponseEntity.ok(token);
}
}
| UTF-8 | Java | 1,669 | java | AuthController.java | Java | [] | null | [] | package uz.pdp.appnews.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import uz.pdp.appnews.entity.User;
import uz.pdp.appnews.payload.ApiResponse;
import uz.pdp.appnews.payload.LoginDto;
import uz.pdp.appnews.payload.RegisterDto;
import uz.pdp.appnews.security.JwtProvider;
import uz.pdp.appnews.service.AuthService;
import javax.validation.Valid;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
AuthService service;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
JwtProvider jwtProvider;
@PostMapping("/register")
public HttpEntity<?> registerUser(@Valid @RequestBody RegisterDto dto){
ApiResponse apiResponse = service.registerUser(dto);
return ResponseEntity.status(apiResponse.isSuccess()?200:409).body(apiResponse);
}
@PostMapping("/login")
public HttpEntity<?> loginUser(@Valid @RequestBody LoginDto dto){
Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword()));
User user = (User) authenticate.getPrincipal();
String token = jwtProvider.generateToken(user.getUsername(), user.getRole());
return ResponseEntity.ok(token);
}
}
| 1,669 | 0.784302 | 0.780707 | 42 | 38.738094 | 30.681978 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false | 0 |
e9bbc36658af348d362714620a829d9ebccbf6a6 | 28,948,079,621,898 | 3f0df372621005ff4c4a81ae54bb79891ef55744 | /core/src/main/java/com/gentics/mesh/core/actions/impl/TagDAOActionsImpl.java | 28b149edda17a22392976222c963fbddd7155fbd | [
"Apache-2.0"
] | permissive | salvadordev/mesh | https://github.com/salvadordev/mesh | 0b6cf24e8f3d91de1a1ed25361e4c9d4ef3487df | 7383aeb767be6c2e9c4b84d46d84172067c136d3 | refs/heads/master | 2022-02-13T02:07:21.149000 | 2021-12-01T11:14:56 | 2021-12-01T11:14:56 | 115,204,486 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gentics.mesh.core.actions.impl;
import java.util.function.Predicate;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.gentics.mesh.cli.BootstrapInitializer;
import com.gentics.mesh.context.BulkActionContext;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.action.DAOActionContext;
import com.gentics.mesh.core.action.TagDAOActions;
import com.gentics.mesh.core.data.TagFamily;
import com.gentics.mesh.core.data.dao.TagDaoWrapper;
import com.gentics.mesh.core.data.page.Page;
import com.gentics.mesh.core.data.perm.InternalPermission;
import com.gentics.mesh.core.data.tag.HibTag;
import com.gentics.mesh.core.data.tagfamily.HibTagFamily;
import com.gentics.mesh.core.data.util.HibClassConverter;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.core.endpoint.PathParameters;
import com.gentics.mesh.core.rest.tag.TagResponse;
import com.gentics.mesh.event.EventQueueBatch;
import com.gentics.mesh.parameter.PagingParameters;
import dagger.Lazy;
/**
* @see TagDAOActions
*/
@Singleton
public class TagDAOActionsImpl implements TagDAOActions {
private Lazy<BootstrapInitializer> boot;
@Inject
public TagDAOActionsImpl(Lazy<BootstrapInitializer> boot) {
this.boot = boot;
}
@Override
public HibTag loadByUuid(DAOActionContext ctx, String tagUuid, InternalPermission perm, boolean errorIfNotFound) {
HibTagFamily hibTagFamily = ctx.parent();
TagFamily tagFamily = HibClassConverter.toGraph(hibTagFamily);
if (perm == null) {
return tagFamily.findByUuid(tagUuid);
// TagDaoWrapper tagDao = tx.tagDao();
// return tagDao.findByUuid(tagFamily, tagUuid);
} else {
return tagFamily.loadObjectByUuid(ctx.ac(), tagUuid, perm, errorIfNotFound);
}
}
@Override
public HibTag loadByName(DAOActionContext ctx, String name, InternalPermission perm, boolean errorIfNotFound) {
TagDaoWrapper tagDao = ctx.tx().tagDao();
HibTagFamily tagFamily = ctx.parent();
if (perm == null) {
if (tagFamily == null) {
return tagDao.findByName(name);
} else {
return tagDao.findByName(tagFamily, name);
}
} else {
throw new RuntimeException("Not supported");
}
}
@Override
public Page<? extends HibTag> loadAll(DAOActionContext ctx, PagingParameters pagingInfo) {
// TagDaoWrapper tagDao = tx.tagDao();
HibTagFamily hibTagFamily = ctx.parent();
if (hibTagFamily != null) {
TagFamily tagFamily = HibClassConverter.toGraph(hibTagFamily);
return tagFamily.findAll(ctx.ac(), pagingInfo);
} else {
return boot.get().tagRoot().findAll(ctx.ac(), pagingInfo);
}
}
@Override
public Page<? extends HibTag> loadAll(DAOActionContext ctx, PagingParameters pagingInfo, Predicate<HibTag> extraFilter) {
// TODO use parent
String tagFamilyUuid = PathParameters.getTagFamilyUuid(ctx.ac());
HibTagFamily tagFamily = getTagFamily(ctx.tx(), ctx.ac(), tagFamilyUuid);
return ctx.tx().tagDao().findAll(tagFamily, ctx.ac(), pagingInfo, extraFilter);
}
@Override
public boolean update(Tx tx, HibTag element, InternalActionContext ac, EventQueueBatch batch) {
TagDaoWrapper tagDao = tx.tagDao();
return tagDao.update(element, ac, batch);
}
@Override
public HibTag create(Tx tx, InternalActionContext ac, EventQueueBatch batch, String tagUuid) {
// TODO add parent uuid parameter and utilize it instead of extracting it from ac
TagDaoWrapper tagDao = tx.tagDao();
String tagFamilyUuid = PathParameters.getTagFamilyUuid(ac);
HibTagFamily tagFamily = getTagFamily(tx, ac, tagFamilyUuid);
if (tagUuid == null) {
return tagDao.create(tagFamily, ac, batch);
} else {
return tagDao.create(tagFamily, ac, batch, tagUuid);
}
}
@Override
public void delete(Tx tx, HibTag tag, BulkActionContext bac) {
TagDaoWrapper tagDao = tx.tagDao();
tagDao.delete(tag, bac);
}
@Override
public TagResponse transformToRestSync(Tx tx, HibTag tag, InternalActionContext ac, int level, String... languageTags) {
TagDaoWrapper tagDao = tx.tagDao();
return tagDao.transformToRestSync(tag, ac, level, languageTags);
}
@Override
public String getAPIPath(Tx tx, InternalActionContext ac, HibTag tag) {
TagDaoWrapper tagDao = tx.tagDao();
return tagDao.getAPIPath(tag, ac);
}
@Override
public String getETag(Tx tx, InternalActionContext ac, HibTag tag) {
TagDaoWrapper tagDao = tx.tagDao();
return tagDao.getETag(tag, ac);
}
private HibTagFamily getTagFamily(Tx tx, InternalActionContext ac, String tagFamilyUuid) {
return tx.tagFamilyDao().findByUuid(tx.getProject(ac), tagFamilyUuid);
}
}
| UTF-8 | Java | 4,559 | java | TagDAOActionsImpl.java | Java | [] | null | [] | package com.gentics.mesh.core.actions.impl;
import java.util.function.Predicate;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.gentics.mesh.cli.BootstrapInitializer;
import com.gentics.mesh.context.BulkActionContext;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.action.DAOActionContext;
import com.gentics.mesh.core.action.TagDAOActions;
import com.gentics.mesh.core.data.TagFamily;
import com.gentics.mesh.core.data.dao.TagDaoWrapper;
import com.gentics.mesh.core.data.page.Page;
import com.gentics.mesh.core.data.perm.InternalPermission;
import com.gentics.mesh.core.data.tag.HibTag;
import com.gentics.mesh.core.data.tagfamily.HibTagFamily;
import com.gentics.mesh.core.data.util.HibClassConverter;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.core.endpoint.PathParameters;
import com.gentics.mesh.core.rest.tag.TagResponse;
import com.gentics.mesh.event.EventQueueBatch;
import com.gentics.mesh.parameter.PagingParameters;
import dagger.Lazy;
/**
* @see TagDAOActions
*/
@Singleton
public class TagDAOActionsImpl implements TagDAOActions {
private Lazy<BootstrapInitializer> boot;
@Inject
public TagDAOActionsImpl(Lazy<BootstrapInitializer> boot) {
this.boot = boot;
}
@Override
public HibTag loadByUuid(DAOActionContext ctx, String tagUuid, InternalPermission perm, boolean errorIfNotFound) {
HibTagFamily hibTagFamily = ctx.parent();
TagFamily tagFamily = HibClassConverter.toGraph(hibTagFamily);
if (perm == null) {
return tagFamily.findByUuid(tagUuid);
// TagDaoWrapper tagDao = tx.tagDao();
// return tagDao.findByUuid(tagFamily, tagUuid);
} else {
return tagFamily.loadObjectByUuid(ctx.ac(), tagUuid, perm, errorIfNotFound);
}
}
@Override
public HibTag loadByName(DAOActionContext ctx, String name, InternalPermission perm, boolean errorIfNotFound) {
TagDaoWrapper tagDao = ctx.tx().tagDao();
HibTagFamily tagFamily = ctx.parent();
if (perm == null) {
if (tagFamily == null) {
return tagDao.findByName(name);
} else {
return tagDao.findByName(tagFamily, name);
}
} else {
throw new RuntimeException("Not supported");
}
}
@Override
public Page<? extends HibTag> loadAll(DAOActionContext ctx, PagingParameters pagingInfo) {
// TagDaoWrapper tagDao = tx.tagDao();
HibTagFamily hibTagFamily = ctx.parent();
if (hibTagFamily != null) {
TagFamily tagFamily = HibClassConverter.toGraph(hibTagFamily);
return tagFamily.findAll(ctx.ac(), pagingInfo);
} else {
return boot.get().tagRoot().findAll(ctx.ac(), pagingInfo);
}
}
@Override
public Page<? extends HibTag> loadAll(DAOActionContext ctx, PagingParameters pagingInfo, Predicate<HibTag> extraFilter) {
// TODO use parent
String tagFamilyUuid = PathParameters.getTagFamilyUuid(ctx.ac());
HibTagFamily tagFamily = getTagFamily(ctx.tx(), ctx.ac(), tagFamilyUuid);
return ctx.tx().tagDao().findAll(tagFamily, ctx.ac(), pagingInfo, extraFilter);
}
@Override
public boolean update(Tx tx, HibTag element, InternalActionContext ac, EventQueueBatch batch) {
TagDaoWrapper tagDao = tx.tagDao();
return tagDao.update(element, ac, batch);
}
@Override
public HibTag create(Tx tx, InternalActionContext ac, EventQueueBatch batch, String tagUuid) {
// TODO add parent uuid parameter and utilize it instead of extracting it from ac
TagDaoWrapper tagDao = tx.tagDao();
String tagFamilyUuid = PathParameters.getTagFamilyUuid(ac);
HibTagFamily tagFamily = getTagFamily(tx, ac, tagFamilyUuid);
if (tagUuid == null) {
return tagDao.create(tagFamily, ac, batch);
} else {
return tagDao.create(tagFamily, ac, batch, tagUuid);
}
}
@Override
public void delete(Tx tx, HibTag tag, BulkActionContext bac) {
TagDaoWrapper tagDao = tx.tagDao();
tagDao.delete(tag, bac);
}
@Override
public TagResponse transformToRestSync(Tx tx, HibTag tag, InternalActionContext ac, int level, String... languageTags) {
TagDaoWrapper tagDao = tx.tagDao();
return tagDao.transformToRestSync(tag, ac, level, languageTags);
}
@Override
public String getAPIPath(Tx tx, InternalActionContext ac, HibTag tag) {
TagDaoWrapper tagDao = tx.tagDao();
return tagDao.getAPIPath(tag, ac);
}
@Override
public String getETag(Tx tx, InternalActionContext ac, HibTag tag) {
TagDaoWrapper tagDao = tx.tagDao();
return tagDao.getETag(tag, ac);
}
private HibTagFamily getTagFamily(Tx tx, InternalActionContext ac, String tagFamilyUuid) {
return tx.tagFamilyDao().findByUuid(tx.getProject(ac), tagFamilyUuid);
}
}
| 4,559 | 0.758938 | 0.758938 | 136 | 32.52206 | 30.039917 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.007353 | false | false | 0 |
1bc7a3c6970cdb4b02adeb94fcce85d4650ef028 | 21,801,254,037,491 | 53a98b301db9ffbc166db4edb0d6cf4e4a81b7b5 | /src/main/java/com/emc/mongoose/base/load/step/client/metrics/MetricsSnapshotsSupplierTask.java | 3ca756a3b82044da444fc2db995286153b7181af | [
"MIT"
] | permissive | emc-mongoose/mongoose-base | https://github.com/emc-mongoose/mongoose-base | 004f5044e958aac8e5b246729f8710133df3700c | fb02df88bfe3b0e720a4bcd9319b88a6d4c63d09 | refs/heads/master | 2023-07-28T12:03:09.934000 | 2023-07-17T23:41:25 | 2023-07-17T23:41:25 | 175,399,579 | 4 | 4 | MIT | false | 2023-07-17T23:41:27 | 2019-03-13T10:36:44 | 2022-09-22T02:22:28 | 2023-07-17T23:41:26 | 13,486 | 4 | 3 | 3 | Java | false | false | package com.emc.mongoose.base.load.step.client.metrics;
import com.emc.mongoose.base.metrics.snapshot.AllMetricsSnapshot;
import com.github.akurilov.fiber4j.Fiber;
import java.util.List;
import java.util.function.Supplier;
public interface MetricsSnapshotsSupplierTask
extends Supplier<List<? extends AllMetricsSnapshot>>, Fiber {
@Override
List<? extends AllMetricsSnapshot> get();
}
| UTF-8 | Java | 394 | java | MetricsSnapshotsSupplierTask.java | Java | [
{
"context": "cs.snapshot.AllMetricsSnapshot;\nimport com.github.akurilov.fiber4j.Fiber;\nimport java.util.List;\nimport java",
"end": 149,
"score": 0.9982566833496094,
"start": 141,
"tag": "USERNAME",
"value": "akurilov"
}
] | null | [] | package com.emc.mongoose.base.load.step.client.metrics;
import com.emc.mongoose.base.metrics.snapshot.AllMetricsSnapshot;
import com.github.akurilov.fiber4j.Fiber;
import java.util.List;
import java.util.function.Supplier;
public interface MetricsSnapshotsSupplierTask
extends Supplier<List<? extends AllMetricsSnapshot>>, Fiber {
@Override
List<? extends AllMetricsSnapshot> get();
}
| 394 | 0.807107 | 0.804569 | 13 | 29.307692 | 24.16095 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 0 |
f5c97338237f0f82a64905c5e96e8a80dbc21087 | 32,444,183,001,057 | ced0fe9bfef43ea2e4077a37ca43ef77201ecbe5 | /service/src/main/java/com/epam/david/config/AppConfig.java | af89f03485c341a76502f2530cd2ad6a5f9adf04 | [] | no_license | abxaz92/book-mvc-epam | https://github.com/abxaz92/book-mvc-epam | ede0c080de775e1b0536e1d9e59977484892ffdd | 42f83c79f314e3474eb4fea40ae92a4c970e2e55 | refs/heads/master | 2021-01-20T09:31:52.484000 | 2018-11-29T21:53:35 | 2018-11-29T21:53:35 | 90,260,998 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.epam.david.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Created by David_Chaava on 5/4/2017.
*/
@Configuration
@ComponentScan({"com.epam.david"})
@EnableTransactionManagement(mode = AdviceMode.PROXY)
@EnableAutoConfiguration
public class AppConfig {
}
| UTF-8 | Java | 569 | java | AppConfig.java | Java | [
{
"context": "on.EnableTransactionManagement;\n\n/**\n * Created by David_Chaava on 5/4/2017.\n */\n@Configuration\n@Component",
"end": 386,
"score": 0.7704430222511292,
"start": 381,
"tag": "NAME",
"value": "David"
},
{
"context": "bleTransactionManagement;\n\n/**\n * Created by Dav... | null | [] | package com.epam.david.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Created by David_Chaava on 5/4/2017.
*/
@Configuration
@ComponentScan({"com.epam.david"})
@EnableTransactionManagement(mode = AdviceMode.PROXY)
@EnableAutoConfiguration
public class AppConfig {
}
| 569 | 0.834798 | 0.824253 | 19 | 28.947369 | 26.422625 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 0 |
ec29c008c2cd822c8211af64fc649a753cf27c1e | 32,126,355,430,373 | cedcb6da09c5d4527d8d7f6d3b811c37c5e0c4fb | /homework4-book-service/src/main/java/ua/edu/ukma/krukovska/bookservice/controller/BookController.java | 6cd202be669cd224a2d8eca6749b292a3f571440 | [] | no_license | YanaKrukovska/javaee-course | https://github.com/YanaKrukovska/javaee-course | 91673a6808ed50b726617057dd241f67ed7b9904 | 089accae1f69a8f603172186e3d106b06df181a2 | refs/heads/master | 2023-04-04T15:18:36.565000 | 2021-04-03T14:05:08 | 2021-04-03T14:05:08 | 340,674,976 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.edu.ukma.krukovska.bookservice.controller;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import ua.edu.ukma.krukovska.bookservice.persistence.model.Book;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
@Controller
public class BookController {
private static final List<Book> database = initDatabase();
@GetMapping("/")
public String showAll() {
return "index";
}
@GetMapping("/book")
@ResponseBody
public List<Book> searchBook(@RequestParam String searchInput) {
return database.stream().filter(book -> checkSearchParams(searchInput.toLowerCase(), book)).collect(Collectors.toList());
}
private boolean checkSearchParams(String searchInputLowercase, Book book) {
return book.getTitle().toLowerCase().contains(searchInputLowercase) ||
book.getIsbn().toLowerCase().contains(searchInputLowercase);
}
@ResponseBody
@GetMapping("/book/all")
public List<Book> getAllBooks() {
return database;
}
@PostMapping("/book")
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public Book addBook(@RequestBody Book book) {
database.add(book);
return book;
}
private static List<Book> initDatabase() {
List<Book> database = new LinkedList<>();
database.add(new Book("Catcher In The Rye", "J.D. Salinger", "978-966-14-8783-2"));
database.add(new Book("Martin Eden", "Jack London", "978-617-07-0777-2"));
database.add(new Book("Flowers for Algernon", "Daniel Keyes", "978-617-12-7611-6"));
return database;
}
}
| UTF-8 | Java | 1,736 | java | BookController.java | Java | [
{
"context": " database.add(new Book(\"Catcher In The Rye\", \"J.D. Salinger\", \"978-966-14-8783-2\"));\n database.add(new",
"end": 1501,
"score": 0.9998294711112976,
"start": 1488,
"tag": "NAME",
"value": "J.D. Salinger"
},
{
"context": "-966-14-8783-2\"));\n data... | null | [] | package ua.edu.ukma.krukovska.bookservice.controller;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import ua.edu.ukma.krukovska.bookservice.persistence.model.Book;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
@Controller
public class BookController {
private static final List<Book> database = initDatabase();
@GetMapping("/")
public String showAll() {
return "index";
}
@GetMapping("/book")
@ResponseBody
public List<Book> searchBook(@RequestParam String searchInput) {
return database.stream().filter(book -> checkSearchParams(searchInput.toLowerCase(), book)).collect(Collectors.toList());
}
private boolean checkSearchParams(String searchInputLowercase, Book book) {
return book.getTitle().toLowerCase().contains(searchInputLowercase) ||
book.getIsbn().toLowerCase().contains(searchInputLowercase);
}
@ResponseBody
@GetMapping("/book/all")
public List<Book> getAllBooks() {
return database;
}
@PostMapping("/book")
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public Book addBook(@RequestBody Book book) {
database.add(book);
return book;
}
private static List<Book> initDatabase() {
List<Book> database = new LinkedList<>();
database.add(new Book("Catcher In The Rye", "<NAME>", "978-966-14-8783-2"));
database.add(new Book("<NAME>", "<NAME>", "978-617-07-0777-2"));
database.add(new Book("Flowers for Algernon", "<NAME>", "978-617-12-7611-6"));
return database;
}
}
| 1,713 | 0.684908 | 0.662442 | 55 | 30.563637 | 29.790031 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 0 |
32b114f829a02198bf5945950b46cdc5789107de | 11,922,829,266,325 | 12fb8f8edf3c7b1dd028b41023a6c9c45d4de0e6 | /app/src/test/java/com/smoothspark/msgme/ui/main/MainPagePresenterTest.java | a4b61401b9f17708f0efb42875f21b4b42acfbd2 | [] | no_license | gabex89/msgme | https://github.com/gabex89/msgme | c338a6b27a8f04e17d30c48006905b86a7fc2f18 | 6fa90240a2204deb08f49194bb7c2846ff4ff680 | refs/heads/master | 2020-03-13T19:43:20.868000 | 2018-05-04T20:26:55 | 2018-05-04T20:26:55 | 131,259,397 | 0 | 0 | null | false | 2018-05-04T20:26:56 | 2018-04-27T07:08:25 | 2018-05-01T21:07:56 | 2018-05-04T20:26:56 | 169 | 0 | 0 | 0 | Java | false | null | package com.smoothspark.msgme.ui.main;
import com.smoothspark.msgme.data.DataManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
/**
* Created by SmoothSpark on 2018. 05. 01.
*/
@RunWith(MockitoJUnitRunner.class)
public class MainPagePresenterTest {
@Mock
MainPageMvpView mockMainPageMvpView;
@Mock
DataManager mockDataManager;
private MainPagePresenter<MainPageMvpView> mainPagePresenter;
@Before
public void setUp() {
mainPagePresenter = new MainPagePresenter<>(mockDataManager);
mainPagePresenter.onAttach(mockMainPageMvpView);
}
@Ignore
@Test
public void testSuccessSendAndReceiveMessage() {
//given
String message = "TEST_MSG";
//when
//then
verify(mockMainPageMvpView).updateMessagesList(message);
}
@After
public void tearDown() throws Exception {
mainPagePresenter.onDetach();
}
} | UTF-8 | Java | 1,127 | java | MainPagePresenterTest.java | Java | [
{
"context": "tic org.mockito.Mockito.verify;\n\n/**\n * Created by SmoothSpark on 2018. 05. 01.\n */\n@RunWith(MockitoJUnitRunner.",
"end": 361,
"score": 0.999502956867218,
"start": 350,
"tag": "USERNAME",
"value": "SmoothSpark"
}
] | null | [] | package com.smoothspark.msgme.ui.main;
import com.smoothspark.msgme.data.DataManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
/**
* Created by SmoothSpark on 2018. 05. 01.
*/
@RunWith(MockitoJUnitRunner.class)
public class MainPagePresenterTest {
@Mock
MainPageMvpView mockMainPageMvpView;
@Mock
DataManager mockDataManager;
private MainPagePresenter<MainPageMvpView> mainPagePresenter;
@Before
public void setUp() {
mainPagePresenter = new MainPagePresenter<>(mockDataManager);
mainPagePresenter.onAttach(mockMainPageMvpView);
}
@Ignore
@Test
public void testSuccessSendAndReceiveMessage() {
//given
String message = "TEST_MSG";
//when
//then
verify(mockMainPageMvpView).updateMessagesList(message);
}
@After
public void tearDown() throws Exception {
mainPagePresenter.onDetach();
}
} | 1,127 | 0.710736 | 0.703638 | 53 | 20.283018 | 20.146049 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.339623 | false | false | 0 |
ce0a9478b7e47cae94ee4b52394e92a6a445aea4 | 27,960,237,166,609 | ef40a77496ad1439c23742d085f9376714426cfd | /src/main/java/co/com/eam/controller/CategoriaController.java | bec9cee867cf6df5c4e8eb64ebce5ce95010095a | [] | no_license | sergiodazaguzman01/pruebaheroku | https://github.com/sergiodazaguzman01/pruebaheroku | 08d7b00915e6fa2a6ab3cf1eacacf3411eae35c1 | 3f430dc9db568f951e65373776a437c021476a8f | refs/heads/master | 2022-12-23T10:49:24.649000 | 2020-09-22T20:01:14 | 2020-09-22T20:01:14 | 297,738,864 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.com.eam.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import co.com.eam.domain.Categoria;
import co.com.eam.repository.ICategoriaRepo;
@Controller
public class CategoriaController {
@Autowired
private ICategoriaRepo iCategoriaRepo;
@GetMapping("/addCategoria")
public String showSignUpForm(Categoria categoria) {
return "add-categoria";
}
@PostMapping("/add_categoria")
public String addCategoria(@Valid Categoria categoria, BindingResult result, Model model) {
if (result.hasErrors()) {
return "add-categoria";
}
iCategoriaRepo.save(categoria);
model.addAttribute("categoria", iCategoriaRepo.findAll());
return "listarcategoria";
}
@GetMapping("/editCategoria/{id_categoria}")
public String showUpdateForm(@PathVariable("id_categoria") int idCategoria, Model model) {
Categoria categoria = iCategoriaRepo.findById(idCategoria).orElseThrow(() -> new IllegalArgumentException("Invalid categoria id:" + idCategoria));
model.addAttribute("categoria", categoria);
return "update-categoria";
}
@PostMapping("/updateCategoria/{id_categoria}")
public String updateCategoria(@PathVariable("id_categoria") int idCategoria, @Valid Categoria categoria, BindingResult result, Model model) {
if (result.hasErrors()) {
categoria.setId_categoria(idCategoria);
return "update-categoria";
}
iCategoriaRepo.save(categoria);
model.addAttribute("categoria", iCategoriaRepo.findAll());
return "listarCategoria";
}
@GetMapping("/deleteCategoria/{id_categoria}")
public String deleteCategoria(@PathVariable("id_categoria") int idCategoria, Model model) {
Categoria categoria = iCategoriaRepo.findById(idCategoria).orElseThrow(() -> new IllegalArgumentException("Invalid categoria id:" + idCategoria));
iCategoriaRepo.delete(categoria);
model.addAttribute("categoria", iCategoriaRepo.findAll());
return "listarCategoria";
}
@GetMapping("/listarcategoria")
public String ListarDepa(Model model) {
model.addAttribute("categoria", iCategoriaRepo.findAll());
return "listarCategoria";
}
} | UTF-8 | Java | 2,673 | java | CategoriaController.java | Java | [] | null | [] | package co.com.eam.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import co.com.eam.domain.Categoria;
import co.com.eam.repository.ICategoriaRepo;
@Controller
public class CategoriaController {
@Autowired
private ICategoriaRepo iCategoriaRepo;
@GetMapping("/addCategoria")
public String showSignUpForm(Categoria categoria) {
return "add-categoria";
}
@PostMapping("/add_categoria")
public String addCategoria(@Valid Categoria categoria, BindingResult result, Model model) {
if (result.hasErrors()) {
return "add-categoria";
}
iCategoriaRepo.save(categoria);
model.addAttribute("categoria", iCategoriaRepo.findAll());
return "listarcategoria";
}
@GetMapping("/editCategoria/{id_categoria}")
public String showUpdateForm(@PathVariable("id_categoria") int idCategoria, Model model) {
Categoria categoria = iCategoriaRepo.findById(idCategoria).orElseThrow(() -> new IllegalArgumentException("Invalid categoria id:" + idCategoria));
model.addAttribute("categoria", categoria);
return "update-categoria";
}
@PostMapping("/updateCategoria/{id_categoria}")
public String updateCategoria(@PathVariable("id_categoria") int idCategoria, @Valid Categoria categoria, BindingResult result, Model model) {
if (result.hasErrors()) {
categoria.setId_categoria(idCategoria);
return "update-categoria";
}
iCategoriaRepo.save(categoria);
model.addAttribute("categoria", iCategoriaRepo.findAll());
return "listarCategoria";
}
@GetMapping("/deleteCategoria/{id_categoria}")
public String deleteCategoria(@PathVariable("id_categoria") int idCategoria, Model model) {
Categoria categoria = iCategoriaRepo.findById(idCategoria).orElseThrow(() -> new IllegalArgumentException("Invalid categoria id:" + idCategoria));
iCategoriaRepo.delete(categoria);
model.addAttribute("categoria", iCategoriaRepo.findAll());
return "listarCategoria";
}
@GetMapping("/listarcategoria")
public String ListarDepa(Model model) {
model.addAttribute("categoria", iCategoriaRepo.findAll());
return "listarCategoria";
}
} | 2,673 | 0.710438 | 0.710438 | 72 | 36.138889 | 34.018501 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 0 |
ed134474f2fe4ccb29dbf4dd67ea4ebde0b1f335 | 9,878,424,837,031 | ee656221fcf0afc476de2a29fa2332705f291e4e | /Cryptocurrencies/app/src/main/java/demo/app/cryptocurrencies/model/Stats.java | c941cca7beb36ee4c39e54c20bd43707d872ba02 | [] | no_license | DevNavadip/Cryptocurrencies_coins | https://github.com/DevNavadip/Cryptocurrencies_coins | 5cededfbafbe0675718d5ee5d120c533aff7127f | 49c0152de7f39a41d2d76d4c7cff7f710e188eb4 | refs/heads/master | 2023-03-29T01:45:43.229000 | 2021-04-01T13:53:58 | 2021-04-01T13:53:58 | 353,712,402 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package demo.app.cryptocurrencies.model;
public class Stats {
private String total;
private String totalExchanges;
private String totalMarkets;
private String totalMarketCap;
private String total24hVolume;
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getTotalExchanges() {
return totalExchanges;
}
public void setTotalExchanges(String totalExchanges) {
this.totalExchanges = totalExchanges;
}
public String getTotalMarkets() {
return totalMarkets;
}
public void setTotalMarkets(String totalMarkets) {
this.totalMarkets = totalMarkets;
}
public String getTotalMarketCap() {
return totalMarketCap;
}
public void setTotalMarketCap(String totalMarketCap) {
this.totalMarketCap = totalMarketCap;
}
public String getTotal24hVolume() {
return total24hVolume;
}
public void setTotal24hVolume(String total24hVolume) {
this.total24hVolume = total24hVolume;
}
}
| UTF-8 | Java | 1,118 | java | Stats.java | Java | [] | null | [] | package demo.app.cryptocurrencies.model;
public class Stats {
private String total;
private String totalExchanges;
private String totalMarkets;
private String totalMarketCap;
private String total24hVolume;
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getTotalExchanges() {
return totalExchanges;
}
public void setTotalExchanges(String totalExchanges) {
this.totalExchanges = totalExchanges;
}
public String getTotalMarkets() {
return totalMarkets;
}
public void setTotalMarkets(String totalMarkets) {
this.totalMarkets = totalMarkets;
}
public String getTotalMarketCap() {
return totalMarketCap;
}
public void setTotalMarketCap(String totalMarketCap) {
this.totalMarketCap = totalMarketCap;
}
public String getTotal24hVolume() {
return total24hVolume;
}
public void setTotal24hVolume(String total24hVolume) {
this.total24hVolume = total24hVolume;
}
}
| 1,118 | 0.669946 | 0.657424 | 54 | 19.703703 | 19.366474 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.296296 | false | false | 0 |
6133971f243efdef66029664664c6e2d0687541b | 24,927,990,239,704 | 048aa598ec126a05434f351c6a9a32d06e47e4f0 | /WiseOlwHostel_Lib/src/uuu/woh/entity/Customer.java | cdf3c3c4d7faedb34025f9b4395359b703b2ad6e | [] | no_license | SeanWangYS/WiseOwlHostel | https://github.com/SeanWangYS/WiseOwlHostel | 918d2e92daea0fcbaf93f0ecdba57d7e6a65dc54 | 5745c07dd08b8999736d11f7afc26230a1584694 | refs/heads/master | 2021-07-17T00:34:55.399000 | 2020-08-24T01:21:48 | 2020-08-24T01:21:48 | 191,128,937 | 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 uuu.woh.entity;
/**
*
* @author Sean
*/
public class Customer {
private String email; //Pkey //required
private String password; //required
private String surname; //required
private String name; //required
private String phone; //required
private char gender; //required
public static final char MALE = 'M';
public static final char FEMALE = 'F';
public Customer(){}
public Customer(String email, String password, String surname, String name) {
this.email = email;
this.password = password;
this.surname = surname;
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) throws WOHException {
if (email != null && email.matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
this.email = email;
}else{
System.out.println("必須輸入格式正確的客戶Email");
throw new WOHException("必須輸入格式正確的客戶Email");
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) throws WOHException {
if(password!=null && password.length()>=6 && password.length()<=12){
this.password = password;
}else{
System.out.println("請輸入6~12碼的密碼");
throw new WOHException("請輸入6~12碼的密碼");
}
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) throws WOHException{
if(phone!=null && phone.matches("[0-9]{10}")){
this.phone = phone;
}else{
System.out.println("電話號碼格式不符");
throw new WOHException("電話號碼格式不符");
}
}
public char getGender() {
return gender;
}
public void setGender(char gender) throws WOHException {
if(gender==MALE || gender==FEMALE){
this.gender = gender;
}else{
System.out.println("請輸入正確性別,M = male,F = female");
throw new WOHException("請輸入正確性別,M = male,F = female");
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" + "email=" + email + ", password=" + password + ", surname=" + surname + ", name=" + name + ", phone=" + phone + ", gender=" + gender + '}';
}
}
| UTF-8 | Java | 2,932 | java | Customer.java | Java | [
{
"context": "or.\n */\npackage uuu.woh.entity;\n\n/**\n *\n * @author Sean\n */\npublic class Customer {\n\n private String e",
"end": 232,
"score": 0.9992775917053223,
"start": 228,
"tag": "NAME",
"value": "Sean"
},
{
"context": " this.email = email;\n this.password... | 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 uuu.woh.entity;
/**
*
* @author Sean
*/
public class Customer {
private String email; //Pkey //required
private String password; //required
private String surname; //required
private String name; //required
private String phone; //required
private char gender; //required
public static final char MALE = 'M';
public static final char FEMALE = 'F';
public Customer(){}
public Customer(String email, String password, String surname, String name) {
this.email = email;
this.password = <PASSWORD>;
this.surname = surname;
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) throws WOHException {
if (email != null && email.matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
this.email = email;
}else{
System.out.println("必須輸入格式正確的客戶Email");
throw new WOHException("必須輸入格式正確的客戶Email");
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) throws WOHException {
if(password!=null && password.length()>=6 && password.length()<=12){
this.password = <PASSWORD>;
}else{
System.out.println("請輸入6~12碼的密碼");
throw new WOHException("請輸入6~12碼的密碼");
}
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) throws WOHException{
if(phone!=null && phone.matches("[0-9]{10}")){
this.phone = phone;
}else{
System.out.println("電話號碼格式不符");
throw new WOHException("電話號碼格式不符");
}
}
public char getGender() {
return gender;
}
public void setGender(char gender) throws WOHException {
if(gender==MALE || gender==FEMALE){
this.gender = gender;
}else{
System.out.println("請輸入正確性別,M = male,F = female");
throw new WOHException("請輸入正確性別,M = male,F = female");
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" + "email=" + email + ", password=" + <PASSWORD> + ", surname=" + surname + ", name=" + name + ", phone=" + phone + ", gender=" + gender + '}';
}
}
| 2,938 | 0.572708 | 0.567335 | 108 | 24.851852 | 26.975233 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 0 |
69db52aa5a7d59bf498a6ff676c27fb2cff1e96a | 26,920,855,070,020 | d27bd5e70114f99cae5af48f26a2f8b651213eff | /cwmd_core/src/main/java/application/core/repository/FlowPathRepository.java | a9a9ba981da7047d844edde44829f752196732c7 | [
"Apache-2.0"
] | permissive | paladin952/cwmd | https://github.com/paladin952/cwmd | 7471eb25965d9bd47cb0ff9e8bef0d74e0d9a86d | 0d8fdaf5d52fcd5bf42265eb0ca75cd081005f17 | refs/heads/develop | 2021-05-03T22:56:40.384000 | 2017-01-22T09:39:26 | 2017-01-22T09:39:26 | 71,712,542 | 0 | 3 | null | false | 2017-01-17T10:54:28 | 2016-10-23T15:43:36 | 2016-12-13T21:02:04 | 2017-01-17T10:54:28 | 32,143 | 0 | 3 | 7 | Java | null | null | package application.core.repository;
import application.core.model.FlowPath;
import application.core.model.PKs.FlowPathPK;
import javax.transaction.Transactional;
@Transactional
public interface FlowPathRepository extends CWMDRepository<FlowPathPK, FlowPath>, FlowPathRepositoryCustom {}
| UTF-8 | Java | 291 | java | FlowPathRepository.java | Java | [] | null | [] | package application.core.repository;
import application.core.model.FlowPath;
import application.core.model.PKs.FlowPathPK;
import javax.transaction.Transactional;
@Transactional
public interface FlowPathRepository extends CWMDRepository<FlowPathPK, FlowPath>, FlowPathRepositoryCustom {}
| 291 | 0.85567 | 0.85567 | 9 | 31.333334 | 32.666668 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 0 |
0d881db3dfe97b63915f4d1a6168d73e37df1a32 | 32,633,161,571,586 | 95c49f466673952b465e19a5ee3ae6eff76bee00 | /src/main/java/com/zhihu/android/app/ebook/p1050d/C10678d.java | 05f68577b3068162e2d35ef76b774b8721e0292d | [] | no_license | Phantoms007/zhihuAPK | https://github.com/Phantoms007/zhihuAPK | 58889c399ae56b16a9160a5f48b807e02c87797e | dcdbd103436a187f9c8b4be8f71bdf7813b6d201 | refs/heads/main | 2023-01-24T01:34:18.716000 | 2020-11-25T17:14:55 | 2020-11-25T17:14:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhihu.android.app.ebook.p1050d;
import android.content.Intent;
import com.zhihu.android.api.SharedProduct;
import com.zhihu.android.api.net.Net;
import com.zhihu.android.api.service2.EBookService;
import com.zhihu.android.app.ebook.util.MemeberWechatShareRecorder;
import java8.util.Optional;
import java8.util.p2234b.AbstractC32237i;
import java8.util.p2234b.AbstractC32239o;
import p2189io.reactivex.p2231i.Schedulers;
/* renamed from: com.zhihu.android.app.ebook.d.d */
/* compiled from: MemeberWechatShareRecorder */
public class C10678d {
/* renamed from: a */
public static boolean m58287a(Intent intent) {
return Optional.m150255b(intent).mo131258a((AbstractC32237i) $$Lambda$FtOLGdVMvd__xTO8UzAcGNOuTAo.INSTANCE).mo131258a((AbstractC32237i) $$Lambda$NmyH2CCzOfbRlLBsMkonxC8ycc.INSTANCE).mo131259a((AbstractC32239o) $$Lambda$qeXANHnXc5kIU8KFjVIgwovd2Fk.INSTANCE).mo131267c();
}
/* renamed from: a */
public static void m58286a(Intent intent, @MemeberWechatShareRecorder.PRODUCT String str, String str2, String str3) {
if (m58287a(intent)) {
((EBookService) Net.createService(EBookService.class)).mo63013a(new SharedProduct(1, new SharedProduct.C9504a(str, str2, str3))).subscribeOn(Schedulers.m148537b()).retry(3).subscribe();
}
}
}
| UTF-8 | Java | 1,315 | java | C10678d.java | Java | [] | null | [] | package com.zhihu.android.app.ebook.p1050d;
import android.content.Intent;
import com.zhihu.android.api.SharedProduct;
import com.zhihu.android.api.net.Net;
import com.zhihu.android.api.service2.EBookService;
import com.zhihu.android.app.ebook.util.MemeberWechatShareRecorder;
import java8.util.Optional;
import java8.util.p2234b.AbstractC32237i;
import java8.util.p2234b.AbstractC32239o;
import p2189io.reactivex.p2231i.Schedulers;
/* renamed from: com.zhihu.android.app.ebook.d.d */
/* compiled from: MemeberWechatShareRecorder */
public class C10678d {
/* renamed from: a */
public static boolean m58287a(Intent intent) {
return Optional.m150255b(intent).mo131258a((AbstractC32237i) $$Lambda$FtOLGdVMvd__xTO8UzAcGNOuTAo.INSTANCE).mo131258a((AbstractC32237i) $$Lambda$NmyH2CCzOfbRlLBsMkonxC8ycc.INSTANCE).mo131259a((AbstractC32239o) $$Lambda$qeXANHnXc5kIU8KFjVIgwovd2Fk.INSTANCE).mo131267c();
}
/* renamed from: a */
public static void m58286a(Intent intent, @MemeberWechatShareRecorder.PRODUCT String str, String str2, String str3) {
if (m58287a(intent)) {
((EBookService) Net.createService(EBookService.class)).mo63013a(new SharedProduct(1, new SharedProduct.C9504a(str, str2, str3))).subscribeOn(Schedulers.m148537b()).retry(3).subscribe();
}
}
}
| 1,315 | 0.765779 | 0.669962 | 27 | 47.703705 | 60.187862 | 277 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 0 |
00e9d2b90c8450f8050657564f907c9b783c037a | 25,400,436,640,461 | 2acdfbe89fce41d7935cf01cd6223f4bb7d39596 | /hibernate6/src/main/java/com/org/HibernateTest.java | c8c3d5f91dbb495190e6262a6eed075e73996188 | [] | no_license | nileshzarkar/hibernate | https://github.com/nileshzarkar/hibernate | 03e62368f660067695c89929d02876148121beec | ac711e273ec5b7201bd1a3600fcdb9f8ede89140 | refs/heads/master | 2015-08-13T23:14:48.583000 | 2014-10-11T01:33:44 | 2014-10-11T01:33:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.org;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.org.entity.model.UserDetails;
/**
* Hello world!
*
*/
public class HibernateTest
{
public static void main( String[] args )
{
UserDetails userDetails = new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("Anvi");
userDetails.setLastName("Zarkar");
userDetails.setDoj(new Date());
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(userDetails);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
| UTF-8 | Java | 900 | java | HibernateTest.java | Java | [
{
"context": "ls.setUserId(1);\n userDetails.setUserName(\"Anvi\");\n userDetails.setLastName(\"Zarkar\");\n ",
"end": 434,
"score": 0.990888237953186,
"start": 430,
"tag": "USERNAME",
"value": "Anvi"
},
{
"context": "serName(\"Anvi\");\n userDetails.setLastNam... | null | [] | package com.org;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.org.entity.model.UserDetails;
/**
* Hello world!
*
*/
public class HibernateTest
{
public static void main( String[] args )
{
UserDetails userDetails = new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("Anvi");
userDetails.setLastName("Zarkar");
userDetails.setDoj(new Date());
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(userDetails);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
| 900 | 0.654444 | 0.653333 | 36 | 24 | 22.123392 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 0 |
c669820a019ae8bf40154528fff2e96b4b730e96 | 1,013,612,337,536 | 94cb7d822b0d2b6275d306fc74c87eecc328fa56 | /src/nl/derpt/android/internal/jobs/GetFirstUnreadTweet.java | 8e2b62c83f982fb54f903957bd7f1da3fbe79ede | [] | no_license | paul999/Derpt | https://github.com/paul999/Derpt | 70f2c83a4d9de55e90f1b5bfc28e114c8fefaba9 | 57c2a887b23718e679c3d0c4baa0c376cd254846 | refs/heads/master | 2019-01-22T23:29:57.053000 | 2013-04-01T17:00:38 | 2013-04-01T17:00:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package nl.derpt.android.internal.jobs;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import com.google.gson.Gson;
import nl.derpt.android.MainActivity;
import nl.derpt.android.R;
import nl.derpt.android.fragments.TweetFragment;
import nl.derpt.android.internal.JSON.TweetData;
import android.app.Fragment;
import android.content.Context;
import android.util.Log;
import android.view.MenuItem;
/**
* @author paul_000
*
*/
public class GetFirstUnreadTweet extends Job {
/**
* @param context
* @param manager
* @param adapter
*/
public GetFirstUnreadTweet(Context context, Manager manager) {
super(context, manager);
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) {
// We need a nice way to handle this...
Log.d("derpt", "Failure");
return;
}
Gson parser = new Gson();
TweetData rs = parser.fromJson(this.response, TweetData.class);
((MainActivity)this.context).account.setCurrent(rs);
Log.d("derpt", "Data " + rs.tweet.text);
Fragment fragment = new TweetFragment();
((MainActivity) this.context).getFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
if (((MainActivity) this.context).menu != null) {
MenuItem m = ((MainActivity) this.context).menu
.findItem(R.id.menu_unread);
String text = this.context.getString(R.string.unknown);
try {
if (rs.unread != null && !rs.unread.equals("null")) {
text = rs.unread;
}
} catch (NullPointerException e) {
}
m.setTitle(text);
} else {
Log.d("derpt", "menu is null");
}
this.manager.showProgress(false);
}
@Override
protected Boolean doInBackground(Void... params) {
HttpResponse response = doGet("/twitter/timeline/me/"
+ ((MainActivity) this.context).account.getId()
+ "/first/unread");
if (response == null) {
return false;
}
StatusLine st = response.getStatusLine();
Log.d("derpt", st.toString());
if (st.getStatusCode() == 200) {
return true;
}
return false;
}
}
| UTF-8 | Java | 2,075 | java | GetFirstUnreadTweet.java | Java | [
{
"context": "Log;\nimport android.view.MenuItem;\n\n/**\n * @author paul_000\n * \n */\npublic class GetFirstUnreadTweet extends ",
"end": 460,
"score": 0.9994735717773438,
"start": 452,
"tag": "USERNAME",
"value": "paul_000"
}
] | null | [] | /**
*
*/
package nl.derpt.android.internal.jobs;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import com.google.gson.Gson;
import nl.derpt.android.MainActivity;
import nl.derpt.android.R;
import nl.derpt.android.fragments.TweetFragment;
import nl.derpt.android.internal.JSON.TweetData;
import android.app.Fragment;
import android.content.Context;
import android.util.Log;
import android.view.MenuItem;
/**
* @author paul_000
*
*/
public class GetFirstUnreadTweet extends Job {
/**
* @param context
* @param manager
* @param adapter
*/
public GetFirstUnreadTweet(Context context, Manager manager) {
super(context, manager);
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) {
// We need a nice way to handle this...
Log.d("derpt", "Failure");
return;
}
Gson parser = new Gson();
TweetData rs = parser.fromJson(this.response, TweetData.class);
((MainActivity)this.context).account.setCurrent(rs);
Log.d("derpt", "Data " + rs.tweet.text);
Fragment fragment = new TweetFragment();
((MainActivity) this.context).getFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
if (((MainActivity) this.context).menu != null) {
MenuItem m = ((MainActivity) this.context).menu
.findItem(R.id.menu_unread);
String text = this.context.getString(R.string.unknown);
try {
if (rs.unread != null && !rs.unread.equals("null")) {
text = rs.unread;
}
} catch (NullPointerException e) {
}
m.setTitle(text);
} else {
Log.d("derpt", "menu is null");
}
this.manager.showProgress(false);
}
@Override
protected Boolean doInBackground(Void... params) {
HttpResponse response = doGet("/twitter/timeline/me/"
+ ((MainActivity) this.context).account.getId()
+ "/first/unread");
if (response == null) {
return false;
}
StatusLine st = response.getStatusLine();
Log.d("derpt", st.toString());
if (st.getStatusCode() == 200) {
return true;
}
return false;
}
}
| 2,075 | 0.671325 | 0.668434 | 102 | 19.343138 | 19.94035 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.686275 | false | false | 0 |
46ac0153cc352fea73bc2681a0664d7c5d063b5e | 16,303,695,856,915 | f3d90b9b05c0e8892100fabe005a4adbfce03f73 | /app/src/main/java/com/example/android/bloodbankapp/statistics/StatisticsReportsFragment.java | 4b89155c8325ec08aab060ac7bfa8ae2228fc1e3 | [
"MIT"
] | permissive | k-slugger/blood-bank-app | https://github.com/k-slugger/blood-bank-app | cd6ebfa090394b4f61abdc92c478f034345ece93 | 946dfb504f72333f265d22f247611f9508f3340d | refs/heads/master | 2021-01-22T18:43:24.129000 | 2017-06-29T21:12:24 | 2017-06-29T21:12:24 | 85,109,189 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.bloodbankapp.statistics;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.bloodbankapp.data.BloodBankContract;
import com.example.android.bloodbankapp.R;
import com.example.android.bloodbankapp.data.BloodBankDbHelper;
import com.example.android.bloodbankapp.statistics.BloodReportDetails;
import com.example.android.bloodbankapp.statistics.Report;
import com.example.android.bloodbankapp.statistics.ReportAdapter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class StatisticsReportsFragment extends Fragment {
ListView listview;
int up=R.drawable.up;
int down= R.drawable.down;
SQLiteDatabase mdb;
//String month[]={"December","January","February","MArch"};
//String bldqtyin[]={"123 units","578 units","456 units","698 units"};
//String bldqtyout[]={"123 units","578 units","456 units","698 units"};
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_statistics_reports, container, false);
listview= (ListView) view.findViewById(R.id.lv_report);
ReportAdapter ra=new ReportAdapter(getContext(),R.layout.row_layout);
BloodBankDbHelper dbh=new BloodBankDbHelper(getActivity());
mdb = dbh.getWritableDatabase();
Cursor c = getReport1();
c.moveToFirst();
int bldin1 =0,bldin2 =0,bldin3 =0,bldin4 =0,bldin5 =0,bldin6 =0,bldin7 =0,bldin8 =0,bldin9 =0,bldin10 =0,bldin11 =0,bldin12 =0;
int bldout1 =0,bldout2 =0,bldout3 =0,bldout4 =0,bldout5 =0,bldout6 =0,bldout7 =0,bldout8 =0,bldout9 =0,bldout10 =0,bldout11 =0,bldout12 =0;
for (int i=0;i<c.getCount();i++){
Log.d("bb",c.getInt(0)+"quant");
Log.d("bb",c.getString(1)+"type");
Log.d("bb",c.getString(2)+"month");
Log.d("bb",c.getString(3)+"name");
Log.d("bb,",c.getInt(4)+"id");
c.moveToNext();
}
c.moveToFirst();
String bldqtyin[]=new String[12];
String bldqtyout[]=new String[12];
String month[]=new String[12];
Log.d("bb",c.getCount()+"fd");
if ((c.getCount())>0 && c != null){
for (int i = 0; i < c.getCount(); i++) {
if (c.getString(1).equals("Donor")) {
Log.d("bb",c.getInt(0)+"Ddd");
if (c.getInt(2) == 01)
bldin1 = bldin1 + c.getInt(0);
if (c.getInt(2) == 02){
bldin2 = bldin2 + c.getInt(0);
Log.d("bb",bldin2+"valueinfeb");
}
if (c.getInt(2) == 03){
bldin3 = bldin3 + c.getInt(0);
Log.d("bb",bldin3+"valuein");
Log.d("bb",c.getString(3));
}
if (c.getInt(2) == 04)
bldin4 = bldin4 + c.getInt(0);
if (c.getInt(2) == 05)
bldin5 = bldin5 + c.getInt(0);
if (c.getInt(2) == 06)
bldin6 = bldin6 + c.getInt(0);
if (c.getInt(2) == 07)
bldin7 = bldin7 + c.getInt(0);
if (8 == c.getInt(2))
bldin8 = bldin8 + c.getInt(0);
if (c.getInt(2) == 9)
bldin9 = bldin9 + c.getInt(0);
if (c.getInt(2) == 10)
bldin10 = bldin10 + c.getInt(0);
if (c.getInt(2) == 11)
bldin11 = bldin11 + c.getInt(0);
if (c.getInt(2) == 12)
bldin12 = bldin12 + c.getInt(0);
}
if (c.getString(1).equals("Receiver")){
Log.d("bb",c.getInt(0)+"Ddd");
if (c.getInt(2) == 01)
bldout1 = bldout1 + c.getInt(0);
if (c.getInt(2) == 02){
bldout2 = bldout2 + c.getInt(0);
Log.d("bb",bldout2+"valueoutfeb");
}
if (c.getInt(2) == 03){
bldout3 = bldout3 + c.getInt(0);
Log.d("bb",bldout3+"valueout");
Log.d("bb",c.getString(3));
}
if (c.getInt(2) == 04)
bldout4 = bldout4 + c.getInt(0);
if (c.getInt(2) == 05)
bldout5 = bldout5 + c.getInt(0);
if (c.getInt(2) == 06)
bldout6 = bldout6 + c.getInt(0);
if (c.getInt(2) == 07)
bldout7 = bldout7 + c.getInt(0);
if (8 == c.getInt(2))
bldout8 = bldout8 + c.getInt(0);
if (c.getInt(2) == 9)
bldout9 = bldout9 + c.getInt(0);
if (c.getInt(2) == 10)
bldout10 = bldout10 + c.getInt(0);
if (c.getInt(2) == 11)
bldout11 = bldout11 + c.getInt(0);
if (c.getInt(2) == 12)
bldout12 = bldout12 + c.getInt(0);
}
c.moveToNext();
}
}
bldqtyin[11]=Integer.toString(bldin12);
bldqtyin[10]=Integer.toString(bldin11);
bldqtyin[9]=Integer.toString(bldin10);
bldqtyin[8]=Integer.toString(bldin9);
bldqtyin[7]=Integer.toString(bldin8);
bldqtyin[6]=Integer.toString(bldin7);
bldqtyin[5]=Integer.toString(bldin6);
bldqtyin[4]=Integer.toString(bldin5);
bldqtyin[3]=Integer.toString(bldin4);
bldqtyin[2]=Integer.toString(bldin3);
bldqtyin[1]=Integer.toString(bldin2);
bldqtyin[0]=Integer.toString(bldin1);
Calendar calender = Calendar.getInstance();
SimpleDateFormat df=new SimpleDateFormat("MMMM");
String currentDate = df.format(calender.getTime());
String current[] = currentDate.split("-");
String currentMonth= current[0];
try {
calender.setTime(df.parse(currentMonth));
for(int i=0;i<12;i++){
String monthname=df.format(calender.getTime());
month[i]=monthname;
calender.add(Calendar.MONTH,-1);
}
} catch (ParseException e) {
e.printStackTrace();
}
bldqtyout[11]=Integer.toString(bldout12);
bldqtyout[10]=Integer.toString(bldout11);
bldqtyout[9]=Integer.toString(bldout10);
bldqtyout[8]=Integer.toString(bldout9);
bldqtyout[7]=Integer.toString(bldout8);
bldqtyout[6]=Integer.toString(bldout7);
bldqtyout[5]=Integer.toString(bldout6);
bldqtyout[4]=Integer.toString(bldout5);
bldqtyout[3]=Integer.toString(bldout4);
bldqtyout[2]=Integer.toString(bldout3);
bldqtyout[1]=Integer.toString(bldout2);
bldqtyout[0]=Integer.toString(bldout1);
for (int i=0;i<12;i++){
Log.d("bb",bldqtyin[i]);
Log.d("bb",bldqtyout[i]);
Log.d("bb",month[i]+"hee");
}
Report r = null;
for(String trace:month){
Log.d("bb",trace+"kk");
if (trace.equals("January")){
Log.d("bb",trace+"hkj");
r=new Report(trace,down,bldqtyin[0],up,bldqtyout[0]);
}
if (trace.equals("February")){
Log.d("bb",trace+"jii");
r=new Report(trace,down,bldqtyin[1],up,bldqtyout[1]);
}
if (trace.equals("March")){
Log.d("bb",trace+"lk");
r=new Report(trace,down,bldqtyin[2],up,bldqtyout[2]);
}
if (trace.equals("April")){
r=new Report(trace,down,bldqtyin[3],up,bldqtyout[3]);
}
if (trace.equals("May")){
r=new Report(trace,down,bldqtyin[4],up,bldqtyout[4]);
}
if (trace.equals("June")){
r=new Report(trace,down,bldqtyin[5],up,bldqtyout[5]);
}
if (trace.equals("July")){
r=new Report(trace,down,bldqtyin[6],up,bldqtyout[6]);
}
if (trace.equals("August")){
r=new Report(trace,down,bldqtyin[7],up,bldqtyout[7]);
}
if (trace.equals("September")){
r=new Report(trace,down,bldqtyin[8],up,bldqtyout[8]);
}
if (trace.equals("October")){
r=new Report(trace,down,bldqtyin[9],up,bldqtyout[9]);
}
if (trace.equals("November")){
r=new Report(trace,down,bldqtyin[10],up,bldqtyout[10]);
}
if (trace.equals("December")){
r=new Report(trace,down,bldqtyin[11],up,bldqtyout[11]);
}
ra.add(r);
}
listview.setAdapter(ra);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView month = (TextView) view.findViewById(R.id.tv_month);
//Toast.makeText(getContext(),month.getText().toString(), Toast.LENGTH_SHORT).show();
Intent intent=new Intent(getActivity(),BloodReportDetails.class);
intent.putExtra("Month",month.getText().toString());
startActivity(intent);
}
});
// Inflate the layout for this fragment
return view;
}
private Cursor getReport1(){
String Query1 = " Select t."+ BloodBankContract.TransactionEntry.COLUMN_QUANTITY
+ " , t." + BloodBankContract.TransactionEntry.COLUMN_TYPE +
" , d." + BloodBankContract.DateEntry.COLUMN_MONTH +" , t." +BloodBankContract.TransactionEntry.COLUMN_NAME+
" , d."+BloodBankContract.DateEntry._ID
+ " from " + BloodBankContract.TransactionEntry.TABLE_NAME +" t INNER JOIN " +
BloodBankContract.DateEntry.TABLE_NAME + " d ON d." + BloodBankContract.DateEntry._ID
+" = t." + BloodBankContract.TransactionEntry.COLUMN_DATE_KEY +" ; ";
Cursor c=mdb.rawQuery(Query1,null);
return c;
}
}
| UTF-8 | Java | 10,962 | java | StatisticsReportsFragment.java | Java | [] | null | [] | package com.example.android.bloodbankapp.statistics;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.bloodbankapp.data.BloodBankContract;
import com.example.android.bloodbankapp.R;
import com.example.android.bloodbankapp.data.BloodBankDbHelper;
import com.example.android.bloodbankapp.statistics.BloodReportDetails;
import com.example.android.bloodbankapp.statistics.Report;
import com.example.android.bloodbankapp.statistics.ReportAdapter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class StatisticsReportsFragment extends Fragment {
ListView listview;
int up=R.drawable.up;
int down= R.drawable.down;
SQLiteDatabase mdb;
//String month[]={"December","January","February","MArch"};
//String bldqtyin[]={"123 units","578 units","456 units","698 units"};
//String bldqtyout[]={"123 units","578 units","456 units","698 units"};
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_statistics_reports, container, false);
listview= (ListView) view.findViewById(R.id.lv_report);
ReportAdapter ra=new ReportAdapter(getContext(),R.layout.row_layout);
BloodBankDbHelper dbh=new BloodBankDbHelper(getActivity());
mdb = dbh.getWritableDatabase();
Cursor c = getReport1();
c.moveToFirst();
int bldin1 =0,bldin2 =0,bldin3 =0,bldin4 =0,bldin5 =0,bldin6 =0,bldin7 =0,bldin8 =0,bldin9 =0,bldin10 =0,bldin11 =0,bldin12 =0;
int bldout1 =0,bldout2 =0,bldout3 =0,bldout4 =0,bldout5 =0,bldout6 =0,bldout7 =0,bldout8 =0,bldout9 =0,bldout10 =0,bldout11 =0,bldout12 =0;
for (int i=0;i<c.getCount();i++){
Log.d("bb",c.getInt(0)+"quant");
Log.d("bb",c.getString(1)+"type");
Log.d("bb",c.getString(2)+"month");
Log.d("bb",c.getString(3)+"name");
Log.d("bb,",c.getInt(4)+"id");
c.moveToNext();
}
c.moveToFirst();
String bldqtyin[]=new String[12];
String bldqtyout[]=new String[12];
String month[]=new String[12];
Log.d("bb",c.getCount()+"fd");
if ((c.getCount())>0 && c != null){
for (int i = 0; i < c.getCount(); i++) {
if (c.getString(1).equals("Donor")) {
Log.d("bb",c.getInt(0)+"Ddd");
if (c.getInt(2) == 01)
bldin1 = bldin1 + c.getInt(0);
if (c.getInt(2) == 02){
bldin2 = bldin2 + c.getInt(0);
Log.d("bb",bldin2+"valueinfeb");
}
if (c.getInt(2) == 03){
bldin3 = bldin3 + c.getInt(0);
Log.d("bb",bldin3+"valuein");
Log.d("bb",c.getString(3));
}
if (c.getInt(2) == 04)
bldin4 = bldin4 + c.getInt(0);
if (c.getInt(2) == 05)
bldin5 = bldin5 + c.getInt(0);
if (c.getInt(2) == 06)
bldin6 = bldin6 + c.getInt(0);
if (c.getInt(2) == 07)
bldin7 = bldin7 + c.getInt(0);
if (8 == c.getInt(2))
bldin8 = bldin8 + c.getInt(0);
if (c.getInt(2) == 9)
bldin9 = bldin9 + c.getInt(0);
if (c.getInt(2) == 10)
bldin10 = bldin10 + c.getInt(0);
if (c.getInt(2) == 11)
bldin11 = bldin11 + c.getInt(0);
if (c.getInt(2) == 12)
bldin12 = bldin12 + c.getInt(0);
}
if (c.getString(1).equals("Receiver")){
Log.d("bb",c.getInt(0)+"Ddd");
if (c.getInt(2) == 01)
bldout1 = bldout1 + c.getInt(0);
if (c.getInt(2) == 02){
bldout2 = bldout2 + c.getInt(0);
Log.d("bb",bldout2+"valueoutfeb");
}
if (c.getInt(2) == 03){
bldout3 = bldout3 + c.getInt(0);
Log.d("bb",bldout3+"valueout");
Log.d("bb",c.getString(3));
}
if (c.getInt(2) == 04)
bldout4 = bldout4 + c.getInt(0);
if (c.getInt(2) == 05)
bldout5 = bldout5 + c.getInt(0);
if (c.getInt(2) == 06)
bldout6 = bldout6 + c.getInt(0);
if (c.getInt(2) == 07)
bldout7 = bldout7 + c.getInt(0);
if (8 == c.getInt(2))
bldout8 = bldout8 + c.getInt(0);
if (c.getInt(2) == 9)
bldout9 = bldout9 + c.getInt(0);
if (c.getInt(2) == 10)
bldout10 = bldout10 + c.getInt(0);
if (c.getInt(2) == 11)
bldout11 = bldout11 + c.getInt(0);
if (c.getInt(2) == 12)
bldout12 = bldout12 + c.getInt(0);
}
c.moveToNext();
}
}
bldqtyin[11]=Integer.toString(bldin12);
bldqtyin[10]=Integer.toString(bldin11);
bldqtyin[9]=Integer.toString(bldin10);
bldqtyin[8]=Integer.toString(bldin9);
bldqtyin[7]=Integer.toString(bldin8);
bldqtyin[6]=Integer.toString(bldin7);
bldqtyin[5]=Integer.toString(bldin6);
bldqtyin[4]=Integer.toString(bldin5);
bldqtyin[3]=Integer.toString(bldin4);
bldqtyin[2]=Integer.toString(bldin3);
bldqtyin[1]=Integer.toString(bldin2);
bldqtyin[0]=Integer.toString(bldin1);
Calendar calender = Calendar.getInstance();
SimpleDateFormat df=new SimpleDateFormat("MMMM");
String currentDate = df.format(calender.getTime());
String current[] = currentDate.split("-");
String currentMonth= current[0];
try {
calender.setTime(df.parse(currentMonth));
for(int i=0;i<12;i++){
String monthname=df.format(calender.getTime());
month[i]=monthname;
calender.add(Calendar.MONTH,-1);
}
} catch (ParseException e) {
e.printStackTrace();
}
bldqtyout[11]=Integer.toString(bldout12);
bldqtyout[10]=Integer.toString(bldout11);
bldqtyout[9]=Integer.toString(bldout10);
bldqtyout[8]=Integer.toString(bldout9);
bldqtyout[7]=Integer.toString(bldout8);
bldqtyout[6]=Integer.toString(bldout7);
bldqtyout[5]=Integer.toString(bldout6);
bldqtyout[4]=Integer.toString(bldout5);
bldqtyout[3]=Integer.toString(bldout4);
bldqtyout[2]=Integer.toString(bldout3);
bldqtyout[1]=Integer.toString(bldout2);
bldqtyout[0]=Integer.toString(bldout1);
for (int i=0;i<12;i++){
Log.d("bb",bldqtyin[i]);
Log.d("bb",bldqtyout[i]);
Log.d("bb",month[i]+"hee");
}
Report r = null;
for(String trace:month){
Log.d("bb",trace+"kk");
if (trace.equals("January")){
Log.d("bb",trace+"hkj");
r=new Report(trace,down,bldqtyin[0],up,bldqtyout[0]);
}
if (trace.equals("February")){
Log.d("bb",trace+"jii");
r=new Report(trace,down,bldqtyin[1],up,bldqtyout[1]);
}
if (trace.equals("March")){
Log.d("bb",trace+"lk");
r=new Report(trace,down,bldqtyin[2],up,bldqtyout[2]);
}
if (trace.equals("April")){
r=new Report(trace,down,bldqtyin[3],up,bldqtyout[3]);
}
if (trace.equals("May")){
r=new Report(trace,down,bldqtyin[4],up,bldqtyout[4]);
}
if (trace.equals("June")){
r=new Report(trace,down,bldqtyin[5],up,bldqtyout[5]);
}
if (trace.equals("July")){
r=new Report(trace,down,bldqtyin[6],up,bldqtyout[6]);
}
if (trace.equals("August")){
r=new Report(trace,down,bldqtyin[7],up,bldqtyout[7]);
}
if (trace.equals("September")){
r=new Report(trace,down,bldqtyin[8],up,bldqtyout[8]);
}
if (trace.equals("October")){
r=new Report(trace,down,bldqtyin[9],up,bldqtyout[9]);
}
if (trace.equals("November")){
r=new Report(trace,down,bldqtyin[10],up,bldqtyout[10]);
}
if (trace.equals("December")){
r=new Report(trace,down,bldqtyin[11],up,bldqtyout[11]);
}
ra.add(r);
}
listview.setAdapter(ra);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView month = (TextView) view.findViewById(R.id.tv_month);
//Toast.makeText(getContext(),month.getText().toString(), Toast.LENGTH_SHORT).show();
Intent intent=new Intent(getActivity(),BloodReportDetails.class);
intent.putExtra("Month",month.getText().toString());
startActivity(intent);
}
});
// Inflate the layout for this fragment
return view;
}
private Cursor getReport1(){
String Query1 = " Select t."+ BloodBankContract.TransactionEntry.COLUMN_QUANTITY
+ " , t." + BloodBankContract.TransactionEntry.COLUMN_TYPE +
" , d." + BloodBankContract.DateEntry.COLUMN_MONTH +" , t." +BloodBankContract.TransactionEntry.COLUMN_NAME+
" , d."+BloodBankContract.DateEntry._ID
+ " from " + BloodBankContract.TransactionEntry.TABLE_NAME +" t INNER JOIN " +
BloodBankContract.DateEntry.TABLE_NAME + " d ON d." + BloodBankContract.DateEntry._ID
+" = t." + BloodBankContract.TransactionEntry.COLUMN_DATE_KEY +" ; ";
Cursor c=mdb.rawQuery(Query1,null);
return c;
}
}
| 10,962 | 0.521255 | 0.489053 | 279 | 38.286739 | 25.713688 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.992832 | false | false | 0 |
cb6aaf134893fb7a905c73a5965db5a7b51c08df | 12,850,542,210,203 | 430d83a4196bb183f8c6cd86de4988022315c4f1 | /src/main/java/ua/training/controller/command/admin/UpdateUserGet.java | 62fafe708b3ff7c8fa2d027bb036d0837f628f5d | [] | no_license | yaruha1990/cashRegisterSystem | https://github.com/yaruha1990/cashRegisterSystem | a2badb28aa42841b2d9aaee10811ef0fd8ed199a | 5e6e0ae2599b1b8c3a0cad1507e2a84e53bdac56 | refs/heads/master | 2020-03-26T16:43:40.535000 | 2018-09-01T07:39:57 | 2018-09-01T07:39:57 | 145,112,598 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.training.controller.command.admin;
import ua.training.controller.command.Command;
import ua.training.model.dao.DaoFactory;
import ua.training.model.dao.UserDao;
import ua.training.model.entity.User;
import ua.training.model.utils.LocaleUtil;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
public class UpdateUserGet implements Command {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserDao userDao = DaoFactory.getInstance().getUserDao();
LocaleUtil localeUtilURL = new LocaleUtil("url");
User user = userDao.findUserById(Integer.valueOf(req.getParameter("id")));
req.setAttribute("user",user);
return localeUtilURL.getText("updateUser");
}
}
| UTF-8 | Java | 926 | java | UpdateUserGet.java | Java | [] | null | [] | package ua.training.controller.command.admin;
import ua.training.controller.command.Command;
import ua.training.model.dao.DaoFactory;
import ua.training.model.dao.UserDao;
import ua.training.model.entity.User;
import ua.training.model.utils.LocaleUtil;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
public class UpdateUserGet implements Command {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserDao userDao = DaoFactory.getInstance().getUserDao();
LocaleUtil localeUtilURL = new LocaleUtil("url");
User user = userDao.findUserById(Integer.valueOf(req.getParameter("id")));
req.setAttribute("user",user);
return localeUtilURL.getText("updateUser");
}
}
| 926 | 0.775378 | 0.775378 | 24 | 37.583332 | 26.536009 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.791667 | false | false | 0 |
0b2f373be3fdf1aecb6a78d10af5c5b692dec5ab | 463,856,524,303 | e4066ce5d2d2338536503e27c36bec10af23dbac | /Validation UAT/workspace/Validation/src/org/gosh/validation/general/MiscValidationTransformer.java | ded7da98c5b1124ee93c859a70e2eb53a29deab0 | [] | no_license | stangg/Anthony-Test | https://github.com/stangg/Anthony-Test | 544ac50898a8a516fa3891959027dddeb73bee5f | a209e404f2251fa8bf5888e1db598449b26c162f | refs/heads/master | 2021-01-25T04:02:36.659000 | 2012-04-03T16:15:55 | 2012-04-03T16:15:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.gosh.validation.general;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.gosh.re.dmcash.bindings.GOSHCC;
import org.gosh.re.dmcash.bindings.GOSHCC.DonorCplxType;
import org.gosh.re.dmcash.bindings.GOSHCC.Relationship;
import org.gosh.re.dmcash.bindings.GOSHCC.Tribute;
import org.gosh.re.dmcash.bindings.GOSHCC.DonorCplxType.ConsCodes;
import org.gosh.re.dmcash.bindings.GOSHCC.DonorCplxType.DonationDetails.DirectDebitDonationCplxType;
import org.gosh.validation.general.error.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.core.Message;
/**
* This does the following, based on original email sent by Dez to team:
* <ul>
* <li>Check that constituent code is consistent.
* <li>Direct debit details, check ids, post status, payment type.
* <li>Installment freq vs no. of installments.
* <li>Schedules, const bank id, and gift status.
* <li>Check countries/counties are in the list in RE.
* </ul>
*
* This also removes "test" records. These are identified as records
* that have a String property that contains the word "test".
*
* This also, also (late addition as a result of extra schema requirement)
* checks the bank details are not blank if the dd is not an upgrade.
*/
public class MiscValidationTransformer {
private Reporter reporter;
@Transformer
public Message<GOSHCC> transform(Message<GOSHCC> message) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
GOSHCC payload = message.getPayload();
Map<DonorCplxType, String> errors = new HashMap<DonorCplxType, String>();
Map<DonorCplxType, DirectDebitDonationCplxType> dds = new HashMap<DonorCplxType, DirectDebitDonationCplxType>();
List<DonorCplxType> donorCplxTypes = payload.getDonorCplxType();
List<DonorCplxType> toRemove = new ArrayList<DonorCplxType>();
String previousConsCode = null;
for (DonorCplxType donorCplxType : donorCplxTypes) {
// Netbanx means web cash donations
if (!"Netbanx".equals(payload.getSupplierID())){
for (ConsCodes consCodes : donorCplxType.getConsCodes()){
if (previousConsCode == null){
previousConsCode = consCodes.getCode();
} else if (!consCodes.getCode().equals(previousConsCode)){
addTo(errors, donorCplxType, "Not all cons codes are the same.");
}
}
}
if (donorCplxType.getDonationDetails() == null && isNotExclusivelyAnHonor(donorCplxType, payload)
&& isNotAWebCashInMemoryRecord(donorCplxType, payload)){
// it is a prospect, so this was requested:
if (addressIsBlank(donorCplxType)){
addTo(errors, donorCplxType, "Some part of the address is blank and shouldn't be");
}
} else if (Boolean.TRUE.equals(donorCplxType.isPrimaryAddress())){
if (addressIsBlank(donorCplxType)){
addTo(errors, donorCplxType, "Some part of the address is blank and shouldn't be");
}
}
if (donorCplxType.getDonationDetails() != null && donorCplxType.getDonationDetails().getDirectDebitDonationCplxType()!=null){
dds.put(donorCplxType, donorCplxType.getDonationDetails().getDirectDebitDonationCplxType());
}
if (StringUtils.containsIgnoreCase(donorCplxType.getFirstName()+donorCplxType.getMiddleName()+donorCplxType.getLastName(),"test")){
toRemove.add(donorCplxType);
}
}
donorCplxTypes.removeAll(toRemove);
for (Entry<DonorCplxType, DirectDebitDonationCplxType> dd : dds.entrySet()) {
if (!"Direct Debit".equals(dd.getValue().getPaymentType())){
addTo(errors, dd.getKey(), "Not all DD's have Direct Debit as payment type.");
}
if (!"Not Posted".equals(dd.getValue().getPostStatus())){
addTo(errors, dd.getKey(), "Not every post status is Not Posted.");
}
if (!"Specific Day".equals(dd.getValue().getScheduleMonthlyType())){
addTo(errors, dd.getKey(), "ScheduleMonthlyType is not Specific Day");
}
if (dd.getValue().getNoOfInstalments()!= null){
switch (dd.getValue().getNoOfInstalments().intValue()) {
case 10:
case 3:
if (!"Annually".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
case 20:
case 6:
if (!"Semi-Annually".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
case 40:
case 12:
if (!"Quarterly".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
case 120:
case 36:
if (!"Monthly".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
case 60:
case 18:
if (!"Bimonthly".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
default:
addTo(errors, dd.getKey(), "Number of installments not set up properly.");
break;
}
}
}
if (!errors.isEmpty()){
return reporter.log(message, errors);
}
return message;
}
private boolean isNotAWebCashInMemoryRecord(DonorCplxType donor, GOSHCC payload) {
for (Relationship relationship : payload.getRelationship()) {
if (StringUtils.equals(relationship.getRelatedSupplierDonorID(), donor.getSupplierDonorID()) &&
isDeceased(donor) && hasConsCodeOfMemo(donor)){
return false;
}
}
return true;
}
private boolean isDeceased(DonorCplxType donor) {
return donor.getDeceasedDate() != null;
}
private boolean hasConsCodeOfMemo(DonorCplxType donor) {
List<ConsCodes> consCodes = donor.getConsCodes();
for (ConsCodes consCode : consCodes) {
if (StringUtils.equals(consCode.getCode(),"MEMO")){
return true;
}
}
return false;
}
private void addTo(Map<DonorCplxType, String> errors, DonorCplxType donorCplxType, String string) {
String prev = errors.get(donorCplxType);
if (StringUtils.isBlank(prev)){
errors.put(donorCplxType, string);
} else {
prev += ("; " + string);
errors.put(donorCplxType, prev);
}
}
private boolean isNotExclusivelyAnHonor(DonorCplxType donor, GOSHCC payload) {
boolean donorIsAnHonor = false;
boolean donorIsAnAcknoledgee = false;
for (Tribute tribute : payload.getTribute()) {
if (StringUtils.equals(donor.getSupplierDonorID(),tribute.getHonerSupplierDonorID())){
donorIsAnHonor = true;
}
if (tribute.getAcknowledgeeSupplierDonorID().contains(donor.getSupplierDonorID())){
donorIsAnAcknoledgee = true;
}
}
return donorIsAnAcknoledgee || !donorIsAnHonor;
}
private boolean addressIsBlank(DonorCplxType donorCplxType) {
boolean addressIsBlank = false;
if (donorCplxType.getAddress() == null || donorCplxType.getAddress().getAddressLine().isEmpty()){
addressIsBlank = true;
} else {
int count = 0;
for (String line : donorCplxType.getAddress().getAddressLine()) {
if (StringUtils.isBlank(line)){
count++;
}
}
if (count == donorCplxType.getAddress().getAddressLine().size()){
addressIsBlank = true;
}
}
if (StringUtils.isBlank(donorCplxType.getCity())||StringUtils.isBlank(donorCplxType.getPostCode())){
addressIsBlank = true;
}
return addressIsBlank;
}
@Autowired
public void setReporter(Reporter reporter) {
this.reporter = reporter;
}
}
| UTF-8 | Java | 7,949 | java | MiscValidationTransformer.java | Java | [] | null | [] | package org.gosh.validation.general;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.gosh.re.dmcash.bindings.GOSHCC;
import org.gosh.re.dmcash.bindings.GOSHCC.DonorCplxType;
import org.gosh.re.dmcash.bindings.GOSHCC.Relationship;
import org.gosh.re.dmcash.bindings.GOSHCC.Tribute;
import org.gosh.re.dmcash.bindings.GOSHCC.DonorCplxType.ConsCodes;
import org.gosh.re.dmcash.bindings.GOSHCC.DonorCplxType.DonationDetails.DirectDebitDonationCplxType;
import org.gosh.validation.general.error.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.core.Message;
/**
* This does the following, based on original email sent by Dez to team:
* <ul>
* <li>Check that constituent code is consistent.
* <li>Direct debit details, check ids, post status, payment type.
* <li>Installment freq vs no. of installments.
* <li>Schedules, const bank id, and gift status.
* <li>Check countries/counties are in the list in RE.
* </ul>
*
* This also removes "test" records. These are identified as records
* that have a String property that contains the word "test".
*
* This also, also (late addition as a result of extra schema requirement)
* checks the bank details are not blank if the dd is not an upgrade.
*/
public class MiscValidationTransformer {
private Reporter reporter;
@Transformer
public Message<GOSHCC> transform(Message<GOSHCC> message) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
GOSHCC payload = message.getPayload();
Map<DonorCplxType, String> errors = new HashMap<DonorCplxType, String>();
Map<DonorCplxType, DirectDebitDonationCplxType> dds = new HashMap<DonorCplxType, DirectDebitDonationCplxType>();
List<DonorCplxType> donorCplxTypes = payload.getDonorCplxType();
List<DonorCplxType> toRemove = new ArrayList<DonorCplxType>();
String previousConsCode = null;
for (DonorCplxType donorCplxType : donorCplxTypes) {
// Netbanx means web cash donations
if (!"Netbanx".equals(payload.getSupplierID())){
for (ConsCodes consCodes : donorCplxType.getConsCodes()){
if (previousConsCode == null){
previousConsCode = consCodes.getCode();
} else if (!consCodes.getCode().equals(previousConsCode)){
addTo(errors, donorCplxType, "Not all cons codes are the same.");
}
}
}
if (donorCplxType.getDonationDetails() == null && isNotExclusivelyAnHonor(donorCplxType, payload)
&& isNotAWebCashInMemoryRecord(donorCplxType, payload)){
// it is a prospect, so this was requested:
if (addressIsBlank(donorCplxType)){
addTo(errors, donorCplxType, "Some part of the address is blank and shouldn't be");
}
} else if (Boolean.TRUE.equals(donorCplxType.isPrimaryAddress())){
if (addressIsBlank(donorCplxType)){
addTo(errors, donorCplxType, "Some part of the address is blank and shouldn't be");
}
}
if (donorCplxType.getDonationDetails() != null && donorCplxType.getDonationDetails().getDirectDebitDonationCplxType()!=null){
dds.put(donorCplxType, donorCplxType.getDonationDetails().getDirectDebitDonationCplxType());
}
if (StringUtils.containsIgnoreCase(donorCplxType.getFirstName()+donorCplxType.getMiddleName()+donorCplxType.getLastName(),"test")){
toRemove.add(donorCplxType);
}
}
donorCplxTypes.removeAll(toRemove);
for (Entry<DonorCplxType, DirectDebitDonationCplxType> dd : dds.entrySet()) {
if (!"Direct Debit".equals(dd.getValue().getPaymentType())){
addTo(errors, dd.getKey(), "Not all DD's have Direct Debit as payment type.");
}
if (!"Not Posted".equals(dd.getValue().getPostStatus())){
addTo(errors, dd.getKey(), "Not every post status is Not Posted.");
}
if (!"Specific Day".equals(dd.getValue().getScheduleMonthlyType())){
addTo(errors, dd.getKey(), "ScheduleMonthlyType is not Specific Day");
}
if (dd.getValue().getNoOfInstalments()!= null){
switch (dd.getValue().getNoOfInstalments().intValue()) {
case 10:
case 3:
if (!"Annually".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
case 20:
case 6:
if (!"Semi-Annually".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
case 40:
case 12:
if (!"Quarterly".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
case 120:
case 36:
if (!"Monthly".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
case 60:
case 18:
if (!"Bimonthly".equals(dd.getValue().getInstallmentFreq())){addTo(errors, dd.getKey(), "Number of installments is not always set up properly against InstallmentFreq.");}
break;
default:
addTo(errors, dd.getKey(), "Number of installments not set up properly.");
break;
}
}
}
if (!errors.isEmpty()){
return reporter.log(message, errors);
}
return message;
}
private boolean isNotAWebCashInMemoryRecord(DonorCplxType donor, GOSHCC payload) {
for (Relationship relationship : payload.getRelationship()) {
if (StringUtils.equals(relationship.getRelatedSupplierDonorID(), donor.getSupplierDonorID()) &&
isDeceased(donor) && hasConsCodeOfMemo(donor)){
return false;
}
}
return true;
}
private boolean isDeceased(DonorCplxType donor) {
return donor.getDeceasedDate() != null;
}
private boolean hasConsCodeOfMemo(DonorCplxType donor) {
List<ConsCodes> consCodes = donor.getConsCodes();
for (ConsCodes consCode : consCodes) {
if (StringUtils.equals(consCode.getCode(),"MEMO")){
return true;
}
}
return false;
}
private void addTo(Map<DonorCplxType, String> errors, DonorCplxType donorCplxType, String string) {
String prev = errors.get(donorCplxType);
if (StringUtils.isBlank(prev)){
errors.put(donorCplxType, string);
} else {
prev += ("; " + string);
errors.put(donorCplxType, prev);
}
}
private boolean isNotExclusivelyAnHonor(DonorCplxType donor, GOSHCC payload) {
boolean donorIsAnHonor = false;
boolean donorIsAnAcknoledgee = false;
for (Tribute tribute : payload.getTribute()) {
if (StringUtils.equals(donor.getSupplierDonorID(),tribute.getHonerSupplierDonorID())){
donorIsAnHonor = true;
}
if (tribute.getAcknowledgeeSupplierDonorID().contains(donor.getSupplierDonorID())){
donorIsAnAcknoledgee = true;
}
}
return donorIsAnAcknoledgee || !donorIsAnHonor;
}
private boolean addressIsBlank(DonorCplxType donorCplxType) {
boolean addressIsBlank = false;
if (donorCplxType.getAddress() == null || donorCplxType.getAddress().getAddressLine().isEmpty()){
addressIsBlank = true;
} else {
int count = 0;
for (String line : donorCplxType.getAddress().getAddressLine()) {
if (StringUtils.isBlank(line)){
count++;
}
}
if (count == donorCplxType.getAddress().getAddressLine().size()){
addressIsBlank = true;
}
}
if (StringUtils.isBlank(donorCplxType.getCity())||StringUtils.isBlank(donorCplxType.getPostCode())){
addressIsBlank = true;
}
return addressIsBlank;
}
@Autowired
public void setReporter(Reporter reporter) {
this.reporter = reporter;
}
}
| 7,949 | 0.710026 | 0.70751 | 206 | 36.927185 | 38.28698 | 180 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.038835 | false | false | 0 |
3515974f62dff064bf1f4237d8d594c9755610bd | 2,070,174,238,806 | e812009c172078ec282e6ca9a3f57da9b5220e61 | /provider/src/main/java/com/lichun/dubbo/provider/service/DemoServiceImpl.java | e6043f9d2530b25046956932873bb5a1d3e10e45 | [] | no_license | 7doggy/springboot-dubbo | https://github.com/7doggy/springboot-dubbo | f17b1e30dd476204be1b2f32074bb0e0b9023313 | ec230d578015e89c9e39a730129ace319f3597dd | refs/heads/master | 2020-04-14T19:30:38.155000 | 2019-01-04T05:03:32 | 2019-01-04T05:03:32 | 164,060,430 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lichun.dubbo.provider.service;
import com.alibaba.dubbo.config.annotation.Service;
import com.lichun.dubbo.api.DemoService;
import org.springframework.stereotype.Component;
/**
* Give a provider to make a service implements api interface.
*/
@Service(interfaceClass = DemoService.class)
@Component
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello " + name;
}
}
| UTF-8 | Java | 454 | java | DemoServiceImpl.java | Java | [] | null | [] | package com.lichun.dubbo.provider.service;
import com.alibaba.dubbo.config.annotation.Service;
import com.lichun.dubbo.api.DemoService;
import org.springframework.stereotype.Component;
/**
* Give a provider to make a service implements api interface.
*/
@Service(interfaceClass = DemoService.class)
@Component
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello " + name;
}
}
| 454 | 0.77533 | 0.77533 | 17 | 25.705883 | 21.859888 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 0 |
7d61dbefb5c1009f08e6ca49f9822b54805acab0 | 21,096,879,427,084 | 549fbe9b69e8f798d88d2adbd83245318925dde7 | /src/DoTutorial/com/loldie/bots/dotutorial/branches/IsInRatPitBranch.java | 838d046d3f3fc9b1ded0a83463c3d5dcdbf27da7 | [] | no_license | N3uR0TiCV0iD/RuneMate-Bots | https://github.com/N3uR0TiCV0iD/RuneMate-Bots | 61a4a86d239201f45402c9bf42fa80a6bdb8a056 | ea0112583031eaade7ddb56a4f0516a1d318ac36 | refs/heads/master | 2023-08-24T15:12:26.455000 | 2023-08-12T14:08:57 | 2023-08-12T14:08:57 | 95,848,413 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.loldie.bots.dotutorial.branches;
import com.loldie.bots.common.logic.ILogicNode;
import com.loldie.bots.common.logic.LogicAreaBranch;
import com.runemate.game.api.hybrid.location.Area;
import com.runemate.game.api.hybrid.location.Coordinate;
public class IsInRatPitBranch extends LogicAreaBranch
{
public static final Coordinate PIT_POS = new Coordinate(3103, 9518, 0);
public static final Area PIT_AREA = new Area.Circular(PIT_POS, 7);
public IsInRatPitBranch(ILogicNode truePath, ILogicNode falsePath)
{
super(PIT_AREA, truePath, falsePath);
}
}
| UTF-8 | Java | 568 | java | IsInRatPitBranch.java | Java | [] | null | [] | package com.loldie.bots.dotutorial.branches;
import com.loldie.bots.common.logic.ILogicNode;
import com.loldie.bots.common.logic.LogicAreaBranch;
import com.runemate.game.api.hybrid.location.Area;
import com.runemate.game.api.hybrid.location.Coordinate;
public class IsInRatPitBranch extends LogicAreaBranch
{
public static final Coordinate PIT_POS = new Coordinate(3103, 9518, 0);
public static final Area PIT_AREA = new Area.Circular(PIT_POS, 7);
public IsInRatPitBranch(ILogicNode truePath, ILogicNode falsePath)
{
super(PIT_AREA, truePath, falsePath);
}
}
| 568 | 0.801056 | 0.783451 | 14 | 39.57143 | 25.594961 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 0 |
58bbabcc4c4a2785aa5151a9cc5be0cb40a735ca | 17,772,574,705,508 | 76c72bad91283a4b43934431cec197266ef0dc2b | /studyredis/src/main/java/com/jin/eledger/pojo/ReponseResult.java | 015e22526042eb8bf8d67ebe1d5f6b821b1e6495 | [] | no_license | study-day/study-demo | https://github.com/study-day/study-demo | c50a94b9373a19bf2e6b1d025f273acfee0126ac | 5be9a127e669190eb73f6d01d59a62a6e3924b24 | refs/heads/master | 2023-02-27T09:54:38.907000 | 2021-02-06T09:18:11 | 2021-02-06T09:18:11 | 289,409,493 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jin.eledger.pojo;
public class ReponseResult {
private byte code;
private String msg;
public byte getCode() {
return code;
}
public void setCode(byte code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
| UTF-8 | Java | 305 | java | ReponseResult.java | Java | [] | null | [] | package com.jin.eledger.pojo;
public class ReponseResult {
private byte code;
private String msg;
public byte getCode() {
return code;
}
public void setCode(byte code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
| 305 | 0.672131 | 0.672131 | 20 | 14.25 | 11.699893 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.35 | false | false | 0 |
d71159c909a036223f9b2ee23385ef21a06c773f | 32,392,643,378,711 | 01480d11e0f811c4ea5f7eb9a9032a3af9933838 | /src/main/java/br/com/flightslist/domain/pilot/Pilot.java | bd51ed8ffa68eb715000438979118ee2f02f66d1 | [] | no_license | dvdpansardis/Flights_List | https://github.com/dvdpansardis/Flights_List | 8723418c01ee86500b7442d8c78cde0c817c757f | 78b98539d6eabd9f94c56a8a5eb8d4587c06eb41 | refs/heads/master | 2021-01-06T20:39:31.500000 | 2017-08-07T18:48:01 | 2017-08-07T18:48:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.flightslist.domain.pilot;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import br.com.flightslist.domain.flight.Flight;
import br.com.flightslist.domain.pilot.type.TypePilot;
/**
* This class represent of Pilot entity, using the patther DDD.
*
* @author David
* @version 1.0
*
*/
@Entity
@Table(name = "FL_PILOT")
public class Pilot {
@Id
@Column(name = "ID_PILOT")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "PILOT_NAME")
private String name;
@Enumerated(EnumType.STRING)
@Column(name = "TYPE_PILOT")
private TypePilot typePilot;
@ManyToMany(mappedBy = "pilots")
private Set<Flight> flights;
public Pilot() {
}
public Pilot(String name, TypePilot typePilot) {
this.name = name;
this.typePilot = typePilot;
}
public String getName() {
return this.name;
}
public TypePilot getTypePilot() {
return typePilot;
}
@Override
public String toString() {
return "[Name Pilot: " + this.name + "]";
}
}
| UTF-8 | Java | 1,293 | java | Pilot.java | Java | [
{
"context": "ilot entity, using the patther DDD.\n * \n * @author David\n * @version 1.0\n *\n */\n@Entity\n@Table(name = \"FL_",
"end": 576,
"score": 0.9995549321174622,
"start": 571,
"tag": "NAME",
"value": "David"
}
] | null | [] | package br.com.flightslist.domain.pilot;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import br.com.flightslist.domain.flight.Flight;
import br.com.flightslist.domain.pilot.type.TypePilot;
/**
* This class represent of Pilot entity, using the patther DDD.
*
* @author David
* @version 1.0
*
*/
@Entity
@Table(name = "FL_PILOT")
public class Pilot {
@Id
@Column(name = "ID_PILOT")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "PILOT_NAME")
private String name;
@Enumerated(EnumType.STRING)
@Column(name = "TYPE_PILOT")
private TypePilot typePilot;
@ManyToMany(mappedBy = "pilots")
private Set<Flight> flights;
public Pilot() {
}
public Pilot(String name, TypePilot typePilot) {
this.name = name;
this.typePilot = typePilot;
}
public String getName() {
return this.name;
}
public TypePilot getTypePilot() {
return typePilot;
}
@Override
public String toString() {
return "[Name Pilot: " + this.name + "]";
}
}
| 1,293 | 0.734725 | 0.733179 | 65 | 18.892307 | 16.862452 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.892308 | false | false | 0 |
146d9f4e15c44e593377338b9644afe892a9f4f4 | 10,788,957,848,111 | 5947b607314ec81a9c4d0534b5863c024fe39852 | /LinNei-Master/src/main/java/com/het/linnei/ui/activity/device/DevShareFindAty.java | e9533e171b7e50bea4c224cfb08f08f5a3ffcaac | [] | no_license | ColinFly/HeaterApp | https://github.com/ColinFly/HeaterApp | ea653cce00dae4481f4e8d41437a238d149ba79f | 60fad5be588448fd97140eee2828c8cb1dfb6ddf | refs/heads/master | 2017-12-03T23:44:13.793000 | 2016-05-30T02:23:05 | 2016-05-30T02:23:05 | 54,194,797 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.het.linnei.ui.activity.device;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.het.clife.business.biz.device.DeviceBindBiz;
import com.het.clife.business.biz.device.DeviceBiz;
import com.het.clife.constant.ParamContant;
import com.het.clife.model.user.UserModel;
import com.het.common.callback.ICallback;
import com.het.common.utils.StringUtils;
import com.het.comres.adapter.CommonAdapter;
import com.het.comres.adapter.MyViewHolder;
import com.het.comres.view.DefaultEditText;
import com.het.comres.view.dialog.PromptUtil;
import com.het.comres.widget.CommonTopBar;
import com.het.dlplug.sdk.model.DeviceModel;
import com.het.linnei.R;
import com.het.linnei.base.BaseActivity;
import com.het.linnei.event.DeviceEvent;
import com.het.linnei.event.UserEvent;
import com.het.linnei.manager.DeviceManager;
import com.het.linnei.manager.UserManager;
import com.het.linnei.share.ShareApi;
import com.het.linnei.share.ShareEvent;
import com.het.linnei.ui.activity.user.UserCenterActivity;
import com.het.linnei.util.HtmlTextUtils;
import com.het.linnei.util.TextHelper;
import java.util.ArrayList;
import java.util.List;
import butterknife.InjectView;
import butterknife.OnClick;
/**
* Created by colin on 15-10-30.
* 待分享设备界面
* 多设备页面可进入
* 单设备分享可进入
*/
public class DevShareFindAty extends BaseActivity {
public static final int SINGLE_SHARE = 1;
public static final int MULTI_SHARE = 2;
@InjectView(R.id.topbar_device_to_share)
CommonTopBar mCommonTopBar;
@InjectView(R.id.et_search_account)
DefaultEditText mEditText;
@InjectView(R.id.tv_search_result)
TextView mSearchResultTv;
@InjectView(R.id.lv_get_user_by_account)
ListView mListView;
private String mAccount;
private DeviceModel mDeviceModel;
private CommonAdapter<UserModel> mAdapter;
private List<UserModel> mUserModelList = new ArrayList<>();
private int mShareFlag;
private List<DeviceModel> mDeviceToShareList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_share_find);
initParams();
initView();
}
private void initParams() {
Bundle bundle = getIntent().getExtras();
mShareFlag = bundle.getInt("flag");
//单设备
if (mShareFlag == SINGLE_SHARE) {
mDeviceModel = mDeviceManager.getDeviceModel();
}
//多设备
if (mShareFlag == MULTI_SHARE) {
mDeviceToShareList = (List<DeviceModel>) bundle.getSerializable("devices");
mDeviceModel = mDeviceToShareList.get(0);
}
}
private void initView() {
initTopBar();
initListView();
}
private void initListView() {
mAdapter = new CommonAdapter<UserModel>(mContext, mUserModelList, R.layout.activity_device_share_find_item) {
@Override
public void convert(MyViewHolder helper, UserModel item) {
helper.setText(R.id.tv_user_account, mAccount);
helper.setText(R.id.tv_user_name, item.getUserName());
if (item.getAvatar() != null) {
helper.setImageURI(R.id.iv_user_icon, Uri.parse(item.getAvatar()));
}
// 设备是否分享(1-未分享,2-已邀请,3-已分享)
if ("1".equals(item.getShare())) {
helper.getView(R.id.bt_agree).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//单设备分享
if (mShareFlag == SINGLE_SHARE) {
Spanned msg = HtmlTextUtils.formatShareHint("您申请向", mAccount, "用户分享", mDeviceModel.getDeviceName(), "设备,是否继续?");
PromptUtil.showPromptDialog(mContext, "设备分享", String.valueOf(msg), "确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDialog();
//请求接口发送数据
mShareManager.oneDeviceShare(mDeviceModel.getDeviceId(), mAccount);
}
});
}
//多设备分享
if (mShareFlag == MULTI_SHARE) {
Spanned msg = HtmlTextUtils.formatShareHint("您申请向", mAccount, "用户分享", TextHelper.getDeviceNames(mDeviceToShareList), "设备,是否继续?");
PromptUtil.showPromptDialog(mContext, "设备分享", String.valueOf(msg), "确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDialog();
//请求接口发送数据
new DeviceBiz().multiInvite(new ICallback<String>() {
@Override
public void onSuccess(String s, int id) {
hideDialog();
PromptUtil.showToast(mContext, "已发送邀请");
startActivity(UserCenterActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
@Override
public void onFailure(int code, String msg, int id) {
hideDialog();
PromptUtil.showToast(mContext, msg);
}
},TextHelper.getDeviceIds(mDeviceToShareList),mAccount, ParamContant.NO_VIEW_ID);
}
});
}
}
});
}
if ("2".equals(item.getShare())) {
Button button = helper.getView(R.id.bt_agree);
button.setBackgroundColor(getResources().getColor(R.color.transparent));
button.setTextColor(getResources().getColor(R.color.text_color_item_subtitle));
button.setText("等待确认");
button.setEnabled(false);
}
if ("3".equals(item.getShare())) {
Button button = helper.getView(R.id.bt_agree);
button.setBackgroundColor(getResources().getColor(R.color.transparent));
button.setTextColor(getResources().getColor(R.color.text_color_item_subtitle));
button.setText("已分享");
button.setEnabled(false);
}
}
};
mListView.setAdapter(mAdapter);
}
//关于设备邀请
public void onEventMainThread(ShareEvent event) {
hideDialog();
switch (event.getMsg()) {
case "deviceSharedSuccess":
PromptUtil.showToast(mContext, "已发送邀请");
startActivity(DevDetailMoreAty.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
break;
case "deviceSharedFailed":
PromptUtil.showToast(mContext, event.getInfo());
break;
}
}
private void initTopBar() {
mCommonTopBar.setTitle(R.string.device_to_share);
mCommonTopBar.setUpNavigateMode();
}
@OnClick({R.id.tv_search})
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_search:
mAccount = mEditText.getText().toString();
if (checkAccount(mAccount)) {
mUserModelList.clear();
mAdapter.notifyDataSetChanged();
showDialog();
findUser();
}
break;
}
}
private void findUser() {
if (mShareFlag == SINGLE_SHARE) {
new ShareApi().getUserByAccount(new ICallback<UserModel>() {
@Override
public void onSuccess(UserModel userModel, int id) {
hideDialog();
mUserModelList.clear();
mUserModelList.add(userModel);
mAdapter.notifyDataSetChanged();
mSearchResultTv.setVisibility(View.VISIBLE);
}
@Override
public void onFailure(int code, String msg, int id) {
hideDialog();
PromptUtil.showToast(mContext, msg);
}
}, mAccount, mDeviceModel.getDeviceId());
}
if (mShareFlag == MULTI_SHARE) {
new ShareApi().getUserByAccount(new ICallback<UserModel>() {
@Override
public void onSuccess(UserModel userModel, int id) {
hideDialog();
mUserModelList.clear();
mUserModelList.add(userModel);
mAdapter.notifyDataSetChanged();
mSearchResultTv.setVisibility(View.VISIBLE);
}
@Override
public void onFailure(int code, String msg, int id) {
hideDialog();
PromptUtil.showToast(mContext, msg);
}
}, mAccount,"");
}
}
private boolean checkAccount(String account) {
if (TextUtils.isEmpty(account)) {
PromptUtil.showToast(mContext, R.string.common_tell_null);
return false;
}
if ( !StringUtils.isEmail(account)&&!StringUtils.isPhoneNum(account)) {
PromptUtil.showToast(mContext, R.string.common_tell_format_wrong);
return false;
}
return true;
}
}
| UTF-8 | Java | 10,796 | java | DevShareFindAty.java | Java | [
{
"context": "ew;\nimport butterknife.OnClick;\n\n/**\n * Created by colin on 15-10-30.\n * 待分享设备界面\n * 多设备页面可进入\n * 单设备分享可进入\n ",
"end": 1479,
"score": 0.8191686868667603,
"start": 1474,
"tag": "USERNAME",
"value": "colin"
}
] | null | [] | package com.het.linnei.ui.activity.device;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.het.clife.business.biz.device.DeviceBindBiz;
import com.het.clife.business.biz.device.DeviceBiz;
import com.het.clife.constant.ParamContant;
import com.het.clife.model.user.UserModel;
import com.het.common.callback.ICallback;
import com.het.common.utils.StringUtils;
import com.het.comres.adapter.CommonAdapter;
import com.het.comres.adapter.MyViewHolder;
import com.het.comres.view.DefaultEditText;
import com.het.comres.view.dialog.PromptUtil;
import com.het.comres.widget.CommonTopBar;
import com.het.dlplug.sdk.model.DeviceModel;
import com.het.linnei.R;
import com.het.linnei.base.BaseActivity;
import com.het.linnei.event.DeviceEvent;
import com.het.linnei.event.UserEvent;
import com.het.linnei.manager.DeviceManager;
import com.het.linnei.manager.UserManager;
import com.het.linnei.share.ShareApi;
import com.het.linnei.share.ShareEvent;
import com.het.linnei.ui.activity.user.UserCenterActivity;
import com.het.linnei.util.HtmlTextUtils;
import com.het.linnei.util.TextHelper;
import java.util.ArrayList;
import java.util.List;
import butterknife.InjectView;
import butterknife.OnClick;
/**
* Created by colin on 15-10-30.
* 待分享设备界面
* 多设备页面可进入
* 单设备分享可进入
*/
public class DevShareFindAty extends BaseActivity {
public static final int SINGLE_SHARE = 1;
public static final int MULTI_SHARE = 2;
@InjectView(R.id.topbar_device_to_share)
CommonTopBar mCommonTopBar;
@InjectView(R.id.et_search_account)
DefaultEditText mEditText;
@InjectView(R.id.tv_search_result)
TextView mSearchResultTv;
@InjectView(R.id.lv_get_user_by_account)
ListView mListView;
private String mAccount;
private DeviceModel mDeviceModel;
private CommonAdapter<UserModel> mAdapter;
private List<UserModel> mUserModelList = new ArrayList<>();
private int mShareFlag;
private List<DeviceModel> mDeviceToShareList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_share_find);
initParams();
initView();
}
private void initParams() {
Bundle bundle = getIntent().getExtras();
mShareFlag = bundle.getInt("flag");
//单设备
if (mShareFlag == SINGLE_SHARE) {
mDeviceModel = mDeviceManager.getDeviceModel();
}
//多设备
if (mShareFlag == MULTI_SHARE) {
mDeviceToShareList = (List<DeviceModel>) bundle.getSerializable("devices");
mDeviceModel = mDeviceToShareList.get(0);
}
}
private void initView() {
initTopBar();
initListView();
}
private void initListView() {
mAdapter = new CommonAdapter<UserModel>(mContext, mUserModelList, R.layout.activity_device_share_find_item) {
@Override
public void convert(MyViewHolder helper, UserModel item) {
helper.setText(R.id.tv_user_account, mAccount);
helper.setText(R.id.tv_user_name, item.getUserName());
if (item.getAvatar() != null) {
helper.setImageURI(R.id.iv_user_icon, Uri.parse(item.getAvatar()));
}
// 设备是否分享(1-未分享,2-已邀请,3-已分享)
if ("1".equals(item.getShare())) {
helper.getView(R.id.bt_agree).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//单设备分享
if (mShareFlag == SINGLE_SHARE) {
Spanned msg = HtmlTextUtils.formatShareHint("您申请向", mAccount, "用户分享", mDeviceModel.getDeviceName(), "设备,是否继续?");
PromptUtil.showPromptDialog(mContext, "设备分享", String.valueOf(msg), "确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDialog();
//请求接口发送数据
mShareManager.oneDeviceShare(mDeviceModel.getDeviceId(), mAccount);
}
});
}
//多设备分享
if (mShareFlag == MULTI_SHARE) {
Spanned msg = HtmlTextUtils.formatShareHint("您申请向", mAccount, "用户分享", TextHelper.getDeviceNames(mDeviceToShareList), "设备,是否继续?");
PromptUtil.showPromptDialog(mContext, "设备分享", String.valueOf(msg), "确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDialog();
//请求接口发送数据
new DeviceBiz().multiInvite(new ICallback<String>() {
@Override
public void onSuccess(String s, int id) {
hideDialog();
PromptUtil.showToast(mContext, "已发送邀请");
startActivity(UserCenterActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
@Override
public void onFailure(int code, String msg, int id) {
hideDialog();
PromptUtil.showToast(mContext, msg);
}
},TextHelper.getDeviceIds(mDeviceToShareList),mAccount, ParamContant.NO_VIEW_ID);
}
});
}
}
});
}
if ("2".equals(item.getShare())) {
Button button = helper.getView(R.id.bt_agree);
button.setBackgroundColor(getResources().getColor(R.color.transparent));
button.setTextColor(getResources().getColor(R.color.text_color_item_subtitle));
button.setText("等待确认");
button.setEnabled(false);
}
if ("3".equals(item.getShare())) {
Button button = helper.getView(R.id.bt_agree);
button.setBackgroundColor(getResources().getColor(R.color.transparent));
button.setTextColor(getResources().getColor(R.color.text_color_item_subtitle));
button.setText("已分享");
button.setEnabled(false);
}
}
};
mListView.setAdapter(mAdapter);
}
//关于设备邀请
public void onEventMainThread(ShareEvent event) {
hideDialog();
switch (event.getMsg()) {
case "deviceSharedSuccess":
PromptUtil.showToast(mContext, "已发送邀请");
startActivity(DevDetailMoreAty.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
break;
case "deviceSharedFailed":
PromptUtil.showToast(mContext, event.getInfo());
break;
}
}
private void initTopBar() {
mCommonTopBar.setTitle(R.string.device_to_share);
mCommonTopBar.setUpNavigateMode();
}
@OnClick({R.id.tv_search})
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_search:
mAccount = mEditText.getText().toString();
if (checkAccount(mAccount)) {
mUserModelList.clear();
mAdapter.notifyDataSetChanged();
showDialog();
findUser();
}
break;
}
}
private void findUser() {
if (mShareFlag == SINGLE_SHARE) {
new ShareApi().getUserByAccount(new ICallback<UserModel>() {
@Override
public void onSuccess(UserModel userModel, int id) {
hideDialog();
mUserModelList.clear();
mUserModelList.add(userModel);
mAdapter.notifyDataSetChanged();
mSearchResultTv.setVisibility(View.VISIBLE);
}
@Override
public void onFailure(int code, String msg, int id) {
hideDialog();
PromptUtil.showToast(mContext, msg);
}
}, mAccount, mDeviceModel.getDeviceId());
}
if (mShareFlag == MULTI_SHARE) {
new ShareApi().getUserByAccount(new ICallback<UserModel>() {
@Override
public void onSuccess(UserModel userModel, int id) {
hideDialog();
mUserModelList.clear();
mUserModelList.add(userModel);
mAdapter.notifyDataSetChanged();
mSearchResultTv.setVisibility(View.VISIBLE);
}
@Override
public void onFailure(int code, String msg, int id) {
hideDialog();
PromptUtil.showToast(mContext, msg);
}
}, mAccount,"");
}
}
private boolean checkAccount(String account) {
if (TextUtils.isEmpty(account)) {
PromptUtil.showToast(mContext, R.string.common_tell_null);
return false;
}
if ( !StringUtils.isEmail(account)&&!StringUtils.isPhoneNum(account)) {
PromptUtil.showToast(mContext, R.string.common_tell_format_wrong);
return false;
}
return true;
}
}
| 10,796 | 0.534974 | 0.533549 | 269 | 38.115242 | 29.234053 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.669145 | false | false | 0 |
9ae514a9a59b7d6020ff62950e9c24c0790baecd | 22,196,391,054,611 | 0385c090ad781a9e7ba915daf8d90c7d58bb2589 | /iterableapi/src/main/java/com/iterable/iterableapi/IterablePushRegistration.java | 889a8e7a5f10bdedf107d1867dd0df261cb47b2f | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | mumbles42/iterable-android-sdk | https://github.com/mumbles42/iterable-android-sdk | 63d090db49f60af434bc4fcb0e1383f2479c4618 | 06bd057a9b8e3a6fc80e9b72cb9349409a9c7990 | refs/heads/master | 2022-11-13T04:47:03.157000 | 2020-07-06T16:44:41 | 2020-07-06T16:44:41 | 278,858,353 | 0 | 0 | MIT | true | 2020-07-11T12:35:30 | 2020-07-11T12:35:22 | 2020-07-11T12:35:24 | 2020-07-11T12:35:28 | 3,293 | 0 | 0 | 1 | null | false | false | package com.iterable.iterableapi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import com.google.firebase.iid.FirebaseInstanceId;
import org.json.JSONObject;
import java.io.IOException;
/**
* Created by David Truong dt@iterable.com
*/
class IterablePushRegistration extends AsyncTask<IterablePushRegistrationData, Void, Void> {
static final String TAG = "IterablePushRegistration";
IterablePushRegistrationData iterablePushRegistrationData;
/**
* Registers or disables the device
*
* @param params Push registration request data
*/
protected Void doInBackground(IterablePushRegistrationData... params) {
iterablePushRegistrationData = params[0];
if (iterablePushRegistrationData.pushIntegrationName != null) {
PushRegistrationObject pushRegistrationObject = getDeviceToken();
if (pushRegistrationObject != null) {
if (iterablePushRegistrationData.pushRegistrationAction == IterablePushRegistrationData.PushRegistrationAction.ENABLE) {
IterableApi.sharedInstance.registerDeviceToken(
iterablePushRegistrationData.email,
iterablePushRegistrationData.userId,
iterablePushRegistrationData.pushIntegrationName,
pushRegistrationObject.token,
IterableApi.getInstance().getDeviceAttributes());
} else if (iterablePushRegistrationData.pushRegistrationAction == IterablePushRegistrationData.PushRegistrationAction.DISABLE) {
IterableApi.sharedInstance.disableToken(
iterablePushRegistrationData.email,
iterablePushRegistrationData.userId,
pushRegistrationObject.token);
}
disableOldDeviceIfNeeded();
}
} else {
IterableLogger.e("IterablePush", "iterablePushRegistrationData has not been specified");
}
return null;
}
/**
* @return PushRegistrationObject
*/
PushRegistrationObject getDeviceToken() {
try {
Context applicationContext = IterableApi.sharedInstance.getMainActivityContext();
if (applicationContext == null) {
IterableLogger.e(TAG, "MainActivity Context is null");
return null;
}
int firebaseResourceId = Util.getFirebaseResouceId(applicationContext);
if (firebaseResourceId == 0) {
IterableLogger.e(TAG, "Could not find firebase_database_url, please check that Firebase SDK is set up properly");
return null;
}
return new PushRegistrationObject(Util.getFirebaseToken());
} catch (Exception e) {
IterableLogger.e(TAG, "Exception while retrieving the device token: check that firebase is added to the build dependencies", e);
return null;
}
}
/**
* If {@link IterableConfig#legacyGCMSenderId} is specified, this will attempt to retrieve the old token
* and disable it to avoid duplicate notifications
*/
private void disableOldDeviceIfNeeded() {
try {
Context applicationContext = IterableApi.sharedInstance.getMainActivityContext();
String gcmSenderId = IterableApi.sharedInstance.config.legacyGCMSenderId;
if (gcmSenderId != null && gcmSenderId.length() > 0 && !gcmSenderId.equals(Util.getSenderId(applicationContext))) {
final SharedPreferences sharedPref = applicationContext.getSharedPreferences(IterableConstants.PUSH_APP_ID, Context.MODE_PRIVATE);
boolean migrationDone = sharedPref.getBoolean(IterableConstants.SHARED_PREFS_FCM_MIGRATION_DONE_KEY, false);
if (!migrationDone) {
String oldToken = Util.getFirebaseToken(gcmSenderId, IterableConstants.MESSAGING_PLATFORM_GOOGLE);
// We disable the device on Iterable but keep the token
if (oldToken != null) {
IterableApi.sharedInstance.disableToken(iterablePushRegistrationData.email, iterablePushRegistrationData.userId, oldToken, new IterableHelper.SuccessHandler() {
@Override
public void onSuccess(@NonNull JSONObject data) {
sharedPref.edit().putBoolean(IterableConstants.SHARED_PREFS_FCM_MIGRATION_DONE_KEY, true).apply();
}
}, null);
}
}
}
} catch (Exception e) {
IterableLogger.e(TAG, "Exception while trying to disable the old device token", e);
}
}
static class Util {
static UtilImpl instance = new UtilImpl();
static int getFirebaseResouceId(Context applicationContext) {
return instance.getFirebaseResouceId(applicationContext);
}
static String getFirebaseToken() {
return instance.getFirebaseToken();
}
static String getFirebaseToken(String senderId, String platform) throws IOException {
return instance.getFirebaseToken(senderId, platform);
}
static String getSenderId(Context applicationContext) {
return instance.getSenderId(applicationContext);
}
static class UtilImpl {
int getFirebaseResouceId(Context applicationContext) {
return applicationContext.getResources().getIdentifier(IterableConstants.FIREBASE_RESOURCE_ID, IterableConstants.ANDROID_STRING, applicationContext.getPackageName());
}
String getFirebaseToken() {
FirebaseInstanceId instanceID = FirebaseInstanceId.getInstance();
return instanceID.getToken();
}
String getFirebaseToken(String senderId, String platform) throws IOException {
FirebaseInstanceId instanceId = FirebaseInstanceId.getInstance();
return instanceId.getToken(senderId, platform);
}
String getSenderId(Context applicationContext) {
int resId = applicationContext.getResources().getIdentifier(IterableConstants.FIREBASE_SENDER_ID, IterableConstants.ANDROID_STRING, applicationContext.getPackageName());
if (resId != 0) {
return applicationContext.getResources().getString(resId);
} else {
return null;
}
}
}
}
static class PushRegistrationObject {
String token;
String messagingPlatform;
PushRegistrationObject(String token) {
this.token = token;
this.messagingPlatform = IterableConstants.MESSAGING_PLATFORM_FIREBASE;
}
}
}
| UTF-8 | Java | 7,037 | java | IterablePushRegistration.java | Java | [
{
"context": "t;\n\nimport java.io.IOException;\n\n/**\n * Created by David Truong dt@iterable.com\n */\nclass IterablePushRegistratio",
"end": 316,
"score": 0.9998705387115479,
"start": 304,
"tag": "NAME",
"value": "David Truong"
},
{
"context": "va.io.IOException;\n\n/**\n * Create... | null | [] | package com.iterable.iterableapi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import com.google.firebase.iid.FirebaseInstanceId;
import org.json.JSONObject;
import java.io.IOException;
/**
* Created by <NAME> <EMAIL>
*/
class IterablePushRegistration extends AsyncTask<IterablePushRegistrationData, Void, Void> {
static final String TAG = "IterablePushRegistration";
IterablePushRegistrationData iterablePushRegistrationData;
/**
* Registers or disables the device
*
* @param params Push registration request data
*/
protected Void doInBackground(IterablePushRegistrationData... params) {
iterablePushRegistrationData = params[0];
if (iterablePushRegistrationData.pushIntegrationName != null) {
PushRegistrationObject pushRegistrationObject = getDeviceToken();
if (pushRegistrationObject != null) {
if (iterablePushRegistrationData.pushRegistrationAction == IterablePushRegistrationData.PushRegistrationAction.ENABLE) {
IterableApi.sharedInstance.registerDeviceToken(
iterablePushRegistrationData.email,
iterablePushRegistrationData.userId,
iterablePushRegistrationData.pushIntegrationName,
pushRegistrationObject.token,
IterableApi.getInstance().getDeviceAttributes());
} else if (iterablePushRegistrationData.pushRegistrationAction == IterablePushRegistrationData.PushRegistrationAction.DISABLE) {
IterableApi.sharedInstance.disableToken(
iterablePushRegistrationData.email,
iterablePushRegistrationData.userId,
pushRegistrationObject.token);
}
disableOldDeviceIfNeeded();
}
} else {
IterableLogger.e("IterablePush", "iterablePushRegistrationData has not been specified");
}
return null;
}
/**
* @return PushRegistrationObject
*/
PushRegistrationObject getDeviceToken() {
try {
Context applicationContext = IterableApi.sharedInstance.getMainActivityContext();
if (applicationContext == null) {
IterableLogger.e(TAG, "MainActivity Context is null");
return null;
}
int firebaseResourceId = Util.getFirebaseResouceId(applicationContext);
if (firebaseResourceId == 0) {
IterableLogger.e(TAG, "Could not find firebase_database_url, please check that Firebase SDK is set up properly");
return null;
}
return new PushRegistrationObject(Util.getFirebaseToken());
} catch (Exception e) {
IterableLogger.e(TAG, "Exception while retrieving the device token: check that firebase is added to the build dependencies", e);
return null;
}
}
/**
* If {@link IterableConfig#legacyGCMSenderId} is specified, this will attempt to retrieve the old token
* and disable it to avoid duplicate notifications
*/
private void disableOldDeviceIfNeeded() {
try {
Context applicationContext = IterableApi.sharedInstance.getMainActivityContext();
String gcmSenderId = IterableApi.sharedInstance.config.legacyGCMSenderId;
if (gcmSenderId != null && gcmSenderId.length() > 0 && !gcmSenderId.equals(Util.getSenderId(applicationContext))) {
final SharedPreferences sharedPref = applicationContext.getSharedPreferences(IterableConstants.PUSH_APP_ID, Context.MODE_PRIVATE);
boolean migrationDone = sharedPref.getBoolean(IterableConstants.SHARED_PREFS_FCM_MIGRATION_DONE_KEY, false);
if (!migrationDone) {
String oldToken = Util.getFirebaseToken(gcmSenderId, IterableConstants.MESSAGING_PLATFORM_GOOGLE);
// We disable the device on Iterable but keep the token
if (oldToken != null) {
IterableApi.sharedInstance.disableToken(iterablePushRegistrationData.email, iterablePushRegistrationData.userId, oldToken, new IterableHelper.SuccessHandler() {
@Override
public void onSuccess(@NonNull JSONObject data) {
sharedPref.edit().putBoolean(IterableConstants.SHARED_PREFS_FCM_MIGRATION_DONE_KEY, true).apply();
}
}, null);
}
}
}
} catch (Exception e) {
IterableLogger.e(TAG, "Exception while trying to disable the old device token", e);
}
}
static class Util {
static UtilImpl instance = new UtilImpl();
static int getFirebaseResouceId(Context applicationContext) {
return instance.getFirebaseResouceId(applicationContext);
}
static String getFirebaseToken() {
return instance.getFirebaseToken();
}
static String getFirebaseToken(String senderId, String platform) throws IOException {
return instance.getFirebaseToken(senderId, platform);
}
static String getSenderId(Context applicationContext) {
return instance.getSenderId(applicationContext);
}
static class UtilImpl {
int getFirebaseResouceId(Context applicationContext) {
return applicationContext.getResources().getIdentifier(IterableConstants.FIREBASE_RESOURCE_ID, IterableConstants.ANDROID_STRING, applicationContext.getPackageName());
}
String getFirebaseToken() {
FirebaseInstanceId instanceID = FirebaseInstanceId.getInstance();
return instanceID.getToken();
}
String getFirebaseToken(String senderId, String platform) throws IOException {
FirebaseInstanceId instanceId = FirebaseInstanceId.getInstance();
return instanceId.getToken(senderId, platform);
}
String getSenderId(Context applicationContext) {
int resId = applicationContext.getResources().getIdentifier(IterableConstants.FIREBASE_SENDER_ID, IterableConstants.ANDROID_STRING, applicationContext.getPackageName());
if (resId != 0) {
return applicationContext.getResources().getString(resId);
} else {
return null;
}
}
}
}
static class PushRegistrationObject {
String token;
String messagingPlatform;
PushRegistrationObject(String token) {
this.token = token;
this.messagingPlatform = IterableConstants.MESSAGING_PLATFORM_FIREBASE;
}
}
}
| 7,023 | 0.634361 | 0.633793 | 164 | 41.896343 | 41.117115 | 185 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.512195 | false | false | 0 |
b3fbcabf600744a0bcb3190e41636f83d26ce3f3 | 3,032,246,980,343 | acc44c3749e89e372e1839325c70e0cba6bee404 | /IGNITE PURVI/sort binary array.java | 9f1340b71de9caf67f00949505d35904324b9539 | [] | no_license | ignite-plus-2021/Assignments-2021 | https://github.com/ignite-plus-2021/Assignments-2021 | fab2f0bf6ea17822cfff0212bc8a82d9a3b5bb29 | d12b6d257b3c0df88d0f64268129ee68cec8a491 | refs/heads/main | 2023-04-27T00:15:23.780000 | 2021-06-08T12:44:26 | 2021-06-08T12:44:26 | 345,991,838 | 0 | 27 | null | false | 2021-05-28T10:57:01 | 2021-03-09T12:02:49 | 2021-05-28T10:49:16 | 2021-05-28T10:57:00 | 484 | 0 | 22 | 4 | Java | false | false | class Binary{
public static void main(String args[]){
int a[] = {0,1,1,0,1,1,0,1,0,0};
int count=0;
for(int i=0;i<a.length;i++){
if(a[i]==0){
count++;
}
}
for(int i=0;i<count;i++){
a[i] = 0;
}
for(int i=count;i<a.length;i++){
a[i]= 1;
}
}
}
| UTF-8 | Java | 412 | java | sort binary array.java | Java | [] | null | [] | class Binary{
public static void main(String args[]){
int a[] = {0,1,1,0,1,1,0,1,0,0};
int count=0;
for(int i=0;i<a.length;i++){
if(a[i]==0){
count++;
}
}
for(int i=0;i<count;i++){
a[i] = 0;
}
for(int i=count;i<a.length;i++){
a[i]= 1;
}
}
}
| 412 | 0.322816 | 0.283981 | 17 | 21.647058 | 13.04265 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.176471 | false | false | 0 |
37ddbb96652bce171cee554a6bbcb9e1b01852ac | 24,189,255,873,291 | 378692140be74e3ace67d96fde88c45e43cc95de | /src/main/java/com/demo/sinck/SinkTest.java | 761beafb3a9e0a345e54d16ede19c53cf67276bf | [] | no_license | wangxiaolin01/flink-demo | https://github.com/wangxiaolin01/flink-demo | 57e0bcc02b974310ba1a19a838d62e2ee7e4f6cd | 511401808e46220587cf6887f83439878dbdd1b3 | refs/heads/master | 2023-06-06T17:30:09.197000 | 2021-07-06T14:32:48 | 2021-07-06T14:32:48 | 383,496,546 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.sinck;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringEncoder;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.core.fs.Path;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink;
public class SinkTest {
public static void main(String[] args) {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
env.setParallelism(1);
env.enableCheckpointing(1000, CheckpointingMode.EXACTLY_ONCE);
DataStreamSource<Long> longDataStreamSource = env.fromSequence(0, 1000);
// longDataStreamSource.addSink(JdbcSink.sink("",
// ((preparedStatement, aLong) -> {
// preparedStatement.setTime(1,aLong.longValue());
// },
// new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
// .withDriverName("com.mysql.jdbc")
// .withUrl("")
// )));
longDataStreamSource.addSink(StreamingFileSink
.forRowFormat(new Path(""),new SimpleStringEncoder<Long>("UTF-8"))
.build());
}
}
| UTF-8 | Java | 1,728 | java | SinkTest.java | Java | [] | null | [] | package com.demo.sinck;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringEncoder;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.core.fs.Path;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink;
public class SinkTest {
public static void main(String[] args) {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
env.setParallelism(1);
env.enableCheckpointing(1000, CheckpointingMode.EXACTLY_ONCE);
DataStreamSource<Long> longDataStreamSource = env.fromSequence(0, 1000);
// longDataStreamSource.addSink(JdbcSink.sink("",
// ((preparedStatement, aLong) -> {
// preparedStatement.setTime(1,aLong.longValue());
// },
// new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
// .withDriverName("com.mysql.jdbc")
// .withUrl("")
// )));
longDataStreamSource.addSink(StreamingFileSink
.forRowFormat(new Path(""),new SimpleStringEncoder<Long>("UTF-8"))
.build());
}
}
| 1,728 | 0.722801 | 0.715278 | 38 | 44.473682 | 27.750521 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736842 | false | false | 0 |
ff75e0e2cc1280c9b7c66df28e07d8f14e712501 | 12,034,498,374,593 | ea5638b76bd1f000e70faab70d8dc6415bdcdd1b | /src/main/java/com/panda/SpringJspWeb/demo/datastructdemo/LoopQueue.java | a2def490d278cf5866bd91870ed06817d92c9628 | [] | no_license | topson-cn/SpringJspWeb | https://github.com/topson-cn/SpringJspWeb | 8f081bdb2474776fccc317de5219ee2cf4de5ef4 | 85fea63b52a6064de392dc3fd7f295c6ddb9e134 | refs/heads/master | 2022-07-12T23:48:59.056000 | 2020-01-22T06:24:23 | 2020-01-22T06:24:23 | 231,495,826 | 0 | 0 | null | false | 2022-06-21T02:33:51 | 2020-01-03T02:23:24 | 2020-01-22T06:24:34 | 2022-06-21T02:33:49 | 2,327 | 0 | 0 | 4 | JavaScript | false | false | package com.panda.SpringJspWeb.demo.datastructdemo;
/**
* 〈一句话功能简述〉<br>
* 循环队列: 数组实现
* @author 18048474
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class LoopQueue<E> {
private Object[] data;
private int maxSize;
private int front;
private int rear;
public LoopQueue(){
this(10);
}
public LoopQueue(int initSize){
if (initSize < 0){
throw new RuntimeException("初始化长度不能小于0: " + initSize);
}
this.data = new Object[initSize];
this.maxSize = initSize;
this.rear = this.front = 0;
}
public boolean enqueue(E e){
if ((rear+1) % data.length == front){
throw new RuntimeException("队列已满");
}
data[rear] = e;
rear = (rear+1) % data.length;
return true;
}
public E peek(){
if (rear == front){
throw new RuntimeException("队列已空");
}
return (E) data[front];
}
public E poll(){
if (rear == front){
throw new RuntimeException("队列已空");
}
E value = (E) data[front];
data[front] = null;
front = (front+1) % data.length;
return value;
}
}
| UTF-8 | Java | 1,325 | java | LoopQueue.java | Java | [
{
"context": "o;\n\n/**\n * 〈一句话功能简述〉<br>\n * 循环队列: 数组实现\n * @author 18048474\n * @see [相关类/方法](可选)\n * @since [产品/模块版本] (可选)\n */",
"end": 107,
"score": 0.9989372491836548,
"start": 99,
"tag": "USERNAME",
"value": "18048474"
}
] | null | [] | package com.panda.SpringJspWeb.demo.datastructdemo;
/**
* 〈一句话功能简述〉<br>
* 循环队列: 数组实现
* @author 18048474
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class LoopQueue<E> {
private Object[] data;
private int maxSize;
private int front;
private int rear;
public LoopQueue(){
this(10);
}
public LoopQueue(int initSize){
if (initSize < 0){
throw new RuntimeException("初始化长度不能小于0: " + initSize);
}
this.data = new Object[initSize];
this.maxSize = initSize;
this.rear = this.front = 0;
}
public boolean enqueue(E e){
if ((rear+1) % data.length == front){
throw new RuntimeException("队列已满");
}
data[rear] = e;
rear = (rear+1) % data.length;
return true;
}
public E peek(){
if (rear == front){
throw new RuntimeException("队列已空");
}
return (E) data[front];
}
public E poll(){
if (rear == front){
throw new RuntimeException("队列已空");
}
E value = (E) data[front];
data[front] = null;
front = (front+1) % data.length;
return value;
}
}
| 1,325 | 0.521883 | 0.508671 | 58 | 19.879311 | 16.124598 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.362069 | false | false | 0 |
ba39be457190ccc490117c563a902f6c770391ef | 14,568,529,077,346 | 5be8c5c03c12e05d845c3102ff0a2948cf6638a8 | /components/camel-snmp/src/test/java/org/apache/camel/component/snmp/SnmpRespondTestSupport.java | 2e0e38dc9e693084cc35b2b84f28bb7a49a93a99 | [
"Apache-2.0"
] | permissive | Talend/apache-camel | https://github.com/Talend/apache-camel | cfc4657dc28a6c5701854b0889b9e0d090675b05 | fe9484bf5236f7af665c35cc7ed29527def8fe48 | refs/heads/master | 2023-08-10T14:15:19.145000 | 2023-06-28T06:30:44 | 2023-06-28T06:30:44 | 35,226,644 | 15 | 61 | Apache-2.0 | true | 2023-08-29T11:53:02 | 2015-05-07T15:03:34 | 2023-02-07T09:06:42 | 2023-08-29T11:53:00 | 644,703 | 15 | 54 | 0 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.snmp;
import java.io.IOException;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.MessageException;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.mp.CounterSupport;
import org.snmp4j.mp.DefaultCounterListener;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.mp.StatusInformation;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class SnmpRespondTestSupport extends SnmpTestSupport {
static final String SECURITY_NAME = "test";
private static final String LOCAL_ADDRESS = "127.0.0.1/0";
Snmp snmpResponder;
String listeningAddress;
@BeforeAll
public void beforeAll() {
SecurityProtocols.getInstance().addDefaultProtocols();
DefaultUdpTransportMapping udpTransportMapping;
try {
udpTransportMapping = new DefaultUdpTransportMapping(new UdpAddress(LOCAL_ADDRESS));
snmpResponder = new Snmp(udpTransportMapping);
TestCommandResponder responder = new TestCommandResponder(snmpResponder);
snmpResponder.addCommandResponder(responder);
SecurityModels respSecModels = new SecurityModels() {
};
CounterSupport.getInstance().addCounterListener(new DefaultCounterListener());
MPv3 mpv3CR = (MPv3) snmpResponder.getMessageDispatcher().getMessageProcessingModel(MPv3.ID);
mpv3CR.setLocalEngineID(MPv3.createLocalEngineID(new OctetString("responder")));
respSecModels.addSecurityModel(new USM(
SecurityProtocols.getInstance(),
new OctetString(mpv3CR.getLocalEngineID()), 0));
mpv3CR.setSecurityModels(respSecModels);
snmpResponder.getUSM().addUser(
new UsmUser(
new OctetString(SECURITY_NAME), AuthSHA.ID, new OctetString("changeit"),
AuthSHA.ID, new OctetString("changeit")));
snmpResponder.listen();
} catch (Exception e) {
throw new RuntimeException(e);
}
listeningAddress = udpTransportMapping.getListenAddress().toString().replaceFirst("/", ":");
}
@AfterAll
public void afterAll(/*ExtensionContext context*/) {
if (snmpResponder != null) {
try {
snmpResponder.close();
} catch (IOException e) {
//nothing
}
}
}
static class TestCommandResponder implements CommandResponder {
private final Snmp commandResponder;
private final Map<String, Integer> counts = new ConcurrentHashMap<>();
public TestCommandResponder(Snmp commandResponder) {
this.commandResponder = commandResponder;
}
@Override
public synchronized void processPdu(CommandResponderEvent event) {
PDU pdu = event.getPDU();
Vector<? extends VariableBinding> vbs;
if (pdu.getVariableBindings() != null) {
vbs = new Vector<>(pdu.getVariableBindings());
} else {
vbs = new Vector<>(0);
}
String key = vbs.stream().sequential().map(vb -> vb.getOid().toString()).collect(Collectors.joining(","));
int version;
//differ snmp versions
if (pdu instanceof PDUv1) {
version = SnmpConstants.version1;
key = "v1_" + key;
} else if (pdu instanceof ScopedPDU) {
version = SnmpConstants.version3;
key = "v3_" + key;
} else {
version = SnmpConstants.version2c;
key = "v2_" + key;
}
int numberOfSent = counts.getOrDefault(key, 0);
try {
PDU response = makeResponse(pdu, ++numberOfSent, version, vbs);
if (response != null) {
response.setRequestID(pdu.getRequestID());
commandResponder.getMessageDispatcher().returnResponsePdu(
event.getMessageProcessingModel(), event.getSecurityModel(),
event.getSecurityName(), event.getSecurityLevel(),
response, event.getMaxSizeResponsePDU(),
event.getStateReference(), new StatusInformation());
}
} catch (MessageException e) {
Assertions.assertNull(e);
}
counts.put(key, numberOfSent);
}
private PDU makeResponse(PDU originalPDU, int counter, int version, Vector<? extends VariableBinding> vbs) {
PDU responsePDU = (PDU) originalPDU.clone();
responsePDU.setType(PDU.RESPONSE);
responsePDU.setErrorStatus(PDU.noError);
responsePDU.setErrorIndex(0);
if (vbs.isEmpty()) {
VariableBinding vb = generateResponseBinding(counter, version, SnmpConstants.sysDescr);
if (vb != null) {
responsePDU.add(vb);
}
} else {
vbs.stream().forEach(vb -> responsePDU.add(generateResponseBinding(counter, version, vb.getOid())));
}
return responsePDU;
}
private VariableBinding generateResponseBinding(int counter, int version, OID oid) {
//real responses
//1.3.6.1.2.1.2.2.1.2 -> 1.3.6.1.2.1.2.2.1.2.1 = ether1
if ("1.3.6.1.2.1.2.2.1.2".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.2.1"), new OctetString("ether1"));
}
//1.3.6.1.2.1.2.2.1.2.1 -> 1.3.6.1.2.1.2.2.1.2.2 = ether2
if ("1.3.6.1.2.1.2.2.1.2.1".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.2.2"), new OctetString("ether2"));
}
//1.3.6.1.2.1.2.2.1.2.2 -> 1.3.6.1.2.1.2.2.1.2.3 = ether3
if ("1.3.6.1.2.1.2.2.1.2.2".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.2.3"), new OctetString("ether3"));
}
//1.3.6.1.2.1.2.2.1.2.3 -> 1.3.6.1.2.1.2.2.1.2.4 = ether4
if ("1.3.6.1.2.1.2.2.1.2.3".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.2.4"), new OctetString("ether4"));
}
//1.3.6.1.2.1.2.2.1.2.4 -> 1.3.6.1.2.1.2.2.1.3.1 = 6
if ("1.3.6.1.2.1.2.2.1.2.4".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.3.1"), new OctetString("6"));
}
return new VariableBinding(
SnmpConstants.sysDescr,
new OctetString("My Printer - response #" + counter + ", using version: " + version));
}
}
public String getListeningAddress() {
return listeningAddress;
}
}
| UTF-8 | Java | 8,547 | java | SnmpRespondTestSupport.java | Java | [
{
"context": "\n private static final String LOCAL_ADDRESS = \"127.0.0.1/0\";\n\n Snmp snmpResponder;\n String listening",
"end": 2167,
"score": 0.9997238516807556,
"start": 2158,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "ring key = vbs.stream().sequential()... | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.snmp;
import java.io.IOException;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.MessageException;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.mp.CounterSupport;
import org.snmp4j.mp.DefaultCounterListener;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.mp.StatusInformation;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class SnmpRespondTestSupport extends SnmpTestSupport {
static final String SECURITY_NAME = "test";
private static final String LOCAL_ADDRESS = "127.0.0.1/0";
Snmp snmpResponder;
String listeningAddress;
@BeforeAll
public void beforeAll() {
SecurityProtocols.getInstance().addDefaultProtocols();
DefaultUdpTransportMapping udpTransportMapping;
try {
udpTransportMapping = new DefaultUdpTransportMapping(new UdpAddress(LOCAL_ADDRESS));
snmpResponder = new Snmp(udpTransportMapping);
TestCommandResponder responder = new TestCommandResponder(snmpResponder);
snmpResponder.addCommandResponder(responder);
SecurityModels respSecModels = new SecurityModels() {
};
CounterSupport.getInstance().addCounterListener(new DefaultCounterListener());
MPv3 mpv3CR = (MPv3) snmpResponder.getMessageDispatcher().getMessageProcessingModel(MPv3.ID);
mpv3CR.setLocalEngineID(MPv3.createLocalEngineID(new OctetString("responder")));
respSecModels.addSecurityModel(new USM(
SecurityProtocols.getInstance(),
new OctetString(mpv3CR.getLocalEngineID()), 0));
mpv3CR.setSecurityModels(respSecModels);
snmpResponder.getUSM().addUser(
new UsmUser(
new OctetString(SECURITY_NAME), AuthSHA.ID, new OctetString("changeit"),
AuthSHA.ID, new OctetString("changeit")));
snmpResponder.listen();
} catch (Exception e) {
throw new RuntimeException(e);
}
listeningAddress = udpTransportMapping.getListenAddress().toString().replaceFirst("/", ":");
}
@AfterAll
public void afterAll(/*ExtensionContext context*/) {
if (snmpResponder != null) {
try {
snmpResponder.close();
} catch (IOException e) {
//nothing
}
}
}
static class TestCommandResponder implements CommandResponder {
private final Snmp commandResponder;
private final Map<String, Integer> counts = new ConcurrentHashMap<>();
public TestCommandResponder(Snmp commandResponder) {
this.commandResponder = commandResponder;
}
@Override
public synchronized void processPdu(CommandResponderEvent event) {
PDU pdu = event.getPDU();
Vector<? extends VariableBinding> vbs;
if (pdu.getVariableBindings() != null) {
vbs = new Vector<>(pdu.getVariableBindings());
} else {
vbs = new Vector<>(0);
}
String key = vbs.stream().sequential().map(vb -> vb.getOid().toString()).collect(Collectors.joining(","));
int version;
//differ snmp versions
if (pdu instanceof PDUv1) {
version = SnmpConstants.version1;
key = "<KEY>;
} else if (pdu instanceof ScopedPDU) {
version = SnmpConstants.version3;
key = "<KEY>;
} else {
version = SnmpConstants.version2c;
key = "<KEY>;
}
int numberOfSent = counts.getOrDefault(key, 0);
try {
PDU response = makeResponse(pdu, ++numberOfSent, version, vbs);
if (response != null) {
response.setRequestID(pdu.getRequestID());
commandResponder.getMessageDispatcher().returnResponsePdu(
event.getMessageProcessingModel(), event.getSecurityModel(),
event.getSecurityName(), event.getSecurityLevel(),
response, event.getMaxSizeResponsePDU(),
event.getStateReference(), new StatusInformation());
}
} catch (MessageException e) {
Assertions.assertNull(e);
}
counts.put(key, numberOfSent);
}
private PDU makeResponse(PDU originalPDU, int counter, int version, Vector<? extends VariableBinding> vbs) {
PDU responsePDU = (PDU) originalPDU.clone();
responsePDU.setType(PDU.RESPONSE);
responsePDU.setErrorStatus(PDU.noError);
responsePDU.setErrorIndex(0);
if (vbs.isEmpty()) {
VariableBinding vb = generateResponseBinding(counter, version, SnmpConstants.sysDescr);
if (vb != null) {
responsePDU.add(vb);
}
} else {
vbs.stream().forEach(vb -> responsePDU.add(generateResponseBinding(counter, version, vb.getOid())));
}
return responsePDU;
}
private VariableBinding generateResponseBinding(int counter, int version, OID oid) {
//real responses
//1.3.6.1.2.1.2.2.1.2 -> 1.3.6.1.2.1.2.2.1.2.1 = ether1
if ("1.3.6.1.2.1.2.2.1.2".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.2.1"), new OctetString("ether1"));
}
//1.3.6.1.2.1.2.2.1.2.1 -> 1.3.6.1.2.1.2.2.1.2.2 = ether2
if ("1.3.6.1.2.1.2.2.1.2.1".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.2.2"), new OctetString("ether2"));
}
//1.3.6.1.2.1.2.2.1.2.2 -> 1.3.6.1.2.1.2.2.1.2.3 = ether3
if ("1.3.6.1.2.1.2.2.1.2.2".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.2.3"), new OctetString("ether3"));
}
//1.3.6.1.2.1.2.2.1.2.3 -> 1.3.6.1.2.1.2.2.1.2.4 = ether4
if ("1.3.6.1.2.1.2.2.1.2.3".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.2.4"), new OctetString("ether4"));
}
//1.3.6.1.2.1.2.2.1.2.4 -> 1.3.6.1.2.1.2.2.1.3.1 = 6
if ("1.3.6.1.2.1.2.2.1.2.4".equals(oid.toString())) {
return new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.3.1"), new OctetString("6"));
}
return new VariableBinding(
SnmpConstants.sysDescr,
new OctetString("My Printer - response #" + counter + ", using version: " + version));
}
}
public String getListeningAddress() {
return listeningAddress;
}
}
| 8,532 | 0.611092 | 0.578098 | 204 | 40.89706 | 29.581629 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642157 | false | false | 0 |
f4de19c959350140591066840d89920732b13b22 | 13,297,218,757,215 | b78ef134adf469e723fc02ec248b1f5dc9224763 | /app/src/main/java/com/vsahin/twitter_api_search/View/MainActivity.java | c5acf5d5aeef9e0aa23de9fe611999bd2da25d3d | [
"MIT"
] | permissive | volkansahin45/Twitter-Api-Search-Example | https://github.com/volkansahin45/Twitter-Api-Search-Example | fa6e8df1a521af6dca2f41ff11d3623026dabcd6 | f231f9be7ae463bd7c8831af9562bb84993fa57c | refs/heads/master | 2021-07-09T07:00:45.594000 | 2017-10-06T08:10:00 | 2017-10-06T08:10:00 | 105,979,446 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vsahin.twitter_api_search.View;
import android.arch.lifecycle.LifecycleActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.FrameLayout;
import com.vsahin.twitter_api_search.R;
import com.vsahin.twitter_api_search.View.TweetList.TweetListFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends LifecycleActivity {
FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fragmentManager = getSupportFragmentManager();
if(getFragmentBackStackCount() == 0){
showFragment(TweetListFragment.newInstance());
}
}
public void showFragment(Fragment nextFragment){
//be sure to not load same fragment
if(isLastFragmentInBackstack(nextFragment)){
return;
}
fragmentManager.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.fragment_container , nextFragment)
.addToBackStack(nextFragment.getClass().getName())
.commit();
}
public boolean isLastFragmentInBackstack(Fragment fragment){
String currentFragmentName;
String nextFragmentName = fragment.getClass().getName();
//if count is 0 it means there isnt any fragment in backstack
int count = getFragmentBackStackCount();
if(count != 0){
currentFragmentName = getLastFragmentNameInBackStack();
if(currentFragmentName.equals(nextFragmentName)){
return true;
}
}
return false;
}
public String getLastFragmentNameInBackStack(){
return fragmentManager.getBackStackEntryAt(getFragmentBackStackCount() - 1).getName();
}
public int getFragmentBackStackCount(){
return fragmentManager.getBackStackEntryCount();
}
@Override
public void onBackPressed() {
if(getFragmentBackStackCount() == 1){
finish();
}
super.onBackPressed();
}
}
| UTF-8 | Java | 2,408 | java | MainActivity.java | Java | [] | null | [] | package com.vsahin.twitter_api_search.View;
import android.arch.lifecycle.LifecycleActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.FrameLayout;
import com.vsahin.twitter_api_search.R;
import com.vsahin.twitter_api_search.View.TweetList.TweetListFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends LifecycleActivity {
FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fragmentManager = getSupportFragmentManager();
if(getFragmentBackStackCount() == 0){
showFragment(TweetListFragment.newInstance());
}
}
public void showFragment(Fragment nextFragment){
//be sure to not load same fragment
if(isLastFragmentInBackstack(nextFragment)){
return;
}
fragmentManager.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.fragment_container , nextFragment)
.addToBackStack(nextFragment.getClass().getName())
.commit();
}
public boolean isLastFragmentInBackstack(Fragment fragment){
String currentFragmentName;
String nextFragmentName = fragment.getClass().getName();
//if count is 0 it means there isnt any fragment in backstack
int count = getFragmentBackStackCount();
if(count != 0){
currentFragmentName = getLastFragmentNameInBackStack();
if(currentFragmentName.equals(nextFragmentName)){
return true;
}
}
return false;
}
public String getLastFragmentNameInBackStack(){
return fragmentManager.getBackStackEntryAt(getFragmentBackStackCount() - 1).getName();
}
public int getFragmentBackStackCount(){
return fragmentManager.getBackStackEntryCount();
}
@Override
public void onBackPressed() {
if(getFragmentBackStackCount() == 1){
finish();
}
super.onBackPressed();
}
}
| 2,408 | 0.679817 | 0.676495 | 77 | 30.272728 | 26.680231 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 0 |
8240ed66911bef899fa6ce24e7bb7fdbc81bbff3 | 18,975,165,520,895 | 58e3d4beac7d1a314546a506e854baab482a4862 | /src/main/java/agency/akcom/upwork/server/dao/UpworkUserSettingsDao.java | 9a76cab57bee9bd60fa9da9a14c8b960ca122bfd | [] | no_license | kupryanov97/upWork | https://github.com/kupryanov97/upWork | 74b93d1544e21eb855e1a2d7fbd9e8c72d526110 | e96cb9739dce88ffc247214b4144af6857709ecc | refs/heads/master | 2020-09-04T13:49:23.878000 | 2019-11-05T13:09:59 | 2019-11-05T13:09:59 | 219,748,601 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package agency.akcom.upwork.server.dao;
import java.util.List;
import agency.akcom.upwork.domain.UpworkUserSettings;
import com.google.appengine.api.datastore.PreparedQuery;
import static com.googlecode.objectify.ObjectifyService.ofy;
public class UpworkUserSettingsDao extends BaseDao<UpworkUserSettings> {
public UpworkUserSettingsDao() {
super(UpworkUserSettings.class);
}
protected UpworkUserSettingsDao(Class<UpworkUserSettings> clazz) {
super(clazz);
}
public List<UpworkUserSettings> getAllEntities(){
return ofy().load().type(UpworkUserSettings.class).list();
}
public UpworkUserSettings findByRef(String Id) throws PreparedQuery.TooManyResultsException {
return getByProperty("userDtoRef", Id);
}
public UpworkUserSettings findByRef2(String Id) throws PreparedQuery.TooManyResultsException {
return getByProperty("id", Id);
}
}
| UTF-8 | Java | 927 | java | UpworkUserSettingsDao.java | Java | [] | null | [] | package agency.akcom.upwork.server.dao;
import java.util.List;
import agency.akcom.upwork.domain.UpworkUserSettings;
import com.google.appengine.api.datastore.PreparedQuery;
import static com.googlecode.objectify.ObjectifyService.ofy;
public class UpworkUserSettingsDao extends BaseDao<UpworkUserSettings> {
public UpworkUserSettingsDao() {
super(UpworkUserSettings.class);
}
protected UpworkUserSettingsDao(Class<UpworkUserSettings> clazz) {
super(clazz);
}
public List<UpworkUserSettings> getAllEntities(){
return ofy().load().type(UpworkUserSettings.class).list();
}
public UpworkUserSettings findByRef(String Id) throws PreparedQuery.TooManyResultsException {
return getByProperty("userDtoRef", Id);
}
public UpworkUserSettings findByRef2(String Id) throws PreparedQuery.TooManyResultsException {
return getByProperty("id", Id);
}
}
| 927 | 0.748652 | 0.747573 | 31 | 28.903225 | 30.718655 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387097 | false | false | 0 |
3ef36e5c5334694639fcfe20d21d6a734c02ecaa | 22,488,448,764,482 | df90c842e5b9c404862ceae3fe142df751c490f9 | /src/main/java/com/reciconnect/domain/Usuario.java | 5b6e0127c63707f4a8a82071023b2116d855dc46 | [] | no_license | rtsouza26/ReciConnectB | https://github.com/rtsouza26/ReciConnectB | c653f90d75ad4eebcf68a73541e679abe3d3725b | ab1913889947d73d9ed28ec67dfc3ea65b7d3759 | refs/heads/master | 2020-05-27T11:37:27.145000 | 2019-05-26T23:53:00 | 2019-05-26T23:53:00 | 188,598,743 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.reciconnect.domain;
import javax.persistence.*;
import javax.validation.constraints.*;
@Entity
@Table(name="TB_USUARIO")
public class Usuario {
@Id
@NotNull
private String email;
@Column
@NotNull
private String nome;
@Column
@NotNull
private String senha;
@Column
@NotNull
private int avatar;
public String getNome() {
return nome;
}
public String getEmail() {
return email;
}
public String getSenha() {
return senha;
}
public int getAvatar() {
return avatar;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setEmail(String email) {
this.email = email;
}
public void setSenha(String senha) {
this.senha = senha;
}
public void setAvatar(int avatar) {
this.avatar = avatar;
}
}
| UTF-8 | Java | 821 | java | Usuario.java | Java | [] | null | [] | package com.reciconnect.domain;
import javax.persistence.*;
import javax.validation.constraints.*;
@Entity
@Table(name="TB_USUARIO")
public class Usuario {
@Id
@NotNull
private String email;
@Column
@NotNull
private String nome;
@Column
@NotNull
private String senha;
@Column
@NotNull
private int avatar;
public String getNome() {
return nome;
}
public String getEmail() {
return email;
}
public String getSenha() {
return senha;
}
public int getAvatar() {
return avatar;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setEmail(String email) {
this.email = email;
}
public void setSenha(String senha) {
this.senha = senha;
}
public void setAvatar(int avatar) {
this.avatar = avatar;
}
}
| 821 | 0.645554 | 0.645554 | 52 | 13.788462 | 11.992524 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.269231 | false | false | 0 |
d1d033cfcf13ea62f72ae02623b6bf5508db131e | 19,138,374,283,789 | 572175142e6157f93c97ad9132f9c45ef364bbc1 | /src/liveproject2/Select_Timing.java | 78e560f874d304b6dd74cfb024048242c9492784 | [] | no_license | iamPrashSri/Coaching-Institute-Management-System | https://github.com/iamPrashSri/Coaching-Institute-Management-System | f91a0f436f0215a8d4c3b49077abefb19a29fa4a | 928f95db3c3f5f53f364542ddfc20142f7372273 | refs/heads/master | 2020-08-18T15:54:52.153000 | 2019-10-24T14:56:02 | 2019-10-24T14:56:02 | 215,808,041 | 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 liveproject2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.proteanit.sql.DbUtils;
import oracle.jdbc.driver.OracleDriver;
/**
*
* @author Hp
*/
public class Select_Timing extends javax.swing.JPanel {
/**
* Creates new form Select_Timing
*/
OracleDriver od;
Connection conn;
PreparedStatement stmt;
ResultSet rs;
public Select_Timing() {
try {
initComponents();
od=new OracleDriver();
DriverManager.registerDriver(od);
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","prashant");
} catch (SQLException ex) {
Logger.getLogger(Select_Timing.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jComboBox3 = new javax.swing.JComboBox();
jComboBox4 = new javax.swing.JComboBox();
jLabel1.setFont(new java.awt.Font("Segoe Print", 1, 18)); // NOI18N
jLabel1.setText("Select timing");
jButton1.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jButton1.setText("SUBMIT");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jComboBox3.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7am", "8am", "9am", "10am", "11am", "12pm", "3pm", "4pm", "5pm", "6pm", "7pm", "8pm" }));
jComboBox4.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "6am", "7am", "8am", "9am", "10am", "11am", "2pm", "3pm", "4pm", "5pm", "6pm", "7pm" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
.addComponent(jButton1))
);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String start_time=jComboBox4.getSelectedItem().toString();
String end_time=jComboBox3.getSelectedItem().toString();
try {
stmt=conn.prepareStatement("select batch_id,batches.subject_id,start_time,end_time from batches,subjects where start_time=? and end_time=? "
+ "and subjects.subject_id=batches.subject_id order by batches.subject_id asc");
stmt.setString(1,start_time);
stmt.setString(2,end_time);
rs=stmt.executeQuery();
Batch_Details.returnInstance2().returnTableInstance().setModel(DbUtils.resultSetToTableModel(rs));
stmt.close();
rs.close();
}
catch(Exception e){}
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox3;
private javax.swing.JComboBox jComboBox4;
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 6,222 | java | Select_Timing.java | Java | [
{
"context": "racle.jdbc.driver.OracleDriver;\n\n/**\n *\n * @author Hp\n */\npublic class Select_Timing extends javax.swin",
"end": 520,
"score": 0.9994737505912781,
"start": 518,
"tag": "USERNAME",
"value": "Hp"
}
] | 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 liveproject2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.proteanit.sql.DbUtils;
import oracle.jdbc.driver.OracleDriver;
/**
*
* @author Hp
*/
public class Select_Timing extends javax.swing.JPanel {
/**
* Creates new form Select_Timing
*/
OracleDriver od;
Connection conn;
PreparedStatement stmt;
ResultSet rs;
public Select_Timing() {
try {
initComponents();
od=new OracleDriver();
DriverManager.registerDriver(od);
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","prashant");
} catch (SQLException ex) {
Logger.getLogger(Select_Timing.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jComboBox3 = new javax.swing.JComboBox();
jComboBox4 = new javax.swing.JComboBox();
jLabel1.setFont(new java.awt.Font("Segoe Print", 1, 18)); // NOI18N
jLabel1.setText("Select timing");
jButton1.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
jButton1.setText("SUBMIT");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jComboBox3.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7am", "8am", "9am", "10am", "11am", "12pm", "3pm", "4pm", "5pm", "6pm", "7pm", "8pm" }));
jComboBox4.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "6am", "7am", "8am", "9am", "10am", "11am", "2pm", "3pm", "4pm", "5pm", "6pm", "7pm" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
.addComponent(jButton1))
);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String start_time=jComboBox4.getSelectedItem().toString();
String end_time=jComboBox3.getSelectedItem().toString();
try {
stmt=conn.prepareStatement("select batch_id,batches.subject_id,start_time,end_time from batches,subjects where start_time=? and end_time=? "
+ "and subjects.subject_id=batches.subject_id order by batches.subject_id asc");
stmt.setString(1,start_time);
stmt.setString(2,end_time);
rs=stmt.executeQuery();
Batch_Details.returnInstance2().returnTableInstance().setModel(DbUtils.resultSetToTableModel(rs));
stmt.close();
rs.close();
}
catch(Exception e){}
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox3;
private javax.swing.JComboBox jComboBox4;
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
| 6,222 | 0.652684 | 0.634362 | 132 | 46.136364 | 40.829056 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.916667 | false | false | 0 |
e1b2fa87d6beeb6b18af2b13d0c4d5a43aee418e | 12,034,498,378,798 | 975993759563ef52e8b12b2c87610bdc59ff3096 | /app/src/main/java/edu/ucmo/cptonline/helper/UploadHelper.java | e0c164f1953eb357a0dbcb7f9f3a8d2ee663b7e7 | [] | no_license | spinachandkale/cptonline_android | https://github.com/spinachandkale/cptonline_android | cfeb138107f7318c94690c92d03cb36b589501c3 | 44e686038651712412015d3b555c3ac26c3427b6 | refs/heads/master | 2021-03-19T14:11:20.614000 | 2017-05-10T14:55:19 | 2017-05-10T14:55:19 | 90,048,346 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.ucmo.cptonline.helper;
import android.os.AsyncTask;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.URLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by avina on 5/3/2017.
*/
public class UploadHelper extends AsyncTask<ArrayList<String>, Void, Integer> {
private int taskResult = -1;
@Override
protected Integer doInBackground(ArrayList<String>... params) {
String CrLf = "\r\n";
String Url = params[0].get(0);
String filename = params[0].get(1);
String contentType = params[0].get(2);
File file = new File(filename);
String uploadFilename = file.getName();
Integer ret = -1;
URLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(Url);
System.out.println("url:" + url);
conn = url.openConnection();
conn.setDoOutput(true);
String postData = "";
InputStream imgIs = new FileInputStream(filename);
byte[] imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename="
+ uploadFilename + CrLf;
message1 += "Content-Type: " + contentType + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--"
+ CrLf;
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
conn.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
os = conn.getOutputStream();
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
os.write(message2.getBytes());
os.flush();
is = conn.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
len = is.read(data);
} while (len > 0);
} catch (Exception e) {
e.printStackTrace();
ret = 0;
} finally {
try {
os.close();
is.close();
ret = 1;
} catch (Exception e) {
e.printStackTrace();
ret = 0;
}
}
return ret;
}
@Override
protected void onPostExecute(Integer result) {
taskResult = (result == 1) ? 1 : 0;
}
public Integer getTaskResult() {
return taskResult;
}
}
// private final String CrLf = "\r\n";
// private String Url;
// private String filename;
// private String uploadFilename;
// private String contentType;
//
// public UploadHelper(String url, String filename, String contentType) {
// this.Url = url;
// this.filename = filename;
// File f = new File(filename);
// uploadFilename = f.getName();
// this.contentType = contentType;
// }
//
// public Boolean httpConn() {
// Boolean ret = Boolean.FALSE;
// URLConnection conn = null;
// OutputStream os = null;
// InputStream is = null;
//
// try {
// URL url = new URL(Url);
// System.out.println("url:" + url);
// conn = url.openConnection();
// conn.setDoOutput(true);
//
// String postData = "";
//
// InputStream imgIs = new FileInputStream(filename);
// byte[] imgData = new byte[imgIs.available()];
// imgIs.read(imgData);
//
// String message1 = "";
// message1 += "-----------------------------4664151417711" + CrLf;
// message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename="
// + uploadFilename + CrLf;
// message1 += "Content-Type: " + contentType + CrLf;
// message1 += CrLf;
//
// // the image is sent between the messages in the multipart message.
//
// String message2 = "";
// message2 += CrLf + "-----------------------------4664151417711--"
// + CrLf;
//
// conn.setRequestProperty("Content-Type",
// "multipart/form-data; boundary=---------------------------4664151417711");
// // might not need to specify the content-length when sending chunked
// // data.
// conn.setRequestProperty("Content-Length", String.valueOf((message1
// .length() + message2.length() + imgData.length)));
//
// os = conn.getOutputStream();
//
// os.write(message1.getBytes());
//
// // SEND THE IMAGE
// int index = 0;
// int size = 1024;
// do {
// if ((index + size) > imgData.length) {
// size = imgData.length - index;
// }
// os.write(imgData, index, size);
// index += size;
// } while (index < imgData.length);
//
// os.write(message2.getBytes());
// os.flush();
//
// is = conn.getInputStream();
//
// char buff = 512;
// int len;
// byte[] data = new byte[buff];
// do {
// len = is.read(data);
// } while (len > 0);
//
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// os.close();
// ret = Boolean.TRUE;
// } catch (Exception e) {
// }
// try {
// is.close();
// } catch (Exception e) {
// }
// }
//
// return ret;
// }
| UTF-8 | Java | 6,650 | java | UploadHelper.java | Java | [
{
"context": "RL;\nimport java.util.ArrayList;\n\n/**\n * Created by avina on 5/3/2017.\n */\n\npublic class UploadHelper exten",
"end": 280,
"score": 0.9956426024436951,
"start": 275,
"tag": "USERNAME",
"value": "avina"
}
] | null | [] | package edu.ucmo.cptonline.helper;
import android.os.AsyncTask;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.URLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by avina on 5/3/2017.
*/
public class UploadHelper extends AsyncTask<ArrayList<String>, Void, Integer> {
private int taskResult = -1;
@Override
protected Integer doInBackground(ArrayList<String>... params) {
String CrLf = "\r\n";
String Url = params[0].get(0);
String filename = params[0].get(1);
String contentType = params[0].get(2);
File file = new File(filename);
String uploadFilename = file.getName();
Integer ret = -1;
URLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(Url);
System.out.println("url:" + url);
conn = url.openConnection();
conn.setDoOutput(true);
String postData = "";
InputStream imgIs = new FileInputStream(filename);
byte[] imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename="
+ uploadFilename + CrLf;
message1 += "Content-Type: " + contentType + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--"
+ CrLf;
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
conn.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
os = conn.getOutputStream();
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
os.write(message2.getBytes());
os.flush();
is = conn.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
len = is.read(data);
} while (len > 0);
} catch (Exception e) {
e.printStackTrace();
ret = 0;
} finally {
try {
os.close();
is.close();
ret = 1;
} catch (Exception e) {
e.printStackTrace();
ret = 0;
}
}
return ret;
}
@Override
protected void onPostExecute(Integer result) {
taskResult = (result == 1) ? 1 : 0;
}
public Integer getTaskResult() {
return taskResult;
}
}
// private final String CrLf = "\r\n";
// private String Url;
// private String filename;
// private String uploadFilename;
// private String contentType;
//
// public UploadHelper(String url, String filename, String contentType) {
// this.Url = url;
// this.filename = filename;
// File f = new File(filename);
// uploadFilename = f.getName();
// this.contentType = contentType;
// }
//
// public Boolean httpConn() {
// Boolean ret = Boolean.FALSE;
// URLConnection conn = null;
// OutputStream os = null;
// InputStream is = null;
//
// try {
// URL url = new URL(Url);
// System.out.println("url:" + url);
// conn = url.openConnection();
// conn.setDoOutput(true);
//
// String postData = "";
//
// InputStream imgIs = new FileInputStream(filename);
// byte[] imgData = new byte[imgIs.available()];
// imgIs.read(imgData);
//
// String message1 = "";
// message1 += "-----------------------------4664151417711" + CrLf;
// message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename="
// + uploadFilename + CrLf;
// message1 += "Content-Type: " + contentType + CrLf;
// message1 += CrLf;
//
// // the image is sent between the messages in the multipart message.
//
// String message2 = "";
// message2 += CrLf + "-----------------------------4664151417711--"
// + CrLf;
//
// conn.setRequestProperty("Content-Type",
// "multipart/form-data; boundary=---------------------------4664151417711");
// // might not need to specify the content-length when sending chunked
// // data.
// conn.setRequestProperty("Content-Length", String.valueOf((message1
// .length() + message2.length() + imgData.length)));
//
// os = conn.getOutputStream();
//
// os.write(message1.getBytes());
//
// // SEND THE IMAGE
// int index = 0;
// int size = 1024;
// do {
// if ((index + size) > imgData.length) {
// size = imgData.length - index;
// }
// os.write(imgData, index, size);
// index += size;
// } while (index < imgData.length);
//
// os.write(message2.getBytes());
// os.flush();
//
// is = conn.getInputStream();
//
// char buff = 512;
// int len;
// byte[] data = new byte[buff];
// do {
// len = is.read(data);
// } while (len > 0);
//
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// os.close();
// ret = Boolean.TRUE;
// } catch (Exception e) {
// }
// try {
// is.close();
// } catch (Exception e) {
// }
// }
//
// return ret;
// }
| 6,650 | 0.476992 | 0.456241 | 217 | 29.645161 | 22.821859 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 0 |
bcec0afed9a033e48575e6b6282594010b681320 | 12,034,498,378,067 | 6758067b257fdd286a3282d454bfd42c8daa7c98 | /src/Task1/Task1_10/CharType.java | 9917be57a0896a073ddbbd8a3793e4c761852d6c | [] | no_license | dziominpavel/EPAM_IntroductionToJava | https://github.com/dziominpavel/EPAM_IntroductionToJava | 98b01d0097f42a928baa4db42f9f401e7a93f68f | 79b10ca9d3241557a6760fff8f9411d51315bc0a | refs/heads/master | 2020-05-20T08:14:38.391000 | 2019-06-21T15:46:33 | 2019-06-21T15:46:33 | 185,028,483 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Task1.Task1_10;
public enum CharType {
VOWEL, CONSONANT
}
| UTF-8 | Java | 71 | java | CharType.java | Java | [] | null | [] | package Task1.Task1_10;
public enum CharType {
VOWEL, CONSONANT
}
| 71 | 0.71831 | 0.661972 | 5 | 13.2 | 10.419213 | 23 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 0 |
8d9ac3a140efcb7984b66716b6f88e6af84d19ae | 12,034,498,377,178 | e200cbeb134b979b35737be769433a6d2e03d538 | /repo/proj3/gitlet/CommitTest.java | 2e48f3a7124dc5780ff3b9a8b8dc374fc9b3d3ee | [] | no_license | Yang-B/CS61b | https://github.com/Yang-B/CS61b | 8dc877f3bc66123472c69e0331f7a60fe93e6472 | bdacb7c33156b44f837c3a97a0c1fa1ae9fd0fca | refs/heads/master | 2021-03-30T18:19:29.694000 | 2017-12-09T19:55:20 | 2017-12-09T19:55:20 | 106,618,626 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gitlet;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.Date;
import java.io.File;
import static gitlet.Utils.*;
import java.util.HashMap;
/** Test CommitTest.
* @author Bo Yang
*/
public class CommitTest {
@Test
public void testCommit() {
Commit initcommit = new Commit("initial commit", new Date(new Long(0)));
File file1 = new File(USERDIR + "/" + "file1.txt");
File file2 = new File(USERDIR + "/" + "file2.txt");
Blob blob1 = new Blob("file 1 content".getBytes());
Blob blob2 = new Blob("file2 content".getBytes());
HashMap<String, String> blobs = new HashMap<>();
blobs.put("file1", blob1.sha1());
blobs.put("file2", blob2.sha1());
Commit commit = new Commit("second commit",
new Date(System.currentTimeMillis()), initcommit.sha1(), blobs);
assertEquals(initcommit.getlogmessage(), "initial commit");
assertEquals(commit.getparent(), initcommit.sha1());
assertEquals(initcommit.gettimestamp(), new Date(new Long(0)));
assertEquals(commit.getblobs(), blobs);
}
@Test
public void testcontains() {
Commit initcommit = new Commit("initial commit", new Date(new Long(0)));
File initcommitfile = new File(COMMITDIR, "/" + initcommit.sha1());
Blob blob1 = new Blob("file 1 content".getBytes());
Blob blob2 = new Blob("file2 content".getBytes());
HashMap<String, String> blobs = new HashMap<>();
blobs.put("file1", blob1.sha1());
blobs.put("file2", blob2.sha1());
Commit commit = new Commit("second commit",
new Date(System.currentTimeMillis()), initcommit.sha1(), blobs);
File commitfile = new File(COMMITDIR, "/" + commit.sha1());
writeObject(initcommitfile, initcommit);
writeObject(commitfile, commit);
assertTrue(Commit.contains(initcommit.sha1()));
assertTrue(Commit.contains(commit.sha1()));
assertTrue(Commit.contains(initcommit.sha1().substring(0, 8)));
assertTrue(Commit.contains(commit.sha1().substring(0, 8)));
initcommitfile.delete();
commitfile.delete();
}
@Test
public void testreadcommit() {
Commit initcommit = new Commit(
"initial commit", new Date(new Long(0)));
File initcommitfile = new File(COMMITDIR, "/" + initcommit.sha1());
Blob blob1 = new Blob("file 1 content".getBytes());
Blob blob2 = new Blob("file2 content".getBytes());
HashMap<String, String> blobs = new HashMap<>();
blobs.put("file1", blob1.sha1());
blobs.put("file2", blob2.sha1());
Commit commit = new Commit("second commit",
new Date(System.currentTimeMillis()), initcommit.sha1(), blobs);
File commitfile = new File(COMMITDIR, "/" + commit.sha1());
writeObject(initcommitfile, initcommit);
writeObject(commitfile, commit);
Commit initcommitread = Commit.readcommit(initcommit.sha1());
Commit commitread = Commit.readcommit(commit.sha1());
assertTrue(initcommit.sha1().equals(initcommitread.sha1()));
assertTrue(commit.sha1().equals(commitread.sha1()));
initcommitfile.delete();
commitfile.delete();
}
}
| UTF-8 | Java | 3,306 | java | CommitTest.java | Java | [
{
"context": "ava.util.HashMap;\n\n/** Test CommitTest.\n * @author Bo Yang\n */\npublic class CommitTest {\n @Test\n publi",
"end": 214,
"score": 0.9997431039810181,
"start": 207,
"tag": "NAME",
"value": "Bo Yang"
}
] | null | [] | package gitlet;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.Date;
import java.io.File;
import static gitlet.Utils.*;
import java.util.HashMap;
/** Test CommitTest.
* @author <NAME>
*/
public class CommitTest {
@Test
public void testCommit() {
Commit initcommit = new Commit("initial commit", new Date(new Long(0)));
File file1 = new File(USERDIR + "/" + "file1.txt");
File file2 = new File(USERDIR + "/" + "file2.txt");
Blob blob1 = new Blob("file 1 content".getBytes());
Blob blob2 = new Blob("file2 content".getBytes());
HashMap<String, String> blobs = new HashMap<>();
blobs.put("file1", blob1.sha1());
blobs.put("file2", blob2.sha1());
Commit commit = new Commit("second commit",
new Date(System.currentTimeMillis()), initcommit.sha1(), blobs);
assertEquals(initcommit.getlogmessage(), "initial commit");
assertEquals(commit.getparent(), initcommit.sha1());
assertEquals(initcommit.gettimestamp(), new Date(new Long(0)));
assertEquals(commit.getblobs(), blobs);
}
@Test
public void testcontains() {
Commit initcommit = new Commit("initial commit", new Date(new Long(0)));
File initcommitfile = new File(COMMITDIR, "/" + initcommit.sha1());
Blob blob1 = new Blob("file 1 content".getBytes());
Blob blob2 = new Blob("file2 content".getBytes());
HashMap<String, String> blobs = new HashMap<>();
blobs.put("file1", blob1.sha1());
blobs.put("file2", blob2.sha1());
Commit commit = new Commit("second commit",
new Date(System.currentTimeMillis()), initcommit.sha1(), blobs);
File commitfile = new File(COMMITDIR, "/" + commit.sha1());
writeObject(initcommitfile, initcommit);
writeObject(commitfile, commit);
assertTrue(Commit.contains(initcommit.sha1()));
assertTrue(Commit.contains(commit.sha1()));
assertTrue(Commit.contains(initcommit.sha1().substring(0, 8)));
assertTrue(Commit.contains(commit.sha1().substring(0, 8)));
initcommitfile.delete();
commitfile.delete();
}
@Test
public void testreadcommit() {
Commit initcommit = new Commit(
"initial commit", new Date(new Long(0)));
File initcommitfile = new File(COMMITDIR, "/" + initcommit.sha1());
Blob blob1 = new Blob("file 1 content".getBytes());
Blob blob2 = new Blob("file2 content".getBytes());
HashMap<String, String> blobs = new HashMap<>();
blobs.put("file1", blob1.sha1());
blobs.put("file2", blob2.sha1());
Commit commit = new Commit("second commit",
new Date(System.currentTimeMillis()), initcommit.sha1(), blobs);
File commitfile = new File(COMMITDIR, "/" + commit.sha1());
writeObject(initcommitfile, initcommit);
writeObject(commitfile, commit);
Commit initcommitread = Commit.readcommit(initcommit.sha1());
Commit commitread = Commit.readcommit(commit.sha1());
assertTrue(initcommit.sha1().equals(initcommitread.sha1()));
assertTrue(commit.sha1().equals(commitread.sha1()));
initcommitfile.delete();
commitfile.delete();
}
}
| 3,305 | 0.624319 | 0.606171 | 76 | 42.5 | 23.521267 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.171053 | false | false | 0 |
cfafa6f139e242b60ba5914c1b74b60495edd58a | 12,610,024,050,960 | 572e2fe46cdbee3870e8468196521f3df6293c63 | /AsistenciaAutomatica/app/src/main/java/com/example/asistenciaautomatica/Asistente.java | 5a52ccb560baaeb27a6b1b8909f74525943bec94 | [] | no_license | bolisteward/AMST_2T2019_Toma-autom-tica-de-asistencia-de-eventos | https://github.com/bolisteward/AMST_2T2019_Toma-autom-tica-de-asistencia-de-eventos | 5c04ab1c0a70a9257e951c96584e31ea20f1f87a | 0bcfe162f0afbaf876e733db8b035822306fe911 | refs/heads/master | 2020-12-18T19:11:44.889000 | 2020-02-01T02:27:56 | 2020-02-01T02:27:56 | 235,493,107 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.asistenciaautomatica;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
public class Asistente extends AppCompatActivity{
private static final String TAG = "Asistente";
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
//vars
private boolean mLocationPermissionGaranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
//views
private Bundle info_user;
private Button btn_Asistir;
private Button btn_salida;
private Button btn_historial;
private TextView txt_nombre;
private TextView txt_correo;
private TextView txt_phone;
private TextView txt_Latitud;
private TextView txt_Longitud;
private TextView txt_matricula;
private ImageView img_foto;
private String userId;
private String disp_Lat1;
private String disp_Long1;
private String disp_Lat2;
private String disp_Long2;
private String name_evento;
private String idEvento;
private String horaActual;
private String idLista;
private String[] horaFinE;
private Spinner spinner;
private Boolean nuevoAsist;
private List<String> eventos;
private Users asistente;
private int anio,mes,dia,horas,minutos;
private HashMap<String, String> info_evento = null;
private DatabaseReference db_reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_asistente);
txt_Latitud = findViewById(R.id.txt_Latitud);
txt_Longitud = findViewById(R.id.txt_Longitud);
txt_nombre = findViewById(R.id.txt_nombre);
txt_correo = findViewById(R.id.txt_correo);
txt_phone = findViewById(R.id.txt_phone);
txt_matricula = findViewById(R.id.txt_matricula);
img_foto = findViewById(R.id.img_foto);
spinner = findViewById(R.id.spinner);
btn_Asistir = findViewById(R.id.btn_Asistir);
btn_salida = findViewById(R.id.btn_salida);
btn_historial = findViewById(R.id.btn_historial);
iniciarBaseDeDatos();
leerBaseDatos();
leerEventos();
Asistir();
btn_historial.setOnClickListener(v -> historialDialog().show());
}
/**
El metodo newAsist permite subir los datos obtenidos de la cuenta de google con el que el usuario
inicia sesion, implemente el metodo getLocationPermission() para obtener la ubicacion y pide al usuario que
ingrese el numero de matricula mediante un cuadro de dialogo.
*/
private void newAsist() {
info_user = getIntent().getBundleExtra("info_user");
if (info_user != null) {
txt_nombre.setText(info_user.getString("user_name"));
txt_phone.setText(info_user.getString("user_phone"));
txt_correo.setText(info_user.getString("user_email"));
userId = info_user.getString("user_id");
String photo = info_user.getString("user_photo");
Picasso.get().load(photo).resize(300, 300).error(R.drawable.usuario).into(img_foto);
asistente = new Users(info_user.getString("user_name"), info_user.getString("user_email"), info_user.getString("user_phone"), info_user.getString("user_id"));
DatabaseReference db_upload = db_reference.child("Asistente");
db_upload.child(userId).setValue(asistente);
if (isServiceOk()) {
getLocationPermission();
}
createCustomDialog().show();
}
}
/**
Se crea un cuadro de dialogo de tipo AlertDialog el cual utuliza el archivo matricula.xml como interfaz grafica.
Se obtiene el dato ingresado y es subido directamente a la base de datos del usuario registrado.
*/
private AlertDialog createCustomDialog() {
final AlertDialog alertDialog;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = getLayoutInflater();
// Inflar y establecer el layout para el dialogo
// Pasar nulo como vista principal porque va en el diseño del diálogo
View v = inflater.inflate(R.layout.matricula, null);
//builder.setView(inflater.inflate(R.layout.dialog_signin, null))
EditText edtMatricula = v.findViewById(R.id.edtMatricula);
Button btn_aceptar = v.findViewById(R.id.btn_aceptar);
builder.setView(v);
alertDialog = builder.create();
// Add action buttons
btn_aceptar.setOnClickListener(
v1 -> {
txt_matricula.setText(edtMatricula.getText().toString());
DatabaseReference db_upload = FirebaseDatabase.getInstance().getReference().child("Asistente").child(userId);
db_upload.child("matricula").setValue(edtMatricula.getText().toString());
alertDialog.dismiss();
}
);
return alertDialog;
}
/**
Cuando el ususario ya existe se implementa el metodo presentarDatos, el cual permite tomar los datos del usuario
de la base de datos y cargarlos en los respectivos TextView's del archivo asistente.xml. Unicamente la ubicacion
se actualiza.
*/
private void presentarDatos(){
info_user = getIntent().getBundleExtra("info_user");
if (info_user != null) {
userId = info_user.getString("user_id");
String photo = info_user.getString("user_photo");
Picasso.get().load(photo).resize(300, 300).error(R.drawable.usuario).into(img_foto);
if (isServiceOk()) {
getLocationPermission();
}
}
DatabaseReference db_asist = db_reference.child("Asistente").child(userId);
db_asist.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Users usr = dataSnapshot.getValue(Users.class);
if (usr!=null) {
txt_nombre.setText(usr.getNombre());
txt_correo.setText(usr.getCorreo());
txt_phone.setText(usr.getTelefono());
txt_matricula.setText(usr.getMatricula());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}
/**
Se cierra la sesion de la cuenta google con la cual ingreso el usuario y es enviado directamente a la MainActivity
*/
public void cerrarSesion(View view) {
FirebaseAuth.getInstance().signOut();
finish();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("msg", "cerrarSesion");
startActivity(intent);
}
/**
El metodo iniciarBase de datos permite establecer desde el inicio la referencia base
que se utilizara para navegar por la base de datos de firebase.
*/
private void iniciarBaseDeDatos() {
db_reference = FirebaseDatabase.getInstance().getReference();
}
/**
Se recorre la base de datos en firebase en la sesion Asistente para determinar si el usuario que ingresa
es nuevo o ya ha ingresado anteriormente. Segun el caso, se llamara al respectivo metodo.
*/
private void leerBaseDatos(){
DatabaseReference asistente = db_reference.child("Asistente");
asistente.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
nuevoAsist = true;
info_user = getIntent().getBundleExtra("info_user");
if (info_user!=null) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> data = (HashMap<String, String>) snapshot.getValue();
if (data != null) {
String userId = data.get("idUser");
assert userId != null;
if (userId.equals(info_user.getString("user_id"))) {
nuevoAsist = false;
presentarDatos();
break;
}
}
}
}
if (nuevoAsist){
newAsist();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e(TAG, "Error!", error.toException());
System.out.println(error.getMessage());
}
});
}
/**
El metodo marcarSalida() implemente la accion del boton de marcar salida del estudiante, en el se verifica
el evento que ha seleccionado de la lista en el spinner y luego se compara y verifican la hora del asistente
con respecto a la hora de inicio y finalizacion del evento para obtener la cant de horas asistidas.
*/
private void marcarSalida(){
btn_salida.setOnClickListener(v -> {
if (name_evento != null && info_evento!=null && !name_evento.equals("Seleccione un Evento")) {
String[] fecha_evento = info_evento.get("Fecha").split("/");
Calendar calendar = Calendar.getInstance();
anio=calendar.get(Calendar.YEAR);
mes=calendar.get(Calendar.MONTH)+1;
dia=calendar.get(Calendar.DAY_OF_MONTH);
int horas = calendar.get(Calendar.HOUR_OF_DAY);
int minutos = calendar.get(Calendar.MINUTE);
if (Conectividad()) {
if (Integer.parseInt(fecha_evento[0]) == anio && mes ==Integer.parseInt(fecha_evento[1]) && dia ==Integer.parseInt(fecha_evento[2])) {
Boolean presente = verifica_Asistencia();
if (presente) {
DatabaseReference db_mSalida = db_reference.child("Asistencias");
db_mSalida.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String id_lista = null;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> data = (HashMap<String, String>) snapshot.getValue();
if (data != null) {
if (data.get("evento").equals(name_evento)) {
id_lista = snapshot.getKey();
break;
}
}
}
if (id_lista!=null){
DatabaseReference db_lista = db_mSalida.child(id_lista).child("lista").child(userId);
String horaFin = horas + ":" + minutos;
db_lista.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
HashMap<String, String> dataUser = (HashMap<String, String>) dataSnapshot.getValue();
System.out.println(dataUser);
String[] horaInicio = dataUser.get("horaInicio").split(":");
horaFinE = info_evento.get("horaFin").split(":");
if (Integer.parseInt(horaFinE[0])== horas && minutos <= Integer.parseInt(horaFinE[1])) {
db_lista.child("horaFin").setValue(horaFin);
if (Integer.parseInt(horaInicio[0]) == horas) {
int minTotal = minutos-Integer.parseInt(horaInicio[1]);
String horaFinAsist = 0+"."+minTotal+"h";
System.out.println("aki1");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
} else {
int horasPresente = horas - Integer.parseInt(horaInicio[0]);
if (minutos > Integer.parseInt(horaInicio[1])) {
int minTotal = minutos - Integer.parseInt(horaInicio[1]);
String horaFinAsist = horasPresente+"."+minTotal+"h";
System.out.println("aki2");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
} else {
int minTotal = 60 + minutos - Integer.parseInt(horaInicio[1]);
String horaFinAsist = horasPresente+"."+minTotal+"h";
System.out.println("aki3");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
}
}
}else if (Integer.parseInt(horaFinE[0]) > horas) {
db_lista.child("horaFin").setValue(horaFin);
if (Integer.parseInt(horaInicio[0]) == horas) {
int minTotal = minutos-Integer.parseInt(horaInicio[1]);
String horaFinAsist = 0+"."+minTotal+"h";
System.out.println("aki4");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
} else {
int horasPresente = horas - Integer.parseInt(horaInicio[0]);
if (minutos > Integer.parseInt(horaInicio[1])) {
int minTotal = minutos - Integer.parseInt(horaInicio[1]);
String horaFinAsist = horasPresente+"."+minTotal+"h";
System.out.println("aki5");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
} else {
int minTotal = 60 + minutos - Integer.parseInt(horaInicio[1]);
String horaFinAsist = (horasPresente-1)+"."+minTotal+"h";
System.out.println("aki6");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
}
}
}else{
int minTotal = 0;
int horaTotal = Integer.parseInt(horaFinE[0]) - Integer.parseInt(horaInicio[0]);
if (Integer.parseInt(horaFinE[1]) > Integer.parseInt(horaInicio[1])){
minTotal = Integer.parseInt(horaFinE[1]) - Integer.parseInt(horaInicio[1]);
}else {
if ( Integer.parseInt(horaFinE[1]) < Integer.parseInt(horaInicio[1])){
minTotal = 60 + Integer.parseInt(horaFinE[1]) - Integer.parseInt(horaInicio[1]);
horaTotal = horaTotal-1;
}
}
String horaFinAsist = horaTotal+"."+minTotal+"h";
db_lista.child("numHoras").setValue(horaFinAsist);
db_lista.child("horaFin").setValue(info_evento.get("horaFin"));
Toast.makeText(Asistente.this, "Hora de salida: " + info_evento.get("horaFin")+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
} else {
Toast.makeText(Asistente.this, "Se encuentra fuera de la zona del evento: " + name_evento, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Asistente.this, "Aun no empieza el evento o el evento ya finalizo. Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(Asistente.this, "No dispone de conexion a Internet.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(Asistente.this, "Seleccione un evento o curso primero." + name_evento, Toast.LENGTH_SHORT).show();
}
});
}
/**
Crea un Alert Dialog utilizando con Interfaz grafica historial_asistencias.xml, en el se presenta
todos los eventos que el usuario ha podido asistir, el boton aceptar es utilizado para salir del
cuadro de dialogo.
*/
private AlertDialog historialDialog() {
final AlertDialog alertDialog;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = getLayoutInflater();
// Inflar y establecer el layout para el dialogo
// Pasar nulo como vista principal porque va en el diseño del diálogo
View v = inflater.inflate(R.layout.historial_asistencias, null);
LinearLayout contEvents = v.findViewById(R.id.contEventos);
info_user = getIntent().getBundleExtra("info_user");
if (info_user!= null) {
userId = info_user.getString("user_id");
try {
DatabaseReference db_historial = db_reference.child("Asistente").child(userId).child("listEventos");
db_historial.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
TextView asitEvento = new TextView(getApplicationContext());
String mensaje = "*" + snapshot.getValue(Boolean.parseBoolean(snapshot.getKey())).toString();
asitEvento.setText(mensaje);
asitEvento.setTextSize(20);
asitEvento.setHintTextColor(getResources().getColor(android.R.color.black));
contEvents.addView(asitEvento);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}catch (NullPointerException e){
Toast.makeText(Asistente.this, "No ha asistido a ningún evento todavía.", Toast.LENGTH_SHORT).show();
}
}
Button btn_aceptar = v.findViewById(R.id.btn_aceptar);
builder.setView(v);
alertDialog = builder.create();
// Add action buttons
btn_aceptar.setOnClickListener(
v1 -> alertDialog.dismiss()
);
return alertDialog;
}
/**
El metodo Asistir() verifica el evento existente y extrae las coordenadas de la zona del evento y
las compara con las del estudiante para validar la asistencia. Ademas, se realiza la respectiva
validacion de la fecha y hora del evento.
*/
private void Asistir(){
btn_Asistir.setOnClickListener(v -> {
Calendar calendar = Calendar.getInstance();
anio=calendar.get(Calendar.YEAR);
mes=calendar.get(Calendar.MONTH)+1;
dia=calendar.get(Calendar.DAY_OF_MONTH);
horas=calendar.get(Calendar.HOUR_OF_DAY);
minutos=calendar.get(Calendar.MINUTE);
horaActual= horas+":"+minutos;
if (name_evento!=null && !name_evento.equals("Seleccione un Evento")) {
if (info_evento!= null) {
String[] fecha_evento = info_evento.get("Fecha").split("/");
String[] hora_evento = info_evento.get("horaInicio").split(":");
String[] hora_finEvento = info_evento.get("horaFin").split(":");
int minRetrado = Integer.parseInt(info_evento.get("minRetraso"));
Boolean retraso = Boolean.parseBoolean(info_evento.get("Retraso"));
if (Conectividad()) {
if (Integer.parseInt(fecha_evento[0]) == anio && Integer.parseInt(fecha_evento[1]) == mes && Integer.parseInt(fecha_evento[2]) == dia) {
if (retraso) {
if (horas == Integer.parseInt(hora_evento[0]) && minutos <= (Integer.parseInt(hora_evento[1]) + minRetrado)
&& minutos >= Integer.parseInt(hora_evento[1])) {
subirAsistencia(false);
} else if (horas >= Integer.parseInt(hora_evento[0]) && minutos > (Integer.parseInt(hora_evento[1]) + minRetrado)) {
if (horas == Integer.parseInt(hora_finEvento[0]) && minutos <= Integer.parseInt(hora_finEvento[1])) {
subirAsistencia(true);
} else if (horas < Integer.parseInt(hora_finEvento[0])) {
subirAsistencia(true);
} else {
Toast.makeText(Asistente.this, "Es posible que el evento ya haya finalizado. \n Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Asistente.this, "Aun no empieza el evento. Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
}
} else {
if (horas >= Integer.parseInt(hora_evento[0])) {
if (horas > Integer.parseInt(hora_finEvento[0])) {
Toast.makeText(Asistente.this, "Es posible que el evento ya haya finalizado. \n Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
} else if (horas == Integer.parseInt(hora_finEvento[0]) && minutos <= Integer.parseInt(hora_finEvento[1])) {
subirAsistencia(false);
} else if (horas < Integer.parseInt(hora_finEvento[0])) {
subirAsistencia(false);
} else {
Toast.makeText(Asistente.this, "Es posible que el evento ya haya finalizado. \n Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Asistente.this, "Aun no empieza el evento o el evento ya finalizo. \n Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(Asistente.this, "Aun no empieza el evento o el evento ya finalizo. Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(Asistente.this, "No dispone de conexion a Internet.", Toast.LENGTH_LONG).show();
}
}
}else{
Toast.makeText(Asistente.this, "Escoja el evento/curso primero",Toast.LENGTH_SHORT).show();
}
});
}
/**
El metodo subirAsistencia(0 permite subir la asistencia del usuario a la base de datos en firebase,
en las respectivas ramas de Asistente y Asistencias, tomando como dato previo el parametro tipo Boolean
de atrasado.
*/
private void subirAsistencia(Boolean atrasado) {
boolean present = verifica_Asistencia();
boolean atraso = atrasado;
DatabaseReference db_listaAsistencia = db_reference.child("Asistencias");
DatabaseReference db_dataAsistente = db_reference.child("Asistente").child(userId).child("listEventos");
db_dataAsistente.child(idEvento).setValue(name_evento);
System.out.println(present+"-"+atrasado);
db_listaAsistencia.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
HashMap<String, String> info_lista = null;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
info_lista = (HashMap<String, String>) snapshot.getValue();
if (info_lista!= null) {
if (info_lista.get("evento").equals(name_evento)) {
idLista = snapshot.getKey();
}else{
System.out.println("no lista");
}
}
}
System.out.println(idLista);
if (atraso) {
Lista lista = new Lista(userId, txt_nombre.getText().toString(), horaActual, "Atrasado", idEvento,0);
db_listaAsistencia.child(idLista).child("lista").child(userId).setValue(lista);
Toast.makeText(Asistente.this, "Asistencia confirmada al evento: "+name_evento+" como: Atrasado", Toast.LENGTH_SHORT).show();
}else{
Lista lista = new Lista(userId, txt_nombre.getText().toString(), horaActual, "Presente", idEvento,0);
db_listaAsistencia.child(idLista).child("lista").child(userId).setValue(lista);
Toast.makeText(Asistente.this, "Asistencia confirmada al evento: "+name_evento+" como: Presente", Toast.LENGTH_SHORT).show();
}
System.out.println("Data Asistente subido");
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}
/**
El metodo verifica_Asistencia() permite verificar si el estudiante se encuentra dentro de la zona
de asistencia del evento, caso contrario enviara un mensaje de aviso. Regresa como valor un valor
tipo Boolean con la respuesta de la validacion.
*/
private boolean verifica_Asistencia(){
boolean presente =false;
Double user_lat = Double.valueOf(txt_Latitud.getText().toString());
Double user_long = Double.valueOf(txt_Longitud.getText().toString());
Double Dps_Lat1 = Double.valueOf(disp_Lat1);
Double Dps_Lat2 = Double.valueOf(disp_Lat2);
Double Dps_Long1 = Double.valueOf(disp_Long1);
Double Dps_Long2 = Double.valueOf(disp_Long2);
System.out.println(disp_Lat1+"-"+disp_Lat2);
System.out.println(user_lat);
System.out.println(disp_Long1+"-"+disp_Long2);
System.out.println(user_long);
if (Dps_Lat1 >=Dps_Lat2) {
if ((Dps_Long1>=Dps_Long2) && (user_lat<=Dps_Lat1) && (user_lat>=Dps_Lat2) && (user_long<=Dps_Long1) && (user_long >=Dps_Long2)){
presente = true;
}
if ((Dps_Long1<=Dps_Long2) && (user_lat<=Dps_Lat1) && (user_lat>=Dps_Lat2) && (user_long>=Dps_Long1) && (user_long <=Dps_Long2)) {
presente = true;
}
if (!presente) {
Toast.makeText(getApplicationContext(), "Se encuentra fuera del rango", Toast.LENGTH_SHORT).show();
}
}
if (Dps_Lat1 <=Dps_Lat2) {
if ((Dps_Long1>=Dps_Long2) && (user_lat>=Dps_Lat1) && (user_lat<=Dps_Lat2) && (user_long<=Dps_Long1) && (user_long >=Dps_Long2)){
presente = true;
}
if ((Dps_Long1<=Dps_Long2) && (user_lat>=Dps_Lat1) && (user_lat<=Dps_Lat2) && (user_long>=Dps_Long1) && (user_long <=Dps_Long2)) {
presente = true;
}
if (!presente) {
Toast.makeText(getApplicationContext(), "Se encuentra fuera del rango", Toast.LENGTH_SHORT).show();
}
}
return presente;
}
/**
Se recorre la sesccion Evento de la base de datos para agregar todos los nombres de los eventos existentes
en el spinner View, y se implementa su accion al ser accedido por el usuario para obtener las corrdenas del evento
seleccionado a traves del metodo leerDispositivo().
*/
private void leerEventos(){
DatabaseReference db_evento = db_reference.child("Evento");
db_evento.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
eventos = new ArrayList<String>();
eventos.add("Seleccione un Evento");
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> data = (HashMap<String, String>) snapshot.getValue();
if (data!= null) {
eventos.add(data.get("Nom_evento"));
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, eventos);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item );
spinner.setAdapter(adapter);
AdapterView.OnItemSelectedListener eventSelected = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> spinner, View container, int position, long id) {
name_evento = spinner.getItemAtPosition(position).toString();
if (position!=0) {
Toast.makeText(Asistente.this,"Ha seleccionado el evento: " + name_evento, Toast.LENGTH_SHORT).show();
DatabaseReference db_eventoAsistir = db_reference.child("Evento");
if (name_evento!=null && !name_evento.equals("Seleccione un Evento")) {
db_eventoAsistir.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> dataEvento = (HashMap<String, String>) snapshot.getValue();
if (dataEvento!= null && dataEvento.get("Nom_evento").equals(name_evento)) {
info_evento = dataEvento;
idEvento = snapshot.getKey();
break;
}
}
leerDispositivo(name_evento);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
spinner.setOnItemSelectedListener(eventSelected);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e(TAG, "Error!", error.toException());
}
});
}
/**
Se recorre la sesion Eventos de la base de datos y se compara con el @parametro ingresado curso para extraer
las coordenadas de dicho evento.
*/
private void leerDispositivo(String curso){
DatabaseReference db_dispositivo = db_reference.child("Dispositivo");
db_dispositivo.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> data = (HashMap<String, String>) snapshot.getValue();
if (data!=null) {
if (data.get("Evento").equals(curso)) {
disp_Lat1 = data.get("Latitud1");
disp_Long1 = data.get("Longitud1");
disp_Lat2 = data.get("Latitud2");
disp_Long2 = data.get("Longitud2");
break;
}
}
}
Asistir();
marcarSalida();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e(TAG, "Error!", error.toException());
System.out.println(error.getMessage());
}
});
}
/**
Devuelve un valor tipo Bool indicando si hay o no conectividad del dispositivo con alguna red de internet.
*/
private boolean Conectividad(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
/**
Verifica si el servicio de google service esta activo para el correcto funcionamiento de las API's
de google utilizadas como geolocalizacion, googleAccount.
*/
private boolean isServiceOk(){
Log.d(TAG, "isServiceOk: checking google service version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(Asistente.this);
if (available == ConnectionResult.SUCCESS){
//Everything is fine and the user can make map request
Log.d(TAG, "isServiceOk: verything is fine and the user can make map request");
return true;
} else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){
//an error ocured but we can resolt it
Log.d(TAG, "isServiceOk: an error occures but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(Asistente.this, available, ERROR_DIALOG_REQUEST);
dialog.show();
}else{
Toast.makeText(this, "You can't make map request", Toast.LENGTH_SHORT).show();
}
return false;
}
/**
Asistir() permite obtener las coordenadas de latitud y longitud del dispositivo en ese
instante y los sobre-escribe en el txt_Latitud y txt_longitud de la interfaz, si se produce un error
mandara una ioException o un mensaje de que la localizacion no se encuentra o es nula.
*/
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting device current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionGaranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(task -> {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
if (currentLocation !=null) {
txt_Latitud.setText(String.valueOf(currentLocation.getLatitude()));
txt_Longitud.setText(String.valueOf(currentLocation.getLongitude()));
DatabaseReference db_upload = FirebaseDatabase.getInstance().getReference().child("Asistente").child(userId);
db_upload.child("asistLat").setValue(String.valueOf(currentLocation.getLatitude()));
db_upload.child("asistLong").setValue(String.valueOf(currentLocation.getLongitude()));
}
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(Asistente.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
/**
EL metodo getLocationPermission() verifica que los permisos y privilegios hayan sido aceptado,
de no ser asi llama al metodo onResquestPermissionsResults para solicitarlos.
*/
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permission.");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION)== PackageManager.PERMISSION_GRANTED){
mLocationPermissionGaranted = true;
getDeviceLocation();
}else{
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
/**
onRequestPermissionResult() permite solicitar al usuario los permisos de poder
utilizar su ubicacion otorgandole a la app los privilegios para obtener las datos de
latitud y longitud. De no ser asi, mostrara un mensaje de falla o no concedido.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mLocationPermissionGaranted = false;
Log.d(TAG, "onRequestPermissionsResult: called.");
switch ( requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if (grantResults.length >0){
for (int i =0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGaranted = false;
Log.d(TAG, "onRequestPermissionsResult: failed.");
return;
}
}
mLocationPermissionGaranted =true;
Log.d(TAG, "onRequestPermissionsResult: permission granted.");
//obtener la localizacion
getDeviceLocation();
}
}
}
}
}
| UTF-8 | Java | 46,072 | java | Asistente.java | Java | [] | null | [] | package com.example.asistenciaautomatica;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
public class Asistente extends AppCompatActivity{
private static final String TAG = "Asistente";
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
//vars
private boolean mLocationPermissionGaranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
//views
private Bundle info_user;
private Button btn_Asistir;
private Button btn_salida;
private Button btn_historial;
private TextView txt_nombre;
private TextView txt_correo;
private TextView txt_phone;
private TextView txt_Latitud;
private TextView txt_Longitud;
private TextView txt_matricula;
private ImageView img_foto;
private String userId;
private String disp_Lat1;
private String disp_Long1;
private String disp_Lat2;
private String disp_Long2;
private String name_evento;
private String idEvento;
private String horaActual;
private String idLista;
private String[] horaFinE;
private Spinner spinner;
private Boolean nuevoAsist;
private List<String> eventos;
private Users asistente;
private int anio,mes,dia,horas,minutos;
private HashMap<String, String> info_evento = null;
private DatabaseReference db_reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_asistente);
txt_Latitud = findViewById(R.id.txt_Latitud);
txt_Longitud = findViewById(R.id.txt_Longitud);
txt_nombre = findViewById(R.id.txt_nombre);
txt_correo = findViewById(R.id.txt_correo);
txt_phone = findViewById(R.id.txt_phone);
txt_matricula = findViewById(R.id.txt_matricula);
img_foto = findViewById(R.id.img_foto);
spinner = findViewById(R.id.spinner);
btn_Asistir = findViewById(R.id.btn_Asistir);
btn_salida = findViewById(R.id.btn_salida);
btn_historial = findViewById(R.id.btn_historial);
iniciarBaseDeDatos();
leerBaseDatos();
leerEventos();
Asistir();
btn_historial.setOnClickListener(v -> historialDialog().show());
}
/**
El metodo newAsist permite subir los datos obtenidos de la cuenta de google con el que el usuario
inicia sesion, implemente el metodo getLocationPermission() para obtener la ubicacion y pide al usuario que
ingrese el numero de matricula mediante un cuadro de dialogo.
*/
private void newAsist() {
info_user = getIntent().getBundleExtra("info_user");
if (info_user != null) {
txt_nombre.setText(info_user.getString("user_name"));
txt_phone.setText(info_user.getString("user_phone"));
txt_correo.setText(info_user.getString("user_email"));
userId = info_user.getString("user_id");
String photo = info_user.getString("user_photo");
Picasso.get().load(photo).resize(300, 300).error(R.drawable.usuario).into(img_foto);
asistente = new Users(info_user.getString("user_name"), info_user.getString("user_email"), info_user.getString("user_phone"), info_user.getString("user_id"));
DatabaseReference db_upload = db_reference.child("Asistente");
db_upload.child(userId).setValue(asistente);
if (isServiceOk()) {
getLocationPermission();
}
createCustomDialog().show();
}
}
/**
Se crea un cuadro de dialogo de tipo AlertDialog el cual utuliza el archivo matricula.xml como interfaz grafica.
Se obtiene el dato ingresado y es subido directamente a la base de datos del usuario registrado.
*/
private AlertDialog createCustomDialog() {
final AlertDialog alertDialog;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = getLayoutInflater();
// Inflar y establecer el layout para el dialogo
// Pasar nulo como vista principal porque va en el diseño del diálogo
View v = inflater.inflate(R.layout.matricula, null);
//builder.setView(inflater.inflate(R.layout.dialog_signin, null))
EditText edtMatricula = v.findViewById(R.id.edtMatricula);
Button btn_aceptar = v.findViewById(R.id.btn_aceptar);
builder.setView(v);
alertDialog = builder.create();
// Add action buttons
btn_aceptar.setOnClickListener(
v1 -> {
txt_matricula.setText(edtMatricula.getText().toString());
DatabaseReference db_upload = FirebaseDatabase.getInstance().getReference().child("Asistente").child(userId);
db_upload.child("matricula").setValue(edtMatricula.getText().toString());
alertDialog.dismiss();
}
);
return alertDialog;
}
/**
Cuando el ususario ya existe se implementa el metodo presentarDatos, el cual permite tomar los datos del usuario
de la base de datos y cargarlos en los respectivos TextView's del archivo asistente.xml. Unicamente la ubicacion
se actualiza.
*/
private void presentarDatos(){
info_user = getIntent().getBundleExtra("info_user");
if (info_user != null) {
userId = info_user.getString("user_id");
String photo = info_user.getString("user_photo");
Picasso.get().load(photo).resize(300, 300).error(R.drawable.usuario).into(img_foto);
if (isServiceOk()) {
getLocationPermission();
}
}
DatabaseReference db_asist = db_reference.child("Asistente").child(userId);
db_asist.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Users usr = dataSnapshot.getValue(Users.class);
if (usr!=null) {
txt_nombre.setText(usr.getNombre());
txt_correo.setText(usr.getCorreo());
txt_phone.setText(usr.getTelefono());
txt_matricula.setText(usr.getMatricula());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}
/**
Se cierra la sesion de la cuenta google con la cual ingreso el usuario y es enviado directamente a la MainActivity
*/
public void cerrarSesion(View view) {
FirebaseAuth.getInstance().signOut();
finish();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("msg", "cerrarSesion");
startActivity(intent);
}
/**
El metodo iniciarBase de datos permite establecer desde el inicio la referencia base
que se utilizara para navegar por la base de datos de firebase.
*/
private void iniciarBaseDeDatos() {
db_reference = FirebaseDatabase.getInstance().getReference();
}
/**
Se recorre la base de datos en firebase en la sesion Asistente para determinar si el usuario que ingresa
es nuevo o ya ha ingresado anteriormente. Segun el caso, se llamara al respectivo metodo.
*/
private void leerBaseDatos(){
DatabaseReference asistente = db_reference.child("Asistente");
asistente.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
nuevoAsist = true;
info_user = getIntent().getBundleExtra("info_user");
if (info_user!=null) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> data = (HashMap<String, String>) snapshot.getValue();
if (data != null) {
String userId = data.get("idUser");
assert userId != null;
if (userId.equals(info_user.getString("user_id"))) {
nuevoAsist = false;
presentarDatos();
break;
}
}
}
}
if (nuevoAsist){
newAsist();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e(TAG, "Error!", error.toException());
System.out.println(error.getMessage());
}
});
}
/**
El metodo marcarSalida() implemente la accion del boton de marcar salida del estudiante, en el se verifica
el evento que ha seleccionado de la lista en el spinner y luego se compara y verifican la hora del asistente
con respecto a la hora de inicio y finalizacion del evento para obtener la cant de horas asistidas.
*/
private void marcarSalida(){
btn_salida.setOnClickListener(v -> {
if (name_evento != null && info_evento!=null && !name_evento.equals("Seleccione un Evento")) {
String[] fecha_evento = info_evento.get("Fecha").split("/");
Calendar calendar = Calendar.getInstance();
anio=calendar.get(Calendar.YEAR);
mes=calendar.get(Calendar.MONTH)+1;
dia=calendar.get(Calendar.DAY_OF_MONTH);
int horas = calendar.get(Calendar.HOUR_OF_DAY);
int minutos = calendar.get(Calendar.MINUTE);
if (Conectividad()) {
if (Integer.parseInt(fecha_evento[0]) == anio && mes ==Integer.parseInt(fecha_evento[1]) && dia ==Integer.parseInt(fecha_evento[2])) {
Boolean presente = verifica_Asistencia();
if (presente) {
DatabaseReference db_mSalida = db_reference.child("Asistencias");
db_mSalida.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String id_lista = null;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> data = (HashMap<String, String>) snapshot.getValue();
if (data != null) {
if (data.get("evento").equals(name_evento)) {
id_lista = snapshot.getKey();
break;
}
}
}
if (id_lista!=null){
DatabaseReference db_lista = db_mSalida.child(id_lista).child("lista").child(userId);
String horaFin = horas + ":" + minutos;
db_lista.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
HashMap<String, String> dataUser = (HashMap<String, String>) dataSnapshot.getValue();
System.out.println(dataUser);
String[] horaInicio = dataUser.get("horaInicio").split(":");
horaFinE = info_evento.get("horaFin").split(":");
if (Integer.parseInt(horaFinE[0])== horas && minutos <= Integer.parseInt(horaFinE[1])) {
db_lista.child("horaFin").setValue(horaFin);
if (Integer.parseInt(horaInicio[0]) == horas) {
int minTotal = minutos-Integer.parseInt(horaInicio[1]);
String horaFinAsist = 0+"."+minTotal+"h";
System.out.println("aki1");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
} else {
int horasPresente = horas - Integer.parseInt(horaInicio[0]);
if (minutos > Integer.parseInt(horaInicio[1])) {
int minTotal = minutos - Integer.parseInt(horaInicio[1]);
String horaFinAsist = horasPresente+"."+minTotal+"h";
System.out.println("aki2");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
} else {
int minTotal = 60 + minutos - Integer.parseInt(horaInicio[1]);
String horaFinAsist = horasPresente+"."+minTotal+"h";
System.out.println("aki3");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
}
}
}else if (Integer.parseInt(horaFinE[0]) > horas) {
db_lista.child("horaFin").setValue(horaFin);
if (Integer.parseInt(horaInicio[0]) == horas) {
int minTotal = minutos-Integer.parseInt(horaInicio[1]);
String horaFinAsist = 0+"."+minTotal+"h";
System.out.println("aki4");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
} else {
int horasPresente = horas - Integer.parseInt(horaInicio[0]);
if (minutos > Integer.parseInt(horaInicio[1])) {
int minTotal = minutos - Integer.parseInt(horaInicio[1]);
String horaFinAsist = horasPresente+"."+minTotal+"h";
System.out.println("aki5");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
} else {
int minTotal = 60 + minutos - Integer.parseInt(horaInicio[1]);
String horaFinAsist = (horasPresente-1)+"."+minTotal+"h";
System.out.println("aki6");
db_lista.child("numHoras").setValue(horaFinAsist);
Toast.makeText(Asistente.this, "Hora de salida: " + horaFin+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
}
}
}else{
int minTotal = 0;
int horaTotal = Integer.parseInt(horaFinE[0]) - Integer.parseInt(horaInicio[0]);
if (Integer.parseInt(horaFinE[1]) > Integer.parseInt(horaInicio[1])){
minTotal = Integer.parseInt(horaFinE[1]) - Integer.parseInt(horaInicio[1]);
}else {
if ( Integer.parseInt(horaFinE[1]) < Integer.parseInt(horaInicio[1])){
minTotal = 60 + Integer.parseInt(horaFinE[1]) - Integer.parseInt(horaInicio[1]);
horaTotal = horaTotal-1;
}
}
String horaFinAsist = horaTotal+"."+minTotal+"h";
db_lista.child("numHoras").setValue(horaFinAsist);
db_lista.child("horaFin").setValue(info_evento.get("horaFin"));
Toast.makeText(Asistente.this, "Hora de salida: " + info_evento.get("horaFin")+" cant. horas presente: "+horaFinAsist, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
} else {
Toast.makeText(Asistente.this, "Se encuentra fuera de la zona del evento: " + name_evento, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Asistente.this, "Aun no empieza el evento o el evento ya finalizo. Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(Asistente.this, "No dispone de conexion a Internet.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(Asistente.this, "Seleccione un evento o curso primero." + name_evento, Toast.LENGTH_SHORT).show();
}
});
}
/**
Crea un Alert Dialog utilizando con Interfaz grafica historial_asistencias.xml, en el se presenta
todos los eventos que el usuario ha podido asistir, el boton aceptar es utilizado para salir del
cuadro de dialogo.
*/
private AlertDialog historialDialog() {
final AlertDialog alertDialog;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = getLayoutInflater();
// Inflar y establecer el layout para el dialogo
// Pasar nulo como vista principal porque va en el diseño del diálogo
View v = inflater.inflate(R.layout.historial_asistencias, null);
LinearLayout contEvents = v.findViewById(R.id.contEventos);
info_user = getIntent().getBundleExtra("info_user");
if (info_user!= null) {
userId = info_user.getString("user_id");
try {
DatabaseReference db_historial = db_reference.child("Asistente").child(userId).child("listEventos");
db_historial.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
TextView asitEvento = new TextView(getApplicationContext());
String mensaje = "*" + snapshot.getValue(Boolean.parseBoolean(snapshot.getKey())).toString();
asitEvento.setText(mensaje);
asitEvento.setTextSize(20);
asitEvento.setHintTextColor(getResources().getColor(android.R.color.black));
contEvents.addView(asitEvento);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}catch (NullPointerException e){
Toast.makeText(Asistente.this, "No ha asistido a ningún evento todavía.", Toast.LENGTH_SHORT).show();
}
}
Button btn_aceptar = v.findViewById(R.id.btn_aceptar);
builder.setView(v);
alertDialog = builder.create();
// Add action buttons
btn_aceptar.setOnClickListener(
v1 -> alertDialog.dismiss()
);
return alertDialog;
}
/**
El metodo Asistir() verifica el evento existente y extrae las coordenadas de la zona del evento y
las compara con las del estudiante para validar la asistencia. Ademas, se realiza la respectiva
validacion de la fecha y hora del evento.
*/
private void Asistir(){
btn_Asistir.setOnClickListener(v -> {
Calendar calendar = Calendar.getInstance();
anio=calendar.get(Calendar.YEAR);
mes=calendar.get(Calendar.MONTH)+1;
dia=calendar.get(Calendar.DAY_OF_MONTH);
horas=calendar.get(Calendar.HOUR_OF_DAY);
minutos=calendar.get(Calendar.MINUTE);
horaActual= horas+":"+minutos;
if (name_evento!=null && !name_evento.equals("Seleccione un Evento")) {
if (info_evento!= null) {
String[] fecha_evento = info_evento.get("Fecha").split("/");
String[] hora_evento = info_evento.get("horaInicio").split(":");
String[] hora_finEvento = info_evento.get("horaFin").split(":");
int minRetrado = Integer.parseInt(info_evento.get("minRetraso"));
Boolean retraso = Boolean.parseBoolean(info_evento.get("Retraso"));
if (Conectividad()) {
if (Integer.parseInt(fecha_evento[0]) == anio && Integer.parseInt(fecha_evento[1]) == mes && Integer.parseInt(fecha_evento[2]) == dia) {
if (retraso) {
if (horas == Integer.parseInt(hora_evento[0]) && minutos <= (Integer.parseInt(hora_evento[1]) + minRetrado)
&& minutos >= Integer.parseInt(hora_evento[1])) {
subirAsistencia(false);
} else if (horas >= Integer.parseInt(hora_evento[0]) && minutos > (Integer.parseInt(hora_evento[1]) + minRetrado)) {
if (horas == Integer.parseInt(hora_finEvento[0]) && minutos <= Integer.parseInt(hora_finEvento[1])) {
subirAsistencia(true);
} else if (horas < Integer.parseInt(hora_finEvento[0])) {
subirAsistencia(true);
} else {
Toast.makeText(Asistente.this, "Es posible que el evento ya haya finalizado. \n Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Asistente.this, "Aun no empieza el evento. Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
}
} else {
if (horas >= Integer.parseInt(hora_evento[0])) {
if (horas > Integer.parseInt(hora_finEvento[0])) {
Toast.makeText(Asistente.this, "Es posible que el evento ya haya finalizado. \n Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
} else if (horas == Integer.parseInt(hora_finEvento[0]) && minutos <= Integer.parseInt(hora_finEvento[1])) {
subirAsistencia(false);
} else if (horas < Integer.parseInt(hora_finEvento[0])) {
subirAsistencia(false);
} else {
Toast.makeText(Asistente.this, "Es posible que el evento ya haya finalizado. \n Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Asistente.this, "Aun no empieza el evento o el evento ya finalizo. \n Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(Asistente.this, "Aun no empieza el evento o el evento ya finalizo. Contactese con al tutor o administrador del " +
"evento para mayor informacion.", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(Asistente.this, "No dispone de conexion a Internet.", Toast.LENGTH_LONG).show();
}
}
}else{
Toast.makeText(Asistente.this, "Escoja el evento/curso primero",Toast.LENGTH_SHORT).show();
}
});
}
/**
El metodo subirAsistencia(0 permite subir la asistencia del usuario a la base de datos en firebase,
en las respectivas ramas de Asistente y Asistencias, tomando como dato previo el parametro tipo Boolean
de atrasado.
*/
private void subirAsistencia(Boolean atrasado) {
boolean present = verifica_Asistencia();
boolean atraso = atrasado;
DatabaseReference db_listaAsistencia = db_reference.child("Asistencias");
DatabaseReference db_dataAsistente = db_reference.child("Asistente").child(userId).child("listEventos");
db_dataAsistente.child(idEvento).setValue(name_evento);
System.out.println(present+"-"+atrasado);
db_listaAsistencia.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
HashMap<String, String> info_lista = null;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
info_lista = (HashMap<String, String>) snapshot.getValue();
if (info_lista!= null) {
if (info_lista.get("evento").equals(name_evento)) {
idLista = snapshot.getKey();
}else{
System.out.println("no lista");
}
}
}
System.out.println(idLista);
if (atraso) {
Lista lista = new Lista(userId, txt_nombre.getText().toString(), horaActual, "Atrasado", idEvento,0);
db_listaAsistencia.child(idLista).child("lista").child(userId).setValue(lista);
Toast.makeText(Asistente.this, "Asistencia confirmada al evento: "+name_evento+" como: Atrasado", Toast.LENGTH_SHORT).show();
}else{
Lista lista = new Lista(userId, txt_nombre.getText().toString(), horaActual, "Presente", idEvento,0);
db_listaAsistencia.child(idLista).child("lista").child(userId).setValue(lista);
Toast.makeText(Asistente.this, "Asistencia confirmada al evento: "+name_evento+" como: Presente", Toast.LENGTH_SHORT).show();
}
System.out.println("Data Asistente subido");
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}
/**
El metodo verifica_Asistencia() permite verificar si el estudiante se encuentra dentro de la zona
de asistencia del evento, caso contrario enviara un mensaje de aviso. Regresa como valor un valor
tipo Boolean con la respuesta de la validacion.
*/
private boolean verifica_Asistencia(){
boolean presente =false;
Double user_lat = Double.valueOf(txt_Latitud.getText().toString());
Double user_long = Double.valueOf(txt_Longitud.getText().toString());
Double Dps_Lat1 = Double.valueOf(disp_Lat1);
Double Dps_Lat2 = Double.valueOf(disp_Lat2);
Double Dps_Long1 = Double.valueOf(disp_Long1);
Double Dps_Long2 = Double.valueOf(disp_Long2);
System.out.println(disp_Lat1+"-"+disp_Lat2);
System.out.println(user_lat);
System.out.println(disp_Long1+"-"+disp_Long2);
System.out.println(user_long);
if (Dps_Lat1 >=Dps_Lat2) {
if ((Dps_Long1>=Dps_Long2) && (user_lat<=Dps_Lat1) && (user_lat>=Dps_Lat2) && (user_long<=Dps_Long1) && (user_long >=Dps_Long2)){
presente = true;
}
if ((Dps_Long1<=Dps_Long2) && (user_lat<=Dps_Lat1) && (user_lat>=Dps_Lat2) && (user_long>=Dps_Long1) && (user_long <=Dps_Long2)) {
presente = true;
}
if (!presente) {
Toast.makeText(getApplicationContext(), "Se encuentra fuera del rango", Toast.LENGTH_SHORT).show();
}
}
if (Dps_Lat1 <=Dps_Lat2) {
if ((Dps_Long1>=Dps_Long2) && (user_lat>=Dps_Lat1) && (user_lat<=Dps_Lat2) && (user_long<=Dps_Long1) && (user_long >=Dps_Long2)){
presente = true;
}
if ((Dps_Long1<=Dps_Long2) && (user_lat>=Dps_Lat1) && (user_lat<=Dps_Lat2) && (user_long>=Dps_Long1) && (user_long <=Dps_Long2)) {
presente = true;
}
if (!presente) {
Toast.makeText(getApplicationContext(), "Se encuentra fuera del rango", Toast.LENGTH_SHORT).show();
}
}
return presente;
}
/**
Se recorre la sesccion Evento de la base de datos para agregar todos los nombres de los eventos existentes
en el spinner View, y se implementa su accion al ser accedido por el usuario para obtener las corrdenas del evento
seleccionado a traves del metodo leerDispositivo().
*/
private void leerEventos(){
DatabaseReference db_evento = db_reference.child("Evento");
db_evento.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
eventos = new ArrayList<String>();
eventos.add("Seleccione un Evento");
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> data = (HashMap<String, String>) snapshot.getValue();
if (data!= null) {
eventos.add(data.get("Nom_evento"));
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, eventos);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item );
spinner.setAdapter(adapter);
AdapterView.OnItemSelectedListener eventSelected = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> spinner, View container, int position, long id) {
name_evento = spinner.getItemAtPosition(position).toString();
if (position!=0) {
Toast.makeText(Asistente.this,"Ha seleccionado el evento: " + name_evento, Toast.LENGTH_SHORT).show();
DatabaseReference db_eventoAsistir = db_reference.child("Evento");
if (name_evento!=null && !name_evento.equals("Seleccione un Evento")) {
db_eventoAsistir.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> dataEvento = (HashMap<String, String>) snapshot.getValue();
if (dataEvento!= null && dataEvento.get("Nom_evento").equals(name_evento)) {
info_evento = dataEvento;
idEvento = snapshot.getKey();
break;
}
}
leerDispositivo(name_evento);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Error!", databaseError.toException());
}
});
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
spinner.setOnItemSelectedListener(eventSelected);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e(TAG, "Error!", error.toException());
}
});
}
/**
Se recorre la sesion Eventos de la base de datos y se compara con el @parametro ingresado curso para extraer
las coordenadas de dicho evento.
*/
private void leerDispositivo(String curso){
DatabaseReference db_dispositivo = db_reference.child("Dispositivo");
db_dispositivo.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HashMap<String, String> data = (HashMap<String, String>) snapshot.getValue();
if (data!=null) {
if (data.get("Evento").equals(curso)) {
disp_Lat1 = data.get("Latitud1");
disp_Long1 = data.get("Longitud1");
disp_Lat2 = data.get("Latitud2");
disp_Long2 = data.get("Longitud2");
break;
}
}
}
Asistir();
marcarSalida();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e(TAG, "Error!", error.toException());
System.out.println(error.getMessage());
}
});
}
/**
Devuelve un valor tipo Bool indicando si hay o no conectividad del dispositivo con alguna red de internet.
*/
private boolean Conectividad(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
/**
Verifica si el servicio de google service esta activo para el correcto funcionamiento de las API's
de google utilizadas como geolocalizacion, googleAccount.
*/
private boolean isServiceOk(){
Log.d(TAG, "isServiceOk: checking google service version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(Asistente.this);
if (available == ConnectionResult.SUCCESS){
//Everything is fine and the user can make map request
Log.d(TAG, "isServiceOk: verything is fine and the user can make map request");
return true;
} else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){
//an error ocured but we can resolt it
Log.d(TAG, "isServiceOk: an error occures but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(Asistente.this, available, ERROR_DIALOG_REQUEST);
dialog.show();
}else{
Toast.makeText(this, "You can't make map request", Toast.LENGTH_SHORT).show();
}
return false;
}
/**
Asistir() permite obtener las coordenadas de latitud y longitud del dispositivo en ese
instante y los sobre-escribe en el txt_Latitud y txt_longitud de la interfaz, si se produce un error
mandara una ioException o un mensaje de que la localizacion no se encuentra o es nula.
*/
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting device current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionGaranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(task -> {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
if (currentLocation !=null) {
txt_Latitud.setText(String.valueOf(currentLocation.getLatitude()));
txt_Longitud.setText(String.valueOf(currentLocation.getLongitude()));
DatabaseReference db_upload = FirebaseDatabase.getInstance().getReference().child("Asistente").child(userId);
db_upload.child("asistLat").setValue(String.valueOf(currentLocation.getLatitude()));
db_upload.child("asistLong").setValue(String.valueOf(currentLocation.getLongitude()));
}
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(Asistente.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
/**
EL metodo getLocationPermission() verifica que los permisos y privilegios hayan sido aceptado,
de no ser asi llama al metodo onResquestPermissionsResults para solicitarlos.
*/
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permission.");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION)== PackageManager.PERMISSION_GRANTED){
mLocationPermissionGaranted = true;
getDeviceLocation();
}else{
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
/**
onRequestPermissionResult() permite solicitar al usuario los permisos de poder
utilizar su ubicacion otorgandole a la app los privilegios para obtener las datos de
latitud y longitud. De no ser asi, mostrara un mensaje de falla o no concedido.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mLocationPermissionGaranted = false;
Log.d(TAG, "onRequestPermissionsResult: called.");
switch ( requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if (grantResults.length >0){
for (int i =0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGaranted = false;
Log.d(TAG, "onRequestPermissionsResult: failed.");
return;
}
}
mLocationPermissionGaranted =true;
Log.d(TAG, "onRequestPermissionsResult: permission granted.");
//obtener la localizacion
getDeviceLocation();
}
}
}
}
}
| 46,072 | 0.528893 | 0.525724 | 920 | 49.071739 | 41.130455 | 198 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.58913 | false | false | 0 |
597b16cd845fd20cc0eaa7418a27b3f5ec44fa81 | 31,971,736,586,135 | b992259d58de4e94dbf2daca93f52863e682420f | /app/src/main/java/org/lntorrent/libretorrent/service/FeedDownloaderWorker.java | 4f7ae0dd81da22f9ec894e5574d4cf021b3687a4 | [] | no_license | hamzadevc/LNTorrentApp | https://github.com/hamzadevc/LNTorrentApp | 4b82e95b836b456a43731a9df49fc4c4dc2f9efb | 8ac52ced62028f97628bef06b0d3a6f684830885 | refs/heads/master | 2022-12-03T20:05:40.921000 | 2020-08-25T13:32:01 | 2020-08-25T13:32:01 | 290,222,079 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.lntorrent.libretorrent.service;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import org.lntorrent.libretorrent.core.RepositoryHelper;
import org.lntorrent.libretorrent.core.exception.DecodeException;
import org.lntorrent.libretorrent.core.exception.FetchLinkException;
import org.lntorrent.libretorrent.core.model.AddTorrentParams;
import org.lntorrent.libretorrent.core.model.TorrentEngine;
import org.lntorrent.libretorrent.core.model.data.MagnetInfo;
import org.lntorrent.libretorrent.core.model.data.Priority;
import org.lntorrent.libretorrent.core.model.data.entity.FeedItem;
import org.lntorrent.libretorrent.core.model.data.metainfo.TorrentMetaInfo;
import org.lntorrent.libretorrent.core.settings.SettingsRepository;
import org.lntorrent.libretorrent.core.storage.FeedRepository;
import org.lntorrent.libretorrent.core.system.FileSystemFacade;
import org.lntorrent.libretorrent.core.system.SystemFacadeHelper;
import org.lntorrent.libretorrent.core.utils.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
/*
* The worker for downloading torrents from RSS/Atom items.
*/
public class FeedDownloaderWorker extends Worker
{
@SuppressWarnings("unused")
private static final String TAG = FeedDownloaderWorker.class.getSimpleName();
public static final String ACTION_DOWNLOAD_TORRENT_LIST = "org.proninyaroslav.libretorrent.service.FeedDownloaderWorker.ACTION_DOWNLOAD_TORRENT_LIST";
public static final String TAG_ACTION = "action";
public static final String TAG_ITEM_ID_LIST = "item_id_list";
private static final long START_ENGINE_RETRY_TIME = 3000; /* ms */
private TorrentEngine engine;
private FeedRepository repo;
private SettingsRepository pref;
public FeedDownloaderWorker(@NonNull Context context, @NonNull WorkerParameters params)
{
super(context, params);
}
@NonNull
@Override
public Result doWork()
{
engine = TorrentEngine.getInstance(getApplicationContext());
repo = RepositoryHelper.getFeedRepository(getApplicationContext());
pref = RepositoryHelper.getSettingsRepository(getApplicationContext());
Data data = getInputData();
String action = data.getString(TAG_ACTION);
if (action == null)
return Result.failure();
if (ACTION_DOWNLOAD_TORRENT_LIST.equals(action))
return addTorrents(fetchTorrents(data.getStringArray(TAG_ITEM_ID_LIST)));
return Result.failure();
}
private ArrayList<AddTorrentParams> fetchTorrents(String... ids)
{
ArrayList<AddTorrentParams> paramsList = new ArrayList<>();
if (ids == null)
return paramsList;
for (FeedItem item : repo.getItemsById(ids)) {
AddTorrentParams params = fetchTorrent(item);
if (params != null)
paramsList.add(params);
}
return paramsList;
}
private AddTorrentParams fetchTorrent(FeedItem item)
{
if (item == null)
return null;
Uri downloadPath = Utils.getTorrentDownloadPath(getApplicationContext());
if (downloadPath == null)
return null;
String name;
Priority[] priorities = null;
boolean isMagnet = false;
String source, sha1hash;
if (item.downloadUrl.startsWith(Utils.MAGNET_PREFIX)) {
MagnetInfo info;
try {
info = engine.parseMagnet(item.downloadUrl);
} catch (IllegalArgumentException e) {
Log.e(TAG, e.getMessage());
return null;
}
sha1hash = info.getSha1hash();
name = info.getName();
isMagnet = true;
source = item.downloadUrl;
} else {
byte[] response;
TorrentMetaInfo info;
try {
response = Utils.fetchHttpUrl(getApplicationContext(), item.downloadUrl);
info = new TorrentMetaInfo(response);
} catch (FetchLinkException e) {
Log.e(TAG, "URL fetch error: " + Log.getStackTraceString(e));
return null;
} catch (DecodeException e) {
Log.e(TAG, "Invalid torrent: " + Log.getStackTraceString(e));
return null;
}
FileSystemFacade fs = SystemFacadeHelper.getFileSystemFacade(getApplicationContext());
if (fs.getDirAvailableBytes(downloadPath) < info.torrentSize) {
Log.e(TAG, "Not enough free space for " + info.torrentName);
return null;
}
File tmp;
try {
tmp = fs.makeTempFile(".torrent");
org.apache.commons.io.FileUtils.writeByteArrayToFile(tmp, response);
} catch (Exception e) {
Log.e(TAG, "Error write torrent file " + info.torrentName + ": " + Log.getStackTraceString(e));
return null;
}
priorities = new Priority[info.fileList.size()];
Arrays.fill(priorities, Priority.DEFAULT);
sha1hash = info.sha1Hash;
name = info.torrentName;
source = Uri.fromFile(tmp).toString();
}
return new AddTorrentParams(source, isMagnet, sha1hash, name,
priorities, downloadPath, false,
!pref.feedStartTorrents());
}
private Result addTorrents(ArrayList<AddTorrentParams> paramsList)
{
if (paramsList == null || paramsList.isEmpty())
return Result.failure();
if (!engine.isRunning())
engine.start();
/* TODO: maybe refactor */
while (!engine.isRunning()) {
try {
Thread.sleep(START_ENGINE_RETRY_TIME);
engine.start();
} catch (InterruptedException e) {
return Result.failure();
}
}
engine.addTorrents(paramsList, true);
return Result.success();
}
}
| UTF-8 | Java | 6,207 | java | FeedDownloaderWorker.java | Java | [] | null | [] |
package org.lntorrent.libretorrent.service;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import org.lntorrent.libretorrent.core.RepositoryHelper;
import org.lntorrent.libretorrent.core.exception.DecodeException;
import org.lntorrent.libretorrent.core.exception.FetchLinkException;
import org.lntorrent.libretorrent.core.model.AddTorrentParams;
import org.lntorrent.libretorrent.core.model.TorrentEngine;
import org.lntorrent.libretorrent.core.model.data.MagnetInfo;
import org.lntorrent.libretorrent.core.model.data.Priority;
import org.lntorrent.libretorrent.core.model.data.entity.FeedItem;
import org.lntorrent.libretorrent.core.model.data.metainfo.TorrentMetaInfo;
import org.lntorrent.libretorrent.core.settings.SettingsRepository;
import org.lntorrent.libretorrent.core.storage.FeedRepository;
import org.lntorrent.libretorrent.core.system.FileSystemFacade;
import org.lntorrent.libretorrent.core.system.SystemFacadeHelper;
import org.lntorrent.libretorrent.core.utils.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
/*
* The worker for downloading torrents from RSS/Atom items.
*/
public class FeedDownloaderWorker extends Worker
{
@SuppressWarnings("unused")
private static final String TAG = FeedDownloaderWorker.class.getSimpleName();
public static final String ACTION_DOWNLOAD_TORRENT_LIST = "org.proninyaroslav.libretorrent.service.FeedDownloaderWorker.ACTION_DOWNLOAD_TORRENT_LIST";
public static final String TAG_ACTION = "action";
public static final String TAG_ITEM_ID_LIST = "item_id_list";
private static final long START_ENGINE_RETRY_TIME = 3000; /* ms */
private TorrentEngine engine;
private FeedRepository repo;
private SettingsRepository pref;
public FeedDownloaderWorker(@NonNull Context context, @NonNull WorkerParameters params)
{
super(context, params);
}
@NonNull
@Override
public Result doWork()
{
engine = TorrentEngine.getInstance(getApplicationContext());
repo = RepositoryHelper.getFeedRepository(getApplicationContext());
pref = RepositoryHelper.getSettingsRepository(getApplicationContext());
Data data = getInputData();
String action = data.getString(TAG_ACTION);
if (action == null)
return Result.failure();
if (ACTION_DOWNLOAD_TORRENT_LIST.equals(action))
return addTorrents(fetchTorrents(data.getStringArray(TAG_ITEM_ID_LIST)));
return Result.failure();
}
private ArrayList<AddTorrentParams> fetchTorrents(String... ids)
{
ArrayList<AddTorrentParams> paramsList = new ArrayList<>();
if (ids == null)
return paramsList;
for (FeedItem item : repo.getItemsById(ids)) {
AddTorrentParams params = fetchTorrent(item);
if (params != null)
paramsList.add(params);
}
return paramsList;
}
private AddTorrentParams fetchTorrent(FeedItem item)
{
if (item == null)
return null;
Uri downloadPath = Utils.getTorrentDownloadPath(getApplicationContext());
if (downloadPath == null)
return null;
String name;
Priority[] priorities = null;
boolean isMagnet = false;
String source, sha1hash;
if (item.downloadUrl.startsWith(Utils.MAGNET_PREFIX)) {
MagnetInfo info;
try {
info = engine.parseMagnet(item.downloadUrl);
} catch (IllegalArgumentException e) {
Log.e(TAG, e.getMessage());
return null;
}
sha1hash = info.getSha1hash();
name = info.getName();
isMagnet = true;
source = item.downloadUrl;
} else {
byte[] response;
TorrentMetaInfo info;
try {
response = Utils.fetchHttpUrl(getApplicationContext(), item.downloadUrl);
info = new TorrentMetaInfo(response);
} catch (FetchLinkException e) {
Log.e(TAG, "URL fetch error: " + Log.getStackTraceString(e));
return null;
} catch (DecodeException e) {
Log.e(TAG, "Invalid torrent: " + Log.getStackTraceString(e));
return null;
}
FileSystemFacade fs = SystemFacadeHelper.getFileSystemFacade(getApplicationContext());
if (fs.getDirAvailableBytes(downloadPath) < info.torrentSize) {
Log.e(TAG, "Not enough free space for " + info.torrentName);
return null;
}
File tmp;
try {
tmp = fs.makeTempFile(".torrent");
org.apache.commons.io.FileUtils.writeByteArrayToFile(tmp, response);
} catch (Exception e) {
Log.e(TAG, "Error write torrent file " + info.torrentName + ": " + Log.getStackTraceString(e));
return null;
}
priorities = new Priority[info.fileList.size()];
Arrays.fill(priorities, Priority.DEFAULT);
sha1hash = info.sha1Hash;
name = info.torrentName;
source = Uri.fromFile(tmp).toString();
}
return new AddTorrentParams(source, isMagnet, sha1hash, name,
priorities, downloadPath, false,
!pref.feedStartTorrents());
}
private Result addTorrents(ArrayList<AddTorrentParams> paramsList)
{
if (paramsList == null || paramsList.isEmpty())
return Result.failure();
if (!engine.isRunning())
engine.start();
/* TODO: maybe refactor */
while (!engine.isRunning()) {
try {
Thread.sleep(START_ENGINE_RETRY_TIME);
engine.start();
} catch (InterruptedException e) {
return Result.failure();
}
}
engine.addTorrents(paramsList, true);
return Result.success();
}
}
| 6,207 | 0.6396 | 0.637989 | 180 | 33.472221 | 27.716507 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622222 | false | false | 0 |
706dfc3b7e94b243d0ac14308c511976881e4a75 | 30,605,936,962,097 | a31d928777bdf36a80854a2275eba85665dacf1b | /src/main/java/com/zyu/xjsy/common/util/JedisCacheManager.java | fef8e8ca0666ba18af654cff82ded06d769345ac | [] | no_license | travy3/xjsy | https://github.com/travy3/xjsy | 39d15f41c351e88b9156d4785e24d34c8da11cc7 | 8d6c751d0bc3fca416c2f6bd72eb5486bfa77bb3 | refs/heads/master | 2022-09-17T14:12:10.259000 | 2016-06-29T09:38:15 | 2016-06-29T09:38:15 | 51,828,991 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zyu.xjsy.common.util;
import com.zyu.xjsy.common.config.Global;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
* Created by chenjie on 2016/4/27.
*/
public class JedisCacheManager implements CacheManager {
private static Logger logger = LoggerFactory.getLogger(JedisCacheManager.class);
private JedisPool jedisPool;
// private RedisManager redisManager;
public static final String KEY_PREFIX = Global.getConfig("redis.keyPrefix");
public Jedis getJedis(){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
}catch (Exception e){
logger.error("[JedisUtils] getJedis error:"+e.getMessage());
if (null != jedis){
jedis.close();
}
}
return jedis;
}
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
//todo
return null;
}
// public RedisManager getRedisManager() {
// return redisManager;
// }
//
// public void setRedisManager(RedisManager redisManager) {
// this.redisManager = redisManager;
// }
}
| UTF-8 | Java | 1,524 | java | JedisCacheManager.java | Java | [
{
"context": " redis.clients.jedis.JedisPool;\n\n/**\n * Created by chenjie on 2016/4/27.\n */\npublic class JedisCacheManager ",
"end": 359,
"score": 0.999600887298584,
"start": 352,
"tag": "USERNAME",
"value": "chenjie"
}
] | null | [] | package com.zyu.xjsy.common.util;
import com.zyu.xjsy.common.config.Global;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
* Created by chenjie on 2016/4/27.
*/
public class JedisCacheManager implements CacheManager {
private static Logger logger = LoggerFactory.getLogger(JedisCacheManager.class);
private JedisPool jedisPool;
// private RedisManager redisManager;
public static final String KEY_PREFIX = Global.getConfig("redis.keyPrefix");
public Jedis getJedis(){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
}catch (Exception e){
logger.error("[JedisUtils] getJedis error:"+e.getMessage());
if (null != jedis){
jedis.close();
}
}
return jedis;
}
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
//todo
return null;
}
// public RedisManager getRedisManager() {
// return redisManager;
// }
//
// public void setRedisManager(RedisManager redisManager) {
// this.redisManager = redisManager;
// }
}
| 1,524 | 0.652887 | 0.646982 | 64 | 22.8125 | 22.470032 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.390625 | false | false | 0 |
0424f80bd866d744f58f922d30da886f7bc38d81 | 31,275,951,873,052 | 190644238eb7ed70d24d80bcef3b811132e60b3c | /Covid-19-DataCollection/src/org/hiber/covid/dao/PersonDAO.java | b346ffa8119d80feb4fd0432cebf507bb609e6a6 | [] | no_license | varunvasudev4/Java | https://github.com/varunvasudev4/Java | 4f800734c1e81cbf41178862ea629f4bb1cfb4f9 | a27f0b92b1b825def729e4a53f431f0acb355d2f | refs/heads/master | 2022-11-19T03:28:21.565000 | 2020-07-08T09:28:30 | 2020-07-08T09:28:30 | 278,039,142 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.hiber.covid.dao;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.xml.crypto.Data;
import org.hiber.covid.dto.Address;
import org.hiber.covid.dto.Person;
import org.hiber.covid.dto.VisitedPlaces;
import org.hiber.covid.utils.SessionFactoryManger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.query.Query;
public class PersonDAO {
Session session = SessionFactoryManger.getFactory().openSession();
public void save(Person person) {
ListIterator li = session.createQuery("from Address").list().listIterator();
Address temp = null;
while(li.hasNext())
{
temp = (Address) li.next();
if(person.getAddr().equals(temp)) {
break;
}
temp = null;
}
if(temp!=null) {
person.setAddr(temp);
}
// boolean already=false;
// List<Person> persons = session.createQuery("from Person where id like '"
// +person.getAddr().getPlace().substring(0, 2).toUpperCase()
// +person.getAddr().getStreet().substring(0, 2).toUpperCase()
// +"%'").getResultList();
//
// for(Person tempP : persons) {
// if(person.equals(tempP)) {
// person=tempP;
// break;
// }
// }
session.beginTransaction();
session.saveOrUpdate(person);
session.createSQLQuery("delete from visited_places where person_id is null").executeUpdate();
session.getTransaction().commit();
}
public Person getById(String id) {
Query query = session.createQuery("from Person where id=:id");
query.setParameter("id", id);
return (Person) query.uniqueResult();
//return session.get(Person.class, id);
}
public List<Person> showAll() {
return session.createQuery("from Person").getResultList();
//return session.createSQLQuery("select * from people").list();
}
public List<Person> showPositive() {
return session.createQuery("from Person where status=true5").getResultList();
}
public void deleteById(String id) {
Person temp = getById(id);
session.beginTransaction();
try {
Query query = session.createQuery("from Person where addr=:n");
Address tempAdd = temp.getAddr();
query.setParameter("n", tempAdd);
query.uniqueResult();
session.delete(temp);
} catch (Exception e) {
Query query = session.createQuery("delete from Person where id=:id");
query.setParameter("id", id);
query.executeUpdate();
}
session.getTransaction().commit();
//session.delete(per);
}
public List<Map> positivePlaces() {
Query query = session.createSQLQuery("select vp.place,p.name from people p , visited_places vp where p.person_id=vp.person_id and vp.place in\r\n" +
"(select place from visited_places group by place having count(place)>1);");
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
return query.list();
}
}
| UTF-8 | Java | 3,003 | java | PersonDAO.java | Java | [] | null | [] | package org.hiber.covid.dao;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.xml.crypto.Data;
import org.hiber.covid.dto.Address;
import org.hiber.covid.dto.Person;
import org.hiber.covid.dto.VisitedPlaces;
import org.hiber.covid.utils.SessionFactoryManger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.query.Query;
public class PersonDAO {
Session session = SessionFactoryManger.getFactory().openSession();
public void save(Person person) {
ListIterator li = session.createQuery("from Address").list().listIterator();
Address temp = null;
while(li.hasNext())
{
temp = (Address) li.next();
if(person.getAddr().equals(temp)) {
break;
}
temp = null;
}
if(temp!=null) {
person.setAddr(temp);
}
// boolean already=false;
// List<Person> persons = session.createQuery("from Person where id like '"
// +person.getAddr().getPlace().substring(0, 2).toUpperCase()
// +person.getAddr().getStreet().substring(0, 2).toUpperCase()
// +"%'").getResultList();
//
// for(Person tempP : persons) {
// if(person.equals(tempP)) {
// person=tempP;
// break;
// }
// }
session.beginTransaction();
session.saveOrUpdate(person);
session.createSQLQuery("delete from visited_places where person_id is null").executeUpdate();
session.getTransaction().commit();
}
public Person getById(String id) {
Query query = session.createQuery("from Person where id=:id");
query.setParameter("id", id);
return (Person) query.uniqueResult();
//return session.get(Person.class, id);
}
public List<Person> showAll() {
return session.createQuery("from Person").getResultList();
//return session.createSQLQuery("select * from people").list();
}
public List<Person> showPositive() {
return session.createQuery("from Person where status=true5").getResultList();
}
public void deleteById(String id) {
Person temp = getById(id);
session.beginTransaction();
try {
Query query = session.createQuery("from Person where addr=:n");
Address tempAdd = temp.getAddr();
query.setParameter("n", tempAdd);
query.uniqueResult();
session.delete(temp);
} catch (Exception e) {
Query query = session.createQuery("delete from Person where id=:id");
query.setParameter("id", id);
query.executeUpdate();
}
session.getTransaction().commit();
//session.delete(per);
}
public List<Map> positivePlaces() {
Query query = session.createSQLQuery("select vp.place,p.name from people p , visited_places vp where p.person_id=vp.person_id and vp.place in\r\n" +
"(select place from visited_places group by place having count(place)>1);");
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
return query.list();
}
}
| 3,003 | 0.65035 | 0.648352 | 120 | 23.025 | 25.778694 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.4 | false | false | 0 |
69550efe4839ae68eb2d8b6f5f54a4785a80ff8b | 987,842,489,412 | f18428f066faf6a7c1786c8bce3dfbdd79e1b784 | /mbtt/ACB_MultiChannelCommonJar/src/com/acb/service/DienlucWS/OutputType.java | 175dffe2a0c5acd0b85f36265283485cc222a0c3 | [] | no_license | anhlt309/build_online.acb_UAT | https://github.com/anhlt309/build_online.acb_UAT | ea9c67ee3068df1a167a63b23e4ed6da54c5a9ac | d2d40e154306fb824804817b4099b9c9acb39a0d | refs/heads/master | 2020-03-26T11:09:54.357000 | 2018-08-14T03:01:04 | 2018-08-14T03:01:04 | 144,830,994 | 0 | 4 | null | false | 2021-02-04T03:16:35 | 2018-08-15T09:05:53 | 2018-08-16T06:31:51 | 2018-08-14T03:31:08 | 121,869 | 0 | 1 | 1 | Java | false | false | //
// Generated By:JAX-WS RI IBM 2.1.1 in JDK 6 (JAXB RI IBM JAXB 2.1.3 in JDK 1.6)
//
package com.acb.service.DienlucWS;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for OutputType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="OutputType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="HoTen" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="DiaChi" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="BillList" type="{http://www.acbonline.com.vn/axis/DienlucWS/}BillListType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OutputType", namespace = "http://www.acbonline.com.vn/axis/DienlucWS/", propOrder = {
"hoTen",
"diaChi",
"billList"
})
public class OutputType {
@XmlElement(name = "HoTen", required = true)
protected String hoTen;
@XmlElement(name = "DiaChi", required = true)
protected String diaChi;
@XmlElement(name = "BillList", required = true)
protected BillListType billList;
/**
* Gets the value of the hoTen property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHoTen() {
return hoTen;
}
/**
* Sets the value of the hoTen property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHoTen(String value) {
this.hoTen = value;
}
/**
* Gets the value of the diaChi property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDiaChi() {
return diaChi;
}
/**
* Sets the value of the diaChi property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDiaChi(String value) {
this.diaChi = value;
}
/**
* Gets the value of the billList property.
*
* @return
* possible object is
* {@link BillListType }
*
*/
public BillListType getBillList() {
return billList;
}
/**
* Sets the value of the billList property.
*
* @param value
* allowed object is
* {@link BillListType }
*
*/
public void setBillList(BillListType value) {
this.billList = value;
}
}
| UTF-8 | Java | 2,878 | java | OutputType.java | Java | [] | null | [] | //
// Generated By:JAX-WS RI IBM 2.1.1 in JDK 6 (JAXB RI IBM JAXB 2.1.3 in JDK 1.6)
//
package com.acb.service.DienlucWS;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for OutputType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="OutputType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="HoTen" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="DiaChi" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="BillList" type="{http://www.acbonline.com.vn/axis/DienlucWS/}BillListType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OutputType", namespace = "http://www.acbonline.com.vn/axis/DienlucWS/", propOrder = {
"hoTen",
"diaChi",
"billList"
})
public class OutputType {
@XmlElement(name = "HoTen", required = true)
protected String hoTen;
@XmlElement(name = "DiaChi", required = true)
protected String diaChi;
@XmlElement(name = "BillList", required = true)
protected BillListType billList;
/**
* Gets the value of the hoTen property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHoTen() {
return hoTen;
}
/**
* Sets the value of the hoTen property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHoTen(String value) {
this.hoTen = value;
}
/**
* Gets the value of the diaChi property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDiaChi() {
return diaChi;
}
/**
* Sets the value of the diaChi property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDiaChi(String value) {
this.diaChi = value;
}
/**
* Gets the value of the billList property.
*
* @return
* possible object is
* {@link BillListType }
*
*/
public BillListType getBillList() {
return billList;
}
/**
* Sets the value of the billList property.
*
* @param value
* allowed object is
* {@link BillListType }
*
*/
public void setBillList(BillListType value) {
this.billList = value;
}
}
| 2,878 | 0.574357 | 0.566018 | 122 | 22.590164 | 22.465183 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.262295 | false | false | 0 |
b10258dbe5b2200073b8114286053b9c84638401 | 13,039,520,714,984 | 7df159b42c785edd04d679851aa09eded908605f | /lorann/view/src/main/java/view/Renderer.java | c3a58e6aba419cca2cbecbe4b2becd9edede5d9a | [] | no_license | NeoDarkFire/Lorann | https://github.com/NeoDarkFire/Lorann | 2afaf5639824d298dbe409bb922ab31c604e72bd | 7bcb0e11a5576a791c48b05c9e75540a626237b9 | refs/heads/master | 2020-03-18T19:09:59.970000 | 2018-06-06T07:48:44 | 2018-06-06T07:48:44 | 135,138,426 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package view;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.KeyListener;
import java.util.Observable;
import model.ILevel;
import showboard.BoardFrame;
import showboard.ISquare;
/**
* <h1>The Class Renderer allows to show the display.</h1>
*
* @author aurel
* @version 1.0
*/
public class Renderer extends Observable implements Runnable {
/**
* Composition because we use the level in this class
*/
private ILevel level;
/**
* Composition because we use the frame in this class
*/
private BoardFrame frame;
/**
* Composition because we use the keyListener in this class
*/
private KeyListener keyListener;
public Renderer() {
super();
}
/**
* Set up the level
*
* @param level The Level.
*
*/
public void setLevel(ILevel level) {
this.level = level;
if (this.frame == null) {
run();
}
this.updateFrame();
}
private void setupFrame() {
this.frame = new BoardFrame("Lorann");
this.updateFrame();
}
public void run() {
this.setupFrame();
this.frame.setVisible(true);
this.addObserver(this.frame.getObserver());
}
/**
* Add the sprite
*
* @param sprite The Sprite.
*/
public void addSprite(Sprite sprite) {
this.frame.addPawn(sprite);
}
/**
* Remove the sprite
*
* @param sprite The Sprite.
*
*/
public void removeSprite(Sprite sprite) {
this.frame.removePawn(sprite);
}
public BoardFrame getFrame() {
return this.frame;
}
public void refresh() {
synchronized (this.frame) {
this.setChanged();
this.notifyObservers();
}
}
private void updateFrame() {
int width, height;
width = this.level.getWidth();
height = this.level.getHeight();
this.frame.setDimension(new Dimension(width, height));
this.frame.setDisplayFrame(new Rectangle(0, 0, width, height));
this.frame.setSize(width*64, height*64);
ISquare square;
synchronized (this.frame) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
square = this.level.getTileAt(x, y);
this.frame.addSquare(square, x, y);
}
}
}
if (this.keyListener != null && this.frame.getKeyListeners().length == 0) {
this.frame.addKeyListener(this.keyListener);
}
}
public void setKeyListener(KeyListener keyListener) {
this.keyListener = keyListener;
}
}
| UTF-8 | Java | 2,466 | java | Renderer.java | Java | [
{
"context": "r allows to show the display.</h1>\r\n *\r\n * @author aurel\r\n * @version 1.0\r\n */\r\n\r\npublic class Renderer ex",
"end": 306,
"score": 0.9989681243896484,
"start": 301,
"tag": "USERNAME",
"value": "aurel"
}
] | null | [] | package view;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.KeyListener;
import java.util.Observable;
import model.ILevel;
import showboard.BoardFrame;
import showboard.ISquare;
/**
* <h1>The Class Renderer allows to show the display.</h1>
*
* @author aurel
* @version 1.0
*/
public class Renderer extends Observable implements Runnable {
/**
* Composition because we use the level in this class
*/
private ILevel level;
/**
* Composition because we use the frame in this class
*/
private BoardFrame frame;
/**
* Composition because we use the keyListener in this class
*/
private KeyListener keyListener;
public Renderer() {
super();
}
/**
* Set up the level
*
* @param level The Level.
*
*/
public void setLevel(ILevel level) {
this.level = level;
if (this.frame == null) {
run();
}
this.updateFrame();
}
private void setupFrame() {
this.frame = new BoardFrame("Lorann");
this.updateFrame();
}
public void run() {
this.setupFrame();
this.frame.setVisible(true);
this.addObserver(this.frame.getObserver());
}
/**
* Add the sprite
*
* @param sprite The Sprite.
*/
public void addSprite(Sprite sprite) {
this.frame.addPawn(sprite);
}
/**
* Remove the sprite
*
* @param sprite The Sprite.
*
*/
public void removeSprite(Sprite sprite) {
this.frame.removePawn(sprite);
}
public BoardFrame getFrame() {
return this.frame;
}
public void refresh() {
synchronized (this.frame) {
this.setChanged();
this.notifyObservers();
}
}
private void updateFrame() {
int width, height;
width = this.level.getWidth();
height = this.level.getHeight();
this.frame.setDimension(new Dimension(width, height));
this.frame.setDisplayFrame(new Rectangle(0, 0, width, height));
this.frame.setSize(width*64, height*64);
ISquare square;
synchronized (this.frame) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
square = this.level.getTileAt(x, y);
this.frame.addSquare(square, x, y);
}
}
}
if (this.keyListener != null && this.frame.getKeyListeners().length == 0) {
this.frame.addKeyListener(this.keyListener);
}
}
public void setKeyListener(KeyListener keyListener) {
this.keyListener = keyListener;
}
}
| 2,466 | 0.623682 | 0.61841 | 125 | 17.736 | 17.962692 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.688 | false | false | 0 |
22cf0333756ec64b11b2e76f124bb2aecae58aa1 | 29,274,497,094,836 | 63b302fa7526b9b23c6e81e7a8406f0053dd9ae5 | /MVN/myproject/testapp/src/main/java/com/testcompany/testapp/BinaryTreeNode.java | d703c3ab5b98faef81448a686efcef5ffdfe3418 | [] | no_license | rgaicherry/Learning | https://github.com/rgaicherry/Learning | e47896b8d0685154431e8abafd7b6abf167ee8f6 | c4ea250f8adc0c035c87a2df568e5c113e25d644 | refs/heads/master | 2020-01-27T21:19:23.052000 | 2017-02-18T06:33:04 | 2017-02-18T06:33:04 | 35,519,750 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.testcompany.testapp;
public abstract class BinaryTreeNode {
BinaryTreeNode leftNode;
BinaryTreeNode rightNode;
String value;
int result;
String displayStr = null;
public abstract void calculateResult();
public abstract void setDisplayStr();
public void setLeftNode (BinaryTreeNode theNode) {
this.leftNode = theNode;
}
public BinaryTreeNode getLeftNode () {
return this.leftNode;
}
public void setRightNode (BinaryTreeNode theNode) {
this.rightNode = theNode;
}
public BinaryTreeNode getRightNode () {
return this.rightNode;
}
public void setValue (String theVal) {
this.value = theVal;
}
public String getValue () {
return this.value;
}
public String getDisplayStr () {
return this.displayStr;
}
public int getResult () {
return this.result;
}
}
| UTF-8 | Java | 867 | java | BinaryTreeNode.java | Java | [] | null | [] | package com.testcompany.testapp;
public abstract class BinaryTreeNode {
BinaryTreeNode leftNode;
BinaryTreeNode rightNode;
String value;
int result;
String displayStr = null;
public abstract void calculateResult();
public abstract void setDisplayStr();
public void setLeftNode (BinaryTreeNode theNode) {
this.leftNode = theNode;
}
public BinaryTreeNode getLeftNode () {
return this.leftNode;
}
public void setRightNode (BinaryTreeNode theNode) {
this.rightNode = theNode;
}
public BinaryTreeNode getRightNode () {
return this.rightNode;
}
public void setValue (String theVal) {
this.value = theVal;
}
public String getValue () {
return this.value;
}
public String getDisplayStr () {
return this.displayStr;
}
public int getResult () {
return this.result;
}
}
| 867 | 0.683968 | 0.683968 | 46 | 16.847826 | 15.997238 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.434783 | false | false | 0 |
36781074c18931265bc87c958110236ca98fc8b3 | 4,045,859,202,081 | 39c2bccf1cca529c7aae360c0f603fe3229bc4f7 | /app/src/main/java/com/example/demo/json/JsonMainTest.java | b8e99d0fff985ca1266d1c0d2f4117ab7d7b752b | [] | no_license | mygzk/VolleyAndroidTest | https://github.com/mygzk/VolleyAndroidTest | ba01e3dc2634484d98ce2a00e455238dbd8d9741 | 34e51d5b4a136adfc17f03a89c83034597012de0 | refs/heads/master | 2021-01-19T06:42:58.377000 | 2016-07-26T06:12:31 | 2016-07-26T06:12:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.json;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
/**
* Created by guozhk on 16-7-5.
*/
public class JsonMainTest {
//static String jsonStr = "[{\"name\":\"name0\",\"age\":0},{\"name\":\"name1\",\"age\":5},{\"name\":\"name2\",\"age\":10},{\"name\":\"name3\",\"age\":15},{\"name\":\"name4\",\"age\":20},{\"name\":\"name5\",\"age\":25},{\"name\":\"name6\",\"age\":30},{\"name\":\"name7\",\"age\":35},{\"name\":\"name8\",\"age\":40},{\"name\":\"name9\",\"age\":45}]";
static String jsonStr = "[{\"name\":\"name0\",\"age\":\"0\",\"list\":[{\"name\":\"name00\",\"age\":\"00\"},{\"name\":\"name01\",\"age\":\"01\"}]},{\"name\":\"name0\",\"age\":\"0\",\"list\":[{\"name\":\"name10\",\"age\":\"10\"}]},{\"name\":\"name1\",\"age\":\"1\"}]";
private static Gson gson = new Gson();
public static void main(String[] args) {
/* List<Person> ps = gson.fromJson(jsonStr, new TypeToken<List<Person>>() {
}.getType());*/
List<Person> ps = GsonHepler.object(jsonStr, new TypeToken<List<Person>>() {
}.getType());
for (int i = 0; i < ps.size(); i++) {
System.out.print("name-" + i + ":" + ps.get(i).getName() + " ");
System.out.println("age-" + i + ":" + ps.get(i).getAge());
}
String s = GsonHepler.gsonToJson(ps, new TypeToken<List<Person>>() {
}.getType());
System.out.print("s-" + s);
}
}
| UTF-8 | Java | 1,478 | java | JsonMainTest.java | Java | [
{
"context": "eToken;\n\nimport java.util.List;\n\n/**\n * Created by guozhk on 16-7-5.\n */\npublic class JsonMainTest {\n\n /",
"end": 152,
"score": 0.9997005462646484,
"start": 146,
"tag": "USERNAME",
"value": "guozhk"
}
] | null | [] | package com.example.demo.json;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
/**
* Created by guozhk on 16-7-5.
*/
public class JsonMainTest {
//static String jsonStr = "[{\"name\":\"name0\",\"age\":0},{\"name\":\"name1\",\"age\":5},{\"name\":\"name2\",\"age\":10},{\"name\":\"name3\",\"age\":15},{\"name\":\"name4\",\"age\":20},{\"name\":\"name5\",\"age\":25},{\"name\":\"name6\",\"age\":30},{\"name\":\"name7\",\"age\":35},{\"name\":\"name8\",\"age\":40},{\"name\":\"name9\",\"age\":45}]";
static String jsonStr = "[{\"name\":\"name0\",\"age\":\"0\",\"list\":[{\"name\":\"name00\",\"age\":\"00\"},{\"name\":\"name01\",\"age\":\"01\"}]},{\"name\":\"name0\",\"age\":\"0\",\"list\":[{\"name\":\"name10\",\"age\":\"10\"}]},{\"name\":\"name1\",\"age\":\"1\"}]";
private static Gson gson = new Gson();
public static void main(String[] args) {
/* List<Person> ps = gson.fromJson(jsonStr, new TypeToken<List<Person>>() {
}.getType());*/
List<Person> ps = GsonHepler.object(jsonStr, new TypeToken<List<Person>>() {
}.getType());
for (int i = 0; i < ps.size(); i++) {
System.out.print("name-" + i + ":" + ps.get(i).getName() + " ");
System.out.println("age-" + i + ":" + ps.get(i).getAge());
}
String s = GsonHepler.gsonToJson(ps, new TypeToken<List<Person>>() {
}.getType());
System.out.print("s-" + s);
}
}
| 1,478 | 0.506766 | 0.47226 | 35 | 41.228573 | 72.195404 | 353 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.371429 | false | false | 0 |
dbf87b62f133fbc3aa7e75021739930b9cc2f088 | 11,115,375,394,288 | ccf939f058113c0ce3bf69dd53c0f490add9a6f4 | /src/Managers/CalendarManager.java | d56e51f2e348c6085b1bd895edf9d850de3eb8fe | [] | no_license | fRandOmizer/PV168-Calendar | https://github.com/fRandOmizer/PV168-Calendar | aa85930cc3b3c15cf20a529209e6fb133f59b906 | c4a59d43cae85cd1468c721330351381c6566372 | refs/heads/master | 2020-05-02T18:56:47.432000 | 2015-04-02T10:02:01 | 2015-04-02T10:02:01 | 31,851,402 | 1 | 0 | null | false | 2015-03-17T22:07:02 | 2015-03-08T13:53:30 | 2015-03-17T22:07:02 | 2015-03-17T22:07:02 | 224 | 1 | 0 | 0 | Java | null | null | package Managers;
import Containers.Day;
import Containers.Note;
import Interfaces.CalendarManagerInterface;
import javax.sql.DataSource;
import java.sql.Date;
import java.time.Month;
import java.time.Year;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
/**
* Created by Richard on 8. 3. 2015.
*/
// METODA CHANGEMONTH BY MALA STALE VRACAT POLE ALE PRAZDNE
public class CalendarManager implements CalendarManagerInterface {
private NoteManager noteManager;
private DayManager dayManager;
private CalendarDescriptionManager descriptionManager;
public CalendarManager(DataSource dataSourceDay, DataSource dataSourceDescription, DataSource dataSourceNote) {
noteManager = new NoteManager(dataSourceNote);
dayManager = new DayManager(dataSourceDay);
descriptionManager = new CalendarDescriptionManager(dataSourceDescription);
}
@Override
public List<Day> changeMonth(Year year, Month month) {
int iYear = year.getValue();
int iMonth = month.getValue();
int iDay = 1;
Calendar cal = new GregorianCalendar(iYear, iMonth, iDay);
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
List<Day> result = new ArrayList<>();
for (int i =0;i<daysInMonth;i++)
{
cal = Calendar.getInstance();
cal.set( cal.YEAR, iYear );
cal.set( cal.MONTH, iMonth );
cal.set( cal.DATE, i+1 );
Date tempDate = new Date(cal.getTime().getTime());
if(dayManager.findByDay(tempDate)!=null)
{
result.add(dayManager.findByDay(tempDate));
}
}
return result;
}
@Override
public List<Note> getNotesForDay(Day day) {
return noteManager.findByDate(day.getIDDate());
}
@Override
public void addNoteToDay(Day day, Note note){
if(day== null || note == null)
{
return;
}
if(dayManager.findByDay(day.getIDDate())==null)
{
dayManager.createDay(day.getIDDate());
}
if(note.isDone())
{
day.setNumberOfFinishedNotes(day.getNumberOfFinishedNotes()+1);
day.setNumberOfNotes(day.getNumberOfNotes() + 1);
}
else
{
day.setNumberOfNotes(day.getNumberOfNotes()+1);
}
dayManager.editDay(day);
note.setDate(day.getIDDate());
noteManager.addNote(note);
}
@Override
public void editNoteToDay(Day day, Note note){
if(note.isDone())
{
day.setNumberOfFinishedNotes(day.getNumberOfFinishedNotes() + 1);
}
dayManager.editDay(day);
noteManager.editNote(note);
}
@Override
public void deleteNoteToDay(Day day, Note note){
noteManager.deleteNote(note);
day.setNumberOfFinishedNotes(day.getNumberOfFinishedNotes() - 1);
day.setNumberOfNotes(day.getNumberOfNotes() - 1);
dayManager.editDay(day);
}
}
| UTF-8 | Java | 3,090 | java | CalendarManager.java | Java | [
{
"context": "alendar;\nimport java.util.List;\n\n/**\n * Created by Richard on 8. 3. 2015.\n */\n\n// METODA CHANGEMONTH BY MALA",
"end": 349,
"score": 0.9982914328575134,
"start": 342,
"tag": "NAME",
"value": "Richard"
},
{
"context": "chard on 8. 3. 2015.\n */\n\n// METODA CHANGEM... | null | [] | package Managers;
import Containers.Day;
import Containers.Note;
import Interfaces.CalendarManagerInterface;
import javax.sql.DataSource;
import java.sql.Date;
import java.time.Month;
import java.time.Year;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
/**
* Created by Richard on 8. 3. 2015.
*/
// METODA CHANGEMONTH BY <NAME>
public class CalendarManager implements CalendarManagerInterface {
private NoteManager noteManager;
private DayManager dayManager;
private CalendarDescriptionManager descriptionManager;
public CalendarManager(DataSource dataSourceDay, DataSource dataSourceDescription, DataSource dataSourceNote) {
noteManager = new NoteManager(dataSourceNote);
dayManager = new DayManager(dataSourceDay);
descriptionManager = new CalendarDescriptionManager(dataSourceDescription);
}
@Override
public List<Day> changeMonth(Year year, Month month) {
int iYear = year.getValue();
int iMonth = month.getValue();
int iDay = 1;
Calendar cal = new GregorianCalendar(iYear, iMonth, iDay);
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
List<Day> result = new ArrayList<>();
for (int i =0;i<daysInMonth;i++)
{
cal = Calendar.getInstance();
cal.set( cal.YEAR, iYear );
cal.set( cal.MONTH, iMonth );
cal.set( cal.DATE, i+1 );
Date tempDate = new Date(cal.getTime().getTime());
if(dayManager.findByDay(tempDate)!=null)
{
result.add(dayManager.findByDay(tempDate));
}
}
return result;
}
@Override
public List<Note> getNotesForDay(Day day) {
return noteManager.findByDate(day.getIDDate());
}
@Override
public void addNoteToDay(Day day, Note note){
if(day== null || note == null)
{
return;
}
if(dayManager.findByDay(day.getIDDate())==null)
{
dayManager.createDay(day.getIDDate());
}
if(note.isDone())
{
day.setNumberOfFinishedNotes(day.getNumberOfFinishedNotes()+1);
day.setNumberOfNotes(day.getNumberOfNotes() + 1);
}
else
{
day.setNumberOfNotes(day.getNumberOfNotes()+1);
}
dayManager.editDay(day);
note.setDate(day.getIDDate());
noteManager.addNote(note);
}
@Override
public void editNoteToDay(Day day, Note note){
if(note.isDone())
{
day.setNumberOfFinishedNotes(day.getNumberOfFinishedNotes() + 1);
}
dayManager.editDay(day);
noteManager.editNote(note);
}
@Override
public void deleteNoteToDay(Day day, Note note){
noteManager.deleteNote(note);
day.setNumberOfFinishedNotes(day.getNumberOfFinishedNotes() - 1);
day.setNumberOfNotes(day.getNumberOfNotes() - 1);
dayManager.editDay(day);
}
}
| 3,062 | 0.632039 | 0.627184 | 106 | 28.150944 | 23.955853 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584906 | false | false | 0 |
22844a69ad28978096a17c220353ec8cd6ee9aed | 23,476,291,245,354 | 4ce29ff0158f07f44ee2957bab6ae1996c559ede | /BookToGo/app/src/main/java/com/cs442/dliu33/booktogo/RegisterFragment.java | cfff0b82efe923becc11b3c46caae09745513da7 | [] | no_license | danna1406/cs442_project | https://github.com/danna1406/cs442_project | c4f40c28781e2b86016eed972e354e5d0c2b349f | 5bfe1e4ba001c7fce0d3d00f29a8e963eb47538b | refs/heads/master | 2022-01-04T23:04:55.071000 | 2021-06-22T21:32:21 | 2021-06-22T21:32:21 | 70,217,804 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cs442.dliu33.booktogo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.cs442.dliu33.booktogo.com.cs442.dliu33.booktogo.data.User;
public class RegisterFragment extends Fragment {
public interface OnLoginListener {
public void userRegister(User user);
public void linkToLogin();
}
View view;
String picUri = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.register, container, false);
final EditText username = (EditText) view.findViewById(R.id.usernameInput);
final EditText email = (EditText) view.findViewById(R.id.emailInput);
final EditText password = (EditText) view.findViewById(R.id.passwordInput);
final EditText confirmPassword = (EditText) view.findViewById(R.id.passwordInputConfirm);
Button register = (Button) view.findViewById(R.id.register);
Button linkToLogin = (Button) view.findViewById(R.id.linkToLogin);
register.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View view) {
OnLoginListener callback = (OnLoginListener) getActivity();
if(password.getText().toString().equals(confirmPassword.getText().toString())) {
User newUser = new User(username.getText().toString(), email.getText().toString(),
password.getText().toString(), "");
callback.userRegister(newUser);
}
else
Toast.makeText(getActivity(),"Password fields do not match!", Toast.LENGTH_LONG).show();
}
}));
linkToLogin.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View view) {
OnLoginListener callback = (OnLoginListener) getActivity();
callback.linkToLogin();
}
}));
return view;
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
| UTF-8 | Java | 2,532 | java | RegisterFragment.java | Java | [] | null | [] | package com.cs442.dliu33.booktogo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.cs442.dliu33.booktogo.com.cs442.dliu33.booktogo.data.User;
public class RegisterFragment extends Fragment {
public interface OnLoginListener {
public void userRegister(User user);
public void linkToLogin();
}
View view;
String picUri = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.register, container, false);
final EditText username = (EditText) view.findViewById(R.id.usernameInput);
final EditText email = (EditText) view.findViewById(R.id.emailInput);
final EditText password = (EditText) view.findViewById(R.id.passwordInput);
final EditText confirmPassword = (EditText) view.findViewById(R.id.passwordInputConfirm);
Button register = (Button) view.findViewById(R.id.register);
Button linkToLogin = (Button) view.findViewById(R.id.linkToLogin);
register.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View view) {
OnLoginListener callback = (OnLoginListener) getActivity();
if(password.getText().toString().equals(confirmPassword.getText().toString())) {
User newUser = new User(username.getText().toString(), email.getText().toString(),
password.getText().toString(), "");
callback.userRegister(newUser);
}
else
Toast.makeText(getActivity(),"Password fields do not match!", Toast.LENGTH_LONG).show();
}
}));
linkToLogin.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View view) {
OnLoginListener callback = (OnLoginListener) getActivity();
callback.linkToLogin();
}
}));
return view;
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
| 2,532 | 0.639021 | 0.632701 | 73 | 33.684933 | 29.922216 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561644 | false | false | 0 |
f5f73bc62f6cca8325928d0b10e3dcdc867e4b68 | 30,391,188,657,182 | 89799326b2439db478fc9a93ef8fb1b394a7e80a | /src/test/java/com/leonhart/bytebuddy/issue/reproduce/BaseSagaTest.java | 97744d7144f28418ed15add85b63d8801ae2c57e | [] | no_license | leozilla/reproduce-bytebuddy-issue | https://github.com/leozilla/reproduce-bytebuddy-issue | 9d35b5c2dc97a558e203bf5e90d4b7cf813c6d58 | 3b37303ce33c45526c72fdce796d0014cb395b04 | refs/heads/master | 2016-09-05T11:40:58.049000 | 2015-08-05T18:50:23 | 2015-08-05T18:50:23 | 39,737,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.leonhart.bytebuddy.issue.reproduce;
import com.codebullets.sagalib.AbstractSaga;
import com.codebullets.sagalib.EventHandler;
import com.codebullets.sagalib.ExecutionContext;
import com.codebullets.sagalib.Saga;
import com.codebullets.sagalib.StartsSaga;
import com.leonhart.bytebuddy.issue.reproduce.messages.Message;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.Pipe;
import static com.leonhart.bytebuddy.issue.reproduce.DynamicSagaTypeBuilder.generateSubClassFor;
import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith;
import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static net.bytebuddy.matcher.ElementMatchers.not;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
public class BaseSagaTest {
private ExecutionContext executionContext;
protected void setup() {
executionContext = mock(ExecutionContext.class);
}
protected ExecutionContext getExecutionContext() {
return executionContext;
}
public Message superCall(final Message message) {
given(executionContext.message()).willReturn(message);
given(getExecutionContext().getHeaderValue("correlationId")).willReturn("Any");
return message;
}
protected <SAGA extends Saga> Class<? extends Saga> generateProxyClassForSagaUnderTest(
final SAGA sagaUnderTest,
final Consumer2<SAGA, Message> contextSetter) {
return generateSubClassFor(sagaUnderTest.getClass())
.withDefaultNullPassingConstructor()
.and(
builder -> builder.method(isAnnotatedWith(StartsSaga.class).or(isAnnotatedWith(EventHandler.class)))
.intercept(
MethodDelegation.to(new ForwardingContextSetupInterceptor<>(sagaUnderTest, contextSetter))
.appendParameterBinder(Pipe.Binder.install(Forwarder.class)))
.method(
isPublic()
.and(isDeclaredBy(sagaUnderTest.getClass()).or(isDeclaredBy(AbstractSaga.class)))
.and(not(isAnnotatedWith(StartsSaga.class)))
.and(not(isAnnotatedWith(EventHandler.class))))
.intercept(MethodDelegation.to(sagaUnderTest).filter(not(isDeclaredBy(Object.class)))))
.buildAndLoad();
}
}
| UTF-8 | Java | 2,804 | java | BaseSagaTest.java | Java | [] | null | [] | package com.leonhart.bytebuddy.issue.reproduce;
import com.codebullets.sagalib.AbstractSaga;
import com.codebullets.sagalib.EventHandler;
import com.codebullets.sagalib.ExecutionContext;
import com.codebullets.sagalib.Saga;
import com.codebullets.sagalib.StartsSaga;
import com.leonhart.bytebuddy.issue.reproduce.messages.Message;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.Pipe;
import static com.leonhart.bytebuddy.issue.reproduce.DynamicSagaTypeBuilder.generateSubClassFor;
import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith;
import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static net.bytebuddy.matcher.ElementMatchers.not;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
public class BaseSagaTest {
private ExecutionContext executionContext;
protected void setup() {
executionContext = mock(ExecutionContext.class);
}
protected ExecutionContext getExecutionContext() {
return executionContext;
}
public Message superCall(final Message message) {
given(executionContext.message()).willReturn(message);
given(getExecutionContext().getHeaderValue("correlationId")).willReturn("Any");
return message;
}
protected <SAGA extends Saga> Class<? extends Saga> generateProxyClassForSagaUnderTest(
final SAGA sagaUnderTest,
final Consumer2<SAGA, Message> contextSetter) {
return generateSubClassFor(sagaUnderTest.getClass())
.withDefaultNullPassingConstructor()
.and(
builder -> builder.method(isAnnotatedWith(StartsSaga.class).or(isAnnotatedWith(EventHandler.class)))
.intercept(
MethodDelegation.to(new ForwardingContextSetupInterceptor<>(sagaUnderTest, contextSetter))
.appendParameterBinder(Pipe.Binder.install(Forwarder.class)))
.method(
isPublic()
.and(isDeclaredBy(sagaUnderTest.getClass()).or(isDeclaredBy(AbstractSaga.class)))
.and(not(isAnnotatedWith(StartsSaga.class)))
.and(not(isAnnotatedWith(EventHandler.class))))
.intercept(MethodDelegation.to(sagaUnderTest).filter(not(isDeclaredBy(Object.class)))))
.buildAndLoad();
}
}
| 2,804 | 0.639087 | 0.63873 | 56 | 49.07143 | 37.810078 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464286 | false | false | 0 |
bf676517e2dc122aa9928d3ba175f904d9edf027 | 8,512,625,212,224 | 76ffe5f918b8c4dd41e4ba30b059ca7466e47c87 | /Clock/NumberDisplay.java | 934db89a9a5cf56eb8571e39a3445116a7497c33 | [] | no_license | JO-Sweeney/Week3 | https://github.com/JO-Sweeney/Week3 | 00a0a128308ca3c8de0d7fd26036eb8d02b45a01 | ecac02ea949c1f9f6179716a926376e822e8ee60 | refs/heads/master | 2020-03-30T13:03:22.635000 | 2018-10-04T18:08:31 | 2018-10-04T18:08:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Clock;
public class NumberDisplay {
private int limit;
private int value;
/* Multiple constructors as minutes and seconds limit are both 59
* whereas hour has a limit dependent on 24 vs 12 hour clock.
* They take in parameters passed from ClockDisplay that were themselves
* passed from Main.
*/
public NumberDisplay(){
this.value = 0;
this.limit = 59;
}
public NumberDisplay(int value){
this.value = value;
this.limit = 59;
}
public NumberDisplay(int value, int limit) {
this.value = value;
this.limit = limit;
}
//getter method
public int getValue(){
return this.value;
}
//used to set the objects value i.e. 59 seconds back to 0
public int setValue(int replacement){
this.value = replacement;
return this.value;
}
//Dependent on whether its reached its limit, either add 1 or use setValue(0) to reset to 0
public int increment(){
if (this.value == this.limit && this.limit == 12){
this.setValue(1);
}else if (this.value == this.limit){
this.setValue(0);
}else {
this.value++;
}
return this.value;
}
//toString function to more easily print - condition makes 1-9 be 01 - 09 (zero-packing)
public String toString(){
if(this.value < 10){
return "0"+this.value;
}
return this.value+"";
}
}
| UTF-8 | Java | 1,358 | java | NumberDisplay.java | Java | [] | null | [] | package Clock;
public class NumberDisplay {
private int limit;
private int value;
/* Multiple constructors as minutes and seconds limit are both 59
* whereas hour has a limit dependent on 24 vs 12 hour clock.
* They take in parameters passed from ClockDisplay that were themselves
* passed from Main.
*/
public NumberDisplay(){
this.value = 0;
this.limit = 59;
}
public NumberDisplay(int value){
this.value = value;
this.limit = 59;
}
public NumberDisplay(int value, int limit) {
this.value = value;
this.limit = limit;
}
//getter method
public int getValue(){
return this.value;
}
//used to set the objects value i.e. 59 seconds back to 0
public int setValue(int replacement){
this.value = replacement;
return this.value;
}
//Dependent on whether its reached its limit, either add 1 or use setValue(0) to reset to 0
public int increment(){
if (this.value == this.limit && this.limit == 12){
this.setValue(1);
}else if (this.value == this.limit){
this.setValue(0);
}else {
this.value++;
}
return this.value;
}
//toString function to more easily print - condition makes 1-9 be 01 - 09 (zero-packing)
public String toString(){
if(this.value < 10){
return "0"+this.value;
}
return this.value+"";
}
}
| 1,358 | 0.642857 | 0.620766 | 60 | 20.633333 | 21.931686 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.816667 | false | false | 0 |
0d86a84a21d65dfa8771ae28ec5f50e64218aea2 | 30,331,059,064,834 | be926858454430502b8095a1628e89b4420789d1 | /src/main/java/com/niit/shopping/model/RegistrationEmailAPI.java | 2debd8ac24b60637d178d4bffc868378b8fe7a52 | [] | no_license | Jayanth-vasu/mailsender | https://github.com/Jayanth-vasu/mailsender | 54fb4f1a55e1d64b55e2f3d0ee570be8c239f1de | ee386688b1c40528d9a57901f0d4032a33b7aa04 | refs/heads/master | 2020-01-28T15:39:43.746000 | 2016-08-28T17:53:42 | 2016-08-28T17:53:42 | 66,782,171 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.niit.shopping.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Crunchify.com
*
*/
@Service("registrationEmail")
public class RegistrationEmailAPI {
@Autowired
MailSender registrationmail ; // MailSender interface defines a strategy
// for sending simple mails
@Transactional
public void readyToSendEmail(String toAddress, String fromAddress, String subject, String msgBody) {
SimpleMailMessage registrationMsg = new SimpleMailMessage();
registrationMsg.setFrom(fromAddress);
registrationMsg.setTo(toAddress);
registrationMsg.setSubject(subject);
registrationMsg.setText(msgBody);
registrationmail.send(registrationMsg);
}
} | UTF-8 | Java | 921 | java | RegistrationEmailAPI.java | Java | [
{
"context": "saction.annotation.Transactional;\n \n/**\n * @author Crunchify.com\n * \n */\n \n@Service(\"registrationEmail\")\npublic cl",
"end": 335,
"score": 0.7621721029281616,
"start": 322,
"tag": "EMAIL",
"value": "Crunchify.com"
}
] | null | [] | package com.niit.shopping.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author <EMAIL>
*
*/
@Service("registrationEmail")
public class RegistrationEmailAPI {
@Autowired
MailSender registrationmail ; // MailSender interface defines a strategy
// for sending simple mails
@Transactional
public void readyToSendEmail(String toAddress, String fromAddress, String subject, String msgBody) {
SimpleMailMessage registrationMsg = new SimpleMailMessage();
registrationMsg.setFrom(fromAddress);
registrationMsg.setTo(toAddress);
registrationMsg.setSubject(subject);
registrationMsg.setText(msgBody);
registrationmail.send(registrationMsg);
}
} | 915 | 0.798046 | 0.798046 | 31 | 28.741936 | 26.014845 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.387097 | false | false | 0 |
4d293e968f8af4b4cb481b018990346620042ede | 13,838,384,649,564 | 96ac36241a66221a465376b61f0d57224bff70f8 | /src/cn/edu/tju/util/GetXY_Base.java | 3b49898224bcf0210ad8afb9c58b9386622e70d7 | [] | no_license | tmeteorj/BaseAddressLocation | https://github.com/tmeteorj/BaseAddressLocation | d7c7b3cf79ab1dee54c3a1991440f3f736e7d3a8 | dd4e154798798269e31853725436ad1ccb0d076d | refs/heads/master | 2021-01-10T02:38:37.222000 | 2016-03-20T14:31:49 | 2016-03-20T14:31:49 | 54,263,902 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edu.tju.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import net.sf.json.JSONObject;
public class GetXY_Base {
//http://api.gpsspg.com/bs/?oid=ÎÒ¶©ÔĵÄoid&mcc=460&mnc=00&a=34860&b=62043&hex=10&type=&to=1&output=json
public String getXY(String oid,String mnc,String big,String small){
try{
URL url = new URL("http://api.gpsspg.com/bs/?oid="+oid+"&mcc=460&mnc="+mnc+"&a="+big+"&b="+small+"&hex=10&type=&to=1&output=json");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));
String res="";
String line;
while((line=br.readLine())!=null){
res+=line;
}
br.close();
System.out.println(res);
JSONObject json = JSONObject.fromObject(res);
String status=json.getString("status");
if(status.equals("200")){
JSONObject result=json.getJSONObject("result");
String lat=result.getString("lat");
String lng=result.getString("lng");
return lng+","+lat;
}
else{
return null;
}
}
catch(IOException e){
return null;
}
}
public void locationLackBase(String oid,String mnc,int startline,int endline,String inputPath,String outputPath,String errorPath)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(
inputPath), "utf-8"));
OutputStreamWriter resw = new OutputStreamWriter(new FileOutputStream(
outputPath,true), "utf-8");
OutputStreamWriter errw = new OutputStreamWriter(new FileOutputStream(
errorPath), "utf-8");
String temp=null;
int linenum=0;
while((temp=br.readLine())!=null){
++linenum;
if(linenum<startline)continue;
else if(linenum>endline)break;
String []info=temp.split(",");
String res=getXY(oid,mnc,info[0],info[1]);
if(res==null){
errw.append(temp+"\r\n");
errw.flush();
}
else{
resw.append(temp+","+res+"\r\n");
resw.flush();
}
}
br.close();
errw.close();
resw.close();
}
}
| WINDOWS-1252 | Java | 2,113 | java | GetXY_Base.java | Java | [] | null | [] | package cn.edu.tju.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import net.sf.json.JSONObject;
public class GetXY_Base {
//http://api.gpsspg.com/bs/?oid=ÎÒ¶©ÔĵÄoid&mcc=460&mnc=00&a=34860&b=62043&hex=10&type=&to=1&output=json
public String getXY(String oid,String mnc,String big,String small){
try{
URL url = new URL("http://api.gpsspg.com/bs/?oid="+oid+"&mcc=460&mnc="+mnc+"&a="+big+"&b="+small+"&hex=10&type=&to=1&output=json");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));
String res="";
String line;
while((line=br.readLine())!=null){
res+=line;
}
br.close();
System.out.println(res);
JSONObject json = JSONObject.fromObject(res);
String status=json.getString("status");
if(status.equals("200")){
JSONObject result=json.getJSONObject("result");
String lat=result.getString("lat");
String lng=result.getString("lng");
return lng+","+lat;
}
else{
return null;
}
}
catch(IOException e){
return null;
}
}
public void locationLackBase(String oid,String mnc,int startline,int endline,String inputPath,String outputPath,String errorPath)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(
inputPath), "utf-8"));
OutputStreamWriter resw = new OutputStreamWriter(new FileOutputStream(
outputPath,true), "utf-8");
OutputStreamWriter errw = new OutputStreamWriter(new FileOutputStream(
errorPath), "utf-8");
String temp=null;
int linenum=0;
while((temp=br.readLine())!=null){
++linenum;
if(linenum<startline)continue;
else if(linenum>endline)break;
String []info=temp.split(",");
String res=getXY(oid,mnc,info[0],info[1]);
if(res==null){
errw.append(temp+"\r\n");
errw.flush();
}
else{
resw.append(temp+","+res+"\r\n");
resw.flush();
}
}
br.close();
errw.close();
resw.close();
}
}
| 2,113 | 0.686936 | 0.670784 | 71 | 28.647888 | 28.962383 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.098592 | false | false | 0 |
f459e697496732a9ce5d4276807e078732c7ca94 | 32,298,154,079,775 | 27849c431a2710755e164f1702593fa0af369ecc | /app/src/main/java/donpironet/be/funproject/Dagger/DaggerConstants.java | 4149274f942a7605df88b800212aa40e6e2d482f | [] | no_license | donpironet/Dagger2Fun | https://github.com/donpironet/Dagger2Fun | 2e72655eb989f5f01b57bef1c0ba8481099bd72f | 85eef933ba2c36cc918c0d3a89195942c5f6a03f | refs/heads/master | 2017-12-03T10:03:00.087000 | 2017-03-23T13:14:33 | 2017-03-23T13:14:33 | 85,950,052 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package donpironet.be.funproject.Dagger;
/**
* Created by donpironet on 23/03/17.
*/
public final class DaggerConstants {
public static final String DEFAULT_RETROFIT = "default_retrofit_client";
public static final String OTHER_RETROFIT = "other_retrofit_client";
}
| UTF-8 | Java | 278 | java | DaggerConstants.java | Java | [
{
"context": "onpironet.be.funproject.Dagger;\n\n/**\n * Created by donpironet on 23/03/17.\n */\n\npublic final class DaggerConsta",
"end": 70,
"score": 0.9996335506439209,
"start": 60,
"tag": "USERNAME",
"value": "donpironet"
}
] | null | [] | package donpironet.be.funproject.Dagger;
/**
* Created by donpironet on 23/03/17.
*/
public final class DaggerConstants {
public static final String DEFAULT_RETROFIT = "default_retrofit_client";
public static final String OTHER_RETROFIT = "other_retrofit_client";
}
| 278 | 0.744604 | 0.723022 | 10 | 26.799999 | 28.392958 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 0 |
d553efb4407f96074d50a644cba8f95e0e72922a | 23,605,140,286,775 | a1d37379f32eed1fc8d02e4c7d6e1aae8556e263 | /src/main/java/agenzia/entities/Cliente.java | caf4b11ad8e7d48b7536a4da671dfb925cf904b5 | [] | no_license | rcclas/agenzia-viaggi | https://github.com/rcclas/agenzia-viaggi | f22b2f3a6e347e0f0719a0bf728052fff885ece4 | ed26b58db5a7fb3e0f170e7c1f7da6c657eb4b7d | refs/heads/main | 2023-06-28T00:56:01.924000 | 2021-07-23T14:06:44 | 2021-07-23T14:06:44 | 386,071,394 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package agenzia.entities;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="clienti")
public class Cliente {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nome;
private String cognome;
private String email;
private String metodo_pagamento;
@ManyToMany
@JoinTable(
name = "prenotazioni",
joinColumns = @JoinColumn(name = "clienti_id"),
inverseJoinColumns = @JoinColumn(name = "viaggi_id")
)
private Set<Viaggio> viaggi;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<Viaggio> getViaggi() {
return viaggi;
}
public void setViaggi(Set<Viaggio> viaggi) {
this.viaggi = viaggi;
}
public String getMetodo_pagamento() {
return metodo_pagamento;
}
public void setMetodo_pagamento(String metodo_pagamento) {
this.metodo_pagamento = metodo_pagamento;
}
}
| UTF-8 | Java | 1,510 | java | Cliente.java | Java | [] | null | [] | package agenzia.entities;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="clienti")
public class Cliente {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nome;
private String cognome;
private String email;
private String metodo_pagamento;
@ManyToMany
@JoinTable(
name = "prenotazioni",
joinColumns = @JoinColumn(name = "clienti_id"),
inverseJoinColumns = @JoinColumn(name = "viaggi_id")
)
private Set<Viaggio> viaggi;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<Viaggio> getViaggi() {
return viaggi;
}
public void setViaggi(Set<Viaggio> viaggi) {
this.viaggi = viaggi;
}
public String getMetodo_pagamento() {
return metodo_pagamento;
}
public void setMetodo_pagamento(String metodo_pagamento) {
this.metodo_pagamento = metodo_pagamento;
}
}
| 1,510 | 0.727152 | 0.727152 | 77 | 18.61039 | 16.03013 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.402597 | false | false | 0 |
f143afd26f251b320297adfe690d7b2fe8955bc9 | 29,824,252,928,621 | 0411273160856b5f3767fbe47796932f4b275a1c | /src/design_pattern/structural/bridge/DB2Impl.java | 6caa9197275ac739068ae102c19a7d50b89e37fd | [] | no_license | Cicinnus0407/DesignPatterns | https://github.com/Cicinnus0407/DesignPatterns | 910f20cd5e839c3e5b35b47f10e3dc86538c487b | 5f393f97a57488e89983ebfc11b2a9203217e395 | refs/heads/master | 2021-09-01T23:01:42.645000 | 2017-12-29T01:40:48 | 2017-12-29T01:40:48 | 103,557,037 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package design_pattern.structural.bridge;
/**
* Created by Cicinnus on 2017/9/30.
*/
public class DB2Impl implements ExactDataImpl {
@Override
public ExactData readFromDB() {
System.out.println("DB2数据读取");
return new ExactData();
}
}
| UTF-8 | Java | 274 | java | DB2Impl.java | Java | [
{
"context": "sign_pattern.structural.bridge;\n\n/**\n * Created by Cicinnus on 2017/9/30.\n */\npublic class DB2Impl implements",
"end": 69,
"score": 0.9990221858024597,
"start": 61,
"tag": "USERNAME",
"value": "Cicinnus"
}
] | null | [] | package design_pattern.structural.bridge;
/**
* Created by Cicinnus on 2017/9/30.
*/
public class DB2Impl implements ExactDataImpl {
@Override
public ExactData readFromDB() {
System.out.println("DB2数据读取");
return new ExactData();
}
}
| 274 | 0.665414 | 0.631579 | 13 | 19.461538 | 17.770395 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 0 |
3e792bc635c7f74e04723c675c08487c48e0fefd | 3,831,110,838,673 | 49a358d1f418af8dc75b2ec0596b305f4bf19338 | /app/src/main/java/com/b2/myapplication/network/networkinterface/GetService.java | 9090b88511a7fd3ecdfe12e4eab90cd367692e85 | [
"Apache-2.0"
] | permissive | rizwanrazi/ShoppingCart | https://github.com/rizwanrazi/ShoppingCart | ab0eb58ad20fb3d67d4a133818a8fe4444062183 | 2888b31427ecb86466e5804e5f25866e029b7450 | refs/heads/main | 2022-12-28T04:14:57.478000 | 2020-10-09T01:59:52 | 2020-10-09T01:59:52 | 302,505,268 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.b2.myapplication.network.networkinterface;
import com.b2.myapplication.model.ProductModel;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by Rizwan Ahmed on 08/10/2020.
*/
public interface GetService {
@GET("products")
Call<ArrayList<ProductModel>> getAllProducts();
}
| UTF-8 | Java | 340 | java | GetService.java | Java | [
{
"context": "Call;\nimport retrofit2.http.GET;\n/**\n * Created by Rizwan Ahmed on 08/10/2020.\n */\npublic interface GetService {\n",
"end": 214,
"score": 0.9998579025268555,
"start": 202,
"tag": "NAME",
"value": "Rizwan Ahmed"
}
] | null | [] | package com.b2.myapplication.network.networkinterface;
import com.b2.myapplication.model.ProductModel;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by <NAME> on 08/10/2020.
*/
public interface GetService {
@GET("products")
Call<ArrayList<ProductModel>> getAllProducts();
}
| 334 | 0.758824 | 0.723529 | 16 | 20.25 | 19.356846 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 0 |
4b313e83c7021737e5fe8c813f81f755926b6f8b | 32,066,225,847,226 | 6a6b433894e9ae391d5d1f2a9c557207ec90e620 | /blog/src/main/java/com/google/style/blog/controller/BoringService.java | 898d3323a99de9b8f38b699a124f23f7a98dab15 | [] | no_license | passliang/monkey | https://github.com/passliang/monkey | 573d92e6ca8a5fa3fc9d3447b9b013d58b3f364c | d49cdacee3c67e466edce54eb9cc5c4d76185f6a | refs/heads/master | 2022-03-03T15:47:09.127000 | 2022-03-03T07:41:12 | 2022-03-03T07:41:12 | 121,089,959 | 7 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.style.blog.controller;
/**
* @author LYL
* @date 2018/2/22 17:55
*/
public interface BoringService {
/**
* 计算 心水
* @param monthSalary monthSalary
*/
void makeTimeSpeedFaster(double monthSalary);
}
| UTF-8 | Java | 254 | java | BoringService.java | Java | [
{
"context": " com.google.style.blog.controller;\n\n/**\n * @author LYL\n * @date 2018/2/22 17:55\n */\npublic interface Bor",
"end": 61,
"score": 0.9996829032897949,
"start": 58,
"tag": "USERNAME",
"value": "LYL"
}
] | null | [] | package com.google.style.blog.controller;
/**
* @author LYL
* @date 2018/2/22 17:55
*/
public interface BoringService {
/**
* 计算 心水
* @param monthSalary monthSalary
*/
void makeTimeSpeedFaster(double monthSalary);
}
| 254 | 0.642276 | 0.597561 | 15 | 15.4 | 16.280048 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.133333 | false | false | 0 |
dca1ff882ccd9e5fa598e6f93707d237fb81bb9e | 317,827,617,351 | 5c21350dc430563e4bbc1e9b402688ebaa3899f2 | /src/main/java/Main.java | 3a6238be9f7f588f9c79df3558b2ba231936bc7b | [] | no_license | Energyneer/tandem_pldr | https://github.com/Energyneer/tandem_pldr | dca074aba5279eb90b1889d1250f5eb67d5cf039 | 333081499daa101af5092d8bdcf302921bc83da7 | refs/heads/master | 2020-07-31T12:08:26.891000 | 2019-09-24T12:37:47 | 2019-09-24T12:37:47 | 210,599,016 | 0 | 0 | null | false | 2020-10-13T16:16:12 | 2019-09-24T12:35:59 | 2019-09-24T12:39:24 | 2020-10-13T16:16:11 | 13 | 0 | 0 | 1 | Java | false | false | import models.User;
import repositories.GameRep;
import repositories.GameRepImpl;
import repositories.UserRep;
import repositories.UserRepImpl;
public class Main {
public static void main(String[] args) {
UserRep userRep = new UserRepImpl();
GameRep gameRep = new GameRepImpl();
gameRep.newGame(userRep.getUser("userA"));
gameRep.newPalindrome("Мем");
gameRep.newPalindrome("Топот");
gameRep.newPalindrome("Стоп");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userB"));
gameRep.newPalindrome("Каток");
gameRep.newPalindrome("Десяток");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userC"));
gameRep.newPalindrome("Заказ");
gameRep.newPalindrome("А роза упала на лапу Азора");
gameRep.newPalindrome("Хил, худ, а дух лих!");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userA"));
gameRep.newPalindrome("Она не жена, но...");
gameRep.newPalindrome("топот");
gameRep.newPalindrome("Мем");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userD"));
gameRep.newPalindrome("Вор влетел в ров.");
gameRep.newPalindrome("Анна");
gameRep.newPalindrome("Кирилл лирик.");
gameRep.newPalindrome("Олесе весело");
gameRep.newPalindrome("Papper");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userE"));
gameRep.newPalindrome("Don't nod.");
gameRep.newPalindrome("Top spot");
gameRep.newPalindrome("Top spot");
gameRep.newPalindrome("Was it a cat I saw?");
gameRep.newPalindrome("Stop");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userF"));
gameRep.newPalindrome("My gym");
gameRep.newPalindrome("No lemon, no melon ");
gameRep.newPalindrome("No winner");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userB"));
gameRep.newPalindrome("Noon");
gameRep.newPalindrome("Redder");
gameRep.newPalindrome("Red rum, sir, is murder");
gameRep.newPalindrome("Каток");
gameRep.endGame();
System.out.println("ALL USERS:");
for (User us : userRep.getAllUsers()) {
System.out.println(us.toString());
}
System.out.println("ALL RECORDS:");
for (User us : gameRep.getRecords()) {
System.out.println(us.toString());
}
}
}
| UTF-8 | Java | 2,618 | java | Main.java | Java | [
{
"context": "Game();\n\n gameRep.newGame(userRep.getUser(\"userB\"));\n gameRep.newPalindrome(\"Noon\");\n ",
"end": 1977,
"score": 0.9947185516357422,
"start": 1972,
"tag": "USERNAME",
"value": "userB"
}
] | null | [] | import models.User;
import repositories.GameRep;
import repositories.GameRepImpl;
import repositories.UserRep;
import repositories.UserRepImpl;
public class Main {
public static void main(String[] args) {
UserRep userRep = new UserRepImpl();
GameRep gameRep = new GameRepImpl();
gameRep.newGame(userRep.getUser("userA"));
gameRep.newPalindrome("Мем");
gameRep.newPalindrome("Топот");
gameRep.newPalindrome("Стоп");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userB"));
gameRep.newPalindrome("Каток");
gameRep.newPalindrome("Десяток");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userC"));
gameRep.newPalindrome("Заказ");
gameRep.newPalindrome("А роза упала на лапу Азора");
gameRep.newPalindrome("Хил, худ, а дух лих!");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userA"));
gameRep.newPalindrome("Она не жена, но...");
gameRep.newPalindrome("топот");
gameRep.newPalindrome("Мем");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userD"));
gameRep.newPalindrome("Вор влетел в ров.");
gameRep.newPalindrome("Анна");
gameRep.newPalindrome("Кирилл лирик.");
gameRep.newPalindrome("Олесе весело");
gameRep.newPalindrome("Papper");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userE"));
gameRep.newPalindrome("Don't nod.");
gameRep.newPalindrome("Top spot");
gameRep.newPalindrome("Top spot");
gameRep.newPalindrome("Was it a cat I saw?");
gameRep.newPalindrome("Stop");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userF"));
gameRep.newPalindrome("My gym");
gameRep.newPalindrome("No lemon, no melon ");
gameRep.newPalindrome("No winner");
gameRep.endGame();
gameRep.newGame(userRep.getUser("userB"));
gameRep.newPalindrome("Noon");
gameRep.newPalindrome("Redder");
gameRep.newPalindrome("Red rum, sir, is murder");
gameRep.newPalindrome("Каток");
gameRep.endGame();
System.out.println("ALL USERS:");
for (User us : userRep.getAllUsers()) {
System.out.println(us.toString());
}
System.out.println("ALL RECORDS:");
for (User us : gameRep.getRecords()) {
System.out.println(us.toString());
}
}
}
| 2,618 | 0.617977 | 0.617977 | 75 | 32.226665 | 18.207378 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.813333 | false | false | 0 |
3f718086ee841af61370e14d4dd03adc6546af53 | 987,842,502,924 | 8ae76acdfdf21b14dd1f68cde48bad0124bb8a06 | /src/main/java/com/babelsubtitles/crawler/extractor/ChapterExtractor.java | b0681e92d184a9298fb5874a168947e0fe8c798a | [
"MIT"
] | permissive | fjavierjimenez/subtitles-crawler | https://github.com/fjavierjimenez/subtitles-crawler | d7b3dcce62471a71e15b2b4fad160f7ec26f7ebb | 2df4704497051fd8a3700a0a8502191b3f787623 | refs/heads/master | 2016-09-05T16:06:30.354000 | 2015-10-09T19:21:12 | 2015-10-09T19:21:12 | 38,896,952 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.babelsubtitles.crawler.extractor;
import com.babelsubtitles.crawler.model.Chapter;
import com.babelsubtitles.crawler.model.Serie;
import rx.Observable;
/**
* Created by Javi on 12/07/2015.
*/
public interface ChapterExtractor {
Observable<Chapter> getChapters(Serie serie, Integer seasonId);
}
| UTF-8 | Java | 314 | java | ChapterExtractor.java | Java | [
{
"context": "el.Serie;\nimport rx.Observable;\n\n/**\n * Created by Javi on 12/07/2015.\n */\npublic interface ChapterExt",
"end": 185,
"score": 0.7508240938186646,
"start": 184,
"tag": "NAME",
"value": "J"
},
{
"context": ".Serie;\nimport rx.Observable;\n\n/**\n * Created by Javi o... | null | [] | package com.babelsubtitles.crawler.extractor;
import com.babelsubtitles.crawler.model.Chapter;
import com.babelsubtitles.crawler.model.Serie;
import rx.Observable;
/**
* Created by Javi on 12/07/2015.
*/
public interface ChapterExtractor {
Observable<Chapter> getChapters(Serie serie, Integer seasonId);
}
| 314 | 0.786624 | 0.761146 | 12 | 25.166666 | 22.560413 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
51bc33a6e07c81d825a29cff203ff71e4fec2734 | 31,842,887,592,889 | a6c72277e479dda36169ab9f50114a887ceb821b | /src/main/java/model/Customer.java | 9e98afe8cd6a2a04d1370f982a2a2089b1ff0296 | [] | no_license | jhontona/ecommerce-model | https://github.com/jhontona/ecommerce-model | 57f6f0f428bcd382acff0f00cfcca6b3087c2146 | f5d5bc567120b4b1668753f2c274ec9b2c0b5d0d | refs/heads/master | 2020-03-29T01:02:01.237000 | 2018-09-19T01:29:39 | 2018-09-19T01:29:39 | 149,367,913 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class Customer
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public String email;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
private String id;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public Invoice invoice;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public ShoppingCart shoppingCart;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Customer(){
super();
}
}
| UTF-8 | Java | 845 | java | Customer.java | Java | [] | null | [] | package model;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class Customer
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public String email;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
private String id;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public Invoice invoice;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public ShoppingCart shoppingCart;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Customer(){
super();
}
}
| 845 | 0.473373 | 0.473373 | 66 | 11.787879 | 10.478716 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.848485 | false | false | 0 |
6331be4917876f97b6fd7b81e63f77102818a2ab | 8,358,006,393,218 | 0e25a937dc61a75750401ca716a693743169eeca | /app/src/main/java/com/zx/player/tools/LifecycleMonitorImpl.java | 59b7e6cc029e2b12192a45d2f17745197fcefe38 | [] | no_license | zhangnn016/zxplayer | https://github.com/zhangnn016/zxplayer | 459d8b713ae0f3418a986e44d658cfc33db9cabe | edf807caf1ccb4675995f822367cbf4068346050 | refs/heads/master | 2021-01-10T00:54:59.567000 | 2015-08-15T00:30:44 | 2015-08-15T00:30:44 | 39,820,463 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zx.player.tools;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by niuniuzhang on 15/7/21.
*/
public class LifecycleMonitorImpl implements LifecycleMonitor {
private static final String TAG = "LifecycleMonitorImpl";
private static final int ON_STOP_CHECK_DELAY = 200;
private Context mContext;
private final ArrayList<ActivityLifecycleCallbacksCompat>
mActivityLifecycleCallbacksCompat = new ArrayList<ActivityLifecycleCallbacksCompat>();
private Map<ActivityLifecycleCallbacksCompat,ActivityLifecycleCallbacksWrapper> mCallbacksMap;
private final ArrayList<APPStateListener> mAPPStateListener = new ArrayList<APPStateListener>();
/**
* 记录调用了onResume的activity,onStop 200ms之后移除
* 只会在主线程中被调用,故不会出现互斥问题
*/
private Set<String> mResumeActivitys = new HashSet<String>();
private Handler mHandler;
protected LifecycleMonitorImpl(Context context) {
mContext = context.getApplicationContext();
if(Build.VERSION.SDK_INT < 14) {
hookInstrumentation();
}else{
mCallbacksMap = new HashMap<ActivityLifecycleCallbacksCompat, ActivityLifecycleCallbacksWrapper>();
}
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksCompat() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
//第一个Activity onResumeed的时候,表明APP进入前台
if (mResumeActivitys.size() == 0) {
synchronized (mAPPStateListener) {
for (APPStateListener listener : mAPPStateListener) {
listener.onEnterForeground();
}
}
PSLog.d(TAG, "=====> enter foreground");
}
String activityString = activity.getClass().getName()+activity.hashCode();
mResumeActivitys.add(activityString);
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
final String activityString = activity.getClass().getName()+activity.hashCode();
/**
* 这里延迟是防止Activity切换时,mResumeActivitys size为0导致误报进入后台
*/
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mResumeActivitys.remove(activityString);
if (mResumeActivitys.size() == 0) {
synchronized (mAPPStateListener) {
for (APPStateListener listener : mAPPStateListener) {
listener.onEnterBackground();
}
}
PSLog.d(TAG, "=====> enter background");
}
}
}, ON_STOP_CHECK_DELAY);
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
mHandler = new Handler(Looper.getMainLooper());
}
/**
* 注册Activity 生命周期监听,兼容 ICE_CREAM_SANDWICH(14) 以前版本
* @param callback 回调
*/
@SuppressLint("NewApi")
@Override
public void registerActivityLifecycleCallbacks(ActivityLifecycleCallbacksCompat callback){
if(callback == null)
return;
if(Build.VERSION.SDK_INT < 14){
synchronized (mActivityLifecycleCallbacksCompat) {
mActivityLifecycleCallbacksCompat.add(callback);
}
}else{
if(!mCallbacksMap.containsKey(callback)) {
ActivityLifecycleCallbacksWrapper realCallback = new ActivityLifecycleCallbacksWrapper(callback);
mCallbacksMap.put(callback,realCallback);
((Application)mContext).registerActivityLifecycleCallbacks(realCallback);
}
}
}
/**
* 注销Activity 生命周期监听,兼容 ICE_CREAM_SANDWICH(14) 以前版本
* @param callback 回调
*/
@SuppressLint("NewApi")
@Override
public synchronized void unregisterActivityLifecycleCallbacks(ActivityLifecycleCallbacksCompat callback) {
if(callback == null)
return;
if(Build.VERSION.SDK_INT < 14){
synchronized (mActivityLifecycleCallbacksCompat) {
mActivityLifecycleCallbacksCompat.remove(callback);
}
}else{
ActivityLifecycleCallbacksWrapper realCallback = mCallbacksMap.get(callback);
if(realCallback != null) {
mCallbacksMap.remove(callback);
((Application) mContext).unregisterActivityLifecycleCallbacks(realCallback);
}
}
}
@Override
public void registerAppStateListener(APPStateListener listener) {
synchronized (mAPPStateListener) {
mAPPStateListener.add(listener);
}
}
@Override
public void unregisterAppStateListener(APPStateListener listener) {
synchronized (mAPPStateListener) {
mAPPStateListener.remove(listener);
}
}
private void hookInstrumentation(){
try {
Class<?> activityThreadC = Class.forName("android.app.ActivityThread");
Method currentActivityThreadM = activityThreadC.getDeclaredMethod("currentActivityThread");
Field instrumentationF = activityThreadC.getDeclaredField("mInstrumentation");
instrumentationF.setAccessible(true);
Object at = currentActivityThreadM.invoke(null);
instrumentationF.set(at,new InstrumentationHook((Instrumentation)instrumentationF.get(at)));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
protected final void dispatchActivityCreatedCompat(Activity activity, Bundle savedInstanceState){
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityCreated(activity, savedInstanceState);
}
}
protected final void dispatchActivityStartedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityStarted(activity);
}
}
protected final void dispatchActivityResumedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityResumed(activity);
}
}
protected final void dispatchActivityPausedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityPaused(activity);
}
}
protected final void dispatchActivityStoppedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityStopped(activity);
}
}
protected final void dispatchActivitySaveInstanceStateCompat(Activity activity, Bundle outState) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivitySaveInstanceState(activity, outState);
}
}
protected final void dispatchActivityDestroyedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityDestroyed(activity);
}
}
}
| UTF-8 | Java | 10,389 | java | LifecycleMonitorImpl.java | Java | [
{
"context": "util.Map;\nimport java.util.Set;\n\n/**\n * Created by niuniuzhang on 15/7/21.\n */\npublic class LifecycleMonitorImpl",
"end": 575,
"score": 0.9997005462646484,
"start": 564,
"tag": "USERNAME",
"value": "niuniuzhang"
}
] | null | [] | package com.zx.player.tools;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by niuniuzhang on 15/7/21.
*/
public class LifecycleMonitorImpl implements LifecycleMonitor {
private static final String TAG = "LifecycleMonitorImpl";
private static final int ON_STOP_CHECK_DELAY = 200;
private Context mContext;
private final ArrayList<ActivityLifecycleCallbacksCompat>
mActivityLifecycleCallbacksCompat = new ArrayList<ActivityLifecycleCallbacksCompat>();
private Map<ActivityLifecycleCallbacksCompat,ActivityLifecycleCallbacksWrapper> mCallbacksMap;
private final ArrayList<APPStateListener> mAPPStateListener = new ArrayList<APPStateListener>();
/**
* 记录调用了onResume的activity,onStop 200ms之后移除
* 只会在主线程中被调用,故不会出现互斥问题
*/
private Set<String> mResumeActivitys = new HashSet<String>();
private Handler mHandler;
protected LifecycleMonitorImpl(Context context) {
mContext = context.getApplicationContext();
if(Build.VERSION.SDK_INT < 14) {
hookInstrumentation();
}else{
mCallbacksMap = new HashMap<ActivityLifecycleCallbacksCompat, ActivityLifecycleCallbacksWrapper>();
}
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksCompat() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
//第一个Activity onResumeed的时候,表明APP进入前台
if (mResumeActivitys.size() == 0) {
synchronized (mAPPStateListener) {
for (APPStateListener listener : mAPPStateListener) {
listener.onEnterForeground();
}
}
PSLog.d(TAG, "=====> enter foreground");
}
String activityString = activity.getClass().getName()+activity.hashCode();
mResumeActivitys.add(activityString);
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
final String activityString = activity.getClass().getName()+activity.hashCode();
/**
* 这里延迟是防止Activity切换时,mResumeActivitys size为0导致误报进入后台
*/
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mResumeActivitys.remove(activityString);
if (mResumeActivitys.size() == 0) {
synchronized (mAPPStateListener) {
for (APPStateListener listener : mAPPStateListener) {
listener.onEnterBackground();
}
}
PSLog.d(TAG, "=====> enter background");
}
}
}, ON_STOP_CHECK_DELAY);
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
mHandler = new Handler(Looper.getMainLooper());
}
/**
* 注册Activity 生命周期监听,兼容 ICE_CREAM_SANDWICH(14) 以前版本
* @param callback 回调
*/
@SuppressLint("NewApi")
@Override
public void registerActivityLifecycleCallbacks(ActivityLifecycleCallbacksCompat callback){
if(callback == null)
return;
if(Build.VERSION.SDK_INT < 14){
synchronized (mActivityLifecycleCallbacksCompat) {
mActivityLifecycleCallbacksCompat.add(callback);
}
}else{
if(!mCallbacksMap.containsKey(callback)) {
ActivityLifecycleCallbacksWrapper realCallback = new ActivityLifecycleCallbacksWrapper(callback);
mCallbacksMap.put(callback,realCallback);
((Application)mContext).registerActivityLifecycleCallbacks(realCallback);
}
}
}
/**
* 注销Activity 生命周期监听,兼容 ICE_CREAM_SANDWICH(14) 以前版本
* @param callback 回调
*/
@SuppressLint("NewApi")
@Override
public synchronized void unregisterActivityLifecycleCallbacks(ActivityLifecycleCallbacksCompat callback) {
if(callback == null)
return;
if(Build.VERSION.SDK_INT < 14){
synchronized (mActivityLifecycleCallbacksCompat) {
mActivityLifecycleCallbacksCompat.remove(callback);
}
}else{
ActivityLifecycleCallbacksWrapper realCallback = mCallbacksMap.get(callback);
if(realCallback != null) {
mCallbacksMap.remove(callback);
((Application) mContext).unregisterActivityLifecycleCallbacks(realCallback);
}
}
}
@Override
public void registerAppStateListener(APPStateListener listener) {
synchronized (mAPPStateListener) {
mAPPStateListener.add(listener);
}
}
@Override
public void unregisterAppStateListener(APPStateListener listener) {
synchronized (mAPPStateListener) {
mAPPStateListener.remove(listener);
}
}
private void hookInstrumentation(){
try {
Class<?> activityThreadC = Class.forName("android.app.ActivityThread");
Method currentActivityThreadM = activityThreadC.getDeclaredMethod("currentActivityThread");
Field instrumentationF = activityThreadC.getDeclaredField("mInstrumentation");
instrumentationF.setAccessible(true);
Object at = currentActivityThreadM.invoke(null);
instrumentationF.set(at,new InstrumentationHook((Instrumentation)instrumentationF.get(at)));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
protected final void dispatchActivityCreatedCompat(Activity activity, Bundle savedInstanceState){
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityCreated(activity, savedInstanceState);
}
}
protected final void dispatchActivityStartedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityStarted(activity);
}
}
protected final void dispatchActivityResumedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityResumed(activity);
}
}
protected final void dispatchActivityPausedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityPaused(activity);
}
}
protected final void dispatchActivityStoppedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityStopped(activity);
}
}
protected final void dispatchActivitySaveInstanceStateCompat(Activity activity, Bundle outState) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivitySaveInstanceState(activity, outState);
}
}
protected final void dispatchActivityDestroyedCompat(Activity activity) {
Object[] callbacks;
synchronized (mActivityLifecycleCallbacksCompat) {
callbacks = mActivityLifecycleCallbacksCompat.toArray();
}
if(callbacks.length > 0){
for(Object callback:callbacks)
((ActivityLifecycleCallbacksCompat)callback).onActivityDestroyed(activity);
}
}
}
| 10,389 | 0.628521 | 0.625478 | 280 | 35.389286 | 29.877045 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.364286 | false | false | 0 |
4e5f27febdbf70811f5d5a4f5851dec832c2f63e | 15,539,191,701,290 | 08d835e125d2c23f9de04111ef886bbca90d971c | /src/main/array/ArrayProuct.java | e36541b1c93f189b081d1f24de34cdada1596cdc | [] | no_license | santanuchoudhury/mycode | https://github.com/santanuchoudhury/mycode | 30e5bea7493bea221c432b49aef7554bff4bee50 | 1490319d2df27c9a3d508f96886e6613fc469113 | refs/heads/master | 2019-06-21T08:38:53.825000 | 2018-10-16T07:10:58 | 2018-10-16T07:10:58 | 25,798,564 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.array;
import java.security.InvalidParameterException;
public class ArrayProuct {
static void products (int[] a) {
validateArray(a);
printArray(a);
int n = a.length;
int[] l = new int[n];
int[] r = new int[n];
int[] p = new int[n];
int i = 0, j = 0;
//initialization
l[0] = 1;
r[n-1] = 1;
//left array
for (i = 1; i < n; i++) {
l[i] = a[i-1] * l[i-1];
}
//right array
for (j = n-2; j >= 0; j--) {
r[j] = a[j+1] * r[j+1];
}
//final product array
for (i = 0; i < n; i++) {
p[i] = l[i] * r[i];
}
printArray(l);
printArray(r);
printArray(p);
}
static void products1 (int[] a) {
validateArray(a);
printArray(a);
int n = a.length;
int i = 0, t = 1;
int[] p = new int[n];
//Initialize the product array as 1
for (i = 0; i < n; i++) {
p[i] = 1;
}
/* In this loop, temp variable contains product of
elements on left side excluding a[i] */
for (i = 0 ; i < n ; i++) {
p[i] = t;
t = t*a[i];
}
t = 1;
/* In this loop, temp variable contains product of
elements on right side excluding a[i] */
for (i = n-1; i >= 0; i--) {
p[i] = p[i]* t;
t = t*a[i];
}
printArray(p);
}
static void validateArray(int[] a) {
if (a == null) {
throw new InvalidParameterException("Input can't be null.");
}
}
static void printArray(int[] a) {
if (a != null) {
System.out.println();
for (int i : a) {
System.out.print(i + ", ");
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
int[] a = new int[] {10, 3, 5};
products(a);
System.out.println();
//products1(a);
}
}
| UTF-8 | Java | 1,677 | java | ArrayProuct.java | Java | [] | null | [] | package main.array;
import java.security.InvalidParameterException;
public class ArrayProuct {
static void products (int[] a) {
validateArray(a);
printArray(a);
int n = a.length;
int[] l = new int[n];
int[] r = new int[n];
int[] p = new int[n];
int i = 0, j = 0;
//initialization
l[0] = 1;
r[n-1] = 1;
//left array
for (i = 1; i < n; i++) {
l[i] = a[i-1] * l[i-1];
}
//right array
for (j = n-2; j >= 0; j--) {
r[j] = a[j+1] * r[j+1];
}
//final product array
for (i = 0; i < n; i++) {
p[i] = l[i] * r[i];
}
printArray(l);
printArray(r);
printArray(p);
}
static void products1 (int[] a) {
validateArray(a);
printArray(a);
int n = a.length;
int i = 0, t = 1;
int[] p = new int[n];
//Initialize the product array as 1
for (i = 0; i < n; i++) {
p[i] = 1;
}
/* In this loop, temp variable contains product of
elements on left side excluding a[i] */
for (i = 0 ; i < n ; i++) {
p[i] = t;
t = t*a[i];
}
t = 1;
/* In this loop, temp variable contains product of
elements on right side excluding a[i] */
for (i = n-1; i >= 0; i--) {
p[i] = p[i]* t;
t = t*a[i];
}
printArray(p);
}
static void validateArray(int[] a) {
if (a == null) {
throw new InvalidParameterException("Input can't be null.");
}
}
static void printArray(int[] a) {
if (a != null) {
System.out.println();
for (int i : a) {
System.out.print(i + ", ");
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
int[] a = new int[] {10, 3, 5};
products(a);
System.out.println();
//products1(a);
}
}
| 1,677 | 0.51938 | 0.502087 | 94 | 16.840425 | 14.035898 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.37234 | false | false | 0 |
e302f7410e0bb0bb5fca4627673fa8c57893443a | 17,016,660,465,486 | ea86380fdd2faf0721640537dc20ae8327ef085e | /src/test/java/cn/osxm/ssmi/chp06/junit/JunitSpringTest.java | e2d438cd088b62002f947d9ad9026760c01070cb | [] | no_license | osxm/ssmi | https://github.com/osxm/ssmi | 5c0c9225f2944599d150cb8db4da98f56ad682f8 | 506ccee5baf1656c30807c247e36cf0fcd1d3354 | refs/heads/master | 2022-12-24T07:16:47.500000 | 2021-12-21T15:56:59 | 2021-12-21T15:56:59 | 160,265,156 | 0 | 3 | null | false | 2022-12-16T00:46:32 | 2018-12-03T23:00:51 | 2021-12-21T15:57:01 | 2022-12-16T00:46:32 | 604 | 0 | 0 | 14 | Java | false | false | /**
* @Title: JunitSpringTest.java
* @Package cn.osxm.ssmi.chp6.junit
* @Description: TODO
* @author osxm:oscarxueming
* @date 2019年1月7日 下午10:27:33
* @version V1.0
*/
package cn.osxm.ssmi.chp06.junit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
/**
* @ClassName: JunitSpringTest
* @Description: 此类仅作概念说明, 不提倡使用此方式测试Spring
* @author oscarchen
*/
public class JunitSpringTest {
@SuppressWarnings("unused")
private ApplicationContext context;
//@Before
@BeforeClass
public static void initSpring() {
System.out.println("初始化容器");
//context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void testMethod1() {
//context.getBean("bean1");
}
@Test
public void testMethod2() {
//context.getBean("bean2");
}
} | GB18030 | Java | 949 | java | JunitSpringTest.java | Java | [
{
"context": "smi.chp6.junit\n * @Description: TODO\n * @author osxm:oscarxueming\n * @date 2019年1月7日 下午10:27:33\n * @ve",
"end": 109,
"score": 0.6213241815567017,
"start": 107,
"tag": "USERNAME",
"value": "xm"
},
{
"context": ".chp6.junit\n * @Description: TODO\n * @author osxm:osca... | null | [] | /**
* @Title: JunitSpringTest.java
* @Package cn.osxm.ssmi.chp6.junit
* @Description: TODO
* @author osxm:oscarxueming
* @date 2019年1月7日 下午10:27:33
* @version V1.0
*/
package cn.osxm.ssmi.chp06.junit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
/**
* @ClassName: JunitSpringTest
* @Description: 此类仅作概念说明, 不提倡使用此方式测试Spring
* @author oscarchen
*/
public class JunitSpringTest {
@SuppressWarnings("unused")
private ApplicationContext context;
//@Before
@BeforeClass
public static void initSpring() {
System.out.println("初始化容器");
//context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void testMethod1() {
//context.getBean("bean1");
}
@Test
public void testMethod2() {
//context.getBean("bean2");
}
} | 949 | 0.67789 | 0.654321 | 43 | 19.744186 | 17.835283 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.232558 | false | false | 0 |
93c528834cd71b2628a5aa821e815b6ea650e3e6 | 18,425,409,730,941 | 630be9caedae55f467f98e4522cab93364f4d650 | /app/src/main/java/com/chumu/jianzhimao/mvp/LetterComparator.java | 1a9745b37b6d42c921faddfe8fbcce71ac7861c2 | [] | no_license | 15335179243/JianZhiMao | https://github.com/15335179243/JianZhiMao | 74a219ad7fd67d6b925b63dc0bd08731207980b9 | 6db1f41b38b2d7967dfedf274fceaa786169eebc | refs/heads/master | 2022-12-27T01:27:38.964000 | 2020-09-02T10:12:05 | 2020-09-02T10:12:05 | 292,249,595 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chumu.jianzhimao.mvp;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chumu.jianzhimao.R;
import com.chumu.jianzhimao.mvp.bean.City;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import java.util.List;
public class LetterComparator implements Comparator<City> {
@Override
public int compare(City l, City r) {
if (l == null || r == null) {
return 0;
}
String lhsSortLetters = l.pys.substring(0, 1).toUpperCase();
String rhsSortLetters = r.pys.substring(0, 1).toUpperCase();
if (lhsSortLetters == null || rhsSortLetters == null) {
return 0;
}
return lhsSortLetters.compareTo(rhsSortLetters);
}
}
| UTF-8 | Java | 819 | java | LetterComparator.java | Java | [] | null | [] | package com.chumu.jianzhimao.mvp;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chumu.jianzhimao.R;
import com.chumu.jianzhimao.mvp.bean.City;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import java.util.List;
public class LetterComparator implements Comparator<City> {
@Override
public int compare(City l, City r) {
if (l == null || r == null) {
return 0;
}
String lhsSortLetters = l.pys.substring(0, 1).toUpperCase();
String rhsSortLetters = r.pys.substring(0, 1).toUpperCase();
if (lhsSortLetters == null || rhsSortLetters == null) {
return 0;
}
return lhsSortLetters.compareTo(rhsSortLetters);
}
}
| 819 | 0.680098 | 0.672772 | 29 | 27.206896 | 24.102339 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false | 0 |
93629b8e38bb11a7b8465b378388f42bf862e8be | 575,525,643,648 | f529642caeab495a4fcb3792f0a421206295d779 | /Console_Rpg/src/Consumables/IConsumable.java | 681e88e6afcb4b9273873a53ad3707ce610756b3 | [] | no_license | Halil-Ibrahim-Kasapoglu/Console_Rpg | https://github.com/Halil-Ibrahim-Kasapoglu/Console_Rpg | 3434a636683d98c05abeee05b9ba997cd0b629e4 | 0f6676160ab14384306e29890d5ecc2c941339cc | refs/heads/main | 2023-05-07T21:24:53.900000 | 2021-05-25T19:24:12 | 2021-05-25T19:24:12 | 365,548,481 | 2 | 1 | null | false | 2021-05-08T18:26:41 | 2021-05-08T15:28:09 | 2021-05-08T15:46:14 | 2021-05-08T18:26:41 | 25 | 2 | 0 | 5 | Java | false | false | package Consumables;
public interface IConsumable {
void Consume();
}
| UTF-8 | Java | 76 | java | IConsumable.java | Java | [] | null | [] | package Consumables;
public interface IConsumable {
void Consume();
}
| 76 | 0.723684 | 0.723684 | 6 | 11.666667 | 11.869662 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
846a1b6132884ecb4dffe60cfea14387e4ea7bf4 | 9,775,345,601,239 | 2ef32a9eff9f7092fc63142d95ff698092be0d8b | /src/main/java/com/kaoriya/qb/ip_range/App.java | cba909f10859d45935b98ff03d8788e4e9e6d98d | [] | no_license | koron/ip_range | https://github.com/koron/ip_range | 216dbf35f6ddb70c94efc112ee78b1bf7815d3ca | 9dc7367105c9361076414a672d648b73ded7a318 | refs/heads/master | 2023-06-28T14:36:40.507000 | 2023-06-14T09:20:13 | 2023-06-14T09:20:13 | 5,658,400 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kaoriya.qb.ip_range;
import java.io.IOException;
import java.util.List;
import org.ardverk.collection.PatriciaTrie;
import org.ardverk.collection.Trie;
import org.ardverk.collection.IntegerKeyAnalyzer;
/**
* Hello world!
*
*/
public class App
{
public static void read(DataReader r, Trie<Integer,TrieData> trie)
throws IOException
{
while (true) {
IPv4RangeData d = r.read();
if (d == null) {
break;
}
List<CIDR> list = CIDRUtils.toCIDR(d);
for (CIDR v : list) {
TrieData td = new TrieData(v, d.getData());
trie.put(v.getAddress().intValue(), td);
}
}
}
public static String find(Trie<Integer,TrieData> trie, int value)
{
TrieData td = trie.selectValue(value);
if (td == null) {
return null;
}
return td.getCIDR().match(value) ? td.getData() : null;
}
public static void func1() throws IOException
{
Trie<Integer,TrieData> trie = new PatriciaTrie<>(
IntegerKeyAnalyzer.INSTANCE);
DataReader reader = new DataReader(System.in);
try {
read(reader, trie);
} finally {
reader.close();
}
int hitCount = 0;
for (int i = Integer.MIN_VALUE; true; ++i) {
String data = find(trie, i);
if (data != null) {
++hitCount;
}
if ((i & 0xffffff) == 0) {
System.out.println("curr=" + ((i >> 24) & 0xff));
}
if (i == Integer.MAX_VALUE) {
break;
}
}
System.out.println("hitCount=" + hitCount);
}
public static String find1a(Trie<Integer,TrieData> trie, int value)
{
TrieData td = trie.selectNearValue(value);
if (td == null) {
return null;
}
return td.getCIDR().match(value) ? td.getData() : null;
}
public static void func1a() throws IOException
{
Trie<Integer,TrieData> trie = new PatriciaTrie<>(
IntegerKeyAnalyzer.INSTANCE);
DataReader reader = new DataReader(System.in);
try {
read(reader, trie);
} finally {
reader.close();
}
int hitCount = 0;
for (int i = Integer.MIN_VALUE; true; ++i) {
String data = find1a(trie, i);
if (data != null) {
++hitCount;
}
if ((i & 0xffffff) == 0) {
System.out.println("curr=" + ((i >> 24) & 0xff));
}
if (i == Integer.MAX_VALUE) {
break;
}
}
System.out.println("hitCount=" + hitCount);
}
public static void read(DataReader r, IntRangeTable<String> table)
throws IOException
{
while (true) {
IPv4RangeData d = r.read();
if (d == null) {
break;
}
int start = IPv4Integer.valueOf(d.getStart());
int end = IPv4Integer.valueOf(d.getEnd());
table.add(start, end, d.getData());
}
}
public static String find(IntRangeTable<String> table, int value)
{
return table.find(IPv4Integer.valueOf(value));
}
public static void func2() throws IOException
{
IntRangeTable<String> table = new IntRangeTable<>();
DataReader reader = new DataReader(System.in);
try {
read(reader, table);
} finally {
reader.close();
}
int hitCount = 0;
for (int i = Integer.MIN_VALUE; true; ++i) {
String data = find(table, i);
if (data != null) {
++hitCount;
}
if ((i & 0xffffff) == 0) {
System.out.println("curr=" + ((i >> 24) & 0xff));
}
if (i == Integer.MAX_VALUE) {
break;
}
}
System.out.println("hitCount=" + hitCount);
}
public static void read(
DataReader r,
Trie<Integer,TrieData> trie,
IntRangeTable<String> table)
throws IOException
{
while (true) {
IPv4RangeData d = r.read();
if (d == null) {
break;
}
List<CIDR> list = CIDRUtils.toCIDR(d);
for (CIDR v : list) {
TrieData td = new TrieData(v, d.getData());
trie.put(v.getAddress().intValue(), td);
}
int start = IPv4Integer.valueOf(d.getStart());
int end = IPv4Integer.valueOf(d.getEnd());
table.add(start, end, d.getData());
}
}
public static String find(
Trie<Integer,TrieData> trie,
IntRangeTable<String> table,
int value)
{
String v1 = find(trie, value);
String v2 = find(table, value);
if (v1 != v2) {
throw new RuntimeException("not match: value=" + value + " trie="
+ v1 + " table=" + v2);
}
return v1;
}
public static void func3() throws IOException
{
IntRangeTable<String> table = new IntRangeTable<>();
Trie<Integer,TrieData> trie = new PatriciaTrie<>(IntegerKeyAnalyzer.INSTANCE);
DataReader reader = new DataReader(System.in);
try {
read(reader, trie, table);
} finally {
reader.close();
}
int hitCount = 0;
for (int i = Integer.MIN_VALUE; true; ++i) {
String data = find(trie, table, i);
if (data != null) {
++hitCount;
}
if ((i & 0xffffff) == 0) {
System.out.println("curr=" + ((i >> 24) & 0xff));
}
if (i == Integer.MAX_VALUE) {
break;
}
}
System.out.println("hitCount=" + hitCount);
}
public static void main(String[] args)
{
try {
Thread.sleep(10000);
long start = System.currentTimeMillis();
func2();
long time = System.currentTimeMillis() - start;
System.out.format("%1$d secs\n", time / 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 6,416 | java | App.java | Java | [] | null | [] | package com.kaoriya.qb.ip_range;
import java.io.IOException;
import java.util.List;
import org.ardverk.collection.PatriciaTrie;
import org.ardverk.collection.Trie;
import org.ardverk.collection.IntegerKeyAnalyzer;
/**
* Hello world!
*
*/
public class App
{
public static void read(DataReader r, Trie<Integer,TrieData> trie)
throws IOException
{
while (true) {
IPv4RangeData d = r.read();
if (d == null) {
break;
}
List<CIDR> list = CIDRUtils.toCIDR(d);
for (CIDR v : list) {
TrieData td = new TrieData(v, d.getData());
trie.put(v.getAddress().intValue(), td);
}
}
}
public static String find(Trie<Integer,TrieData> trie, int value)
{
TrieData td = trie.selectValue(value);
if (td == null) {
return null;
}
return td.getCIDR().match(value) ? td.getData() : null;
}
public static void func1() throws IOException
{
Trie<Integer,TrieData> trie = new PatriciaTrie<>(
IntegerKeyAnalyzer.INSTANCE);
DataReader reader = new DataReader(System.in);
try {
read(reader, trie);
} finally {
reader.close();
}
int hitCount = 0;
for (int i = Integer.MIN_VALUE; true; ++i) {
String data = find(trie, i);
if (data != null) {
++hitCount;
}
if ((i & 0xffffff) == 0) {
System.out.println("curr=" + ((i >> 24) & 0xff));
}
if (i == Integer.MAX_VALUE) {
break;
}
}
System.out.println("hitCount=" + hitCount);
}
public static String find1a(Trie<Integer,TrieData> trie, int value)
{
TrieData td = trie.selectNearValue(value);
if (td == null) {
return null;
}
return td.getCIDR().match(value) ? td.getData() : null;
}
public static void func1a() throws IOException
{
Trie<Integer,TrieData> trie = new PatriciaTrie<>(
IntegerKeyAnalyzer.INSTANCE);
DataReader reader = new DataReader(System.in);
try {
read(reader, trie);
} finally {
reader.close();
}
int hitCount = 0;
for (int i = Integer.MIN_VALUE; true; ++i) {
String data = find1a(trie, i);
if (data != null) {
++hitCount;
}
if ((i & 0xffffff) == 0) {
System.out.println("curr=" + ((i >> 24) & 0xff));
}
if (i == Integer.MAX_VALUE) {
break;
}
}
System.out.println("hitCount=" + hitCount);
}
public static void read(DataReader r, IntRangeTable<String> table)
throws IOException
{
while (true) {
IPv4RangeData d = r.read();
if (d == null) {
break;
}
int start = IPv4Integer.valueOf(d.getStart());
int end = IPv4Integer.valueOf(d.getEnd());
table.add(start, end, d.getData());
}
}
public static String find(IntRangeTable<String> table, int value)
{
return table.find(IPv4Integer.valueOf(value));
}
public static void func2() throws IOException
{
IntRangeTable<String> table = new IntRangeTable<>();
DataReader reader = new DataReader(System.in);
try {
read(reader, table);
} finally {
reader.close();
}
int hitCount = 0;
for (int i = Integer.MIN_VALUE; true; ++i) {
String data = find(table, i);
if (data != null) {
++hitCount;
}
if ((i & 0xffffff) == 0) {
System.out.println("curr=" + ((i >> 24) & 0xff));
}
if (i == Integer.MAX_VALUE) {
break;
}
}
System.out.println("hitCount=" + hitCount);
}
public static void read(
DataReader r,
Trie<Integer,TrieData> trie,
IntRangeTable<String> table)
throws IOException
{
while (true) {
IPv4RangeData d = r.read();
if (d == null) {
break;
}
List<CIDR> list = CIDRUtils.toCIDR(d);
for (CIDR v : list) {
TrieData td = new TrieData(v, d.getData());
trie.put(v.getAddress().intValue(), td);
}
int start = IPv4Integer.valueOf(d.getStart());
int end = IPv4Integer.valueOf(d.getEnd());
table.add(start, end, d.getData());
}
}
public static String find(
Trie<Integer,TrieData> trie,
IntRangeTable<String> table,
int value)
{
String v1 = find(trie, value);
String v2 = find(table, value);
if (v1 != v2) {
throw new RuntimeException("not match: value=" + value + " trie="
+ v1 + " table=" + v2);
}
return v1;
}
public static void func3() throws IOException
{
IntRangeTable<String> table = new IntRangeTable<>();
Trie<Integer,TrieData> trie = new PatriciaTrie<>(IntegerKeyAnalyzer.INSTANCE);
DataReader reader = new DataReader(System.in);
try {
read(reader, trie, table);
} finally {
reader.close();
}
int hitCount = 0;
for (int i = Integer.MIN_VALUE; true; ++i) {
String data = find(trie, table, i);
if (data != null) {
++hitCount;
}
if ((i & 0xffffff) == 0) {
System.out.println("curr=" + ((i >> 24) & 0xff));
}
if (i == Integer.MAX_VALUE) {
break;
}
}
System.out.println("hitCount=" + hitCount);
}
public static void main(String[] args)
{
try {
Thread.sleep(10000);
long start = System.currentTimeMillis();
func2();
long time = System.currentTimeMillis() - start;
System.out.format("%1$d secs\n", time / 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 6,416 | 0.48192 | 0.473192 | 231 | 26.774891 | 20.753584 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.554113 | false | false | 0 |
db1f19776a2723d808a88e3863608cfa83ffa956 | 7,602,092,150,772 | 067df685707d1ea5452663d33152d72e6bf71a92 | /src/ConnectionManager.java | b03acef6b9f6020c2ae19fd1089ef0986659ea53 | [] | no_license | brenoafb/axur-challenge | https://github.com/brenoafb/axur-challenge | 274c811fe1b18f8e9bc5b7b3f1eeb10b57fb627e | 19645fcbdd08f63d61c248a887be496bfe562ff2 | refs/heads/master | 2023-03-26T22:01:51.998000 | 2021-03-28T13:40:05 | 2021-03-28T13:40:05 | 350,440,931 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package src;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Optional;
public class ConnectionManager {
private HttpURLConnection con;
private int timeout = 5000;
public boolean setupConnection(URL url) {
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(timeout);
con.setReadTimeout(timeout);
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestProperty("Content-Type", "text/html");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
System.err.println("ConnectionManager: Timeout");
return false;
} catch (java.io.IOException e) {
System.err.println("ConnectionManager: IOException");
return false;
}
}
public Optional<String> getContents() {
try {
InputStreamReader reader = new InputStreamReader(con.getInputStream());
// System.err.println(String.format("Encoding: %s", reader.getEncoding()));
BufferedReader in = new BufferedReader(reader);
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
String processedLine = inputLine.toLowerCase(); // canonize the input
content.append(processedLine);
}
in.close();
con.disconnect();
return Optional.of(content.toString());
} catch (IOException e) {
System.err.println("ConnectionManager: Error fetching page contents");
return Optional.empty();
}
}
} | UTF-8 | Java | 1,661 | java | ConnectionManager.java | Java | [] | null | [] | package src;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Optional;
public class ConnectionManager {
private HttpURLConnection con;
private int timeout = 5000;
public boolean setupConnection(URL url) {
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(timeout);
con.setReadTimeout(timeout);
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestProperty("Content-Type", "text/html");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
System.err.println("ConnectionManager: Timeout");
return false;
} catch (java.io.IOException e) {
System.err.println("ConnectionManager: IOException");
return false;
}
}
public Optional<String> getContents() {
try {
InputStreamReader reader = new InputStreamReader(con.getInputStream());
// System.err.println(String.format("Encoding: %s", reader.getEncoding()));
BufferedReader in = new BufferedReader(reader);
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
String processedLine = inputLine.toLowerCase(); // canonize the input
content.append(processedLine);
}
in.close();
con.disconnect();
return Optional.of(content.toString());
} catch (IOException e) {
System.err.println("ConnectionManager: Error fetching page contents");
return Optional.empty();
}
}
} | 1,661 | 0.683925 | 0.680915 | 51 | 31.588236 | 22.819992 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 0 |
750b0b668f1c118682b5c965036a232a1804d1a3 | 33,706,903,351,059 | 9bbbd2d8eea0a5068889c1bd0bbba90efea4f6ba | /easycluster-serialization/src/main/java/org/easycluster/easycluster/serialization/tlv/encode/encoders/BooleanTLVEncoder.java | 1765a9375c8f31e5f697083b25fa8efd59833399 | [] | no_license | xinster819/utils | https://github.com/xinster819/utils | 99e77d62547ed4c262fbccbb6d983190b062b3dc | cb42243a2af54b42e18287d10ece5e13224c1294 | refs/heads/master | 2020-05-20T05:22:14.315000 | 2015-05-10T06:09:10 | 2015-05-10T06:09:10 | 35,354,257 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.easycluster.easycluster.serialization.tlv.encode.encoders;
import java.util.Arrays;
import java.util.List;
import org.easycluster.easycluster.serialization.tlv.encode.TLVEncodeContext;
import org.easycluster.easycluster.serialization.tlv.encode.TLVEncoder;
public class BooleanTLVEncoder implements TLVEncoder {
public List<byte[]> encode(Object src, TLVEncodeContext ctx) {
if (src instanceof Boolean) {
return Arrays.asList(new byte[] { (byte) ((Boolean) src ? 1 : 0) });
} else {
throw new RuntimeException("BooleanTLVEncoder: wrong source type. [" + src.getClass() + "]");
}
}
}
| UTF-8 | Java | 613 | java | BooleanTLVEncoder.java | Java | [] | null | [] | package org.easycluster.easycluster.serialization.tlv.encode.encoders;
import java.util.Arrays;
import java.util.List;
import org.easycluster.easycluster.serialization.tlv.encode.TLVEncodeContext;
import org.easycluster.easycluster.serialization.tlv.encode.TLVEncoder;
public class BooleanTLVEncoder implements TLVEncoder {
public List<byte[]> encode(Object src, TLVEncodeContext ctx) {
if (src instanceof Boolean) {
return Arrays.asList(new byte[] { (byte) ((Boolean) src ? 1 : 0) });
} else {
throw new RuntimeException("BooleanTLVEncoder: wrong source type. [" + src.getClass() + "]");
}
}
}
| 613 | 0.75367 | 0.750408 | 18 | 33.055557 | 32.896255 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 0 |
0c0deca4bd1ae2d8b3d95099bf63f35f69309085 | 7,327,214,263,369 | 47c4e00a3e387a38e3b5491131da010d84fc2a5f | /eKartFront/src/main/java/com/niit/ekartfront/util/SendMail.java | d54742bade2524319bb584243e05cb92ab3d10ce | [] | no_license | ponmuthu5990/eKart | https://github.com/ponmuthu5990/eKart | af19d7be57690c7524a518fe1746f4f975520125 | 67d296c05c6891db16442e4f2e81561714f7c0f4 | refs/heads/master | 2021-01-02T22:34:09.644000 | 2018-01-06T10:16:48 | 2018-01-06T10:16:48 | 99,341,505 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.niit.ekartfront.util;
import org.springframework.mail.SimpleMailMessage;
public class SendMail {
public static SimpleMailMessage sendingMail(String recipientAddress, String subject, String message){
SimpleMailMessage email = new SimpleMailMessage();
email.setTo(recipientAddress);
email.setSubject(subject);
email.setText(message);
return email;
}
}
| UTF-8 | Java | 440 | java | SendMail.java | Java | [] | null | [] | package com.niit.ekartfront.util;
import org.springframework.mail.SimpleMailMessage;
public class SendMail {
public static SimpleMailMessage sendingMail(String recipientAddress, String subject, String message){
SimpleMailMessage email = new SimpleMailMessage();
email.setTo(recipientAddress);
email.setSubject(subject);
email.setText(message);
return email;
}
}
| 440 | 0.681818 | 0.681818 | 19 | 21.157894 | 26.184092 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.368421 | false | false | 0 |
c9b9a67c63c9530c7514ae632502dce5b696586c | 9,637,906,654,289 | fc6be6f6464e87de292e692ef22e6f3b7ccc8e95 | /src/main/java/py/org/fundacionparaguaya/pspserver/families/specifications/FamilySpecification.java | cc9991565e74fd2677ba048a64b283319a1cc064 | [
"Apache-2.0"
] | permissive | jazvillagra/FP-PSP-SERVER | https://github.com/jazvillagra/FP-PSP-SERVER | ca502b271b54337cd89d84aae9db920573cd8951 | 20922c8174f8d2b11bf7c00202e12e0f817c9a44 | refs/heads/master | 2020-03-10T08:48:36.703000 | 2018-03-20T19:31:51 | 2018-03-20T19:31:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package py.org.fundacionparaguaya.pspserver.families.specifications;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import py.org.fundacionparaguaya.pspserver.families.dtos.FamilyFilterDTO;
import py.org.fundacionparaguaya.pspserver.families.entities.FamilyEntity;
import py.org.fundacionparaguaya.pspserver.families.entities.FamilyEntity_;
import py.org.fundacionparaguaya.pspserver.network.entities.ApplicationEntity;
import py.org.fundacionparaguaya.pspserver.system.entities.CityEntity;
import py.org.fundacionparaguaya.pspserver.system.entities.CountryEntity;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* @author bsandoval
*
*/
public class FamilySpecification {
private static final String ID_ATTRIBUTE = "id";
public static Specification<FamilyEntity> byFilter(FamilyFilterDTO filter) {
return new Specification<FamilyEntity>() {
@Override
public Predicate toPredicate(Root<FamilyEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<>();
if (filter.getApplicationId() != null) {
Join<FamilyEntity, ApplicationEntity> joinApplication = root.join(FamilyEntity_.getApplication());
Expression<Long> byApplicationId = joinApplication.<Long>get(ID_ATTRIBUTE);
predicates.add(cb.equal(byApplicationId, filter.getApplicationId()));
}
if (filter.getOrganizationId() != null) {
Expression<Long> byOrganizationId = root
.join(FamilyEntity_.getOrganization())
.<Long>get(ID_ATTRIBUTE);
predicates.add(cb.equal(byOrganizationId, filter.getOrganizationId()));
}
if (filter.getCountryId() != null) {
Join<FamilyEntity, CountryEntity> joinCountry = root.join(FamilyEntity_.getCountry());
Expression<Long> byCountryId = joinCountry.<Long>get(ID_ATTRIBUTE);
predicates.add(cb.equal(byCountryId, filter.getCountryId()));
}
if (filter.getCityId() != null) {
Join<FamilyEntity, CityEntity> joinCity = root.join(FamilyEntity_.getCity());
Expression<Long> byCityId = joinCity.<Long>get(ID_ATTRIBUTE);
predicates.add(cb.equal(byCityId, filter.getCityId()));
}
if(StringUtils.isNotEmpty(filter.getName())) {
String nameParamQuery = "%" + filter.getName().toLowerCase().replaceAll("\\s", "%") + "%";
Expression<String> likeName = cb.lower(root.get(FamilyEntity_.getName()));
predicates.add(cb.like(likeName, nameParamQuery));
}
if (filter.getLastModifiedGt() != null) {
LocalDateTime dateTimeParam = LocalDateTime.parse(filter.getLastModifiedGt());
Predicate predicate = cb.greaterThan(root.get(FamilyEntity_.getLastModifiedAt()), dateTimeParam);
predicates.add(predicate);
}
predicates.add(cb.isTrue(root.get(FamilyEntity_.getIsActive())));
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
}
| UTF-8 | Java | 3,872 | java | FamilySpecification.java | Java | [
{
"context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author bsandoval\n *\n */\npublic class FamilySpecification {\n \n ",
"end": 1014,
"score": 0.999464213848114,
"start": 1005,
"tag": "USERNAME",
"value": "bsandoval"
}
] | null | [] | /**
*
*/
package py.org.fundacionparaguaya.pspserver.families.specifications;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import py.org.fundacionparaguaya.pspserver.families.dtos.FamilyFilterDTO;
import py.org.fundacionparaguaya.pspserver.families.entities.FamilyEntity;
import py.org.fundacionparaguaya.pspserver.families.entities.FamilyEntity_;
import py.org.fundacionparaguaya.pspserver.network.entities.ApplicationEntity;
import py.org.fundacionparaguaya.pspserver.system.entities.CityEntity;
import py.org.fundacionparaguaya.pspserver.system.entities.CountryEntity;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* @author bsandoval
*
*/
public class FamilySpecification {
private static final String ID_ATTRIBUTE = "id";
public static Specification<FamilyEntity> byFilter(FamilyFilterDTO filter) {
return new Specification<FamilyEntity>() {
@Override
public Predicate toPredicate(Root<FamilyEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<>();
if (filter.getApplicationId() != null) {
Join<FamilyEntity, ApplicationEntity> joinApplication = root.join(FamilyEntity_.getApplication());
Expression<Long> byApplicationId = joinApplication.<Long>get(ID_ATTRIBUTE);
predicates.add(cb.equal(byApplicationId, filter.getApplicationId()));
}
if (filter.getOrganizationId() != null) {
Expression<Long> byOrganizationId = root
.join(FamilyEntity_.getOrganization())
.<Long>get(ID_ATTRIBUTE);
predicates.add(cb.equal(byOrganizationId, filter.getOrganizationId()));
}
if (filter.getCountryId() != null) {
Join<FamilyEntity, CountryEntity> joinCountry = root.join(FamilyEntity_.getCountry());
Expression<Long> byCountryId = joinCountry.<Long>get(ID_ATTRIBUTE);
predicates.add(cb.equal(byCountryId, filter.getCountryId()));
}
if (filter.getCityId() != null) {
Join<FamilyEntity, CityEntity> joinCity = root.join(FamilyEntity_.getCity());
Expression<Long> byCityId = joinCity.<Long>get(ID_ATTRIBUTE);
predicates.add(cb.equal(byCityId, filter.getCityId()));
}
if(StringUtils.isNotEmpty(filter.getName())) {
String nameParamQuery = "%" + filter.getName().toLowerCase().replaceAll("\\s", "%") + "%";
Expression<String> likeName = cb.lower(root.get(FamilyEntity_.getName()));
predicates.add(cb.like(likeName, nameParamQuery));
}
if (filter.getLastModifiedGt() != null) {
LocalDateTime dateTimeParam = LocalDateTime.parse(filter.getLastModifiedGt());
Predicate predicate = cb.greaterThan(root.get(FamilyEntity_.getLastModifiedAt()), dateTimeParam);
predicates.add(predicate);
}
predicates.add(cb.isTrue(root.get(FamilyEntity_.getIsActive())));
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
}
| 3,872 | 0.62345 | 0.623192 | 84 | 45.095238 | 34.473461 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false | 0 |
6cea0672fa7faa07ab535ce5f12d770b1f7663e9 | 2,628,520,011,402 | 086185861d3dfc9507b03927d1262414eb280523 | /newsnews-apis/src/main/java/com/light/apis/article/ApArticleCollectionControllerApi.java | 55d2b48f10cd7cb63b5afdf5d72ee5aa7008cacd | [] | no_license | houhaiiiii/News | https://github.com/houhaiiiii/News | 1e86eef97c71fde1b68a557b1ca68b27809733ff | 03dba52f73cd706e828680c66dd9a2977e854155 | refs/heads/master | 2023-06-18T20:20:55.344000 | 2021-07-22T16:01:13 | 2021-07-22T16:01:13 | 326,561,969 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.light.apis.article;
import com.light.model.article.dtos.CollectionBehaviorDto;
import com.light.model.common.dtos.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(value = "app端-文章收藏功能", tags = "article-collection", description = "app端-文章收藏功能")
public interface ApArticleCollectionControllerApi {
@ApiOperation("收藏文章")
public ResponseResult collect(CollectionBehaviorDto dto);
}
| UTF-8 | Java | 489 | java | ApArticleCollectionControllerApi.java | Java | [] | null | [] | package com.light.apis.article;
import com.light.model.article.dtos.CollectionBehaviorDto;
import com.light.model.common.dtos.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(value = "app端-文章收藏功能", tags = "article-collection", description = "app端-文章收藏功能")
public interface ApArticleCollectionControllerApi {
@ApiOperation("收藏文章")
public ResponseResult collect(CollectionBehaviorDto dto);
}
| 489 | 0.79691 | 0.79691 | 14 | 31.357143 | 27.041258 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 0 |
4e26a165d39a78bfd8f31e5b4697fcf512ca6148 | 27,187,143,009,746 | efab9fc501d7d8b53e54f20c0fb1f00d7012a272 | /Java_example/src/com/kh/example/practice3/run/Run.java | e2da3f15f7e4d84fe56b2a3cc2cb6c5fc40478c8 | [] | no_license | DK2554/JAVA_E | https://github.com/DK2554/JAVA_E | 7be99f42aa9334dcefe51bdec08bc4b0e477d33f | 4f16e8436c0ece699934eb4a67d0ea58ca0237aa | refs/heads/master | 2022-11-17T18:35:46.329000 | 2020-07-02T13:37:40 | 2020-07-02T13:37:40 | 275,790,190 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kh.example.practice3.run;
import com.kh.example.practice3.model.vo.Circle;
public class Run {
public static void main(String[] args) {
Circle cr=new Circle();
cr.getAreaOfCircle();
cr.getSizeOfCircle();
cr.incrementRadius();
cr.getAreaOfCircle();
cr.getSizeOfCircle();
}
}
| UTF-8 | Java | 312 | java | Run.java | Java | [] | null | [] | package com.kh.example.practice3.run;
import com.kh.example.practice3.model.vo.Circle;
public class Run {
public static void main(String[] args) {
Circle cr=new Circle();
cr.getAreaOfCircle();
cr.getSizeOfCircle();
cr.incrementRadius();
cr.getAreaOfCircle();
cr.getSizeOfCircle();
}
}
| 312 | 0.695513 | 0.689103 | 19 | 15.421053 | 15.298145 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.473684 | false | false | 0 |
15b32a7a7cceff5f55009d7cb61a4dc75a3ac81b | 29,583,734,748,533 | 708a95d12844db8ae9c5d9e02a17618394dcd0da | /src/jp/co/yh123/tank/chara/ActionWalk.java | b21876e58f26974b1344fe8427f3f75151f34cbf | [] | no_license | yohamta/swing-roguelike | https://github.com/yohamta/swing-roguelike | 708fa8bfea29323a19981ac09733fbf2fafb7d61 | f2d05d023bbdcc18e5c311a9b338e3614a74ac35 | refs/heads/master | 2021-05-28T19:19:49.365000 | 2015-04-06T14:25:54 | 2015-04-06T14:25:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package src.jp.co.yh123.tank.chara;
import src.jp.co.yh123.tank.collabo.IMaptipClbInterface;
import src.jp.co.yh123.tank.map.Map;
import src.jp.co.yh123.tank.map.MapFactory;
import src.jp.co.yh123.zlibrary.util.DebugUtil;
import src.jp.co.yh123.zlibrary.util.GameMath;
public class ActionWalk implements ICharaAction {
private int _toCellX = 0;
private int _toCellY = 0;
private int _moveFrame = 1;
private double _tgX, _tgY;
private int _execCount = 0;
private double _spdX, _spdY;
private boolean _isEnd = false;
public ActionWalk(int moveFrame, int toCellX, int toCellY, Chara c)
throws Exception {
_moveFrame = moveFrame;
_toCellX = toCellX;
_toCellY = toCellY;
setVxyToCellxy(c);
IMaptipClbInterface tip = (IMaptipClbInterface) MapFactory.getMap()
.get(c.getCellX(), c.getCellY());
tip.reserve(c);
}
public void doAction(Chara c) throws Exception {
_execCount++;
if (_moveFrame > 1) {
// 移動
c.setPosition(c.getX() + _spdX, c.getY() + _spdY);
// // 移動しすぎを矯正
// if (_spdX > 0 && c.getX() > _tgX) {
// // 行き過ぎ
// c.setPosition(_tgX, c.getY());
// } else if (_spdX < 0 && c.getX() < _tgX) {
// // 行き過ぎ
// c.setPosition(_tgX, c.getY());
// }
// if (_spdY > 0 && c.getY() > _tgY) {
// // 行き過ぎ
// c.setPosition(c.getX(), _tgY);
// } else if (_spdY < 0 && c.getY() < _tgY) {
// // 行き過ぎ
// c.setPosition(c.getX(), _tgY);
// }
}
// 到着判定
if (_execCount >= _moveFrame) {
// 到着
MapFactory.getMap().get(c.getCellX(), c.getCellY()).removeChara(c);
DebugUtil.assertTrue(c.isAlive());
MapFactory.getMap().get(_toCellX, _toCellY).setChara(c);
// 周りを確認
c.watchAround();
// // 罠判定
// MapTip tip = c.getCurrentMaptip();
// if (tip.isMapObject() && tip.getMapObject().isTrap()) {
// ApplicationFacade.getGame().trapProc(tip, tip.getMapObject());
// }
_isEnd = true;
c.useMovePoint(Chara.NORMAL_SPEED);
c.changeAction(new ActionWait());
}
}
public boolean isDoingAction(Chara c) {
return !_isEnd;
}
/**
* 速度設定 ■目的に向かって弾を飛ばす <br>
* 目標に向かって飛ぶ弾の関数() <br>
* { <br>
* 弾の初期化 <br>
* ├目標までの距離検出 <br>
* │・目標までの距離X=(目標の座標X)ー(弾の座標X) <br>
* │・目標までの距離Y=(目標の座標Y)ー(弾の座標Y) <br>
* │ ↓ <br>
* └弾の発射角度取得し移動量設定 <br>
* ・弾の発射角度=atan2(目標までの距離Y、目標までの距離X) <br>
* ・弾の移動量X=cos(弾の発射角度)×弾のスピード <br>
* ・弾の移動量Y=sin(弾の発射角度)×弾のスピード <br>
* ↓ <br>
* 移動量を計算し目的地まで飛ばす <br>
* ・弾の座標X+=弾の移動量X <br>
* ・弾の座標Y+=弾の移動量Y <br>
* ↓ <br>
* 当たるか画面外に出たら初めから <br>
* <br>
*
* @param ent
* @return
*/
private void setVxyToCellxy(Chara c) throws Exception {
if (_moveFrame > 1) {
// // 移動先
_tgX = Map.getCharaXofCell(c, _toCellX, _toCellY);
_tgY = Map.getCharaYofCell(c, _toCellX, _toCellY);
// 移動角度
double deg = GameMath.atan2(_tgX - c.getX(), _tgY - c.getY());
// double deg = c.getDirectionToNext(_toCellX, _toCellY);
// フレーム数から移動速度計算
this._spdX = GameMath.abs(_tgX - c.getX()) / (_moveFrame - 1);
this._spdY = GameMath.abs(_tgY - c.getY()) / (_moveFrame - 1);
// 移動速度
_spdX = (double) (GameMath.cos((int) (deg + 0.5)) * _spdX);
_spdY = (double) (GameMath.sin((int) (deg + 0.5)) * _spdY);
// ApplicationFacade.getModel().map.dump();
}
}
}
| SHIFT_JIS | Java | 3,971 | java | ActionWalk.java | Java | [] | null | [] | package src.jp.co.yh123.tank.chara;
import src.jp.co.yh123.tank.collabo.IMaptipClbInterface;
import src.jp.co.yh123.tank.map.Map;
import src.jp.co.yh123.tank.map.MapFactory;
import src.jp.co.yh123.zlibrary.util.DebugUtil;
import src.jp.co.yh123.zlibrary.util.GameMath;
public class ActionWalk implements ICharaAction {
private int _toCellX = 0;
private int _toCellY = 0;
private int _moveFrame = 1;
private double _tgX, _tgY;
private int _execCount = 0;
private double _spdX, _spdY;
private boolean _isEnd = false;
public ActionWalk(int moveFrame, int toCellX, int toCellY, Chara c)
throws Exception {
_moveFrame = moveFrame;
_toCellX = toCellX;
_toCellY = toCellY;
setVxyToCellxy(c);
IMaptipClbInterface tip = (IMaptipClbInterface) MapFactory.getMap()
.get(c.getCellX(), c.getCellY());
tip.reserve(c);
}
public void doAction(Chara c) throws Exception {
_execCount++;
if (_moveFrame > 1) {
// 移動
c.setPosition(c.getX() + _spdX, c.getY() + _spdY);
// // 移動しすぎを矯正
// if (_spdX > 0 && c.getX() > _tgX) {
// // 行き過ぎ
// c.setPosition(_tgX, c.getY());
// } else if (_spdX < 0 && c.getX() < _tgX) {
// // 行き過ぎ
// c.setPosition(_tgX, c.getY());
// }
// if (_spdY > 0 && c.getY() > _tgY) {
// // 行き過ぎ
// c.setPosition(c.getX(), _tgY);
// } else if (_spdY < 0 && c.getY() < _tgY) {
// // 行き過ぎ
// c.setPosition(c.getX(), _tgY);
// }
}
// 到着判定
if (_execCount >= _moveFrame) {
// 到着
MapFactory.getMap().get(c.getCellX(), c.getCellY()).removeChara(c);
DebugUtil.assertTrue(c.isAlive());
MapFactory.getMap().get(_toCellX, _toCellY).setChara(c);
// 周りを確認
c.watchAround();
// // 罠判定
// MapTip tip = c.getCurrentMaptip();
// if (tip.isMapObject() && tip.getMapObject().isTrap()) {
// ApplicationFacade.getGame().trapProc(tip, tip.getMapObject());
// }
_isEnd = true;
c.useMovePoint(Chara.NORMAL_SPEED);
c.changeAction(new ActionWait());
}
}
public boolean isDoingAction(Chara c) {
return !_isEnd;
}
/**
* 速度設定 ■目的に向かって弾を飛ばす <br>
* 目標に向かって飛ぶ弾の関数() <br>
* { <br>
* 弾の初期化 <br>
* ├目標までの距離検出 <br>
* │・目標までの距離X=(目標の座標X)ー(弾の座標X) <br>
* │・目標までの距離Y=(目標の座標Y)ー(弾の座標Y) <br>
* │ ↓ <br>
* └弾の発射角度取得し移動量設定 <br>
* ・弾の発射角度=atan2(目標までの距離Y、目標までの距離X) <br>
* ・弾の移動量X=cos(弾の発射角度)×弾のスピード <br>
* ・弾の移動量Y=sin(弾の発射角度)×弾のスピード <br>
* ↓ <br>
* 移動量を計算し目的地まで飛ばす <br>
* ・弾の座標X+=弾の移動量X <br>
* ・弾の座標Y+=弾の移動量Y <br>
* ↓ <br>
* 当たるか画面外に出たら初めから <br>
* <br>
*
* @param ent
* @return
*/
private void setVxyToCellxy(Chara c) throws Exception {
if (_moveFrame > 1) {
// // 移動先
_tgX = Map.getCharaXofCell(c, _toCellX, _toCellY);
_tgY = Map.getCharaYofCell(c, _toCellX, _toCellY);
// 移動角度
double deg = GameMath.atan2(_tgX - c.getX(), _tgY - c.getY());
// double deg = c.getDirectionToNext(_toCellX, _toCellY);
// フレーム数から移動速度計算
this._spdX = GameMath.abs(_tgX - c.getX()) / (_moveFrame - 1);
this._spdY = GameMath.abs(_tgY - c.getY()) / (_moveFrame - 1);
// 移動速度
_spdX = (double) (GameMath.cos((int) (deg + 0.5)) * _spdX);
_spdY = (double) (GameMath.sin((int) (deg + 0.5)) * _spdY);
// ApplicationFacade.getModel().map.dump();
}
}
}
| 3,971 | 0.578838 | 0.568107 | 131 | 23.610687 | 20.533188 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.076336 | false | false | 0 |
4071d85a0f5bb19f24a0f47ffd474f155dcae2bd | 33,268,816,694,841 | 1d02771abbe5f5080489c0da2fa7d32406e4eb98 | /src/test/java/com/knownstylenolife/hadoop/workshop/common/service/LinkDataServiceTest.java | 1f1a41ad1d760d16620dba97e4a0a533e44e96c1 | [
"Apache-2.0"
] | permissive | manboubird/hadoop-workshop | https://github.com/manboubird/hadoop-workshop | 7f3cda4f7df85a13e7994537fda8ea8f601b5cf4 | ec338a04d1775c717f49abc47a36073e649f3107 | refs/heads/master | 2020-12-30T11:15:32.471000 | 2011-09-04T16:41:48 | 2011-09-04T16:41:48 | 2,021,521 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.knownstylenolife.hadoop.workshop.common.service;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Iterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import com.knownstylenolife.hadoop.workshop.common.dao.DbcpConnectionManager;
import com.knownstylenolife.hadoop.workshop.common.dao.LinkDao;
public class LinkDataServiceTest {
private LinkDataService derbyService;
private String linkFilePath = "LinkDataServiceTest/testImportlinks2Db/links.txt";
private File linkFile;
private String derbyDirPath = "target/LinkDb";
private File derbyDir;
@Before
public void setUp() throws Exception {
derbyDir = new File(derbyDirPath);
linkFile = new File(Resources.getResource(getClass(), linkFilePath).toURI());
derbyService = new LinkDataService();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testImportLinks() throws Exception {
if(derbyDir.exists()) {
Files.deleteRecursively(derbyDir);
}
derbyService.importLinks2Db(linkFile.getAbsolutePath(), derbyDirPath);
assertThat(derbyDir.exists(), is(true));
DbcpConnectionManager.init(new File(derbyDirPath), false);
for(String line : Files.readLines(linkFile, Charsets.US_ASCII)) {
Iterator<String> itr = Splitter.on("\t").omitEmptyStrings().trimResults().split(line).iterator();
String word = itr.next();
String link = itr.next();
assertThat(LinkDao.selectUrlByWord(word), is(link));
}
DbcpConnectionManager.shutdownDriver();
}
@Test
public void testGetMstData() throws Exception {
// derbyService.importLinks2Db(linkFile.getAbsolutePath(), derbyDirPath);
derbyService.prepareDatabase(derbyDirPath);
DbcpConnectionManager.init(new File(derbyDirPath), false);
for(String line : Files.readLines(linkFile, Charsets.US_ASCII)) {
Iterator<String> itr = Splitter.on("\t").omitEmptyStrings().trimResults().split(line).iterator();
String word = itr.next();
String link = itr.next();
assertThat(derbyService.getMstData(word), is(link));
}
derbyService.shutDownDatabase();
}
}
| UTF-8 | Java | 2,294 | java | LinkDataServiceTest.java | Java | [] | null | [] | package com.knownstylenolife.hadoop.workshop.common.service;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Iterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import com.knownstylenolife.hadoop.workshop.common.dao.DbcpConnectionManager;
import com.knownstylenolife.hadoop.workshop.common.dao.LinkDao;
public class LinkDataServiceTest {
private LinkDataService derbyService;
private String linkFilePath = "LinkDataServiceTest/testImportlinks2Db/links.txt";
private File linkFile;
private String derbyDirPath = "target/LinkDb";
private File derbyDir;
@Before
public void setUp() throws Exception {
derbyDir = new File(derbyDirPath);
linkFile = new File(Resources.getResource(getClass(), linkFilePath).toURI());
derbyService = new LinkDataService();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testImportLinks() throws Exception {
if(derbyDir.exists()) {
Files.deleteRecursively(derbyDir);
}
derbyService.importLinks2Db(linkFile.getAbsolutePath(), derbyDirPath);
assertThat(derbyDir.exists(), is(true));
DbcpConnectionManager.init(new File(derbyDirPath), false);
for(String line : Files.readLines(linkFile, Charsets.US_ASCII)) {
Iterator<String> itr = Splitter.on("\t").omitEmptyStrings().trimResults().split(line).iterator();
String word = itr.next();
String link = itr.next();
assertThat(LinkDao.selectUrlByWord(word), is(link));
}
DbcpConnectionManager.shutdownDriver();
}
@Test
public void testGetMstData() throws Exception {
// derbyService.importLinks2Db(linkFile.getAbsolutePath(), derbyDirPath);
derbyService.prepareDatabase(derbyDirPath);
DbcpConnectionManager.init(new File(derbyDirPath), false);
for(String line : Files.readLines(linkFile, Charsets.US_ASCII)) {
Iterator<String> itr = Splitter.on("\t").omitEmptyStrings().trimResults().split(line).iterator();
String word = itr.next();
String link = itr.next();
assertThat(derbyService.getMstData(word), is(link));
}
derbyService.shutDownDatabase();
}
}
| 2,294 | 0.763731 | 0.762424 | 71 | 31.309858 | 26.624987 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.830986 | false | false | 0 |
7427d233c6a163ee84d483378a2fcacf84340b86 | 10,462,540,350,478 | 51de8829d17551f0ecfa8f234d5822eac96d860a | /src/main/java/net/io_0/caja/LoggingUtils.java | 9139fcf4f697d5430ff7ec5cd37863b9b5d4c0ca | [
"Apache-2.0"
] | permissive | peeeto/caja | https://github.com/peeeto/caja | fb337d69754ee6f99076625be785166b415c69b3 | db688302885563817a712d3952c7e220c75552aa | refs/heads/master | 2023-02-19T23:17:48.834000 | 2021-01-23T10:02:19 | 2021-01-23T10:02:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.io_0.caja;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import static lombok.AccessLevel.PRIVATE;
import static net.io_0.caja.configuration.CacheConfig.LogLevel;
@NoArgsConstructor(access = PRIVATE)
public class LoggingUtils {
public static void logThrough(Logger log, LogLevel logLevel, String format, Object... arguments) {
switch (logLevel) {
case TRACE: log.trace(format, arguments); break;
case INFO: log.info(format, arguments); break;
case WARN: log.warn(format, arguments); break;
case ERROR: log.error(format, arguments); break;
case OFF: break;
default /* DEBUG */: log.debug(format, arguments);
}
}
}
| UTF-8 | Java | 688 | java | LoggingUtils.java | Java | [] | null | [] | package net.io_0.caja;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import static lombok.AccessLevel.PRIVATE;
import static net.io_0.caja.configuration.CacheConfig.LogLevel;
@NoArgsConstructor(access = PRIVATE)
public class LoggingUtils {
public static void logThrough(Logger log, LogLevel logLevel, String format, Object... arguments) {
switch (logLevel) {
case TRACE: log.trace(format, arguments); break;
case INFO: log.info(format, arguments); break;
case WARN: log.warn(format, arguments); break;
case ERROR: log.error(format, arguments); break;
case OFF: break;
default /* DEBUG */: log.debug(format, arguments);
}
}
}
| 688 | 0.715116 | 0.710756 | 21 | 31.761906 | 25.817869 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.095238 | false | false | 0 |
8d8dec7b05185367336183bac185586d5799ea67 | 816,043,840,844 | fbc9268f66e52c4b418cbd034cd0b6d03a4097a8 | /src/com/store/BuilderWindow.java | 5710abb645195afb9eb61a6c60402d279bab1795 | [] | no_license | Kemikals/AlsThingy | https://github.com/Kemikals/AlsThingy | af9619cab1309560c087c16ed55838d950b23736 | 7703c58366164e6412ef03350cbcf0b1d3e1a942 | refs/heads/master | 2023-03-17T11:36:57.001000 | 2021-03-09T22:04:40 | 2021-03-09T22:04:40 | 344,738,128 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.store;
import com.components.Component;
import com.components.MotherBoard;
import com.components.hardware.Cpu;
import com.components.hardware.Disk;
import com.components.hardware.Ram;
import com.components.software.OperatingSystem;
import com.helpers.Fonts;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;
public class BuilderWindow {
private final JFrame frame;
private final JProgressBar progressBar;
private final List<JComponent> selections;
private final JTextArea view;
private JComboBox<Ram> ramCombo;
private JComboBox<Cpu> cpuCombo;
private JComboBox<Disk> diskCombo;
private JComboBox<OperatingSystem> osCombo;
private Timer timer;
private JButton buildButton;
private static final int TIMER_DELAY = 35;
private static final int MIN_WIDTH = 820;
private static final int MIN_HEIGHT = 500;
private static final int ROWS = 4;
private static final int COLS = 2;
private static final int LABEL_FONT_SIZE = 20;
private static final int BUTTON_FONT_SIZE = 12;
private static final int TEXT_AREA_FONT_SIZE = 20;
private static final int SPACE_BETWEEN_BUTTONS_HEIGHT = 0;
private static final int SPACE_BETWEEN_BUTTONS_WIDTH = 100;
private static final int SPACE_ABOVE_AND_BELOW_BUTTONS_HEIGHT = 20;
private static final int SPACE_ABOVE_AND_BELOW_BUTTONS_WIDTH = 0;
private final MotherBoard board;
public BuilderWindow(MotherBoard board) {
this.board = board;
frame = new JFrame();
progressBar = new JProgressBar();
view = new JTextArea();
addAndStyleComponents(frame, progressBar, view);
selections = List.of(ramCombo, cpuCombo, diskCombo, osCombo, buildButton);
}
private void addAndStyleComponents(JFrame frame, JProgressBar progressBar, JTextArea view) {
JPanel container = new JPanel();
frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
frame.add(container);
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
container.add(createTitle());
container.add(createTopSelectionPanel());
container.add(Box.createRigidArea(new Dimension(SPACE_ABOVE_AND_BELOW_BUTTONS_WIDTH, SPACE_ABOVE_AND_BELOW_BUTTONS_HEIGHT)));
container.add(createButtons());
container.add(Box.createRigidArea(new Dimension(SPACE_ABOVE_AND_BELOW_BUTTONS_WIDTH, SPACE_ABOVE_AND_BELOW_BUTTONS_HEIGHT)));
container.add(progressBar);
container.add(view);
view.setFont(Fonts.Bold_Size(TEXT_AREA_FONT_SIZE));
frame.setVisible(true);
}
private JPanel createTitle() {
JPanel box = new JPanel();
box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
box.setAlignmentX(java.awt.Component.CENTER_ALIGNMENT);
box.add(createLabel(" COMPUTER STORE"));
box.add(createLabel("LETS BUILD YOUR COMPUTER"));
return box;
}
private JLabel createLabel(String name) {
JLabel label = new JLabel(name);
label.setFont(Fonts.Plain_Size(LABEL_FONT_SIZE));
return label;
}
private JPanel createTopSelectionPanel() {
JPanel container = new JPanel();
container.setLayout(new GridLayout(ROWS, COLS));
ramCombo = new JComboBox<>(new Ram[]{new Ram("8 GB"), new Ram("16 GB"), new Ram("32 GB")});
ramCombo.addActionListener((e) -> board.setRam(ramCombo.getItemAt(ramCombo.getSelectedIndex())));
createSelection(container, ramCombo, "SELECT MEMORY SIZE ( RAM ) : ");
cpuCombo = new JComboBox<>(new Cpu[]{new Cpu("2 GHz"), new Cpu("3 GHz"), new Cpu("4 GHz")});
cpuCombo.addActionListener((e) -> board.setCpu(cpuCombo.getItemAt(cpuCombo.getSelectedIndex())));
createSelection(container, cpuCombo, "SELECT CPU (PROCESSOR): ");
diskCombo = new JComboBox<>(new Disk[]{new Disk("120 GB"), new Disk("250 GB"), new Disk("512 GB")});
diskCombo.addActionListener((e) -> board.setDisk(diskCombo.getItemAt(diskCombo.getSelectedIndex())));
createSelection(container, diskCombo, "SELECT YOUR STORAGE SIZE : ");
osCombo = new JComboBox<>(new OperatingSystem[]{new OperatingSystem("DOS"), new OperatingSystem("WINDOWS"), new OperatingSystem("MAC"), new OperatingSystem("LINUX")});
osCombo.addActionListener((e) -> board.setOs(osCombo.getItemAt(osCombo.getSelectedIndex())));
createSelection(container, osCombo, "OPERATING SYSTEM TO INSTALL : ");
return container;
}
private void createSelection(JPanel container, JComboBox<?> combo, String label) {
combo.setSelectedIndex(-1);
container.add(createLabel(label));
container.add(combo);
}
private Box createButtons() {
Box box = new Box(BoxLayout.X_AXIS);
JButton printButton = new JButton("PRINT ORDER SHEET");
printButton.setFont(Fonts.Bold_Size(BUTTON_FONT_SIZE));
buildButton = new JButton("ORDER AND BUILD");
buildButton.addActionListener(this::build);
buildButton.setFont(Fonts.Bold_Size(BUTTON_FONT_SIZE));
box.add(printButton);
box.add(Box.createRigidArea(new Dimension(SPACE_BETWEEN_BUTTONS_WIDTH, SPACE_BETWEEN_BUTTONS_HEIGHT)));
box.add(buildButton);
return box;
}
private void build(ActionEvent a) {
setSelectionsEnabled(false);
view.setText("");
progressBar.setValue(0);
timer = new Timer(TIMER_DELAY, (e) -> {
handleProgressUpdate(board, progressBar.getValue());
updateProgressBar();
});
timer.start();
}
private void handleProgressUpdate(MotherBoard board, int progressBarPercent) {
if (progressBarPercent == 5) {
handleInstallComponent(board.getRam(), InstallMessage.RAM, InstallMessage.RAM_FAILURE);
} else if (progressBarPercent == 30) {
handleInstallComponent(board.getCpu(), InstallMessage.CPU, InstallMessage.CPU_FAILURE);
} else if (progressBarPercent == 50) {
handleInstallComponent(board.getDisk(), InstallMessage.DISK, InstallMessage.DISK_FAILURE);
} else if (progressBarPercent == 75) {
handleOsInstall();
} else if (progressBarPercent == 100) {
handleBuildComplete();
}
}
private void handleInstallComponent(Component component, InstallMessage success, InstallMessage failure) {
addMessage((component != null ? success : failure).toString());
if (component != null) {
component.install();
} else {
timer.stop();
setSelectionsEnabled(true);
}
}
private void handleOsInstall() {
if (board.getOs() != null && board.getOs().isInstallableOnBoard(board)) {
handleInstallComponent(board.getOs(), InstallMessage.OS, InstallMessage.OS_FAILURE);
} else {
addMessage(InstallMessage.OS_FAILURE.toString());
setSelectionsEnabled(true);
timer.stop();
}
}
private void handleBuildComplete() {
timer.stop();
JOptionPane.showMessageDialog(frame, "CONGRATS ORDER IS COMPLETED AND YOUR COMPUTER IS ALL SET ");
}
private void updateProgressBar() {
progressBar.setValue(progressBar.getValue() + 1);
}
private void addMessage(String message) {
view.append(message + System.lineSeparator());
}
private void setSelectionsEnabled(boolean value) {
selections.forEach(selection -> selection.setEnabled(value));
}
} | UTF-8 | Java | 7,819 | java | BuilderWindow.java | Java | [] | null | [] | package com.store;
import com.components.Component;
import com.components.MotherBoard;
import com.components.hardware.Cpu;
import com.components.hardware.Disk;
import com.components.hardware.Ram;
import com.components.software.OperatingSystem;
import com.helpers.Fonts;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;
public class BuilderWindow {
private final JFrame frame;
private final JProgressBar progressBar;
private final List<JComponent> selections;
private final JTextArea view;
private JComboBox<Ram> ramCombo;
private JComboBox<Cpu> cpuCombo;
private JComboBox<Disk> diskCombo;
private JComboBox<OperatingSystem> osCombo;
private Timer timer;
private JButton buildButton;
private static final int TIMER_DELAY = 35;
private static final int MIN_WIDTH = 820;
private static final int MIN_HEIGHT = 500;
private static final int ROWS = 4;
private static final int COLS = 2;
private static final int LABEL_FONT_SIZE = 20;
private static final int BUTTON_FONT_SIZE = 12;
private static final int TEXT_AREA_FONT_SIZE = 20;
private static final int SPACE_BETWEEN_BUTTONS_HEIGHT = 0;
private static final int SPACE_BETWEEN_BUTTONS_WIDTH = 100;
private static final int SPACE_ABOVE_AND_BELOW_BUTTONS_HEIGHT = 20;
private static final int SPACE_ABOVE_AND_BELOW_BUTTONS_WIDTH = 0;
private final MotherBoard board;
public BuilderWindow(MotherBoard board) {
this.board = board;
frame = new JFrame();
progressBar = new JProgressBar();
view = new JTextArea();
addAndStyleComponents(frame, progressBar, view);
selections = List.of(ramCombo, cpuCombo, diskCombo, osCombo, buildButton);
}
private void addAndStyleComponents(JFrame frame, JProgressBar progressBar, JTextArea view) {
JPanel container = new JPanel();
frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
frame.add(container);
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
container.add(createTitle());
container.add(createTopSelectionPanel());
container.add(Box.createRigidArea(new Dimension(SPACE_ABOVE_AND_BELOW_BUTTONS_WIDTH, SPACE_ABOVE_AND_BELOW_BUTTONS_HEIGHT)));
container.add(createButtons());
container.add(Box.createRigidArea(new Dimension(SPACE_ABOVE_AND_BELOW_BUTTONS_WIDTH, SPACE_ABOVE_AND_BELOW_BUTTONS_HEIGHT)));
container.add(progressBar);
container.add(view);
view.setFont(Fonts.Bold_Size(TEXT_AREA_FONT_SIZE));
frame.setVisible(true);
}
private JPanel createTitle() {
JPanel box = new JPanel();
box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
box.setAlignmentX(java.awt.Component.CENTER_ALIGNMENT);
box.add(createLabel(" COMPUTER STORE"));
box.add(createLabel("LETS BUILD YOUR COMPUTER"));
return box;
}
private JLabel createLabel(String name) {
JLabel label = new JLabel(name);
label.setFont(Fonts.Plain_Size(LABEL_FONT_SIZE));
return label;
}
private JPanel createTopSelectionPanel() {
JPanel container = new JPanel();
container.setLayout(new GridLayout(ROWS, COLS));
ramCombo = new JComboBox<>(new Ram[]{new Ram("8 GB"), new Ram("16 GB"), new Ram("32 GB")});
ramCombo.addActionListener((e) -> board.setRam(ramCombo.getItemAt(ramCombo.getSelectedIndex())));
createSelection(container, ramCombo, "SELECT MEMORY SIZE ( RAM ) : ");
cpuCombo = new JComboBox<>(new Cpu[]{new Cpu("2 GHz"), new Cpu("3 GHz"), new Cpu("4 GHz")});
cpuCombo.addActionListener((e) -> board.setCpu(cpuCombo.getItemAt(cpuCombo.getSelectedIndex())));
createSelection(container, cpuCombo, "SELECT CPU (PROCESSOR): ");
diskCombo = new JComboBox<>(new Disk[]{new Disk("120 GB"), new Disk("250 GB"), new Disk("512 GB")});
diskCombo.addActionListener((e) -> board.setDisk(diskCombo.getItemAt(diskCombo.getSelectedIndex())));
createSelection(container, diskCombo, "SELECT YOUR STORAGE SIZE : ");
osCombo = new JComboBox<>(new OperatingSystem[]{new OperatingSystem("DOS"), new OperatingSystem("WINDOWS"), new OperatingSystem("MAC"), new OperatingSystem("LINUX")});
osCombo.addActionListener((e) -> board.setOs(osCombo.getItemAt(osCombo.getSelectedIndex())));
createSelection(container, osCombo, "OPERATING SYSTEM TO INSTALL : ");
return container;
}
private void createSelection(JPanel container, JComboBox<?> combo, String label) {
combo.setSelectedIndex(-1);
container.add(createLabel(label));
container.add(combo);
}
private Box createButtons() {
Box box = new Box(BoxLayout.X_AXIS);
JButton printButton = new JButton("PRINT ORDER SHEET");
printButton.setFont(Fonts.Bold_Size(BUTTON_FONT_SIZE));
buildButton = new JButton("ORDER AND BUILD");
buildButton.addActionListener(this::build);
buildButton.setFont(Fonts.Bold_Size(BUTTON_FONT_SIZE));
box.add(printButton);
box.add(Box.createRigidArea(new Dimension(SPACE_BETWEEN_BUTTONS_WIDTH, SPACE_BETWEEN_BUTTONS_HEIGHT)));
box.add(buildButton);
return box;
}
private void build(ActionEvent a) {
setSelectionsEnabled(false);
view.setText("");
progressBar.setValue(0);
timer = new Timer(TIMER_DELAY, (e) -> {
handleProgressUpdate(board, progressBar.getValue());
updateProgressBar();
});
timer.start();
}
private void handleProgressUpdate(MotherBoard board, int progressBarPercent) {
if (progressBarPercent == 5) {
handleInstallComponent(board.getRam(), InstallMessage.RAM, InstallMessage.RAM_FAILURE);
} else if (progressBarPercent == 30) {
handleInstallComponent(board.getCpu(), InstallMessage.CPU, InstallMessage.CPU_FAILURE);
} else if (progressBarPercent == 50) {
handleInstallComponent(board.getDisk(), InstallMessage.DISK, InstallMessage.DISK_FAILURE);
} else if (progressBarPercent == 75) {
handleOsInstall();
} else if (progressBarPercent == 100) {
handleBuildComplete();
}
}
private void handleInstallComponent(Component component, InstallMessage success, InstallMessage failure) {
addMessage((component != null ? success : failure).toString());
if (component != null) {
component.install();
} else {
timer.stop();
setSelectionsEnabled(true);
}
}
private void handleOsInstall() {
if (board.getOs() != null && board.getOs().isInstallableOnBoard(board)) {
handleInstallComponent(board.getOs(), InstallMessage.OS, InstallMessage.OS_FAILURE);
} else {
addMessage(InstallMessage.OS_FAILURE.toString());
setSelectionsEnabled(true);
timer.stop();
}
}
private void handleBuildComplete() {
timer.stop();
JOptionPane.showMessageDialog(frame, "CONGRATS ORDER IS COMPLETED AND YOUR COMPUTER IS ALL SET ");
}
private void updateProgressBar() {
progressBar.setValue(progressBar.getValue() + 1);
}
private void addMessage(String message) {
view.append(message + System.lineSeparator());
}
private void setSelectionsEnabled(boolean value) {
selections.forEach(selection -> selection.setEnabled(value));
}
} | 7,819 | 0.652129 | 0.645351 | 190 | 39.163158 | 32.500198 | 175 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.863158 | false | false | 0 |
515acdfb744b85bfe2b195fe2d0bf26018335ca8 | 27,470,610,878,262 | 807e22547b915aa10f3c936eb57d7df7b334d2c0 | /Project/Project 3/Project3Task1Server/src/blockchaintask0/EchoServerThreadTCP.java | 42b8e7e34e4f1b03b1a76cac0ed1a42233eb5fe3 | [] | no_license | ZipeiXiao/Distrubuted-System | https://github.com/ZipeiXiao/Distrubuted-System | 7ea8852c94c836d7a02b84cf62a5cbae40359e29 | dece2dac3a0cd4bc0c888c84dcfa5ca954e71eec | refs/heads/master | 2020-11-30T05:33:42.145000 | 2020-07-01T05:27:47 | 2020-07-01T05:27:47 | 230,318,627 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Author: Zipei (Tina) Xiao
* Last Modified: Oct. 16th, 2019
*
* This program demonstrates a very simple stand-alone Blockchain.
* Behind the scenes, there will be a client server interaction
* using JSON over TCP sockets.
*
* The message transfers in this program is formatted by two JSON messages types
* – a message to encapsulate requests from the client
* and a message to encapsulate responses from the server.
* Each JSON request message will include a signature.
*/
package blockchaintask0;
import com.alibaba.fastjson.JSON;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static blockchaintask0.Server.getHash;
/**
* The EchoServerThreadTCP class includes the Key generator
* and other security methods,
* i.e., methods other than the TCP socket transfer.
*/
public class EchoServerThreadTCP extends Thread {
Socket clientSocket = null;
BlockChain blockChain;
/**
* Constructor of this class
* New a Thread with the correct socket information
* @param clientSocket the TCP Socket
* @param blockChain the blockchain objects that the client asks for
*/
public EchoServerThreadTCP(Socket clientSocket, BlockChain blockChain) {
this.clientSocket = clientSocket;
this.blockChain = blockChain;
}
/**
* The server will make two checks before servicing any client request.
* First, does the public key (included with each request) hash to the ID
* (also provided with each request)?
* Second, is the request properly signed?
*/
public void run() {
try {
// Set up "in" to read from the client socket
Scanner in;
in = new Scanner(clientSocket.getInputStream());
// Set up "out" to write to the client socket
PrintWriter out;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
/*
* Forever, read a line from the socket print it to the console echo it (i.e.
* write it) back to the client
*/
while (true) {
ServerResponse serverResponse = new ServerResponse();
String requestString = in.nextLine();
//received JSON string
System.out.println("requestString: " + requestString);
ClientRequest request = JSON.parseObject(requestString, ClientRequest.class);
ClientMessage message = request.getMessage();
// Each request to the server must be signed using the private key.
BigInteger signed = new BigInteger(request.getSignedHash());
// The signature must be checked on the server.
BigInteger clear = signed.modPow(message.getE(), message.getN());
// Decode to a string
String clearStr = new String(clear.toByteArray());
// It is very important that the big integer created with the hash (before signing) is positive
if (clearStr.equals("00" + getHash(JSON.toJSONString(message)))) {
// Sign Verify ok
// if the user choose to see the status
if (message.getMenu() == '0') {
serverResponse.appendln(String.format("Current size of chain: %d", blockChain.getChainSize()));
serverResponse.appendln(String.format("Current hashes per second by this machine: %d",
blockChain.hashesPerSecond()));
serverResponse.appendln(String.format("Difficulty of most recent block: %d",
blockChain.getLatestBlock().getDifficulty()));
serverResponse.appendln(String.format("Nonce for most recent block: %s",
blockChain.getLatestBlock().getNonce().toString()));
serverResponse.appendln(String.format("Chain hash: %s", blockChain.getChainHash()));
} else if (message.getMenu() == '1') {
// All blocks added to the Blockchain will have a difficulty
// passed in to the program by the user at run time.
long currentTimeMillis = System.currentTimeMillis();
//new block
Block newBlock = new Block(
// increase the index by one
blockChain.getLatestBlock().getIndex() + 1,
new Timestamp(System.currentTimeMillis()),
message.getTransaction(),
message.getDifficulty());
//This new block's previous hash must hold the hash of the most recently added block
newBlock.setPrevHash(blockChain.getChainHash());
// update the class field using the hash value of new block
String chainHash = newBlock.proofOfWork();
blockChain.setChainHash(chainHash);
// Add a block containing that transaction to the block chain.
blockChain.addBlock(newBlock);
serverResponse.appendln(String.format(
"Total execution time to add this block was %d milliseconds",
System.currentTimeMillis() - currentTimeMillis));
// If the user selects option 2
} else if (message.getMenu() == '2') {
long currentTimeMillis = System.currentTimeMillis();
serverResponse.appendln("Verifying entire chain");
// call the isChainValid method and display the results.
serverResponse.appendln(String.format("Chain verification: %b", blockChain.isChainValid()));
// display the number of milliseconds it took for validate to run.
serverResponse.appendln(String.format(
"Total execution time required to verify the chain was %d milliseconds",
System.currentTimeMillis() - currentTimeMillis));
} else if (message.getMenu() == '3') {
serverResponse.appendln("View the Blockchain");
serverResponse.appendln(JSON.toJSONString(blockChain));
} else if (message.getMenu() == '4') {
serverResponse.appendln("Corrupt the Blockchain");
if (message.getBlockID() >= 0 && message.getBlockID() < blockChain.getChainSize()) {
List<Block> blocks = blockChain.getDs_chain();
// get the block that user want to change
Block block = blocks.get(message.getBlockID());
// add new data for block
block.setTx(message.getTransaction());
serverResponse.appendln(String.format(
"Block %d now holds %s",
message.getBlockID(),
block.getTx()));
}
} else if (message.getMenu() == '5') {
serverResponse.appendln("Repairing the entire chain");
long currentTimeMillis = System.currentTimeMillis();
blockChain.repairChain();
serverResponse.appendln(String.format(
"Total execution time required to repair the chain was %d milliseconds",
System.currentTimeMillis() - currentTimeMillis));
}
} else {
// If the signature fails to verify, send an appropriate error message back to the client.
serverResponse.setMessageBody("Error in request");
}
System.out.println(serverResponse.getMessageBody());
out.println(JSON.toJSONString(serverResponse));
out.flush();
}
} catch (Exception e) {
System.out.println("Exception:" + e.getMessage());
// If quitting (typically by you sending quit signal) clean up sockets
} finally {
try {
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
// ignore exception on close
}
}
}
}
| UTF-8 | Java | 9,049 | java | EchoServerThreadTCP.java | Java | [
{
"context": "/**\n * Author: Zipei (Tina) Xiao\n * Last Modified: Oct. 16th, 2019\n *\n * This prog",
"end": 32,
"score": 0.9785273671150208,
"start": 15,
"tag": "NAME",
"value": "Zipei (Tina) Xiao"
}
] | null | [] | /**
* Author: <NAME>
* Last Modified: Oct. 16th, 2019
*
* This program demonstrates a very simple stand-alone Blockchain.
* Behind the scenes, there will be a client server interaction
* using JSON over TCP sockets.
*
* The message transfers in this program is formatted by two JSON messages types
* – a message to encapsulate requests from the client
* and a message to encapsulate responses from the server.
* Each JSON request message will include a signature.
*/
package blockchaintask0;
import com.alibaba.fastjson.JSON;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static blockchaintask0.Server.getHash;
/**
* The EchoServerThreadTCP class includes the Key generator
* and other security methods,
* i.e., methods other than the TCP socket transfer.
*/
public class EchoServerThreadTCP extends Thread {
Socket clientSocket = null;
BlockChain blockChain;
/**
* Constructor of this class
* New a Thread with the correct socket information
* @param clientSocket the TCP Socket
* @param blockChain the blockchain objects that the client asks for
*/
public EchoServerThreadTCP(Socket clientSocket, BlockChain blockChain) {
this.clientSocket = clientSocket;
this.blockChain = blockChain;
}
/**
* The server will make two checks before servicing any client request.
* First, does the public key (included with each request) hash to the ID
* (also provided with each request)?
* Second, is the request properly signed?
*/
public void run() {
try {
// Set up "in" to read from the client socket
Scanner in;
in = new Scanner(clientSocket.getInputStream());
// Set up "out" to write to the client socket
PrintWriter out;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
/*
* Forever, read a line from the socket print it to the console echo it (i.e.
* write it) back to the client
*/
while (true) {
ServerResponse serverResponse = new ServerResponse();
String requestString = in.nextLine();
//received JSON string
System.out.println("requestString: " + requestString);
ClientRequest request = JSON.parseObject(requestString, ClientRequest.class);
ClientMessage message = request.getMessage();
// Each request to the server must be signed using the private key.
BigInteger signed = new BigInteger(request.getSignedHash());
// The signature must be checked on the server.
BigInteger clear = signed.modPow(message.getE(), message.getN());
// Decode to a string
String clearStr = new String(clear.toByteArray());
// It is very important that the big integer created with the hash (before signing) is positive
if (clearStr.equals("00" + getHash(JSON.toJSONString(message)))) {
// Sign Verify ok
// if the user choose to see the status
if (message.getMenu() == '0') {
serverResponse.appendln(String.format("Current size of chain: %d", blockChain.getChainSize()));
serverResponse.appendln(String.format("Current hashes per second by this machine: %d",
blockChain.hashesPerSecond()));
serverResponse.appendln(String.format("Difficulty of most recent block: %d",
blockChain.getLatestBlock().getDifficulty()));
serverResponse.appendln(String.format("Nonce for most recent block: %s",
blockChain.getLatestBlock().getNonce().toString()));
serverResponse.appendln(String.format("Chain hash: %s", blockChain.getChainHash()));
} else if (message.getMenu() == '1') {
// All blocks added to the Blockchain will have a difficulty
// passed in to the program by the user at run time.
long currentTimeMillis = System.currentTimeMillis();
//new block
Block newBlock = new Block(
// increase the index by one
blockChain.getLatestBlock().getIndex() + 1,
new Timestamp(System.currentTimeMillis()),
message.getTransaction(),
message.getDifficulty());
//This new block's previous hash must hold the hash of the most recently added block
newBlock.setPrevHash(blockChain.getChainHash());
// update the class field using the hash value of new block
String chainHash = newBlock.proofOfWork();
blockChain.setChainHash(chainHash);
// Add a block containing that transaction to the block chain.
blockChain.addBlock(newBlock);
serverResponse.appendln(String.format(
"Total execution time to add this block was %d milliseconds",
System.currentTimeMillis() - currentTimeMillis));
// If the user selects option 2
} else if (message.getMenu() == '2') {
long currentTimeMillis = System.currentTimeMillis();
serverResponse.appendln("Verifying entire chain");
// call the isChainValid method and display the results.
serverResponse.appendln(String.format("Chain verification: %b", blockChain.isChainValid()));
// display the number of milliseconds it took for validate to run.
serverResponse.appendln(String.format(
"Total execution time required to verify the chain was %d milliseconds",
System.currentTimeMillis() - currentTimeMillis));
} else if (message.getMenu() == '3') {
serverResponse.appendln("View the Blockchain");
serverResponse.appendln(JSON.toJSONString(blockChain));
} else if (message.getMenu() == '4') {
serverResponse.appendln("Corrupt the Blockchain");
if (message.getBlockID() >= 0 && message.getBlockID() < blockChain.getChainSize()) {
List<Block> blocks = blockChain.getDs_chain();
// get the block that user want to change
Block block = blocks.get(message.getBlockID());
// add new data for block
block.setTx(message.getTransaction());
serverResponse.appendln(String.format(
"Block %d now holds %s",
message.getBlockID(),
block.getTx()));
}
} else if (message.getMenu() == '5') {
serverResponse.appendln("Repairing the entire chain");
long currentTimeMillis = System.currentTimeMillis();
blockChain.repairChain();
serverResponse.appendln(String.format(
"Total execution time required to repair the chain was %d milliseconds",
System.currentTimeMillis() - currentTimeMillis));
}
} else {
// If the signature fails to verify, send an appropriate error message back to the client.
serverResponse.setMessageBody("Error in request");
}
System.out.println(serverResponse.getMessageBody());
out.println(JSON.toJSONString(serverResponse));
out.flush();
}
} catch (Exception e) {
System.out.println("Exception:" + e.getMessage());
// If quitting (typically by you sending quit signal) clean up sockets
} finally {
try {
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
// ignore exception on close
}
}
}
}
| 9,038 | 0.554548 | 0.552448 | 194 | 45.634022 | 32.576397 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.453608 | false | false | 0 |
60fc99efb773eeabf3a884ae95214a5e08a1eebf | 6,914,897,379,804 | d447153f9dcc2e225a2871a2a4c1e3a49a05a5e8 | /src/main/java/presentation/ChefGUI.java | 7952d60e4854a9f5528b07f9d452db0ab43d9b8e | [] | no_license | PatriciaMateiu/restaurant-management-system | https://github.com/PatriciaMateiu/restaurant-management-system | 20910fd63dfee998fe4ef9f344f4214ee22b787d | f0c4061c49ec123ba72f2a3278702565406202a2 | refs/heads/master | 2022-04-10T08:40:43.175000 | 2020-03-28T16:47:27 | 2020-03-28T16:47:27 | 250,596,922 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package presentation;
import business.Order;
import javafx.beans.value.ObservableValue;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
public class ChefGUI implements Observer {
private JFrame chef = new JFrame("CHEF");
private JTextArea jtx = new JTextArea();
private JPanel jp = new JPanel();
//private ObservableValue ov = null;
public ChefGUI() {
jp.setPreferredSize(new Dimension(600, 400));
jp.add(jtx);
chef.setSize(600,400);
chef.add(jp);
chef.setVisible(true);
chef.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setText(JTextArea ta, String str){
String s = ta.getText();
if(s != ""){
s = s + "\n" + str;}
else {s = str;}
ta.setText(s);
}
public void update(Observable obs, Object obj) {
setText(jtx, "A new order waits to be cooked");
chef.invalidate();
chef.validate();
chef.repaint();
}
}
| UTF-8 | Java | 1,115 | java | ChefGUI.java | Java | [] | null | [] | package presentation;
import business.Order;
import javafx.beans.value.ObservableValue;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
public class ChefGUI implements Observer {
private JFrame chef = new JFrame("CHEF");
private JTextArea jtx = new JTextArea();
private JPanel jp = new JPanel();
//private ObservableValue ov = null;
public ChefGUI() {
jp.setPreferredSize(new Dimension(600, 400));
jp.add(jtx);
chef.setSize(600,400);
chef.add(jp);
chef.setVisible(true);
chef.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setText(JTextArea ta, String str){
String s = ta.getText();
if(s != ""){
s = s + "\n" + str;}
else {s = str;}
ta.setText(s);
}
public void update(Observable obs, Object obj) {
setText(jtx, "A new order waits to be cooked");
chef.invalidate();
chef.validate();
chef.repaint();
}
}
| 1,115 | 0.623318 | 0.612556 | 47 | 22.723404 | 17.832199 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.680851 | false | false | 0 |
7e2ecfcaa42c501117478fac53783547c04fd6aa | 9,637,906,662,307 | bb3f8e4b20532486c6cc482756246df9a7df9d35 | /goolege/holeworld/Journal.java | 207632a3c6ab872c051b0af242ea568a3f13ed35 | [] | no_license | caixiaoting298/shuaiqideting | https://github.com/caixiaoting298/shuaiqideting | a5c36a34c0c504a6571a919dbcbf14985dcae6d9 | 3e417a9b66d58ced8d4dbebc66e7d6ef4fa854ce | refs/heads/master | 2020-07-22T06:51:42.247000 | 2019-11-10T02:42:32 | 2019-11-10T02:42:32 | 207,108,219 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.reading;
public class Journal implements Reading {
int price,pages;
String publishing_time;
public Journal(int pages,int price,String publishing_time) {
this.pages = pages;
this.price = price;
this.publishing_time = publishing_time;
}
//实现接口方法Info()
public void Info() {
System.out.println("This is a Journal,which has " + pages + " pages," +"costs " + price +" yuan,and publish once every "+publishing_time+".");
}
}
| UTF-8 | Java | 514 | java | Journal.java | Java | [] | null | [] | package com.google.reading;
public class Journal implements Reading {
int price,pages;
String publishing_time;
public Journal(int pages,int price,String publishing_time) {
this.pages = pages;
this.price = price;
this.publishing_time = publishing_time;
}
//实现接口方法Info()
public void Info() {
System.out.println("This is a Journal,which has " + pages + " pages," +"costs " + price +" yuan,and publish once every "+publishing_time+".");
}
}
| 514 | 0.640562 | 0.640562 | 15 | 32.200001 | 35.777462 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866667 | false | false | 0 |
9e95550dc6b376abe509bd2fa735064266616581 | 7,206,955,164,466 | d6ca672cf2784c3521826810ef5626d6902d7a2d | /src/main/java/com/mec/mfct/sender/ISendSection.java | 69692a544b3e257747afc16a6ada4b4510d83a43 | [] | no_license | 123quan123/Multiplefilecloudtransfer | https://github.com/123quan123/Multiplefilecloudtransfer | 4209310a369f360c9ab526fd381dcc9d127e908e | 4943c41a0fa008a0054157b702501841e5667997 | refs/heads/master | 2022-04-17T07:47:20.733000 | 2020-04-17T17:23:42 | 2020-04-17T17:23:42 | 256,566,179 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mec.mfct.sender;
import com.mec.mfct.resource.ResourceBaseInfo;
import com.mec.rmi.node.Node;
public interface ISendSection {
void sendSectionInfo(Node receiverNode, ResourceBaseInfo rbi);
}
| UTF-8 | Java | 219 | java | ISendSection.java | Java | [] | null | [] | package com.mec.mfct.sender;
import com.mec.mfct.resource.ResourceBaseInfo;
import com.mec.rmi.node.Node;
public interface ISendSection {
void sendSectionInfo(Node receiverNode, ResourceBaseInfo rbi);
}
| 219 | 0.762557 | 0.762557 | 8 | 25.25 | 22.614985 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 0 |
1193378916b6d5e070984ec3bee693cd8a9ab20d | 10,857,677,376,390 | 41858c4d72d7ab3aaa41cb5fa9bd11cf46ff3f0a | /src/main/java/com/java1234/framework/DisPatcherServlet.java | 437f0286e22e79fa0fcc9dc47451b92ada40adef | [] | no_license | fjhjava/smartFramework-web | https://github.com/fjhjava/smartFramework-web | ee6ffd68137607350d182c0f80b78f0d4cf1b6e7 | fecdbe490830f0d2a5c62d3a223c2291e76a211c | refs/heads/master | 2021-01-11T03:06:08.251000 | 2016-10-17T08:37:22 | 2016-10-17T08:41:20 | 71,117,301 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.java1234.framework;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.java1234.bean.Data;
import com.java1234.bean.Handler;
import com.java1234.bean.Param;
import com.java1234.bean.View;
import com.java1234.helper.BeanHelper;
import com.java1234.helper.ConfigHelper;
import com.java1234.helper.ControllerHelper;
import com.java1234.util.ArrayUtil;
import com.java1234.util.CodecUtil;
import com.java1234.util.JsonUtil;
import com.java1234.util.ReflectionUtil;
import com.java1234.util.StreamUtil;
import com.java1234.util.StringUtil;
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DisPatcherServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void init() throws ServletException {
// 初始化Helper
HelperLoader.init();
// 获取servletContext(注册servlet)
ServletContext servletContext = this.getServletContext();
// 注册jsp的servlet
ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
// 注册静态资源servlet
ServletRegistration defaultServlet = servletContext.getServletRegistration("deafult");
defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
}
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取请求方法
String requestMethod = request.getMethod().toLowerCase();
String requestPath = request.getPathInfo();
// 获取Action处理器
Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
if (handler != null) {
// 获取Controller
Class<?> controllerClass = handler.getControllerClass();
Object controllerBean = BeanHelper.getBean(controllerClass);
// 创建请求对象
Map<String, Object> paramMap = new HashMap<String, Object>();
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
String paramValue = request.getParameter(paramName);
paramMap.put(paramName, paramValue);
}
String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
if (StringUtil.isNotEmpty(body)) {
String[] params = StringUtil.splitString(body, "&");
if (ArrayUtil.isNotEmpty(params)) {
for (String param : params) {
String[] array = StringUtil.splitString(param, "=");
if (ArrayUtil.isNotEmpty(array) && array.length == 2) {
String paramName = array[0];
String paramValue = array[1];
paramMap.put(paramName, paramValue);
}
}
}
}
Param param = new Param(paramMap);
// 调用action方法
Method actionMethod = handler.getActionMethod();
Object result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, param);
// 处理返回结果
if (result instanceof View) {
// 返回jsp
View view = (View) result;
String path = view.getPath();
if (StringUtil.isNotEmpty(path)) {
if (path.startsWith("/")) {
response.sendRedirect(request.getContextPath() + path);
} else {
Map<String, Object> model = view.getModel();
for (Map.Entry<String, Object> enty : model.entrySet()) {
request.setAttribute(enty.getKey(), enty.getValue());
}
request.getRequestDispatcher(ConfigHelper.getAppJspPath() + path).forward(request, response);
}
} else if (result instanceof Data) {
// 返回json
Data data = (Data) result;
Object model = data.getModel();
if (model != null) {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
String json = JsonUtil.toJson(model);
writer.write(json);
writer.flush();
writer.close();
}
}
}
}
}
}
| UTF-8 | Java | 4,455 | java | DisPatcherServlet.java | Java | [] | null | [] | package com.java1234.framework;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.java1234.bean.Data;
import com.java1234.bean.Handler;
import com.java1234.bean.Param;
import com.java1234.bean.View;
import com.java1234.helper.BeanHelper;
import com.java1234.helper.ConfigHelper;
import com.java1234.helper.ControllerHelper;
import com.java1234.util.ArrayUtil;
import com.java1234.util.CodecUtil;
import com.java1234.util.JsonUtil;
import com.java1234.util.ReflectionUtil;
import com.java1234.util.StreamUtil;
import com.java1234.util.StringUtil;
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DisPatcherServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void init() throws ServletException {
// 初始化Helper
HelperLoader.init();
// 获取servletContext(注册servlet)
ServletContext servletContext = this.getServletContext();
// 注册jsp的servlet
ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
// 注册静态资源servlet
ServletRegistration defaultServlet = servletContext.getServletRegistration("deafult");
defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
}
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取请求方法
String requestMethod = request.getMethod().toLowerCase();
String requestPath = request.getPathInfo();
// 获取Action处理器
Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
if (handler != null) {
// 获取Controller
Class<?> controllerClass = handler.getControllerClass();
Object controllerBean = BeanHelper.getBean(controllerClass);
// 创建请求对象
Map<String, Object> paramMap = new HashMap<String, Object>();
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
String paramValue = request.getParameter(paramName);
paramMap.put(paramName, paramValue);
}
String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
if (StringUtil.isNotEmpty(body)) {
String[] params = StringUtil.splitString(body, "&");
if (ArrayUtil.isNotEmpty(params)) {
for (String param : params) {
String[] array = StringUtil.splitString(param, "=");
if (ArrayUtil.isNotEmpty(array) && array.length == 2) {
String paramName = array[0];
String paramValue = array[1];
paramMap.put(paramName, paramValue);
}
}
}
}
Param param = new Param(paramMap);
// 调用action方法
Method actionMethod = handler.getActionMethod();
Object result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, param);
// 处理返回结果
if (result instanceof View) {
// 返回jsp
View view = (View) result;
String path = view.getPath();
if (StringUtil.isNotEmpty(path)) {
if (path.startsWith("/")) {
response.sendRedirect(request.getContextPath() + path);
} else {
Map<String, Object> model = view.getModel();
for (Map.Entry<String, Object> enty : model.entrySet()) {
request.setAttribute(enty.getKey(), enty.getValue());
}
request.getRequestDispatcher(ConfigHelper.getAppJspPath() + path).forward(request, response);
}
} else if (result instanceof Data) {
// 返回json
Data data = (Data) result;
Object model = data.getModel();
if (model != null) {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
String json = JsonUtil.toJson(model);
writer.write(json);
writer.flush();
writer.close();
}
}
}
}
}
}
| 4,455 | 0.702089 | 0.687859 | 125 | 32.855999 | 23.548656 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.184 | false | false | 0 |
8cbbad4a5c88123e27179332b92ecf00a10847d9 | 19,524,921,381,675 | 3f746c5b62dd4503c3dbf2b4eed5d34bc684cd7b | /juc/src/main/java/com/mashibing/juc/c04/T004_taobao2_02_condition.java | 2c54d8626ac5dc2ba1d1a2ea83341298e11e15ab | [] | no_license | tianxingqian/java-study | https://github.com/tianxingqian/java-study | f9c374f58615d7013eebc218e44f160f1ad581de | 14ba426d2b7176089dd65fa804d93c77b0ad2737 | refs/heads/master | 2023-03-24T11:35:41.169000 | 2021-03-21T12:17:27 | 2021-03-21T12:17:27 | 320,969,118 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mashibing.juc.c04;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 写一个固定容量的容器,拥有put、get、getCount,支持2个生产者、10个消费者,阻塞调用
* 使用条件将 生产者、消费者 分类唤醒
* consumerCon.await(); // 容器中数据为0时, 消费者 等待
* producureCon.signalAll(); // 同时唤醒生产者
*
* producureCon.await(); // 容器中数据满了, 生产者等待
* consumerCon.signalAll(); // 同时唤醒消费者
*/
public class T004_taobao2_02_condition<T> {
private LinkedList<T> linkedList = new LinkedList<>();
private int count = 10;
private ReentrantLock lock = new ReentrantLock();
private Condition producureCon = lock.newCondition();
private Condition consumerCon = lock.newCondition();
public void put(T t) {
try {
lock.lock();
while (linkedList.size() == 10) {
System.out.println("满了");
try {
producureCon.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
consumerCon.signalAll();
}
linkedList.add(t);
++count;
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public T get() {
T t = null;
try {
lock.lock();
while (linkedList.size() == 0) {
System.out.println("空了");
try {
consumerCon.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t = linkedList.removeFirst();
count--;
producureCon.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return t;
}
public static void main(String[] args) {
T004_taobao2_02_condition<String> c = new T004_taobao2_02_condition();
// 消费者线程
for (int i =0; i< 10; i++) {
new Thread(()->{
for (int j=0; j<5; j++) System.out.println(c.get());
}, "Consumer" + i).start();
}
// 生产者
for (int i=0; i<2; i++) {
new Thread(()->{
for (int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
}, "p" + i).start();
}
}
}
| UTF-8 | Java | 2,630 | java | T004_taobao2_02_condition.java | Java | [] | null | [] | package com.mashibing.juc.c04;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 写一个固定容量的容器,拥有put、get、getCount,支持2个生产者、10个消费者,阻塞调用
* 使用条件将 生产者、消费者 分类唤醒
* consumerCon.await(); // 容器中数据为0时, 消费者 等待
* producureCon.signalAll(); // 同时唤醒生产者
*
* producureCon.await(); // 容器中数据满了, 生产者等待
* consumerCon.signalAll(); // 同时唤醒消费者
*/
public class T004_taobao2_02_condition<T> {
private LinkedList<T> linkedList = new LinkedList<>();
private int count = 10;
private ReentrantLock lock = new ReentrantLock();
private Condition producureCon = lock.newCondition();
private Condition consumerCon = lock.newCondition();
public void put(T t) {
try {
lock.lock();
while (linkedList.size() == 10) {
System.out.println("满了");
try {
producureCon.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
consumerCon.signalAll();
}
linkedList.add(t);
++count;
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public T get() {
T t = null;
try {
lock.lock();
while (linkedList.size() == 0) {
System.out.println("空了");
try {
consumerCon.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t = linkedList.removeFirst();
count--;
producureCon.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return t;
}
public static void main(String[] args) {
T004_taobao2_02_condition<String> c = new T004_taobao2_02_condition();
// 消费者线程
for (int i =0; i< 10; i++) {
new Thread(()->{
for (int j=0; j<5; j++) System.out.println(c.get());
}, "Consumer" + i).start();
}
// 生产者
for (int i=0; i<2; i++) {
new Thread(()->{
for (int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
}, "p" + i).start();
}
}
}
| 2,630 | 0.489712 | 0.473663 | 84 | 27.928572 | 18.984821 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 0 |
b9cf8e83acb0f90e4f632638eaac67e18482d5ed | 17,437,567,253,268 | bcba8539e695ecc34ba5c221f5f23a82d1f96bfd | /src/test/java/com/example/ziying/service/TelevisionServiceTest.java | deb2f76d75a048f0e2c89ca0ddb675e7cadb289d | [] | no_license | 1802343117/ziying-api | https://github.com/1802343117/ziying-api | 8da16ddcfd752bc7b6533bd0106395437f7e9b62 | 9963c1584af6595203bd4f1ee1a7e5f23f846f2c | refs/heads/main | 2023-08-27T02:41:41.755000 | 2021-10-25T10:08:52 | 2021-10-25T10:08:52 | 418,348,454 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.ziying.service;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
class TelevisionServiceTest {
@Resource
private TelevisionService televisionService;
@Test
void tVList() {
System.out.println(televisionService.tVList());
}
} | UTF-8 | Java | 390 | java | TelevisionServiceTest.java | Java | [] | null | [] | package com.example.ziying.service;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
class TelevisionServiceTest {
@Resource
private TelevisionService televisionService;
@Test
void tVList() {
System.out.println(televisionService.tVList());
}
} | 390 | 0.723077 | 0.723077 | 18 | 19.777779 | 19.80616 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
21ba4662873211abaa670a49390171ba3b23d867 | 38,482,906,992,363 | fa024cf7f0aa467c78dc94e87daa8528c19103d3 | /Array/src/array/ArraySortAsc.java | 1b78f788db2f4599597911173ae99cccc8a35184 | [] | no_license | grepfunlife/HomeWork | https://github.com/grepfunlife/HomeWork | 41836b870d8ae560e41aacf39a49a80973754de1 | cfd11ebebd63b858e1e364a8aa0990200317a169 | refs/heads/master | 2021-01-21T13:57:45.499000 | 2016-05-16T13:36:46 | 2016-05-16T13:36:46 | 45,569,686 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package array;
import java.util.Arrays;
public class ArraySortAsc {
public static void main(String[] args) {
int[] a = new int[5];
System.out.println("Befor sort:");
for (int i = 0; i < a.length; i++) {
a[i] = (int)(Math.random() * 100);
System.out.println(a[i]);
}
Arrays.sort(a);
System.out.println("After sort:");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
| UTF-8 | Java | 513 | java | ArraySortAsc.java | Java | [] | null | [] | package array;
import java.util.Arrays;
public class ArraySortAsc {
public static void main(String[] args) {
int[] a = new int[5];
System.out.println("Befor sort:");
for (int i = 0; i < a.length; i++) {
a[i] = (int)(Math.random() * 100);
System.out.println(a[i]);
}
Arrays.sort(a);
System.out.println("After sort:");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
| 513 | 0.477583 | 0.465887 | 23 | 21.304348 | 17.503876 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false | 0 |
7e7a6b17ca348a258b54b9f414b48b6d4bf3d994 | 2,173,253,501,563 | e7f0e6866791166605387a8e19742edc3419d6ad | /java210208/src/com/design/BaseBallGameLogic.java | 6b0b5c866e675ff29b568772a33c884f5d92648d | [] | no_license | RNCST/java210208 | https://github.com/RNCST/java210208 | 6f55ff5629b9ab6d7f0936d58f4fbb29ca2b9905 | 177e2dc92925fb2f9e92661f8099222973fa2665 | refs/heads/main | 2023-04-17T21:08:41.709000 | 2021-05-14T00:02:19 | 2021-05-14T00:02:19 | 336,936,454 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.design;
public class BaseBallGameLogic {
//JTexaArea에 순번 출력하기
int cnt = 0;
//컴퓨터가 난수발생으로 얻어낸 값 저장
int[] com = new int[3]; // 컴퓨터가 채번하는 값은 메소드가 필요하다. 메소드 중심의 코딩을 전개하기.
// 새 게임을 눌렀을때 재사용, 정답을 눌렀을때.
int[] my = new int[3]; // 사용자가 입력한 값은 로컬에서 온다.
public void nanSu(){
com[0] = (int)(Math.random()*10);
do{
com[1] = (int)(Math.random()*10);
}while(com[0]==com[1]);
do{
com[2] = (int)(Math.random()*10);
}while((com[0]==com[2])||(com[1]==com[2]));
System.out.println(com[0]+""+com[1]+""+com[2]);
}
//전광판에 출력될 메시지를 작성하는 메소드 선언
/**
* @param input jp_center속지-남쪽-JTextField - "256"
* @return 1스 0볼, 2스 1볼
* 전역변수 - 회차 cnt (static 고려 대상이긴하지만 바뀌어야함)
* 지역변수 - strike, ball (static 고려 대상이 아님)
*/
public String call(String input){
//스트라이크를 카운트할 변수
int strike = 0;
//볼을 카운트할 변수
int ball = 0;
int temp = 0;
//반드시 세자리 숫자 이어야 한다.
if(input.length()!=3){
return "세자리 숫자만 입력하세요!!!";
}
temp = Integer.parseInt(input);
my[0] = temp/100;//백자리를 받는다.
my[1] = (temp%100)/10;//십자리를 받는다.
my[2] = temp%10;
for(int i=0;i<com.length;i++){
for(int j=0;j<my.length;j++){
//같은 숫자가 존재하는 경우(볼확보)
//컴퓨터가 채번한 숫자가 있는지 비교
if(com[i] == my[j]){
//자리수까지도 일치하는 경우(스트라이크확보)
//그 숫자가 존재하는 배열의 인덱스값을 비교
if(i==j){
strike++;
}else{
ball++;
}
}// end of if ////////////////
}////// end of inner for ////////////////
}////////// end of outter for ////////////////
if(strike == 3) return "정답입니다.";
return strike+"스트라이크" +ball+"볼";
}///////////// end of call ////////////////////////
} | UTF-8 | Java | 2,283 | java | BaseBallGameLogic.java | Java | [] | null | [] | package com.design;
public class BaseBallGameLogic {
//JTexaArea에 순번 출력하기
int cnt = 0;
//컴퓨터가 난수발생으로 얻어낸 값 저장
int[] com = new int[3]; // 컴퓨터가 채번하는 값은 메소드가 필요하다. 메소드 중심의 코딩을 전개하기.
// 새 게임을 눌렀을때 재사용, 정답을 눌렀을때.
int[] my = new int[3]; // 사용자가 입력한 값은 로컬에서 온다.
public void nanSu(){
com[0] = (int)(Math.random()*10);
do{
com[1] = (int)(Math.random()*10);
}while(com[0]==com[1]);
do{
com[2] = (int)(Math.random()*10);
}while((com[0]==com[2])||(com[1]==com[2]));
System.out.println(com[0]+""+com[1]+""+com[2]);
}
//전광판에 출력될 메시지를 작성하는 메소드 선언
/**
* @param input jp_center속지-남쪽-JTextField - "256"
* @return 1스 0볼, 2스 1볼
* 전역변수 - 회차 cnt (static 고려 대상이긴하지만 바뀌어야함)
* 지역변수 - strike, ball (static 고려 대상이 아님)
*/
public String call(String input){
//스트라이크를 카운트할 변수
int strike = 0;
//볼을 카운트할 변수
int ball = 0;
int temp = 0;
//반드시 세자리 숫자 이어야 한다.
if(input.length()!=3){
return "세자리 숫자만 입력하세요!!!";
}
temp = Integer.parseInt(input);
my[0] = temp/100;//백자리를 받는다.
my[1] = (temp%100)/10;//십자리를 받는다.
my[2] = temp%10;
for(int i=0;i<com.length;i++){
for(int j=0;j<my.length;j++){
//같은 숫자가 존재하는 경우(볼확보)
//컴퓨터가 채번한 숫자가 있는지 비교
if(com[i] == my[j]){
//자리수까지도 일치하는 경우(스트라이크확보)
//그 숫자가 존재하는 배열의 인덱스값을 비교
if(i==j){
strike++;
}else{
ball++;
}
}// end of if ////////////////
}////// end of inner for ////////////////
}////////// end of outter for ////////////////
if(strike == 3) return "정답입니다.";
return strike+"스트라이크" +ball+"볼";
}///////////// end of call ////////////////////////
} | 2,283 | 0.485764 | 0.457873 | 65 | 24.507692 | 16.277519 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.307692 | false | false | 0 |
0167281874eae135c34caa2586858aacbe6f03db | 28,630,252,033,467 | 8a1308cc53d12e53dc3797bdbe4f92f130bf4b35 | /src/main/java/com/example/currencyexchange/exception/ExceptionHandling.java | 6ef416637d2e18d4c2628fa75176750888dea781 | [] | no_license | irerin07/currencyexchange | https://github.com/irerin07/currencyexchange | 499851fd0f46c52608414091d66dde64b913684e | d85c5f4d1e98eeb32b82a52b3d5df0e07da5c77c | refs/heads/master | 2023-06-10T15:29:53.533000 | 2020-05-25T07:53:40 | 2020-05-25T07:53:40 | 190,319,487 | 0 | 0 | null | false | 2023-05-26T22:16:42 | 2019-06-05T03:26:57 | 2020-05-25T07:53:44 | 2023-05-26T22:16:41 | 195 | 0 | 0 | 1 | Java | false | false | package com.example.currencyexchange.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.RestClientException;
@ControllerAdvice
@Slf4j
public class ExceptionHandling {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity exception(NullPointerException exception) {
log.error("NullPointerException in the class: " + exception.getClass().getName() + "with : " + exception.getMessage() + ". Cause: " + exception.getCause());
return new ResponseEntity(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity exception(IllegalArgumentException exception) {
log.error("IllegalArgumentException in the class: " + exception.getClass().getName() + "with : " + exception.getMessage() + ". Cause: " + exception.getCause());
return new ResponseEntity(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(RestClientException.class)
public ResponseEntity exception(RestClientException exception) {
log.error("RestClientException in the class: " + exception.getClass().getName() + "with : " + exception.getMessage() + ". Cause: " + exception.getCause());
return new ResponseEntity(exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
| UTF-8 | Java | 1,568 | java | ExceptionHandling.java | Java | [] | null | [] | package com.example.currencyexchange.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.RestClientException;
@ControllerAdvice
@Slf4j
public class ExceptionHandling {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity exception(NullPointerException exception) {
log.error("NullPointerException in the class: " + exception.getClass().getName() + "with : " + exception.getMessage() + ". Cause: " + exception.getCause());
return new ResponseEntity(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity exception(IllegalArgumentException exception) {
log.error("IllegalArgumentException in the class: " + exception.getClass().getName() + "with : " + exception.getMessage() + ". Cause: " + exception.getCause());
return new ResponseEntity(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(RestClientException.class)
public ResponseEntity exception(RestClientException exception) {
log.error("RestClientException in the class: " + exception.getClass().getName() + "with : " + exception.getMessage() + ". Cause: " + exception.getCause());
return new ResponseEntity(exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
| 1,568 | 0.757015 | 0.755102 | 30 | 51.266666 | 47.370125 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false | 0 |
9a79edcd6117e1825dc71a1335b70b85a851a79a | 31,181,462,609,507 | 4bb4a51ea57e8755ecd27861bc00a0f1503c9f53 | /Cluedo/src/Cluedo/Rooms.java | a55396e49a5589cde10dc7f24088e97688d581a6 | [] | no_license | michaelpearson/Swen-222-Cluedo | https://github.com/michaelpearson/Swen-222-Cluedo | 77867a0d887f0d3c697523ec328462c78ff6b2b6 | e848a5108bf2ee8f622baa24f3dfa7522ccca797 | refs/heads/master | 2021-03-12T20:41:29.172000 | 2015-07-26T23:18:44 | 2015-07-26T23:18:44 | 22,446,700 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Cluedo;
public enum Rooms implements CardValues{
KITCHEN ("Kitchen", "Images/Kitchen.png"),
BALL_ROOM ("Ball Room", "Images/BallRoom.png"),
CONSERVATORY ("Conservatory", "Images/Conservatory.png"),
BILLIARD_ROOM ("Billiard Room", "Images/BilliardRoom.png"),
LIBRARY ("Library", "Images/Library.png"),
STUDY ("Study", "Images/Study.png"),
HALL ("Hall", "Images/Hall.png"),
LOUNGE ("Lounge", "Images/Lounge.png"),
DINING_ROOM ("Dining Room", "Images/DiningRoom.png");
private static final String objectType = "Room";
private String name;
private String image;
Rooms(String name, String image) {
this.name = name;
this.image = image;
}
public String getName()
{
return(this.name);
}
public String getImage() {
return this.image;
}
public void printValue() {
System.out.print(this.name);
}
public String getObjectType() {
return(objectType);
}
}
| UTF-8 | Java | 892 | java | Rooms.java | Java | [] | null | [] | package Cluedo;
public enum Rooms implements CardValues{
KITCHEN ("Kitchen", "Images/Kitchen.png"),
BALL_ROOM ("Ball Room", "Images/BallRoom.png"),
CONSERVATORY ("Conservatory", "Images/Conservatory.png"),
BILLIARD_ROOM ("Billiard Room", "Images/BilliardRoom.png"),
LIBRARY ("Library", "Images/Library.png"),
STUDY ("Study", "Images/Study.png"),
HALL ("Hall", "Images/Hall.png"),
LOUNGE ("Lounge", "Images/Lounge.png"),
DINING_ROOM ("Dining Room", "Images/DiningRoom.png");
private static final String objectType = "Room";
private String name;
private String image;
Rooms(String name, String image) {
this.name = name;
this.image = image;
}
public String getName()
{
return(this.name);
}
public String getImage() {
return this.image;
}
public void printValue() {
System.out.print(this.name);
}
public String getObjectType() {
return(objectType);
}
}
| 892 | 0.692825 | 0.692825 | 36 | 23.777779 | 18.301657 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.861111 | false | false | 0 |
424be238294bb117dc384642efce49a5825c47de | 26,388,279,100,984 | ddffb8f48574b38e536dcc2f9fb2511b490b16f9 | /demo-springdata-neo4j/src/main/java/com/service/TDeviceService.java | 411084453ea79268af8e6aab0d06081d45f5eab4 | [] | no_license | littlemujiang/mydemo | https://github.com/littlemujiang/mydemo | 6aaa505f465793486a6d43af8a75b1a3000f6ae5 | 0cc5c313de62224270c2ca4b29007f37e238ddfe | refs/heads/master | 2021-01-20T04:08:07.050000 | 2019-02-21T03:21:23 | 2019-02-21T03:21:23 | 101,381,622 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2018 org.citic.iiot, Inc. All Rights Reserved.
*/
package com.service;
import com.model.Param;
import com.model.TDevice;
import com.dao.TDeviceRepository;
import com.model.TSensor;
import org.json.JSONException;
import org.json.JSONObject;
import org.neo4j.ogm.response.model.NodeModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Simple to Introduction
* className: TDeviceService
*
* @author mujiang
* @version 2018/4/3 上午10:31
*/
@Service
public class TDeviceService {
private static Logger logger = LoggerFactory.getLogger(TDeviceService.class);
@Autowired
TDeviceRepository tDeviceRepository;
@Transactional
public void createDevice(){
try {
for(int i=0; i<1 ;i ++){
TDevice td1 = new TDevice();
TSensor sensor = new TSensor();
sensor.setSensorId(UUID.randomUUID().toString());
sensor.setSensorName("nnn");
TSensor sensor2 = new TSensor();
sensor2.setSensorId(UUID.randomUUID().toString());
sensor2.setSensorName("mmm");
List<TSensor> sensors = new ArrayList<TSensor>();
sensors.add(sensor);
sensors.add(sensor2);
td1.setDeviceId( UUID.randomUUID().toString() );
td1.setDeviceName("tDevice" + i);
td1.setCategoryId("CT303");
td1.setModelId("MD050");
td1.setConnectorId("CN050");
td1.setSensorNum( i * 5 );
td1.setSensors(sensors);
// JSONObject json = new JSONObject();
Param json = new Param();
json.put("_latitude", "经度");
json.put("_longitude", "纬度");
json.put("_brand", "pinpai");
td1.setParamJson(json);
tDeviceRepository.save(td1);
// tSensorsRepository.save(sensor);
// tDeviceSensorRelationRepository.save(relation);
}
logger.info("* * * * * * * * * * * * * * * *");
logger.info("create device done");
logger.info("* * * * * * * * * * * * * * * *");
}catch (Exception e){
logger.error(e.getMessage());
}
}
public void devicesQuery(String ctId, String mdId, String cnId){
// List<TDevice> devices = tDeviceRepository.findByCategoryIdOrModelIdOrConnectorId(ctId,mdId,cnId);
List<TDevice> devices = tDeviceRepository.findByCategoryIdAndModelIdAndConnectorId(ctId,mdId,cnId);
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
logger.info("query device by query: " );
logger.info(String.valueOf(devices.get(0).getSensors().size()));
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}
public void devicesQueryTest(String ctId, String mdId, String cnId){
TDevice device = new TDevice();
device.setCategoryId(ctId);
device.setModelId(mdId);
device.setConnectorId(cnId);
ExampleMatcher matcher = ExampleMatcher.matching()
.withIncludeNullValues();
Example<TDevice> deviceExample = Example.of(device, matcher);
List<TDevice> devices = tDeviceRepository.findByCategoryIdOrModelIdOrConnectorId(ctId,mdId,cnId);
// List<TDevice> devices = tDeviceExampleRepository.findAll(deviceExample);
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
logger.info("query device by notNull: " );
logger.info(devices.toString());
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}
public void sensorFilter(String ctId, int begin, int end){
List<TDevice> devices = tDeviceRepository.findByCategoryIdAndSensorNumBetween(ctId,begin,end);
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
logger.info("filter by sensorNum: " );
logger.info(devices.toString());
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}
public void deviceFilter(String ctId, String param){
try {
JSONObject paramJSON = new JSONObject();
paramJSON.put("latitude",param);
paramJSON.put("longitude", "纬度");
// TDevice devices = tDeviceRepository.findByCategoryId(ctId);
TDevice devices = tDeviceRepository.findByCategoryId(ctId);
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
logger.info("query result: " );
logger.info(devices.toString());
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}catch (JSONException e){
logger.error(e.getMessage());
}
}
} | UTF-8 | Java | 5,582 | java | TDeviceService.java | Java | [
{
"context": "duction\n * className: TDeviceService\n *\n * @author mujiang\n * @version 2018/4/3 上午10:31\n */\n\n@Service\npublic",
"end": 849,
"score": 0.7382581233978271,
"start": 842,
"tag": "USERNAME",
"value": "mujiang"
}
] | null | [] | /*
* Copyright (C) 2018 org.citic.iiot, Inc. All Rights Reserved.
*/
package com.service;
import com.model.Param;
import com.model.TDevice;
import com.dao.TDeviceRepository;
import com.model.TSensor;
import org.json.JSONException;
import org.json.JSONObject;
import org.neo4j.ogm.response.model.NodeModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Simple to Introduction
* className: TDeviceService
*
* @author mujiang
* @version 2018/4/3 上午10:31
*/
@Service
public class TDeviceService {
private static Logger logger = LoggerFactory.getLogger(TDeviceService.class);
@Autowired
TDeviceRepository tDeviceRepository;
@Transactional
public void createDevice(){
try {
for(int i=0; i<1 ;i ++){
TDevice td1 = new TDevice();
TSensor sensor = new TSensor();
sensor.setSensorId(UUID.randomUUID().toString());
sensor.setSensorName("nnn");
TSensor sensor2 = new TSensor();
sensor2.setSensorId(UUID.randomUUID().toString());
sensor2.setSensorName("mmm");
List<TSensor> sensors = new ArrayList<TSensor>();
sensors.add(sensor);
sensors.add(sensor2);
td1.setDeviceId( UUID.randomUUID().toString() );
td1.setDeviceName("tDevice" + i);
td1.setCategoryId("CT303");
td1.setModelId("MD050");
td1.setConnectorId("CN050");
td1.setSensorNum( i * 5 );
td1.setSensors(sensors);
// JSONObject json = new JSONObject();
Param json = new Param();
json.put("_latitude", "经度");
json.put("_longitude", "纬度");
json.put("_brand", "pinpai");
td1.setParamJson(json);
tDeviceRepository.save(td1);
// tSensorsRepository.save(sensor);
// tDeviceSensorRelationRepository.save(relation);
}
logger.info("* * * * * * * * * * * * * * * *");
logger.info("create device done");
logger.info("* * * * * * * * * * * * * * * *");
}catch (Exception e){
logger.error(e.getMessage());
}
}
public void devicesQuery(String ctId, String mdId, String cnId){
// List<TDevice> devices = tDeviceRepository.findByCategoryIdOrModelIdOrConnectorId(ctId,mdId,cnId);
List<TDevice> devices = tDeviceRepository.findByCategoryIdAndModelIdAndConnectorId(ctId,mdId,cnId);
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
logger.info("query device by query: " );
logger.info(String.valueOf(devices.get(0).getSensors().size()));
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}
public void devicesQueryTest(String ctId, String mdId, String cnId){
TDevice device = new TDevice();
device.setCategoryId(ctId);
device.setModelId(mdId);
device.setConnectorId(cnId);
ExampleMatcher matcher = ExampleMatcher.matching()
.withIncludeNullValues();
Example<TDevice> deviceExample = Example.of(device, matcher);
List<TDevice> devices = tDeviceRepository.findByCategoryIdOrModelIdOrConnectorId(ctId,mdId,cnId);
// List<TDevice> devices = tDeviceExampleRepository.findAll(deviceExample);
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
logger.info("query device by notNull: " );
logger.info(devices.toString());
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}
public void sensorFilter(String ctId, int begin, int end){
List<TDevice> devices = tDeviceRepository.findByCategoryIdAndSensorNumBetween(ctId,begin,end);
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
logger.info("filter by sensorNum: " );
logger.info(devices.toString());
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}
public void deviceFilter(String ctId, String param){
try {
JSONObject paramJSON = new JSONObject();
paramJSON.put("latitude",param);
paramJSON.put("longitude", "纬度");
// TDevice devices = tDeviceRepository.findByCategoryId(ctId);
TDevice devices = tDeviceRepository.findByCategoryId(ctId);
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
logger.info("query result: " );
logger.info(devices.toString());
logger.info("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");
}catch (JSONException e){
logger.error(e.getMessage());
}
}
} | 5,582 | 0.528566 | 0.520661 | 160 | 33.793751 | 32.196873 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.68125 | false | false | 0 |
bafa3301709509bfffd0f29eccc8e545ca733713 | 17,403,207,544,368 | f69f62b7ec58529dc2c55c93d00e556b6a0498cb | /maze-traversal-back/resource-api/maze-traversal-api/src/main/java/edu/nileuniversity/grad/resource/api/mazetraversalapi/controller/MazeController.java | a819ed3aa16731d65fb13c1dee2c79f0e4a4f24f | [
"MIT"
] | permissive | 50Hertz/maze-solver | https://github.com/50Hertz/maze-solver | b93a27617cc9a593d65bbc783d52d70ff069f9a6 | 2e792cbb235247089daf535e14ef3874588fa82e | refs/heads/main | 2023-07-04T05:45:16.090000 | 2021-08-05T15:28:03 | 2021-08-05T15:28:03 | 376,891,688 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.nileuniversity.grad.resource.api.mazetraversalapi.controller;
import com.activedge.test.resource.pojo.RestResponsePojo;
import edu.nileuniversity.grad.resource.api.mazetraversalapi.dto.MazeDto;
import edu.nileuniversity.grad.resource.api.mazetraversalapi.services.MazeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/maze")
@Slf4j
public class MazeController {
private final MazeService mazeService;
public MazeController(MazeService mazeService) {
this.mazeService = mazeService;
}
@CrossOrigin
@PostMapping("")
public RestResponsePojo<MazeDto> solveMaze(@Valid @RequestBody MazeDto mazeDto) {
RestResponsePojo<MazeDto> responsePojo = new RestResponsePojo<>();
mazeDto = mazeService.solveMaze(mazeDto);
responsePojo.setMessage("Maze successfully solved.");
responsePojo.setData(mazeDto);
return responsePojo;
}
}
| UTF-8 | Java | 1,018 | java | MazeController.java | Java | [] | null | [] | package edu.nileuniversity.grad.resource.api.mazetraversalapi.controller;
import com.activedge.test.resource.pojo.RestResponsePojo;
import edu.nileuniversity.grad.resource.api.mazetraversalapi.dto.MazeDto;
import edu.nileuniversity.grad.resource.api.mazetraversalapi.services.MazeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/maze")
@Slf4j
public class MazeController {
private final MazeService mazeService;
public MazeController(MazeService mazeService) {
this.mazeService = mazeService;
}
@CrossOrigin
@PostMapping("")
public RestResponsePojo<MazeDto> solveMaze(@Valid @RequestBody MazeDto mazeDto) {
RestResponsePojo<MazeDto> responsePojo = new RestResponsePojo<>();
mazeDto = mazeService.solveMaze(mazeDto);
responsePojo.setMessage("Maze successfully solved.");
responsePojo.setData(mazeDto);
return responsePojo;
}
}
| 1,018 | 0.763261 | 0.760314 | 32 | 30.8125 | 27.423117 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 0 |
bb426e3209cc7bd5ae152df7e63b1183a96d0b38 | 21,741,124,517,264 | 9d1658359dccf7c54958c70f9d0a237c9ef3a961 | /src/object/PreviousPhoto.java | 45b2026cdd9c8eb3b5d51484d7ece4e003175d13 | [] | no_license | chensunCS/Cosmetic-After-sales-Service | https://github.com/chensunCS/Cosmetic-After-sales-Service | 917a978db1744a2ac3ee50ee618b51129f116de6 | fd0a2ced8c4c9b5411b4000920cf8337b6c45ffb | refs/heads/master | 2021-05-14T11:11:14.805000 | 2018-01-16T03:02:02 | 2018-01-16T03:02:02 | 116,373,064 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package object;
import java.util.Date;
public class PreviousPhoto {
private String userID = ""; //用户ID
private String previousPhotoID = "";//当前照片信息的ID
private Date date = new Date();//文件上传的日期
private String fileName = "";//文件名
private String filePath = "";//文件路径
//setter
public void setUserID(String userID) {
this.userID = userID;
}
public void setPreviousPhotoID(String previousPhotoID) {
this.previousPhotoID = previousPhotoID;
}
public void setDate(Date date) {
this.date = date;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
//getter
public String getUserID() {
return this.userID;
}
public String getPreviousPhotoID() {
return this.previousPhotoID;
}
public Date getDate() {
return this.date;
}
public String getFileName() {
return this.fileName;
}
public String getFilePath() {
return this.filePath;
}
}
| GB18030 | Java | 1,013 | java | PreviousPhoto.java | Java | [] | null | [] | package object;
import java.util.Date;
public class PreviousPhoto {
private String userID = ""; //用户ID
private String previousPhotoID = "";//当前照片信息的ID
private Date date = new Date();//文件上传的日期
private String fileName = "";//文件名
private String filePath = "";//文件路径
//setter
public void setUserID(String userID) {
this.userID = userID;
}
public void setPreviousPhotoID(String previousPhotoID) {
this.previousPhotoID = previousPhotoID;
}
public void setDate(Date date) {
this.date = date;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
//getter
public String getUserID() {
return this.userID;
}
public String getPreviousPhotoID() {
return this.previousPhotoID;
}
public Date getDate() {
return this.date;
}
public String getFileName() {
return this.fileName;
}
public String getFilePath() {
return this.filePath;
}
}
| 1,013 | 0.710445 | 0.710445 | 47 | 19.574469 | 16.221531 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.468085 | false | false | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.