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
2804678a2f0fc6d935548b0ff1b6886a51ccccd4
27,255,862,526,891
e51e008eef650fc8da1c5b0b553a424e0251bd8e
/src/main/java/com/AOC2020/Executables/AdventOfCode2020Data.java
900706d2ad51fe67d78ea12a64fce009c1243342
[]
no_license
SebastianLindfors/AdventOfCode2020
https://github.com/SebastianLindfors/AdventOfCode2020
379ff6cb5fe3e7bba64a7b2be24edf5577fdec32
5b001af7e98f2ec354a7412a90e928e810f3128a
refs/heads/main
2023-02-18T10:46:55.934000
2021-01-22T10:21:56
2021-01-22T10:21:56
317,351,423
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.AOC2020.Executables; import com.AOC2020.Tasks.*; public class AdventOfCode2020Data { public static void main(String args[]) { int dayToCompute = 19; AoCChallenge day; switch (dayToCompute) { case 1: day = new Day1("Day1Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 2: day = new Day2("Day2Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 3: day = new Day3("Day3Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 4: day = new Day4("Day4Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 5: day = new Day5("Day5Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 6: day = new Day6("Day6Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 7: day = new Day7("Day7Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 8: day = new Day8("Day8Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 9: day = new Day9("Day9Data.txt"); System.out.println("Solution to task 1: " + ((Day9) day).getTask1SolutionAsLong()); System.out.println("Solution to task 2: " + ((Day9) day).getTask2SolutionAsLong()); break; case 10: day = new Day10("Day10Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + ((Day10) day).getTask2SolutionAsLong()); break; case 11: day = new Day11("Day11Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 12: day = new Day12("Day12Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 13: day = new Day13("Day13Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + ((Day13) day).getTask2SolutionAsLong()); break; case 14: day = new Day14("Day14Data.txt"); System.out.println("Solution to task 1: " + ((Day14) day).getTask1SolutionAsLong()); System.out.println("Solution to task 2: " + ((Day14) day).getTask2SolutionAsLong()); break; case 15: day = new Day15("Day15Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 16: day = new Day16("Day16Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + ((Day16) day).getTask2SolutionAsLong()); break; case 17: day = new Day17("Day17Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 18: day = new Day18("Day18Data.txt"); System.out.println("Solution to task 1: " + ((Day18) day).getTask1SolutionAsLong()); System.out.println("Solution to task 2: " + ((Day18) day).getTask2SolutionAsLong()); break; case 19: day = new Day19("Day19Data.txt"); AoCChallenge day2 = new Day19("Day19Data2.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; } } }
UTF-8
Java
4,704
java
AdventOfCode2020Data.java
Java
[]
null
[]
package com.AOC2020.Executables; import com.AOC2020.Tasks.*; public class AdventOfCode2020Data { public static void main(String args[]) { int dayToCompute = 19; AoCChallenge day; switch (dayToCompute) { case 1: day = new Day1("Day1Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 2: day = new Day2("Day2Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 3: day = new Day3("Day3Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 4: day = new Day4("Day4Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 5: day = new Day5("Day5Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 6: day = new Day6("Day6Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 7: day = new Day7("Day7Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 8: day = new Day8("Day8Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 9: day = new Day9("Day9Data.txt"); System.out.println("Solution to task 1: " + ((Day9) day).getTask1SolutionAsLong()); System.out.println("Solution to task 2: " + ((Day9) day).getTask2SolutionAsLong()); break; case 10: day = new Day10("Day10Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + ((Day10) day).getTask2SolutionAsLong()); break; case 11: day = new Day11("Day11Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 12: day = new Day12("Day12Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 13: day = new Day13("Day13Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + ((Day13) day).getTask2SolutionAsLong()); break; case 14: day = new Day14("Day14Data.txt"); System.out.println("Solution to task 1: " + ((Day14) day).getTask1SolutionAsLong()); System.out.println("Solution to task 2: " + ((Day14) day).getTask2SolutionAsLong()); break; case 15: day = new Day15("Day15Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 16: day = new Day16("Day16Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + ((Day16) day).getTask2SolutionAsLong()); break; case 17: day = new Day17("Day17Data.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; case 18: day = new Day18("Day18Data.txt"); System.out.println("Solution to task 1: " + ((Day18) day).getTask1SolutionAsLong()); System.out.println("Solution to task 2: " + ((Day18) day).getTask2SolutionAsLong()); break; case 19: day = new Day19("Day19Data.txt"); AoCChallenge day2 = new Day19("Day19Data2.txt"); System.out.println("Solution to task 1: " + day.getTask1Solution()); System.out.println("Solution to task 2: " + day.getTask2Solution()); break; } } }
4,704
0.598002
0.555697
114
40.254387
30.500162
92
false
false
0
0
0
0
0
0
0.710526
false
false
3
0ff0723e22fd4a02dca322da709146d6ac2aac6a
2,216,203,177,478
5ed2e858a6118547a5fd6f7079cb76b17fd08815
/crm/src/main/java/com/jingren/jing/question/bean/correction/CorrectionQuestion.java
05c8538c6cc5038b14f2f960add7724ca58d24fc
[]
no_license
luxiaofei222/jr_crm
https://github.com/luxiaofei222/jr_crm
eca84db83e30635ea49bb084b211a2569f15599d
32b95a3f67c5545e55c260c9142cb603f7623046
refs/heads/master
2021-01-22T13:52:09.972000
2017-08-18T11:15:33
2017-08-18T11:15:33
100,696,658
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jingren.jing.question.bean.correction; import java.io.Serializable; import java.util.Date; import com.jingren.jing.question.bean.chapter_exercises.ChapterQuestion; import com.jingren.jing.school.bean.user.User; /** * @Title: CorrectionQuestion.java * @Package com.jingren.jing.question.bean.correction * @Description: TODO 题目纠错信息 * @author 鲁晓飞 MR.Lu * @date 2017年2月7日 下午5:30:57 * @version 网校+CRM系统 V1.0 */ public class CorrectionQuestion implements Serializable{ private static final long serialVersionUID = 1L; private Integer correction_id; private Integer user_id; private String question_type; private Integer question_id; private Date correction_time; private String correction_content; private String correction_type; private Integer correction_state;//0,未查看 1已查看 private User user; private ChapterQuestion chapterQuestion;//章节练习题目 public Integer getCorrection_id() { return correction_id; } public void setCorrection_id(Integer correction_id) { this.correction_id = correction_id; } public Integer getUser_id() { return user_id; } public void setUser_id(Integer user_id) { this.user_id = user_id; } public String getQuestion_type() { return question_type; } public void setQuestion_type(String question_type) { this.question_type = question_type; } public Integer getQuestion_id() { return question_id; } public void setQuestion_id(Integer question_id) { this.question_id = question_id; } public Date getCorrection_time() { return correction_time; } public void setCorrection_time(Date correction_time) { this.correction_time = correction_time; } public String getCorrection_content() { return correction_content; } public void setCorrection_content(String correction_content) { this.correction_content = correction_content; } public String getCorrection_type() { return correction_type; } public void setCorrection_type(String correction_type) { this.correction_type = correction_type; } public static long getSerialversionuid() { return serialVersionUID; } public Integer getCorrection_state() { return correction_state; } public void setCorrection_state(Integer correction_state) { this.correction_state = correction_state; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public ChapterQuestion getChapterQuestion() { return chapterQuestion; } public void setChapterQuestion(ChapterQuestion chapterQuestion) { this.chapterQuestion = chapterQuestion; } }
UTF-8
Java
2,590
java
CorrectionQuestion.java
Java
[ { "context": "correction \n* @Description: TODO 题目纠错信息\n* @author 鲁晓飞 MR.Lu \n* @date 2017年2月7日 下午5:30:57 \n* @version ", "end": 359, "score": 0.9998051524162292, "start": 356, "tag": "NAME", "value": "鲁晓飞" }, { "context": "rection \n* @Description: TODO 题目纠错信息\n* @author 鲁晓飞 MR.Lu \n* @date 2017年2月7日 下午5:30:57 \n* @version 网校+CRM", "end": 365, "score": 0.8512639999389648, "start": 360, "tag": "USERNAME", "value": "MR.Lu" } ]
null
[]
package com.jingren.jing.question.bean.correction; import java.io.Serializable; import java.util.Date; import com.jingren.jing.question.bean.chapter_exercises.ChapterQuestion; import com.jingren.jing.school.bean.user.User; /** * @Title: CorrectionQuestion.java * @Package com.jingren.jing.question.bean.correction * @Description: TODO 题目纠错信息 * @author 鲁晓飞 MR.Lu * @date 2017年2月7日 下午5:30:57 * @version 网校+CRM系统 V1.0 */ public class CorrectionQuestion implements Serializable{ private static final long serialVersionUID = 1L; private Integer correction_id; private Integer user_id; private String question_type; private Integer question_id; private Date correction_time; private String correction_content; private String correction_type; private Integer correction_state;//0,未查看 1已查看 private User user; private ChapterQuestion chapterQuestion;//章节练习题目 public Integer getCorrection_id() { return correction_id; } public void setCorrection_id(Integer correction_id) { this.correction_id = correction_id; } public Integer getUser_id() { return user_id; } public void setUser_id(Integer user_id) { this.user_id = user_id; } public String getQuestion_type() { return question_type; } public void setQuestion_type(String question_type) { this.question_type = question_type; } public Integer getQuestion_id() { return question_id; } public void setQuestion_id(Integer question_id) { this.question_id = question_id; } public Date getCorrection_time() { return correction_time; } public void setCorrection_time(Date correction_time) { this.correction_time = correction_time; } public String getCorrection_content() { return correction_content; } public void setCorrection_content(String correction_content) { this.correction_content = correction_content; } public String getCorrection_type() { return correction_type; } public void setCorrection_type(String correction_type) { this.correction_type = correction_type; } public static long getSerialversionuid() { return serialVersionUID; } public Integer getCorrection_state() { return correction_state; } public void setCorrection_state(Integer correction_state) { this.correction_state = correction_state; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public ChapterQuestion getChapterQuestion() { return chapterQuestion; } public void setChapterQuestion(ChapterQuestion chapterQuestion) { this.chapterQuestion = chapterQuestion; } }
2,590
0.758498
0.752174
94
25.914894
19.431089
72
false
false
0
0
0
0
0
0
1.425532
false
false
3
f7392c8daa574e2025a23deb21c319fb62c61d4b
7,507,602,844,231
d41b4b5b654162a045fa65a77ba1080028607641
/csm/evs-csm-pojo/src/main/java/com/sgcc/evs/csm/entity/ManagementCarExample.java
83db9980495a3b606bb885d411713d9b3b634898
[]
no_license
2286252881/study-2018
https://github.com/2286252881/study-2018
ee58608c14f3f6ce1e9f65c8f0e7eba7c38e88c7
b5fd3a64caf2fd7acc4832e2ce1133f64f2b4e7b
refs/heads/master
2018-11-03T14:02:00.698000
2018-10-28T04:32:46
2018-10-28T04:32:46
143,394,289
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sgcc.evs.csm.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ManagementCarExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ManagementCarExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andCarBrandIdIsNull() { addCriterion("car_brand_id is null"); return (Criteria) this; } public Criteria andCarBrandIdIsNotNull() { addCriterion("car_brand_id is not null"); return (Criteria) this; } public Criteria andCarBrandIdEqualTo(Long value) { addCriterion("car_brand_id =", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdNotEqualTo(Long value) { addCriterion("car_brand_id <>", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdGreaterThan(Long value) { addCriterion("car_brand_id >", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdGreaterThanOrEqualTo(Long value) { addCriterion("car_brand_id >=", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdLessThan(Long value) { addCriterion("car_brand_id <", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdLessThanOrEqualTo(Long value) { addCriterion("car_brand_id <=", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdIn(List<Long> values) { addCriterion("car_brand_id in", values, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdNotIn(List<Long> values) { addCriterion("car_brand_id not in", values, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdBetween(Long value1, Long value2) { addCriterion("car_brand_id between", value1, value2, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdNotBetween(Long value1, Long value2) { addCriterion("car_brand_id not between", value1, value2, "carBrandId"); return (Criteria) this; } public Criteria andCarTypeIdIsNull() { addCriterion("car_type_id is null"); return (Criteria) this; } public Criteria andCarTypeIdIsNotNull() { addCriterion("car_type_id is not null"); return (Criteria) this; } public Criteria andCarTypeIdEqualTo(Long value) { addCriterion("car_type_id =", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdNotEqualTo(Long value) { addCriterion("car_type_id <>", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdGreaterThan(Long value) { addCriterion("car_type_id >", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdGreaterThanOrEqualTo(Long value) { addCriterion("car_type_id >=", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdLessThan(Long value) { addCriterion("car_type_id <", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdLessThanOrEqualTo(Long value) { addCriterion("car_type_id <=", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdIn(List<Long> values) { addCriterion("car_type_id in", values, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdNotIn(List<Long> values) { addCriterion("car_type_id not in", values, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdBetween(Long value1, Long value2) { addCriterion("car_type_id between", value1, value2, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdNotBetween(Long value1, Long value2) { addCriterion("car_type_id not between", value1, value2, "carTypeId"); return (Criteria) this; } public Criteria andCarManagerIdIsNull() { addCriterion("car_manager_id is null"); return (Criteria) this; } public Criteria andCarManagerIdIsNotNull() { addCriterion("car_manager_id is not null"); return (Criteria) this; } public Criteria andCarManagerIdEqualTo(String value) { addCriterion("car_manager_id =", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdNotEqualTo(String value) { addCriterion("car_manager_id <>", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdGreaterThan(String value) { addCriterion("car_manager_id >", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdGreaterThanOrEqualTo(String value) { addCriterion("car_manager_id >=", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdLessThan(String value) { addCriterion("car_manager_id <", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdLessThanOrEqualTo(String value) { addCriterion("car_manager_id <=", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdLike(String value) { addCriterion("car_manager_id like", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdNotLike(String value) { addCriterion("car_manager_id not like", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdIn(List<String> values) { addCriterion("car_manager_id in", values, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdNotIn(List<String> values) { addCriterion("car_manager_id not in", values, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdBetween(String value1, String value2) { addCriterion("car_manager_id between", value1, value2, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdNotBetween(String value1, String value2) { addCriterion("car_manager_id not between", value1, value2, "carManagerId"); return (Criteria) this; } public Criteria andCompactIdIsNull() { addCriterion("compact_id is null"); return (Criteria) this; } public Criteria andCompactIdIsNotNull() { addCriterion("compact_id is not null"); return (Criteria) this; } public Criteria andCompactIdEqualTo(Long value) { addCriterion("compact_id =", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdNotEqualTo(Long value) { addCriterion("compact_id <>", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdGreaterThan(Long value) { addCriterion("compact_id >", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdGreaterThanOrEqualTo(Long value) { addCriterion("compact_id >=", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdLessThan(Long value) { addCriterion("compact_id <", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdLessThanOrEqualTo(Long value) { addCriterion("compact_id <=", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdIn(List<Long> values) { addCriterion("compact_id in", values, "compactId"); return (Criteria) this; } public Criteria andCompactIdNotIn(List<Long> values) { addCriterion("compact_id not in", values, "compactId"); return (Criteria) this; } public Criteria andCompactIdBetween(Long value1, Long value2) { addCriterion("compact_id between", value1, value2, "compactId"); return (Criteria) this; } public Criteria andCompactIdNotBetween(Long value1, Long value2) { addCriterion("compact_id not between", value1, value2, "compactId"); return (Criteria) this; } public Criteria andCarNoIsNull() { addCriterion("car_no is null"); return (Criteria) this; } public Criteria andCarNoIsNotNull() { addCriterion("car_no is not null"); return (Criteria) this; } public Criteria andCarNoEqualTo(String value) { addCriterion("car_no =", value, "carNo"); return (Criteria) this; } public Criteria andCarNoNotEqualTo(String value) { addCriterion("car_no <>", value, "carNo"); return (Criteria) this; } public Criteria andCarNoGreaterThan(String value) { addCriterion("car_no >", value, "carNo"); return (Criteria) this; } public Criteria andCarNoGreaterThanOrEqualTo(String value) { addCriterion("car_no >=", value, "carNo"); return (Criteria) this; } public Criteria andCarNoLessThan(String value) { addCriterion("car_no <", value, "carNo"); return (Criteria) this; } public Criteria andCarNoLessThanOrEqualTo(String value) { addCriterion("car_no <=", value, "carNo"); return (Criteria) this; } public Criteria andCarNoLike(String value) { addCriterion("car_no like", value, "carNo"); return (Criteria) this; } public Criteria andCarNoNotLike(String value) { addCriterion("car_no not like", value, "carNo"); return (Criteria) this; } public Criteria andCarNoIn(List<String> values) { addCriterion("car_no in", values, "carNo"); return (Criteria) this; } public Criteria andCarNoNotIn(List<String> values) { addCriterion("car_no not in", values, "carNo"); return (Criteria) this; } public Criteria andCarNoBetween(String value1, String value2) { addCriterion("car_no between", value1, value2, "carNo"); return (Criteria) this; } public Criteria andCarNoNotBetween(String value1, String value2) { addCriterion("car_no not between", value1, value2, "carNo"); return (Criteria) this; } public Criteria andCarFrameNoIsNull() { addCriterion("car_frame_no is null"); return (Criteria) this; } public Criteria andCarFrameNoIsNotNull() { addCriterion("car_frame_no is not null"); return (Criteria) this; } public Criteria andCarFrameNoEqualTo(String value) { addCriterion("car_frame_no =", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoNotEqualTo(String value) { addCriterion("car_frame_no <>", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoGreaterThan(String value) { addCriterion("car_frame_no >", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoGreaterThanOrEqualTo(String value) { addCriterion("car_frame_no >=", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoLessThan(String value) { addCriterion("car_frame_no <", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoLessThanOrEqualTo(String value) { addCriterion("car_frame_no <=", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoLike(String value) { addCriterion("car_frame_no like", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoNotLike(String value) { addCriterion("car_frame_no not like", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoIn(List<String> values) { addCriterion("car_frame_no in", values, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoNotIn(List<String> values) { addCriterion("car_frame_no not in", values, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoBetween(String value1, String value2) { addCriterion("car_frame_no between", value1, value2, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoNotBetween(String value1, String value2) { addCriterion("car_frame_no not between", value1, value2, "carFrameNo"); return (Criteria) this; } public Criteria andCarEngineIsNull() { addCriterion("car_engine is null"); return (Criteria) this; } public Criteria andCarEngineIsNotNull() { addCriterion("car_engine is not null"); return (Criteria) this; } public Criteria andCarEngineEqualTo(String value) { addCriterion("car_engine =", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineNotEqualTo(String value) { addCriterion("car_engine <>", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineGreaterThan(String value) { addCriterion("car_engine >", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineGreaterThanOrEqualTo(String value) { addCriterion("car_engine >=", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineLessThan(String value) { addCriterion("car_engine <", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineLessThanOrEqualTo(String value) { addCriterion("car_engine <=", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineLike(String value) { addCriterion("car_engine like", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineNotLike(String value) { addCriterion("car_engine not like", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineIn(List<String> values) { addCriterion("car_engine in", values, "carEngine"); return (Criteria) this; } public Criteria andCarEngineNotIn(List<String> values) { addCriterion("car_engine not in", values, "carEngine"); return (Criteria) this; } public Criteria andCarEngineBetween(String value1, String value2) { addCriterion("car_engine between", value1, value2, "carEngine"); return (Criteria) this; } public Criteria andCarEngineNotBetween(String value1, String value2) { addCriterion("car_engine not between", value1, value2, "carEngine"); return (Criteria) this; } public Criteria andOnNoTimeIsNull() { addCriterion("on_no_time is null"); return (Criteria) this; } public Criteria andOnNoTimeIsNotNull() { addCriterion("on_no_time is not null"); return (Criteria) this; } public Criteria andOnNoTimeEqualTo(Date value) { addCriterion("on_no_time =", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeNotEqualTo(Date value) { addCriterion("on_no_time <>", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeGreaterThan(Date value) { addCriterion("on_no_time >", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeGreaterThanOrEqualTo(Date value) { addCriterion("on_no_time >=", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeLessThan(Date value) { addCriterion("on_no_time <", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeLessThanOrEqualTo(Date value) { addCriterion("on_no_time <=", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeIn(List<Date> values) { addCriterion("on_no_time in", values, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeNotIn(List<Date> values) { addCriterion("on_no_time not in", values, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeBetween(Date value1, Date value2) { addCriterion("on_no_time between", value1, value2, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeNotBetween(Date value1, Date value2) { addCriterion("on_no_time not between", value1, value2, "onNoTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeIsNull() { addCriterion("first_insurance_time is null"); return (Criteria) this; } public Criteria andFirstInsuranceTimeIsNotNull() { addCriterion("first_insurance_time is not null"); return (Criteria) this; } public Criteria andFirstInsuranceTimeEqualTo(Date value) { addCriterion("first_insurance_time =", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeNotEqualTo(Date value) { addCriterion("first_insurance_time <>", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeGreaterThan(Date value) { addCriterion("first_insurance_time >", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeGreaterThanOrEqualTo(Date value) { addCriterion("first_insurance_time >=", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeLessThan(Date value) { addCriterion("first_insurance_time <", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeLessThanOrEqualTo(Date value) { addCriterion("first_insurance_time <=", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeIn(List<Date> values) { addCriterion("first_insurance_time in", values, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeNotIn(List<Date> values) { addCriterion("first_insurance_time not in", values, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeBetween(Date value1, Date value2) { addCriterion("first_insurance_time between", value1, value2, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeNotBetween(Date value1, Date value2) { addCriterion("first_insurance_time not between", value1, value2, "firstInsuranceTime"); return (Criteria) this; } public Criteria andOldCompactNameIsNull() { addCriterion("old_compact_name is null"); return (Criteria) this; } public Criteria andOldCompactNameIsNotNull() { addCriterion("old_compact_name is not null"); return (Criteria) this; } public Criteria andOldCompactNameEqualTo(String value) { addCriterion("old_compact_name =", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameNotEqualTo(String value) { addCriterion("old_compact_name <>", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameGreaterThan(String value) { addCriterion("old_compact_name >", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameGreaterThanOrEqualTo(String value) { addCriterion("old_compact_name >=", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameLessThan(String value) { addCriterion("old_compact_name <", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameLessThanOrEqualTo(String value) { addCriterion("old_compact_name <=", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameLike(String value) { addCriterion("old_compact_name like", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameNotLike(String value) { addCriterion("old_compact_name not like", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameIn(List<String> values) { addCriterion("old_compact_name in", values, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameNotIn(List<String> values) { addCriterion("old_compact_name not in", values, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameBetween(String value1, String value2) { addCriterion("old_compact_name between", value1, value2, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameNotBetween(String value1, String value2) { addCriterion("old_compact_name not between", value1, value2, "oldCompactName"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andValidIsNull() { addCriterion("valid is null"); return (Criteria) this; } public Criteria andValidIsNotNull() { addCriterion("valid is not null"); return (Criteria) this; } public Criteria andValidEqualTo(String value) { addCriterion("valid =", value, "valid"); return (Criteria) this; } public Criteria andValidNotEqualTo(String value) { addCriterion("valid <>", value, "valid"); return (Criteria) this; } public Criteria andValidGreaterThan(String value) { addCriterion("valid >", value, "valid"); return (Criteria) this; } public Criteria andValidGreaterThanOrEqualTo(String value) { addCriterion("valid >=", value, "valid"); return (Criteria) this; } public Criteria andValidLessThan(String value) { addCriterion("valid <", value, "valid"); return (Criteria) this; } public Criteria andValidLessThanOrEqualTo(String value) { addCriterion("valid <=", value, "valid"); return (Criteria) this; } public Criteria andValidLike(String value) { addCriterion("valid like", value, "valid"); return (Criteria) this; } public Criteria andValidNotLike(String value) { addCriterion("valid not like", value, "valid"); return (Criteria) this; } public Criteria andValidIn(List<String> values) { addCriterion("valid in", values, "valid"); return (Criteria) this; } public Criteria andValidNotIn(List<String> values) { addCriterion("valid not in", values, "valid"); return (Criteria) this; } public Criteria andValidBetween(String value1, String value2) { addCriterion("valid between", value1, value2, "valid"); return (Criteria) this; } public Criteria andValidNotBetween(String value1, String value2) { addCriterion("valid not between", value1, value2, "valid"); return (Criteria) this; } public Criteria andDelFlagIsNull() { addCriterion("del_flag is null"); return (Criteria) this; } public Criteria andDelFlagIsNotNull() { addCriterion("del_flag is not null"); return (Criteria) this; } public Criteria andDelFlagEqualTo(String value) { addCriterion("del_flag =", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotEqualTo(String value) { addCriterion("del_flag <>", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagGreaterThan(String value) { addCriterion("del_flag >", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagGreaterThanOrEqualTo(String value) { addCriterion("del_flag >=", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagLessThan(String value) { addCriterion("del_flag <", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagLessThanOrEqualTo(String value) { addCriterion("del_flag <=", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagLike(String value) { addCriterion("del_flag like", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotLike(String value) { addCriterion("del_flag not like", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagIn(List<String> values) { addCriterion("del_flag in", values, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotIn(List<String> values) { addCriterion("del_flag not in", values, "delFlag"); return (Criteria) this; } public Criteria andDelFlagBetween(String value1, String value2) { addCriterion("del_flag between", value1, value2, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotBetween(String value1, String value2) { addCriterion("del_flag not between", value1, value2, "delFlag"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
UTF-8
Java
38,997
java
ManagementCarExample.java
Java
[]
null
[]
package com.sgcc.evs.csm.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ManagementCarExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ManagementCarExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andCarBrandIdIsNull() { addCriterion("car_brand_id is null"); return (Criteria) this; } public Criteria andCarBrandIdIsNotNull() { addCriterion("car_brand_id is not null"); return (Criteria) this; } public Criteria andCarBrandIdEqualTo(Long value) { addCriterion("car_brand_id =", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdNotEqualTo(Long value) { addCriterion("car_brand_id <>", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdGreaterThan(Long value) { addCriterion("car_brand_id >", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdGreaterThanOrEqualTo(Long value) { addCriterion("car_brand_id >=", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdLessThan(Long value) { addCriterion("car_brand_id <", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdLessThanOrEqualTo(Long value) { addCriterion("car_brand_id <=", value, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdIn(List<Long> values) { addCriterion("car_brand_id in", values, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdNotIn(List<Long> values) { addCriterion("car_brand_id not in", values, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdBetween(Long value1, Long value2) { addCriterion("car_brand_id between", value1, value2, "carBrandId"); return (Criteria) this; } public Criteria andCarBrandIdNotBetween(Long value1, Long value2) { addCriterion("car_brand_id not between", value1, value2, "carBrandId"); return (Criteria) this; } public Criteria andCarTypeIdIsNull() { addCriterion("car_type_id is null"); return (Criteria) this; } public Criteria andCarTypeIdIsNotNull() { addCriterion("car_type_id is not null"); return (Criteria) this; } public Criteria andCarTypeIdEqualTo(Long value) { addCriterion("car_type_id =", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdNotEqualTo(Long value) { addCriterion("car_type_id <>", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdGreaterThan(Long value) { addCriterion("car_type_id >", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdGreaterThanOrEqualTo(Long value) { addCriterion("car_type_id >=", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdLessThan(Long value) { addCriterion("car_type_id <", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdLessThanOrEqualTo(Long value) { addCriterion("car_type_id <=", value, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdIn(List<Long> values) { addCriterion("car_type_id in", values, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdNotIn(List<Long> values) { addCriterion("car_type_id not in", values, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdBetween(Long value1, Long value2) { addCriterion("car_type_id between", value1, value2, "carTypeId"); return (Criteria) this; } public Criteria andCarTypeIdNotBetween(Long value1, Long value2) { addCriterion("car_type_id not between", value1, value2, "carTypeId"); return (Criteria) this; } public Criteria andCarManagerIdIsNull() { addCriterion("car_manager_id is null"); return (Criteria) this; } public Criteria andCarManagerIdIsNotNull() { addCriterion("car_manager_id is not null"); return (Criteria) this; } public Criteria andCarManagerIdEqualTo(String value) { addCriterion("car_manager_id =", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdNotEqualTo(String value) { addCriterion("car_manager_id <>", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdGreaterThan(String value) { addCriterion("car_manager_id >", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdGreaterThanOrEqualTo(String value) { addCriterion("car_manager_id >=", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdLessThan(String value) { addCriterion("car_manager_id <", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdLessThanOrEqualTo(String value) { addCriterion("car_manager_id <=", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdLike(String value) { addCriterion("car_manager_id like", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdNotLike(String value) { addCriterion("car_manager_id not like", value, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdIn(List<String> values) { addCriterion("car_manager_id in", values, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdNotIn(List<String> values) { addCriterion("car_manager_id not in", values, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdBetween(String value1, String value2) { addCriterion("car_manager_id between", value1, value2, "carManagerId"); return (Criteria) this; } public Criteria andCarManagerIdNotBetween(String value1, String value2) { addCriterion("car_manager_id not between", value1, value2, "carManagerId"); return (Criteria) this; } public Criteria andCompactIdIsNull() { addCriterion("compact_id is null"); return (Criteria) this; } public Criteria andCompactIdIsNotNull() { addCriterion("compact_id is not null"); return (Criteria) this; } public Criteria andCompactIdEqualTo(Long value) { addCriterion("compact_id =", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdNotEqualTo(Long value) { addCriterion("compact_id <>", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdGreaterThan(Long value) { addCriterion("compact_id >", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdGreaterThanOrEqualTo(Long value) { addCriterion("compact_id >=", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdLessThan(Long value) { addCriterion("compact_id <", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdLessThanOrEqualTo(Long value) { addCriterion("compact_id <=", value, "compactId"); return (Criteria) this; } public Criteria andCompactIdIn(List<Long> values) { addCriterion("compact_id in", values, "compactId"); return (Criteria) this; } public Criteria andCompactIdNotIn(List<Long> values) { addCriterion("compact_id not in", values, "compactId"); return (Criteria) this; } public Criteria andCompactIdBetween(Long value1, Long value2) { addCriterion("compact_id between", value1, value2, "compactId"); return (Criteria) this; } public Criteria andCompactIdNotBetween(Long value1, Long value2) { addCriterion("compact_id not between", value1, value2, "compactId"); return (Criteria) this; } public Criteria andCarNoIsNull() { addCriterion("car_no is null"); return (Criteria) this; } public Criteria andCarNoIsNotNull() { addCriterion("car_no is not null"); return (Criteria) this; } public Criteria andCarNoEqualTo(String value) { addCriterion("car_no =", value, "carNo"); return (Criteria) this; } public Criteria andCarNoNotEqualTo(String value) { addCriterion("car_no <>", value, "carNo"); return (Criteria) this; } public Criteria andCarNoGreaterThan(String value) { addCriterion("car_no >", value, "carNo"); return (Criteria) this; } public Criteria andCarNoGreaterThanOrEqualTo(String value) { addCriterion("car_no >=", value, "carNo"); return (Criteria) this; } public Criteria andCarNoLessThan(String value) { addCriterion("car_no <", value, "carNo"); return (Criteria) this; } public Criteria andCarNoLessThanOrEqualTo(String value) { addCriterion("car_no <=", value, "carNo"); return (Criteria) this; } public Criteria andCarNoLike(String value) { addCriterion("car_no like", value, "carNo"); return (Criteria) this; } public Criteria andCarNoNotLike(String value) { addCriterion("car_no not like", value, "carNo"); return (Criteria) this; } public Criteria andCarNoIn(List<String> values) { addCriterion("car_no in", values, "carNo"); return (Criteria) this; } public Criteria andCarNoNotIn(List<String> values) { addCriterion("car_no not in", values, "carNo"); return (Criteria) this; } public Criteria andCarNoBetween(String value1, String value2) { addCriterion("car_no between", value1, value2, "carNo"); return (Criteria) this; } public Criteria andCarNoNotBetween(String value1, String value2) { addCriterion("car_no not between", value1, value2, "carNo"); return (Criteria) this; } public Criteria andCarFrameNoIsNull() { addCriterion("car_frame_no is null"); return (Criteria) this; } public Criteria andCarFrameNoIsNotNull() { addCriterion("car_frame_no is not null"); return (Criteria) this; } public Criteria andCarFrameNoEqualTo(String value) { addCriterion("car_frame_no =", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoNotEqualTo(String value) { addCriterion("car_frame_no <>", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoGreaterThan(String value) { addCriterion("car_frame_no >", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoGreaterThanOrEqualTo(String value) { addCriterion("car_frame_no >=", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoLessThan(String value) { addCriterion("car_frame_no <", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoLessThanOrEqualTo(String value) { addCriterion("car_frame_no <=", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoLike(String value) { addCriterion("car_frame_no like", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoNotLike(String value) { addCriterion("car_frame_no not like", value, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoIn(List<String> values) { addCriterion("car_frame_no in", values, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoNotIn(List<String> values) { addCriterion("car_frame_no not in", values, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoBetween(String value1, String value2) { addCriterion("car_frame_no between", value1, value2, "carFrameNo"); return (Criteria) this; } public Criteria andCarFrameNoNotBetween(String value1, String value2) { addCriterion("car_frame_no not between", value1, value2, "carFrameNo"); return (Criteria) this; } public Criteria andCarEngineIsNull() { addCriterion("car_engine is null"); return (Criteria) this; } public Criteria andCarEngineIsNotNull() { addCriterion("car_engine is not null"); return (Criteria) this; } public Criteria andCarEngineEqualTo(String value) { addCriterion("car_engine =", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineNotEqualTo(String value) { addCriterion("car_engine <>", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineGreaterThan(String value) { addCriterion("car_engine >", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineGreaterThanOrEqualTo(String value) { addCriterion("car_engine >=", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineLessThan(String value) { addCriterion("car_engine <", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineLessThanOrEqualTo(String value) { addCriterion("car_engine <=", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineLike(String value) { addCriterion("car_engine like", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineNotLike(String value) { addCriterion("car_engine not like", value, "carEngine"); return (Criteria) this; } public Criteria andCarEngineIn(List<String> values) { addCriterion("car_engine in", values, "carEngine"); return (Criteria) this; } public Criteria andCarEngineNotIn(List<String> values) { addCriterion("car_engine not in", values, "carEngine"); return (Criteria) this; } public Criteria andCarEngineBetween(String value1, String value2) { addCriterion("car_engine between", value1, value2, "carEngine"); return (Criteria) this; } public Criteria andCarEngineNotBetween(String value1, String value2) { addCriterion("car_engine not between", value1, value2, "carEngine"); return (Criteria) this; } public Criteria andOnNoTimeIsNull() { addCriterion("on_no_time is null"); return (Criteria) this; } public Criteria andOnNoTimeIsNotNull() { addCriterion("on_no_time is not null"); return (Criteria) this; } public Criteria andOnNoTimeEqualTo(Date value) { addCriterion("on_no_time =", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeNotEqualTo(Date value) { addCriterion("on_no_time <>", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeGreaterThan(Date value) { addCriterion("on_no_time >", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeGreaterThanOrEqualTo(Date value) { addCriterion("on_no_time >=", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeLessThan(Date value) { addCriterion("on_no_time <", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeLessThanOrEqualTo(Date value) { addCriterion("on_no_time <=", value, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeIn(List<Date> values) { addCriterion("on_no_time in", values, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeNotIn(List<Date> values) { addCriterion("on_no_time not in", values, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeBetween(Date value1, Date value2) { addCriterion("on_no_time between", value1, value2, "onNoTime"); return (Criteria) this; } public Criteria andOnNoTimeNotBetween(Date value1, Date value2) { addCriterion("on_no_time not between", value1, value2, "onNoTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeIsNull() { addCriterion("first_insurance_time is null"); return (Criteria) this; } public Criteria andFirstInsuranceTimeIsNotNull() { addCriterion("first_insurance_time is not null"); return (Criteria) this; } public Criteria andFirstInsuranceTimeEqualTo(Date value) { addCriterion("first_insurance_time =", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeNotEqualTo(Date value) { addCriterion("first_insurance_time <>", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeGreaterThan(Date value) { addCriterion("first_insurance_time >", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeGreaterThanOrEqualTo(Date value) { addCriterion("first_insurance_time >=", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeLessThan(Date value) { addCriterion("first_insurance_time <", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeLessThanOrEqualTo(Date value) { addCriterion("first_insurance_time <=", value, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeIn(List<Date> values) { addCriterion("first_insurance_time in", values, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeNotIn(List<Date> values) { addCriterion("first_insurance_time not in", values, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeBetween(Date value1, Date value2) { addCriterion("first_insurance_time between", value1, value2, "firstInsuranceTime"); return (Criteria) this; } public Criteria andFirstInsuranceTimeNotBetween(Date value1, Date value2) { addCriterion("first_insurance_time not between", value1, value2, "firstInsuranceTime"); return (Criteria) this; } public Criteria andOldCompactNameIsNull() { addCriterion("old_compact_name is null"); return (Criteria) this; } public Criteria andOldCompactNameIsNotNull() { addCriterion("old_compact_name is not null"); return (Criteria) this; } public Criteria andOldCompactNameEqualTo(String value) { addCriterion("old_compact_name =", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameNotEqualTo(String value) { addCriterion("old_compact_name <>", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameGreaterThan(String value) { addCriterion("old_compact_name >", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameGreaterThanOrEqualTo(String value) { addCriterion("old_compact_name >=", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameLessThan(String value) { addCriterion("old_compact_name <", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameLessThanOrEqualTo(String value) { addCriterion("old_compact_name <=", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameLike(String value) { addCriterion("old_compact_name like", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameNotLike(String value) { addCriterion("old_compact_name not like", value, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameIn(List<String> values) { addCriterion("old_compact_name in", values, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameNotIn(List<String> values) { addCriterion("old_compact_name not in", values, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameBetween(String value1, String value2) { addCriterion("old_compact_name between", value1, value2, "oldCompactName"); return (Criteria) this; } public Criteria andOldCompactNameNotBetween(String value1, String value2) { addCriterion("old_compact_name not between", value1, value2, "oldCompactName"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andValidIsNull() { addCriterion("valid is null"); return (Criteria) this; } public Criteria andValidIsNotNull() { addCriterion("valid is not null"); return (Criteria) this; } public Criteria andValidEqualTo(String value) { addCriterion("valid =", value, "valid"); return (Criteria) this; } public Criteria andValidNotEqualTo(String value) { addCriterion("valid <>", value, "valid"); return (Criteria) this; } public Criteria andValidGreaterThan(String value) { addCriterion("valid >", value, "valid"); return (Criteria) this; } public Criteria andValidGreaterThanOrEqualTo(String value) { addCriterion("valid >=", value, "valid"); return (Criteria) this; } public Criteria andValidLessThan(String value) { addCriterion("valid <", value, "valid"); return (Criteria) this; } public Criteria andValidLessThanOrEqualTo(String value) { addCriterion("valid <=", value, "valid"); return (Criteria) this; } public Criteria andValidLike(String value) { addCriterion("valid like", value, "valid"); return (Criteria) this; } public Criteria andValidNotLike(String value) { addCriterion("valid not like", value, "valid"); return (Criteria) this; } public Criteria andValidIn(List<String> values) { addCriterion("valid in", values, "valid"); return (Criteria) this; } public Criteria andValidNotIn(List<String> values) { addCriterion("valid not in", values, "valid"); return (Criteria) this; } public Criteria andValidBetween(String value1, String value2) { addCriterion("valid between", value1, value2, "valid"); return (Criteria) this; } public Criteria andValidNotBetween(String value1, String value2) { addCriterion("valid not between", value1, value2, "valid"); return (Criteria) this; } public Criteria andDelFlagIsNull() { addCriterion("del_flag is null"); return (Criteria) this; } public Criteria andDelFlagIsNotNull() { addCriterion("del_flag is not null"); return (Criteria) this; } public Criteria andDelFlagEqualTo(String value) { addCriterion("del_flag =", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotEqualTo(String value) { addCriterion("del_flag <>", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagGreaterThan(String value) { addCriterion("del_flag >", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagGreaterThanOrEqualTo(String value) { addCriterion("del_flag >=", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagLessThan(String value) { addCriterion("del_flag <", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagLessThanOrEqualTo(String value) { addCriterion("del_flag <=", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagLike(String value) { addCriterion("del_flag like", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotLike(String value) { addCriterion("del_flag not like", value, "delFlag"); return (Criteria) this; } public Criteria andDelFlagIn(List<String> values) { addCriterion("del_flag in", values, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotIn(List<String> values) { addCriterion("del_flag not in", values, "delFlag"); return (Criteria) this; } public Criteria andDelFlagBetween(String value1, String value2) { addCriterion("del_flag between", value1, value2, "delFlag"); return (Criteria) this; } public Criteria andDelFlagNotBetween(String value1, String value2) { addCriterion("del_flag not between", value1, value2, "delFlag"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
38,997
0.583378
0.580096
1,171
32.303158
26.511835
102
false
false
0
0
0
0
0
0
0.743809
false
false
3
98d8a0b9fe84f2408c60ccfe7b15fb6fb04aec86
12,008,728,567,288
1d67508afa4db281b4cb08ce25cfcb753124e0aa
/src/SSF/Net/RoutingInfoIC.java
d86fb6834cd53cab655547b6e2f1743b87fc66c9
[]
no_license
gusa1120/SSFNET5
https://github.com/gusa1120/SSFNET5
d0459c91ae34b1f15c85bfee3bd95e58acbb9978
170459439227a4d8a037e200c7c6d31aa498939e
refs/heads/master
2016-09-05T11:57:49.979000
2015-03-01T08:44:11
2015-03-01T08:44:11
31,491,235
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package SSF.Net; import SSF.Net.Util.*; /** Forwarding data stored in a node in a RoutingTable (in core). */ public class RoutingInfoIC extends RoutingInfo { /** Destination IP address prefix. */ protected String DEST_IP; /** IP address of the node that's the next hop */ protected int NEXT_HOP_IP; /** Prefix length of the IP address. */ /** Reference to the network interface that gets us to the next hop */ protected NIC INTERFACE; /** Cost metric -- unused for the moment */ protected int COST; /** Administrative Distance -- for tiebreaking among routing protocols */ protected int ADIST; /** Linked list of routes to the same destination IP address */ protected RoutingInfoIC nextRoute; /** Name of the routing protocol where this route originated. */ protected String PROTOCOL; public RoutingInfoIC(String dest_ip, int next_hop, NIC iface, int cost, int adist, String src) { DEST_IP = dest_ip; NEXT_HOP_IP = next_hop; INTERFACE = iface; COST = cost; ADIST = adist; nextRoute = null; PROTOCOL = src; } public final NIC next_hop_interface() { return INTERFACE; } public final String dest_ip() { return DEST_IP; } public final int next_hop_ip() { return NEXT_HOP_IP; } /** Returns the cost. */ public int cost() { return COST; } /** Returns the administrative distance. */ public int adist() { return ADIST; } public final String getProtocol() { return PROTOCOL; } public RoutingInfo nextRoute() { return nextRoute; } /** Insert one or more new routes into the linked list, sorted primarily by * administrative distance and secondarily by cost. Return the new head * route (either the new route, or this route, whichever is lower-cost). */ public RoutingInfo addRoute(RoutingInfo newRte) { RoutingInfoIC newRoute = (RoutingInfoIC)newRte; RoutingInfo ret = null; RoutingInfoIC moreRoutes = (RoutingInfoIC)newRoute.nextRoute; newRoute.nextRoute = null; if (newRoute.ADIST<ADIST || (newRoute.ADIST==ADIST && newRoute.COST<=COST)) { newRoute.nextRoute = this; ret = newRoute; } else { nextRoute = (RoutingInfoIC)(nextRoute==null?newRoute: nextRoute.addRoute(newRoute)); ret = this; } return (moreRoutes==null?ret:ret.addRoute(moreRoutes)); } /** Remove the given route, and return the new head route (either this * route, or if this route was removed, the next route). */ public RoutingInfo removeRoute(RoutingInfo oldRoute) { if (oldRoute.equals(this)) { RoutingInfo ret = nextRoute; nextRoute = null; return ret; } else { nextRoute = (RoutingInfoIC)nextRoute.removeRoute(oldRoute); return this; } } /** Remove routes from the given protocol, and return the new head route * (either this route, or if this route was removed, the next route). * The special protocol name "*" matches all protocols. If the list * argument is non-null, insert deleted routes into the list. */ public RoutingInfo removeRoutesFrom(String protocol) { if ("*".equals(protocol)||(null!=PROTOCOL && PROTOCOL.equals(protocol))) return (null==nextRoute?null:nextRoute.removeRoutesFrom(protocol)); else { if (null!=nextRoute) nextRoute = (RoutingInfoIC)nextRoute.removeRoutesFrom(protocol); return this; } } /** Return the list of routes inserted by the given protocol. * The special protocol name "*" matches all protocols. */ public RoutingInfo[] findRoutesFrom(String protocol) { int len =0; for (RoutingInfoIC rif = this; null!=rif; rif=rif.nextRoute) if ("*".equals(protocol) || protocol.equals(rif.PROTOCOL)) len++; RoutingInfo[] ret = new RoutingInfo[len]; len=0; for (RoutingInfoIC rif = this; null!=rif; rif=rif.nextRoute) if ("*".equals(protocol) || protocol.equals(rif.PROTOCOL)) ret[len++]=rif; return ret; } /** Find the first (best) route inserted by the named protocol. */ public RoutingInfo findRouteFrom(String protocol) { if ("*".equals(protocol) || protocol.equals(PROTOCOL)) return this; else return (null==nextRoute?null:nextRoute.findRouteFrom(protocol)); } /** * Returns the routing information as a string. * * @return the routing information as a string */ public String toString() { return toString(false, null); } /** * Returns the routing information as a string. * * @param usenhi Whether to use the NHI or IP prefix address format. * @param topnet The top-level Net in the simulation. * @return the routing information as a string */ public String toString(boolean usenhi, Net topnet) { if (usenhi) { String nexthop = null; nexthop = topnet.ip_to_nhi(IP_s.IPtoString(next_hop_ip())); if (nexthop == null) { nexthop = "none"; } String dest = topnet.ip_to_nhi(DEST_IP); if (dest == null || dest.indexOf("-") >= 0) { // there was no NHI equivalent for the IP prefix dest = DEST_IP; } String ws = " "; // 17 spaces return (dest + ws.substring(0,Math.max(17-dest.length(),1)) + " nxt=" + nexthop + " cost=" + COST + " adist="+ ADIST + " if=" + topnet.ip_to_nhi(IP_s.IPtoString(next_hop_interface().ipAddr)) + " src=" + PROTOCOL); } else { return ("{dst=" + DEST_IP + " :nxt=" + IP_s.IPtoString(next_hop_ip()) + " :cost=" + COST + " :adist=" + ADIST + " :if=" + next_hop_interface() +" :src=" + PROTOCOL + "}"); } } /** * Converts this routing info into a series of bytes and inserts them into a * given byte array. * * @param bytes A byte array in which to place the results. * @param bindex The index into the given byte array at which to begin * placing the results. * @param usenhi Whether or not to use NHI addressing. * @param topnet The top-level Net in the simulation. * @return the total number of bytes produced by the conversion */ public int toBytes(byte[] bytes, int bindex, boolean usenhi, Net topnet) { int startindex = bindex; if (next_hop_ip() == 0) { bytes[bindex++] = 0; // indicate that next hop is unknown } else { bytes[bindex++] = 1; // indicate that next hop is known } if (usenhi) { if (next_hop_ip() != 0) { String nexthop = topnet.ip_to_nhi(IP_s.IPtoString(next_hop_ip())); bindex += RadixTreeRoutingTable.nhi2bytes(nexthop,bytes,bindex); } bytes[bindex++] = (byte)COST; bytes[bindex++] = (byte)ADIST; bytes[bindex++] = RoutingInfo.encodeSource(PROTOCOL); String iface = topnet.ip_to_nhi(IP_s.IPtoString(next_hop_interface(). ipAddr)); bindex += RadixTreeRoutingTable.nhi2bytes(iface,bytes,bindex); } else { if (next_hop_ip() != 0) { bindex += RadixTreeRoutingTable.ipprefix2bytes(next_hop_ip(),32, bytes,bindex); } bytes[bindex++] = (byte)COST; bytes[bindex++] = (byte)ADIST; bytes[bindex++] = RoutingInfo.encodeSource(PROTOCOL); bindex += RadixTreeRoutingTable.ipprefix2bytes(next_hop_interface(). ipAddr,32,bytes,bindex); } return bindex - startindex; } } // end class RoutingInfoIC /*= =*/ /*= Copyright (c) 1997--2000 SSF Research Network =*/ /*= =*/ /*= SSFNet is open source software, distributed under the GNU General =*/ /*= Public License. See the file COPYING in the 'doc' subdirectory of =*/ /*= the SSFNet distribution, or http://www.fsf.org/copyleft/gpl.html =*/ /*= =*/
UTF-8
Java
8,191
java
RoutingInfoIC.java
Java
[]
null
[]
package SSF.Net; import SSF.Net.Util.*; /** Forwarding data stored in a node in a RoutingTable (in core). */ public class RoutingInfoIC extends RoutingInfo { /** Destination IP address prefix. */ protected String DEST_IP; /** IP address of the node that's the next hop */ protected int NEXT_HOP_IP; /** Prefix length of the IP address. */ /** Reference to the network interface that gets us to the next hop */ protected NIC INTERFACE; /** Cost metric -- unused for the moment */ protected int COST; /** Administrative Distance -- for tiebreaking among routing protocols */ protected int ADIST; /** Linked list of routes to the same destination IP address */ protected RoutingInfoIC nextRoute; /** Name of the routing protocol where this route originated. */ protected String PROTOCOL; public RoutingInfoIC(String dest_ip, int next_hop, NIC iface, int cost, int adist, String src) { DEST_IP = dest_ip; NEXT_HOP_IP = next_hop; INTERFACE = iface; COST = cost; ADIST = adist; nextRoute = null; PROTOCOL = src; } public final NIC next_hop_interface() { return INTERFACE; } public final String dest_ip() { return DEST_IP; } public final int next_hop_ip() { return NEXT_HOP_IP; } /** Returns the cost. */ public int cost() { return COST; } /** Returns the administrative distance. */ public int adist() { return ADIST; } public final String getProtocol() { return PROTOCOL; } public RoutingInfo nextRoute() { return nextRoute; } /** Insert one or more new routes into the linked list, sorted primarily by * administrative distance and secondarily by cost. Return the new head * route (either the new route, or this route, whichever is lower-cost). */ public RoutingInfo addRoute(RoutingInfo newRte) { RoutingInfoIC newRoute = (RoutingInfoIC)newRte; RoutingInfo ret = null; RoutingInfoIC moreRoutes = (RoutingInfoIC)newRoute.nextRoute; newRoute.nextRoute = null; if (newRoute.ADIST<ADIST || (newRoute.ADIST==ADIST && newRoute.COST<=COST)) { newRoute.nextRoute = this; ret = newRoute; } else { nextRoute = (RoutingInfoIC)(nextRoute==null?newRoute: nextRoute.addRoute(newRoute)); ret = this; } return (moreRoutes==null?ret:ret.addRoute(moreRoutes)); } /** Remove the given route, and return the new head route (either this * route, or if this route was removed, the next route). */ public RoutingInfo removeRoute(RoutingInfo oldRoute) { if (oldRoute.equals(this)) { RoutingInfo ret = nextRoute; nextRoute = null; return ret; } else { nextRoute = (RoutingInfoIC)nextRoute.removeRoute(oldRoute); return this; } } /** Remove routes from the given protocol, and return the new head route * (either this route, or if this route was removed, the next route). * The special protocol name "*" matches all protocols. If the list * argument is non-null, insert deleted routes into the list. */ public RoutingInfo removeRoutesFrom(String protocol) { if ("*".equals(protocol)||(null!=PROTOCOL && PROTOCOL.equals(protocol))) return (null==nextRoute?null:nextRoute.removeRoutesFrom(protocol)); else { if (null!=nextRoute) nextRoute = (RoutingInfoIC)nextRoute.removeRoutesFrom(protocol); return this; } } /** Return the list of routes inserted by the given protocol. * The special protocol name "*" matches all protocols. */ public RoutingInfo[] findRoutesFrom(String protocol) { int len =0; for (RoutingInfoIC rif = this; null!=rif; rif=rif.nextRoute) if ("*".equals(protocol) || protocol.equals(rif.PROTOCOL)) len++; RoutingInfo[] ret = new RoutingInfo[len]; len=0; for (RoutingInfoIC rif = this; null!=rif; rif=rif.nextRoute) if ("*".equals(protocol) || protocol.equals(rif.PROTOCOL)) ret[len++]=rif; return ret; } /** Find the first (best) route inserted by the named protocol. */ public RoutingInfo findRouteFrom(String protocol) { if ("*".equals(protocol) || protocol.equals(PROTOCOL)) return this; else return (null==nextRoute?null:nextRoute.findRouteFrom(protocol)); } /** * Returns the routing information as a string. * * @return the routing information as a string */ public String toString() { return toString(false, null); } /** * Returns the routing information as a string. * * @param usenhi Whether to use the NHI or IP prefix address format. * @param topnet The top-level Net in the simulation. * @return the routing information as a string */ public String toString(boolean usenhi, Net topnet) { if (usenhi) { String nexthop = null; nexthop = topnet.ip_to_nhi(IP_s.IPtoString(next_hop_ip())); if (nexthop == null) { nexthop = "none"; } String dest = topnet.ip_to_nhi(DEST_IP); if (dest == null || dest.indexOf("-") >= 0) { // there was no NHI equivalent for the IP prefix dest = DEST_IP; } String ws = " "; // 17 spaces return (dest + ws.substring(0,Math.max(17-dest.length(),1)) + " nxt=" + nexthop + " cost=" + COST + " adist="+ ADIST + " if=" + topnet.ip_to_nhi(IP_s.IPtoString(next_hop_interface().ipAddr)) + " src=" + PROTOCOL); } else { return ("{dst=" + DEST_IP + " :nxt=" + IP_s.IPtoString(next_hop_ip()) + " :cost=" + COST + " :adist=" + ADIST + " :if=" + next_hop_interface() +" :src=" + PROTOCOL + "}"); } } /** * Converts this routing info into a series of bytes and inserts them into a * given byte array. * * @param bytes A byte array in which to place the results. * @param bindex The index into the given byte array at which to begin * placing the results. * @param usenhi Whether or not to use NHI addressing. * @param topnet The top-level Net in the simulation. * @return the total number of bytes produced by the conversion */ public int toBytes(byte[] bytes, int bindex, boolean usenhi, Net topnet) { int startindex = bindex; if (next_hop_ip() == 0) { bytes[bindex++] = 0; // indicate that next hop is unknown } else { bytes[bindex++] = 1; // indicate that next hop is known } if (usenhi) { if (next_hop_ip() != 0) { String nexthop = topnet.ip_to_nhi(IP_s.IPtoString(next_hop_ip())); bindex += RadixTreeRoutingTable.nhi2bytes(nexthop,bytes,bindex); } bytes[bindex++] = (byte)COST; bytes[bindex++] = (byte)ADIST; bytes[bindex++] = RoutingInfo.encodeSource(PROTOCOL); String iface = topnet.ip_to_nhi(IP_s.IPtoString(next_hop_interface(). ipAddr)); bindex += RadixTreeRoutingTable.nhi2bytes(iface,bytes,bindex); } else { if (next_hop_ip() != 0) { bindex += RadixTreeRoutingTable.ipprefix2bytes(next_hop_ip(),32, bytes,bindex); } bytes[bindex++] = (byte)COST; bytes[bindex++] = (byte)ADIST; bytes[bindex++] = RoutingInfo.encodeSource(PROTOCOL); bindex += RadixTreeRoutingTable.ipprefix2bytes(next_hop_interface(). ipAddr,32,bytes,bindex); } return bindex - startindex; } } // end class RoutingInfoIC /*= =*/ /*= Copyright (c) 1997--2000 SSF Research Network =*/ /*= =*/ /*= SSFNet is open source software, distributed under the GNU General =*/ /*= Public License. See the file COPYING in the 'doc' subdirectory of =*/ /*= the SSFNet distribution, or http://www.fsf.org/copyleft/gpl.html =*/ /*= =*/
8,191
0.596875
0.593212
244
32.569672
27.107845
79
false
false
0
0
0
0
0
0
0.586066
false
false
3
bae92c6cc0cfdcb440546c0a31ecf37e3db1e23a
24,043,226,932,640
0e7a84d82453368fdb57b7b5a37676a33186a7f0
/src/com/company/DayFour.java
0f915cf1e732306c42547c37d698337d5a4ea672
[]
no_license
dimauchitjavu/LearningJava
https://github.com/dimauchitjavu/LearningJava
43902596d5ce9b9b5cdb226a5d6e8912c9462694
ec9c21215ae84ce4f120f973a2a46c8d2c026c6e
refs/heads/master
2023-02-22T17:41:02.276000
2021-01-25T17:13:13
2021-01-25T17:13:13
311,498,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import java.util.Scanner; import java.util.stream.IntStream; public class DayFour { static void taskFour() { Scanner in = new Scanner(System.in); System.out.println("Please enter task number: "); String msg = in.nextLine(); int task = Integer.parseInt(msg); switch (task) { case 1: Scanner intScan = new Scanner(System.in); System.out.println("Please enter length of array: "); int n = intScan.nextInt(); int[] randArray = new int[n]; System.out.println("Cоздан массив"); int nOnes = 0; int nMoreThanEight = 0; int nEven = 0; int nUneven = 0; for(int i = 0;i < n;i++){ randArray[i] = ThreadLocalRandom.current().nextInt(0, 11); System.out.print(randArray[i] + " "); if(randArray[i] == 1){ nOnes++; }else if(randArray[i] > 8){ nMoreThanEight++; } if(randArray[i]%2 == 0){ nEven++; }else{ nUneven++; } } System.out.println("\nКоличество чисел больше 8: " + nMoreThanEight); System.out.println("Количество чисел равных 1: " + nOnes); System.out.println("Количество четных чисел: " + nEven); System.out.println("Количество нечетных чисел: " + nUneven); System.out.println("Сумма всех элементов массива: " + IntStream.of(randArray).sum()); break; case 2: int[] randArrayHundred = new int[100]; for(int i = 0;i < 100;i++) { randArrayHundred[i] = ThreadLocalRandom.current().nextInt(0, 1001); } int nZeroSum = 0; int nZeroNum = 0; int hundredMin = 1001; int hundredMax = 0; for (int i: randArrayHundred) { if(i%10 == 0){ nZeroNum++; nZeroSum+=i; } if (hundredMax < i){ hundredMax = i; } if(hundredMin > i){ hundredMin = i; } } System.out.println("Количество чисел кратных 10: " + nZeroNum); System.out.println("Сумма чисел кратных 10: " + nZeroSum); System.out.println("Максимум: " + hundredMax); System.out.println("Минимум: " + hundredMin); break; case 3: int[][] twoDMass = new int[12][8]; for (int i = 0; i < 12; i++) { for (int j = 0; j < 8; j++) { twoDMass[i][j] = ThreadLocalRandom.current().nextInt(0, 51); System.out.print(twoDMass[i][j] + " "); } System.out.println(); } int max = 0; for (int[] line: twoDMass) { if(IntStream.of(line).sum() > max){ max = IntStream.of(line).sum(); } } System.out.println("Max " + max); break; case 4: int[] triples = new int[100]; for (int j = 0; j < 100; j++) { triples[j] = ThreadLocalRandom.current().nextInt(0, 10001); System.out.print(triples[j] + " "); } int[] triplesSum = new int[100]; int arrMax = 0; int arrMaxInd = 0; for (int j = 1; j < 99; j++) { triplesSum[j] = triples[j - 1] + triples[j] + triples[j + 1]; if(arrMax < triplesSum[j]){ arrMax = triplesSum[j]; arrMaxInd = j-1; } } System.out.println(); System.out.println("Максимум: " + arrMax); System.out.println("Индекс максимума: " + arrMaxInd); break; default: System.out.println("Wrong task!"); break; } } }
UTF-8
Java
4,806
java
DayFour.java
Java
[]
null
[]
package com.company; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import java.util.Scanner; import java.util.stream.IntStream; public class DayFour { static void taskFour() { Scanner in = new Scanner(System.in); System.out.println("Please enter task number: "); String msg = in.nextLine(); int task = Integer.parseInt(msg); switch (task) { case 1: Scanner intScan = new Scanner(System.in); System.out.println("Please enter length of array: "); int n = intScan.nextInt(); int[] randArray = new int[n]; System.out.println("Cоздан массив"); int nOnes = 0; int nMoreThanEight = 0; int nEven = 0; int nUneven = 0; for(int i = 0;i < n;i++){ randArray[i] = ThreadLocalRandom.current().nextInt(0, 11); System.out.print(randArray[i] + " "); if(randArray[i] == 1){ nOnes++; }else if(randArray[i] > 8){ nMoreThanEight++; } if(randArray[i]%2 == 0){ nEven++; }else{ nUneven++; } } System.out.println("\nКоличество чисел больше 8: " + nMoreThanEight); System.out.println("Количество чисел равных 1: " + nOnes); System.out.println("Количество четных чисел: " + nEven); System.out.println("Количество нечетных чисел: " + nUneven); System.out.println("Сумма всех элементов массива: " + IntStream.of(randArray).sum()); break; case 2: int[] randArrayHundred = new int[100]; for(int i = 0;i < 100;i++) { randArrayHundred[i] = ThreadLocalRandom.current().nextInt(0, 1001); } int nZeroSum = 0; int nZeroNum = 0; int hundredMin = 1001; int hundredMax = 0; for (int i: randArrayHundred) { if(i%10 == 0){ nZeroNum++; nZeroSum+=i; } if (hundredMax < i){ hundredMax = i; } if(hundredMin > i){ hundredMin = i; } } System.out.println("Количество чисел кратных 10: " + nZeroNum); System.out.println("Сумма чисел кратных 10: " + nZeroSum); System.out.println("Максимум: " + hundredMax); System.out.println("Минимум: " + hundredMin); break; case 3: int[][] twoDMass = new int[12][8]; for (int i = 0; i < 12; i++) { for (int j = 0; j < 8; j++) { twoDMass[i][j] = ThreadLocalRandom.current().nextInt(0, 51); System.out.print(twoDMass[i][j] + " "); } System.out.println(); } int max = 0; for (int[] line: twoDMass) { if(IntStream.of(line).sum() > max){ max = IntStream.of(line).sum(); } } System.out.println("Max " + max); break; case 4: int[] triples = new int[100]; for (int j = 0; j < 100; j++) { triples[j] = ThreadLocalRandom.current().nextInt(0, 10001); System.out.print(triples[j] + " "); } int[] triplesSum = new int[100]; int arrMax = 0; int arrMaxInd = 0; for (int j = 1; j < 99; j++) { triplesSum[j] = triples[j - 1] + triples[j] + triples[j + 1]; if(arrMax < triplesSum[j]){ arrMax = triplesSum[j]; arrMaxInd = j-1; } } System.out.println(); System.out.println("Максимум: " + arrMax); System.out.println("Индекс максимума: " + arrMaxInd); break; default: System.out.println("Wrong task!"); break; } } }
4,806
0.411114
0.393749
114
39.412281
20.341303
101
false
false
0
0
0
0
0
0
0.736842
false
false
3
5ca95787f90164b40609ad330f1da8f4758f7955
23,184,233,480,044
a247e5533ff8133f96842fdb4d369e55d35fdef6
/src/main/java/yuzunyannn/elementalsorcery/explore/StarPrays.java
67835d424098aee1776896ee061acd681f3623de
[]
no_license
Yuzunyannn/ElementalSorcery
https://github.com/Yuzunyannn/ElementalSorcery
76a4d37319e68fbca64a97cbe9673928008f1a85
1457d81ea41114363a894202ae75ae4ca51e1360
refs/heads/master
2023-08-31T13:21:52.185000
2023-08-19T12:09:52
2023-08-19T12:09:52
183,849,638
13
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package yuzunyannn.elementalsorcery.explore; import java.util.ArrayList; import java.util.List; import yuzunyannn.elementalsorcery.api.tile.IStarPray; public class StarPrays { public static final List<IStarPray> prays = new ArrayList<>(); static { prays.add(new StarPrayMeal()); prays.add(new StarPrayHeal()); prays.add(new StarPrayTool()); prays.add(new StarPrayRepair()); prays.add(new StarPrayBattle()); prays.add(new StarPrayBackHome()); prays.add(new StarPrayEnchantment()); prays.add(new StarPrayItemChange()); prays.add(new StarPrayGrimoirePotent()); } }
UTF-8
Java
613
java
StarPrays.java
Java
[]
null
[]
package yuzunyannn.elementalsorcery.explore; import java.util.ArrayList; import java.util.List; import yuzunyannn.elementalsorcery.api.tile.IStarPray; public class StarPrays { public static final List<IStarPray> prays = new ArrayList<>(); static { prays.add(new StarPrayMeal()); prays.add(new StarPrayHeal()); prays.add(new StarPrayTool()); prays.add(new StarPrayRepair()); prays.add(new StarPrayBattle()); prays.add(new StarPrayBackHome()); prays.add(new StarPrayEnchantment()); prays.add(new StarPrayItemChange()); prays.add(new StarPrayGrimoirePotent()); } }
613
0.717781
0.717781
24
23.541666
19.152849
63
false
false
0
0
0
0
0
0
1.458333
false
false
3
e692dec1b8fe3c510dbff823fb9f0624cd60aa37
29,145,648,119,570
19ff738d3b92c7dcf9e78b92fd83d32a764d8fd3
/checkin/check-in-manager/src/main/java/com/hz/business/base/pojo/User.java
6ab98fd10fa7dc70d4b6ce698793c5575e5ae2b5
[]
no_license
hz656765117/testmavenmodul
https://github.com/hz656765117/testmavenmodul
46cd0a2098bc6bb5af82924eea84cab674992a39
758bdb31c537f950a1b5c7bd975c2fa2063770cb
refs/heads/master
2021-01-11T23:31:46.441000
2017-01-11T10:00:23
2017-01-11T10:00:23
78,593,164
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hz.business.base.pojo; import java.io.Serializable; public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private Integer id; private String name; private String pwd; private Integer gender; private String stuNo; private String picUrl; private String tel; private String email; private String school; private String createTime; private String updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd == null ? null : pwd.trim(); } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public String getStuNo() { return stuNo; } public void setStuNo(String stuNo) { this.stuNo = stuNo == null ? null : stuNo.trim(); } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl == null ? null : picUrl.trim(); } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel == null ? null : tel.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getSchool() { return school; } public void setSchool(String school) { this.school = school == null ? null : school.trim(); } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime == null ? null : createTime.trim(); } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime == null ? null : updateTime.trim(); } }
UTF-8
Java
2,286
java
User.java
Java
[]
null
[]
package com.hz.business.base.pojo; import java.io.Serializable; public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private Integer id; private String name; private String pwd; private Integer gender; private String stuNo; private String picUrl; private String tel; private String email; private String school; private String createTime; private String updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd == null ? null : pwd.trim(); } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public String getStuNo() { return stuNo; } public void setStuNo(String stuNo) { this.stuNo = stuNo == null ? null : stuNo.trim(); } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl == null ? null : picUrl.trim(); } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel == null ? null : tel.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getSchool() { return school; } public void setSchool(String school) { this.school = school == null ? null : school.trim(); } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime == null ? null : createTime.trim(); } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime == null ? null : updateTime.trim(); } }
2,286
0.587052
0.586614
120
18.058332
18.840248
72
false
false
0
0
0
0
0
0
0.333333
false
false
3
4ae40b0e8008fa3907fe671cfcd8625cda518eed
15,753,940,099,882
e53397a3c2c85be9e8d6e7d8f374fe2c35417f8a
/library_hw11_webflux/src/main/java/ru/avalieva/com/library_hw11_webflux/repository/GenreRepository.java
416e53ea9cd6402cfd29ed027b9834cd80748825
[]
no_license
alfiyashka/otus_spring
https://github.com/alfiyashka/otus_spring
79f096cc832e75702e2f67a9186f6a05b3eef209
31a43c785ad94604a8a4b9b816f99f1f5b81a019
refs/heads/master
2022-07-17T21:02:44.004000
2020-05-29T19:57:07
2020-05-29T19:57:07
224,483,926
0
0
null
false
2022-06-21T03:11:49
2019-11-27T17:31:30
2020-05-29T19:57:12
2022-06-21T03:11:48
373
0
0
7
Java
false
false
package ru.avalieva.com.library_hw11_webflux.repository; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import reactor.core.publisher.Mono; import ru.avalieva.com.library_hw11_webflux.domain.Genre; public interface GenreRepository extends ReactiveMongoRepository<Genre, String> { Mono<Genre> findByGenreName(String name); }
UTF-8
Java
360
java
GenreRepository.java
Java
[]
null
[]
package ru.avalieva.com.library_hw11_webflux.repository; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import reactor.core.publisher.Mono; import ru.avalieva.com.library_hw11_webflux.domain.Genre; public interface GenreRepository extends ReactiveMongoRepository<Genre, String> { Mono<Genre> findByGenreName(String name); }
360
0.830556
0.819444
10
35
30.938648
81
false
false
0
0
0
0
0
0
0.6
false
false
3
5590a4e8e8e40d62f5863982af907800103bdc00
1,889,785,616,799
6aade2b7c37cc1a6f4f873bf016a3a9bbc3c55d3
/dataStructure/src/线性结构_1数组/二分查找有序.java
966e14fcd1fbd385cd5fc6e7df266bc1cc36b6a5
[]
no_license
zhangyuge3hao/Coding
https://github.com/zhangyuge3hao/Coding
db0b8af426be91838f2a37fbecf8b7e3b247bcb0
4036f093d2e882fcd3ad4c390541f7a026038acc
refs/heads/master
2020-05-04T21:04:37.092000
2019-04-04T09:55:28
2019-04-04T09:55:28
179,463,225
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package 线性结构_1数组; /** * @author 张宇_Yu Zhang E-mail:zy1128zy@163.com * @version 创建时间:2019年3月29日 下午5:28:00 * * */ public class 二分查找有序 {//必须是有序列才可用 public static void main(String[] args) { int[] arr = {1,2,3,4,5,6,7,8}; int target = 8; erfen(arr,target); erfen1(arr,target); } public static void erfen(int[] arr,int target){ /** * 使用begin、mid、end来记录数组边界和查找中间点 */ int len = arr.length; int begin =0,end = len-1; int mid = (begin + end)/2; int times = 0;//记录查找的次数,用于在=len时退出循环,表示全部数字查找完毕 boolean flag = false;//找到退出判断标记 //--------视频错误----若开始的位置和结束的位置重合,或者开始位置在结束位置后面,即:begin >= end //若开始位置在结束位置后面,即:begin > end while(times <= len){ if(arr[mid] < target){ begin = mid+1; }else if(arr[mid] > target){ end = mid-1; }else if(begin > end){ System.out.println("while内,查无此数"); break; } else{ flag = true; break; } mid = (begin + end)/2; times++; } if(flag){ System.out.println("找到这个数"+target+",在下标:"+mid); }else{ System.out.println("查无此数"); } } public static void erfen1(int[] arr,int target){ int len = arr.length; int index = len/2; int times = 0;//记录查找的次数,用于在=len时退出循环,表示全部数字查找完毕 boolean flag = false; while(times<=len){ if(target < arr[index]){ index /= 2; }else if(target > arr[index]){ index += (len - index)/2; }else{ flag = true; break; } times++; } if(flag){ System.out.println("找到这个数"+target+",在下标:"+index); }else{ System.out.println("查无此数"); } } }
GB18030
Java
1,896
java
二分查找有序.java
Java
[ { "context": "package 线性结构_1数组;\n/**\n* @author 张宇_Yu Zhang E-mail:zy1128zy@163.com\n* @version 创建时间:2019年3月29", "end": 43, "score": 0.9928740859031677, "start": 32, "tag": "NAME", "value": "张宇_Yu Zhang" }, { "context": "ackage 线性结构_1数组;\n/**\n* @author 张宇_Yu Zhang E-mail:zy1128zy@163.com\n* @version 创建时间:2019年3月29日 下午5:28:00\n* \n* \n*/\npub", "end": 67, "score": 0.9999248385429382, "start": 51, "tag": "EMAIL", "value": "zy1128zy@163.com" } ]
null
[]
package 线性结构_1数组; /** * @author <NAME> E-mail:<EMAIL> * @version 创建时间:2019年3月29日 下午5:28:00 * * */ public class 二分查找有序 {//必须是有序列才可用 public static void main(String[] args) { int[] arr = {1,2,3,4,5,6,7,8}; int target = 8; erfen(arr,target); erfen1(arr,target); } public static void erfen(int[] arr,int target){ /** * 使用begin、mid、end来记录数组边界和查找中间点 */ int len = arr.length; int begin =0,end = len-1; int mid = (begin + end)/2; int times = 0;//记录查找的次数,用于在=len时退出循环,表示全部数字查找完毕 boolean flag = false;//找到退出判断标记 //--------视频错误----若开始的位置和结束的位置重合,或者开始位置在结束位置后面,即:begin >= end //若开始位置在结束位置后面,即:begin > end while(times <= len){ if(arr[mid] < target){ begin = mid+1; }else if(arr[mid] > target){ end = mid-1; }else if(begin > end){ System.out.println("while内,查无此数"); break; } else{ flag = true; break; } mid = (begin + end)/2; times++; } if(flag){ System.out.println("找到这个数"+target+",在下标:"+mid); }else{ System.out.println("查无此数"); } } public static void erfen1(int[] arr,int target){ int len = arr.length; int index = len/2; int times = 0;//记录查找的次数,用于在=len时退出循环,表示全部数字查找完毕 boolean flag = false; while(times<=len){ if(target < arr[index]){ index /= 2; }else if(target > arr[index]){ index += (len - index)/2; }else{ flag = true; break; } times++; } if(flag){ System.out.println("找到这个数"+target+",在下标:"+index); }else{ System.out.println("查无此数"); } } }
1,878
0.59242
0.564495
70
20.485714
15.360192
63
false
false
0
0
0
0
0
0
2.8
false
false
3
b19657d084cf583dca40d2c77e0969b4b6237bb8
27,109,833,597,861
dc4348c52ce7c2c8027513723110d7a167d50297
/imageCrop/imageCrop.java
2da6258b473eb7302ed6d26ce2520694a72b0227
[]
no_license
AdityaVandan/JavaImageProcessing
https://github.com/AdityaVandan/JavaImageProcessing
a575ee7a38a3e342fcf3ccd5db3da3dec6a4f2dd
8f606fab29b9b69742b433c03b00b41bf3a4c8d4
refs/heads/master
2020-04-30T22:45:10.537000
2019-03-22T11:37:47
2019-03-22T11:37:47
177,127,485
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; import java.io.*; import javax.imageio.*; import java.awt.image.*; class ImageCrop { ImageCrop() { } public BufferedImage getCroppedImage(BufferedImage i,int startX,int startY,int cWidth,int cHeight) { int height,width; int matrix[][]; BufferedImage croppedImage1,croppedImage2,croppedImage3,croppedImage4; try { height=i.getHeight(); width=i.getWidth(); croppedImage=new BufferedImage(cWidth,cHeight,BufferedImage.TYPE_INT_RGB); if(height==cHeight && cWidth==cWidth) return i; if((startX+cWidth)>height || (startY+cHeight)>width) { System.out.println("Image out of Bounds"); return croppedImage; } for(int x=startX;x<(startX+cWidth);x++) { for(int y=startY;y<(startY+cHeight);y++) { croppedImage.setRGB(x-startX,y-startY,i.getRGB(x,y)); //matrix[x-startX][y-startY]=i.getRGB(x,y); } } }catch(Exception ioException) { System.out.println("Crop method Error "+ioException.getMessage()); } return croppedImage; } } class ImageCropExample { public static void main(String gg[]) { if(gg.length<5) return; int x,y,height,width; x=Integer.parseInt(gg[1]); y=Integer.parseInt(gg[2]); width=Integer.parseInt(gg[3]); height=Integer.parseInt(gg[4]); ImageCrop im=new ImageCrop(); BufferedImage inputImage=null; try { File file=new File(gg[0]); inputImage=ImageIO.read(file); File outputFile=new File("CroppedImage.jpg"); BufferedImage outputImage=im.getCroppedImage(inputImage,x,y,height,width); ImageIO.write(outputImage,"jpg",outputFile); }catch(IOException ioException) { System.out.println("Main Function Error"); } } }
UTF-8
Java
1,603
java
imageCrop.java
Java
[]
null
[]
import java.awt.*; import java.io.*; import javax.imageio.*; import java.awt.image.*; class ImageCrop { ImageCrop() { } public BufferedImage getCroppedImage(BufferedImage i,int startX,int startY,int cWidth,int cHeight) { int height,width; int matrix[][]; BufferedImage croppedImage1,croppedImage2,croppedImage3,croppedImage4; try { height=i.getHeight(); width=i.getWidth(); croppedImage=new BufferedImage(cWidth,cHeight,BufferedImage.TYPE_INT_RGB); if(height==cHeight && cWidth==cWidth) return i; if((startX+cWidth)>height || (startY+cHeight)>width) { System.out.println("Image out of Bounds"); return croppedImage; } for(int x=startX;x<(startX+cWidth);x++) { for(int y=startY;y<(startY+cHeight);y++) { croppedImage.setRGB(x-startX,y-startY,i.getRGB(x,y)); //matrix[x-startX][y-startY]=i.getRGB(x,y); } } }catch(Exception ioException) { System.out.println("Crop method Error "+ioException.getMessage()); } return croppedImage; } } class ImageCropExample { public static void main(String gg[]) { if(gg.length<5) return; int x,y,height,width; x=Integer.parseInt(gg[1]); y=Integer.parseInt(gg[2]); width=Integer.parseInt(gg[3]); height=Integer.parseInt(gg[4]); ImageCrop im=new ImageCrop(); BufferedImage inputImage=null; try { File file=new File(gg[0]); inputImage=ImageIO.read(file); File outputFile=new File("CroppedImage.jpg"); BufferedImage outputImage=im.getCroppedImage(inputImage,x,y,height,width); ImageIO.write(outputImage,"jpg",outputFile); }catch(IOException ioException) { System.out.println("Main Function Error"); } } }
1,603
0.720524
0.714286
67
21.925373
22.312111
98
false
false
0
0
0
0
0
0
0.895522
false
false
3
5231a0633274a6f6e8624802ad449da64dde05d8
31,413,390,871,619
60f6d57bff7c33ddef121811ba61b83a0f7b01f8
/blog-blog/src/main/java/com/wang/blog/controller/site/user/SettingsController.java
7dd287b8e39b0022f7a7e0757f90c69369bb5d25
[]
no_license
SpectatorWjx/blog
https://github.com/SpectatorWjx/blog
2e078d69dd4aa49893cca94103d23c6416510f03
b1bd2952cfdf96db3c63cff089b2452a11cc4012
refs/heads/master
2022-09-28T15:48:26.788000
2022-09-22T08:08:47
2022-09-22T08:08:47
289,801,903
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wang.blog.controller.site.user; import com.wang.blog.base.lang.Consts; import com.wang.blog.base.utils.FileKit; import com.wang.blog.controller.site.posts.UploadController; import com.wang.blog.service.SecurityCodeService; import com.wang.blog.service.UserService; import com.wang.blog.service.upyun.UpYunService; import com.wang.blog.vo.AccountProfile; import com.wang.blog.vo.UserVO; import com.wang.blog.controller.BaseController; import com.wang.blog.controller.site.Views; import com.wang.common.common.base.Result; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.Assert; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; /** * @author wjx * @date 2019/08/13 */ @Controller @RequestMapping("/settings") public class SettingsController extends BaseController { @Autowired private UserService userService; @Autowired private UpYunService upYunService; @Autowired private SecurityCodeService securityCodeService; @GetMapping(value = "/profile") public String view(ModelMap model) { AccountProfile profile = getProfile(); UserVO view = userService.get(profile.getId()); view.setAvatar(profile.getAvatar()); model.put("view", view); return view(Views.SETTINGS_PROFILE); } @GetMapping(value = "/email") public String email() { return view(Views.SETTINGS_EMAIL); } @GetMapping(value = "/avatar") public String avatar() { return view(Views.SETTINGS_AVATAR); } @GetMapping(value = "/password") public String password() { return view(Views.SETTINGS_PASSWORD); } @PostMapping(value = "/profile") @ResponseBody public Result updateProfile(String name, String signature, ModelMap model) { AccountProfile profile = getProfile(); try { UserVO user = new UserVO(); user.setId(profile.getId()); user.setName(name); user.setSignature(signature); putProfile(userService.update(user)); // put 最新信息 UserVO view = userService.get(profile.getId()); model.put("view", view); return Result.success(); } catch (Exception e) { return Result.exception(500, e.getMessage()); } } @PostMapping(value = "/email") @ResponseBody public Result updateEmail(String email, String code) { AccountProfile profile = getProfile(); try { Assert.hasLength(email, "请输入邮箱地址"); Assert.hasLength(code, "请输入验证码"); securityCodeService.verify(String.valueOf(profile.getId()), Consts.CODE_BIND, code); // 先执行修改,判断邮箱是否更改,或邮箱是否被人使用 AccountProfile p = userService.updateEmail(profile.getId(), email); putProfile(p); return Result.success(); } catch (Exception e) { return Result.exception(500, e.getMessage()); } } @PostMapping(value = "/password") @ResponseBody public Result updatePassword(String oldPassword, String password) { try { AccountProfile profile = getProfile(); userService.updatePassword(profile.getId(), oldPassword, password); SecurityUtils.getSubject().logout(); return Result.success(); } catch (Exception e) { return Result.exception(500, e.getMessage()); } } @PostMapping("/avatar") @ResponseBody public UploadController.UploadResult updateAvatar(@RequestParam(value = "file", required = false) MultipartFile file){ UploadController.UploadResult result = new UploadController.UploadResult(); AccountProfile profile = getProfile(); ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = servletRequestAttributes.getRequest(); String crop = request.getParameter("crop"); // 检查空 if (null == file || file.isEmpty()) { return result.error(UploadController.errorInfo.get("NOFILE")); } String fileName = file.getOriginalFilename(); // 检查类型 if (!FileKit.checkFileType(fileName)) { return result.error(UploadController.errorInfo.get("TYPE")); } // 保存图片 try { String path = ""; if(siteOptions.getValue("storage_scheme").equals("upyun")) { String bucket_name = siteOptions.getValue("upyun_oss_bucket"); String operator = siteOptions.getValue("upyun_oss_operator"); String operator_key = siteOptions.getValue("upyun_oss_password"); String domain = siteOptions.getValue("upyun_oss_domain"); String src = siteOptions.getValue("upyun_oss_src"); String savePath = upYunService.upload(file, bucket_name, operator, operator_key, src); if(!StringUtils.isEmpty(savePath)){ if (StringUtils.isNotBlank(crop)) { Integer[] imageSize = siteOptions.getIntegerArrayValue(crop, Consts.SEPARATOR_X); int height = ServletRequestUtils.getIntParameter(request, "height", imageSize[1]); int width = ServletRequestUtils.getIntParameter(request, "width", imageSize[0]); path = domain+savePath+"!/both/"+width+"x"+height; } else { path = domain + savePath+"!/both/"+250+"x"+250; } } } AccountProfile user = userService.updateAvatar(profile.getId(), path); putProfile(user); result.ok(UploadController.errorInfo.get("SUCCESS")); result.setName(fileName); result.setPath(path); result.setSize(file.getSize()); } catch (Exception e) { result.error(UploadController.errorInfo.get("UNKNOWN")); } return result; } }
UTF-8
Java
6,652
java
SettingsController.java
Java
[ { "context": "x.servlet.http.HttpServletRequest;\n\n/**\n * @author wjx\n * @date 2019/08/13\n */\n@Controller\n@RequestMappi", "end": 1182, "score": 0.9995745420455933, "start": 1179, "tag": "USERNAME", "value": "wjx" } ]
null
[]
package com.wang.blog.controller.site.user; import com.wang.blog.base.lang.Consts; import com.wang.blog.base.utils.FileKit; import com.wang.blog.controller.site.posts.UploadController; import com.wang.blog.service.SecurityCodeService; import com.wang.blog.service.UserService; import com.wang.blog.service.upyun.UpYunService; import com.wang.blog.vo.AccountProfile; import com.wang.blog.vo.UserVO; import com.wang.blog.controller.BaseController; import com.wang.blog.controller.site.Views; import com.wang.common.common.base.Result; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.Assert; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; /** * @author wjx * @date 2019/08/13 */ @Controller @RequestMapping("/settings") public class SettingsController extends BaseController { @Autowired private UserService userService; @Autowired private UpYunService upYunService; @Autowired private SecurityCodeService securityCodeService; @GetMapping(value = "/profile") public String view(ModelMap model) { AccountProfile profile = getProfile(); UserVO view = userService.get(profile.getId()); view.setAvatar(profile.getAvatar()); model.put("view", view); return view(Views.SETTINGS_PROFILE); } @GetMapping(value = "/email") public String email() { return view(Views.SETTINGS_EMAIL); } @GetMapping(value = "/avatar") public String avatar() { return view(Views.SETTINGS_AVATAR); } @GetMapping(value = "/password") public String password() { return view(Views.SETTINGS_PASSWORD); } @PostMapping(value = "/profile") @ResponseBody public Result updateProfile(String name, String signature, ModelMap model) { AccountProfile profile = getProfile(); try { UserVO user = new UserVO(); user.setId(profile.getId()); user.setName(name); user.setSignature(signature); putProfile(userService.update(user)); // put 最新信息 UserVO view = userService.get(profile.getId()); model.put("view", view); return Result.success(); } catch (Exception e) { return Result.exception(500, e.getMessage()); } } @PostMapping(value = "/email") @ResponseBody public Result updateEmail(String email, String code) { AccountProfile profile = getProfile(); try { Assert.hasLength(email, "请输入邮箱地址"); Assert.hasLength(code, "请输入验证码"); securityCodeService.verify(String.valueOf(profile.getId()), Consts.CODE_BIND, code); // 先执行修改,判断邮箱是否更改,或邮箱是否被人使用 AccountProfile p = userService.updateEmail(profile.getId(), email); putProfile(p); return Result.success(); } catch (Exception e) { return Result.exception(500, e.getMessage()); } } @PostMapping(value = "/password") @ResponseBody public Result updatePassword(String oldPassword, String password) { try { AccountProfile profile = getProfile(); userService.updatePassword(profile.getId(), oldPassword, password); SecurityUtils.getSubject().logout(); return Result.success(); } catch (Exception e) { return Result.exception(500, e.getMessage()); } } @PostMapping("/avatar") @ResponseBody public UploadController.UploadResult updateAvatar(@RequestParam(value = "file", required = false) MultipartFile file){ UploadController.UploadResult result = new UploadController.UploadResult(); AccountProfile profile = getProfile(); ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = servletRequestAttributes.getRequest(); String crop = request.getParameter("crop"); // 检查空 if (null == file || file.isEmpty()) { return result.error(UploadController.errorInfo.get("NOFILE")); } String fileName = file.getOriginalFilename(); // 检查类型 if (!FileKit.checkFileType(fileName)) { return result.error(UploadController.errorInfo.get("TYPE")); } // 保存图片 try { String path = ""; if(siteOptions.getValue("storage_scheme").equals("upyun")) { String bucket_name = siteOptions.getValue("upyun_oss_bucket"); String operator = siteOptions.getValue("upyun_oss_operator"); String operator_key = siteOptions.getValue("upyun_oss_password"); String domain = siteOptions.getValue("upyun_oss_domain"); String src = siteOptions.getValue("upyun_oss_src"); String savePath = upYunService.upload(file, bucket_name, operator, operator_key, src); if(!StringUtils.isEmpty(savePath)){ if (StringUtils.isNotBlank(crop)) { Integer[] imageSize = siteOptions.getIntegerArrayValue(crop, Consts.SEPARATOR_X); int height = ServletRequestUtils.getIntParameter(request, "height", imageSize[1]); int width = ServletRequestUtils.getIntParameter(request, "width", imageSize[0]); path = domain+savePath+"!/both/"+width+"x"+height; } else { path = domain + savePath+"!/both/"+250+"x"+250; } } } AccountProfile user = userService.updateAvatar(profile.getId(), path); putProfile(user); result.ok(UploadController.errorInfo.get("SUCCESS")); result.setName(fileName); result.setPath(path); result.setSize(file.getSize()); } catch (Exception e) { result.error(UploadController.errorInfo.get("UNKNOWN")); } return result; } }
6,652
0.64325
0.639279
169
37.745564
27.208385
131
false
false
0
0
0
0
0
0
0.680473
false
false
3
322ec25912d7ede645f3e377b2716acad268e219
6,210,522,729,757
121afa112028db42a9ae68390740cc1466a7435e
/app/src/main/java/com/inspius/yo_video/activity/CommentActivity.java
fa3a009f97ea159787440b17d82dc7bbc6c7e160
[]
no_license
krishan2890/YoVideo-Android
https://github.com/krishan2890/YoVideo-Android
186a4fc0d8af8004b2f3310e5e5827b3771f4dd5
e0701b85ba2bcd34ae4aaab2d40c31de1ffa0f8c
refs/heads/master
2020-03-15T20:27:32.155000
2017-01-17T12:06:01
2017-01-17T12:06:01
132,333,021
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.inspius.yo_video.activity; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.inputmethod.InputMethodManager; import com.inspius.coreapp.CoreAppActivity; import com.inspius.yo_video.R; import com.inspius.yo_video.app.AppConstant; import com.inspius.yo_video.fragment.CommentFragment; import com.inspius.yo_video.model.VideoModel; import butterknife.ButterKnife; import butterknife.OnClick; public class CommentActivity extends CoreAppActivity { private ProgressDialog loadingDialog; private VideoModel videoModel; @Override protected int getLayoutResourceId() { return R.id.container; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment); ButterKnife.bind(this); if (getIntent() == null) return; if (getIntent().getExtras() == null) return; if (!getIntent().getExtras().containsKey(AppConstant.KEY_BUNDLE_VIDEO)) return; videoModel = (VideoModel) getIntent().getExtras().getSerializable(AppConstant.KEY_BUNDLE_VIDEO); if (videoModel == null) return; setupActionBar(); mHostActivityImplement.addFragment(CommentFragment.newInstance(videoModel), true); } private void setupActionBar() { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); } public void hideKeyBoard() { View view = getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } public void showLoading(String message) { if (isFinishing()) return; if (loadingDialog != null && loadingDialog.isShowing()) return; try { if (loadingDialog == null) { loadingDialog = new ProgressDialog(this); loadingDialog.setCancelable(false); } if (!message.isEmpty()) loadingDialog.setMessage(message); loadingDialog.show(); } catch (Exception e) { e.printStackTrace(); } } public void hideLoading() { if (isFinishing()) return; try { if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.dismiss(); } catch (Exception e) { e.printStackTrace(); } } @OnClick(R.id.imvHeaderBack) void doBack() { onBackPressed(); } @Override public void handleBackPressInThisActivity() { finish(); } }
UTF-8
Java
3,017
java
CommentActivity.java
Java
[]
null
[]
package com.inspius.yo_video.activity; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.inputmethod.InputMethodManager; import com.inspius.coreapp.CoreAppActivity; import com.inspius.yo_video.R; import com.inspius.yo_video.app.AppConstant; import com.inspius.yo_video.fragment.CommentFragment; import com.inspius.yo_video.model.VideoModel; import butterknife.ButterKnife; import butterknife.OnClick; public class CommentActivity extends CoreAppActivity { private ProgressDialog loadingDialog; private VideoModel videoModel; @Override protected int getLayoutResourceId() { return R.id.container; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment); ButterKnife.bind(this); if (getIntent() == null) return; if (getIntent().getExtras() == null) return; if (!getIntent().getExtras().containsKey(AppConstant.KEY_BUNDLE_VIDEO)) return; videoModel = (VideoModel) getIntent().getExtras().getSerializable(AppConstant.KEY_BUNDLE_VIDEO); if (videoModel == null) return; setupActionBar(); mHostActivityImplement.addFragment(CommentFragment.newInstance(videoModel), true); } private void setupActionBar() { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); } public void hideKeyBoard() { View view = getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } public void showLoading(String message) { if (isFinishing()) return; if (loadingDialog != null && loadingDialog.isShowing()) return; try { if (loadingDialog == null) { loadingDialog = new ProgressDialog(this); loadingDialog.setCancelable(false); } if (!message.isEmpty()) loadingDialog.setMessage(message); loadingDialog.show(); } catch (Exception e) { e.printStackTrace(); } } public void hideLoading() { if (isFinishing()) return; try { if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.dismiss(); } catch (Exception e) { e.printStackTrace(); } } @OnClick(R.id.imvHeaderBack) void doBack() { onBackPressed(); } @Override public void handleBackPressInThisActivity() { finish(); } }
3,017
0.636062
0.635399
108
26.935184
23.554615
105
false
false
0
0
0
0
0
0
0.435185
false
false
3
7ef07cb2cc171954fd1d061ae3933a442c78b8b2
12,275,016,534,842
85c77c9e097b8d7cfbb25a508b1d63dec80f52e1
/app/src/main/java/net/naucu/englishxianshi/ui/SecurityCenterActivity.java
2f64287e241af9c354ebb87767968179ce3e5bd4
[]
no_license
songshuilin/English
https://github.com/songshuilin/English
1643d89e31bbc9d0797592600f54985aa4cbf824
23097f3abd737f2c71294d22d6c7d7ea4b00ef35
refs/heads/master
2021-01-14T08:23:10.248000
2017-02-14T14:34:54
2017-02-14T14:34:54
81,954,081
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.naucu.englishxianshi.ui; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import com.app.myTool.ActionTitleBarWidget; import com.app.myTool.ActionTitleBarWidget.ClickListener; import net.naucu.englishxianshi.R; import net.naucu.englishxianshi.ui.account.AccountActivity; import net.naucu.englishxianshi.ui.base.BaseActivity; /** * 类名: ModifyGenderActivity.java * 描述: TODO 安全中心 * 作者: youyou_pc * 时间: 2015年11月26日 * 上午10:32:20 */ public class SecurityCenterActivity extends BaseActivity implements OnClickListener { public static SecurityCenterActivity activity; private ActionTitleBarWidget titlebar;// 初始化标题控件 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_securitycenter); activity = this; initView(); initTitleBar(); initEvent(); } private void initEvent() { titlebar.OnTitleBarClickListener(clickListener); } private void initView() { titlebar = (ActionTitleBarWidget) findViewById(R.id.titlebar); findViewById(R.id.rl_loginpassword).setOnClickListener(this); } private void initTitleBar() { titlebar.setTitleBackgroundResource(R.drawable.menubutton_select, 0); titlebar.setLeftGravity(Gravity.CENTER); titlebar.setLeftIco(R.drawable.back); titlebar.setCenterGravity(Gravity.CENTER); titlebar.setTitleBarBackgroundColor(Color.WHITE); titlebar.setCenterText(getString(R.string.Securitycenter), 17, Color.BLACK); } private ClickListener clickListener = new ClickListener() { @Override public void onright(View v) { } @Override public void onleft(View v) { finish(); } @Override public void oncenter(View arg0) { // TODO Auto-generated method stub } }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.rl_loginpassword: Intent intentUpdatePass = new Intent(this, AccountActivity.class); intentUpdatePass.putExtra(AccountActivity.OPT_TYPE, 3); startActivity(intentUpdatePass); break; } } }
UTF-8
Java
2,484
java
SecurityCenterActivity.java
Java
[ { "context": " ModifyGenderActivity.java\n * 描述: TODO 安全中心\n * 作者: youyou_pc\n * 时间: 2015年11月26日\n * 上午10:32:20\n */\npublic class", "end": 547, "score": 0.9996669292449951, "start": 538, "tag": "USERNAME", "value": "youyou_pc" } ]
null
[]
package net.naucu.englishxianshi.ui; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import com.app.myTool.ActionTitleBarWidget; import com.app.myTool.ActionTitleBarWidget.ClickListener; import net.naucu.englishxianshi.R; import net.naucu.englishxianshi.ui.account.AccountActivity; import net.naucu.englishxianshi.ui.base.BaseActivity; /** * 类名: ModifyGenderActivity.java * 描述: TODO 安全中心 * 作者: youyou_pc * 时间: 2015年11月26日 * 上午10:32:20 */ public class SecurityCenterActivity extends BaseActivity implements OnClickListener { public static SecurityCenterActivity activity; private ActionTitleBarWidget titlebar;// 初始化标题控件 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_securitycenter); activity = this; initView(); initTitleBar(); initEvent(); } private void initEvent() { titlebar.OnTitleBarClickListener(clickListener); } private void initView() { titlebar = (ActionTitleBarWidget) findViewById(R.id.titlebar); findViewById(R.id.rl_loginpassword).setOnClickListener(this); } private void initTitleBar() { titlebar.setTitleBackgroundResource(R.drawable.menubutton_select, 0); titlebar.setLeftGravity(Gravity.CENTER); titlebar.setLeftIco(R.drawable.back); titlebar.setCenterGravity(Gravity.CENTER); titlebar.setTitleBarBackgroundColor(Color.WHITE); titlebar.setCenterText(getString(R.string.Securitycenter), 17, Color.BLACK); } private ClickListener clickListener = new ClickListener() { @Override public void onright(View v) { } @Override public void onleft(View v) { finish(); } @Override public void oncenter(View arg0) { // TODO Auto-generated method stub } }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.rl_loginpassword: Intent intentUpdatePass = new Intent(this, AccountActivity.class); intentUpdatePass.putExtra(AccountActivity.OPT_TYPE, 3); startActivity(intentUpdatePass); break; } } }
2,484
0.67775
0.669951
85
27.658823
23.789545
85
false
false
0
0
0
0
0
0
0.470588
false
false
3
15cc14d3e1970a222ac6353c9bbb418bccc8c980
17,093,969,867,720
f9a95296a6e33f7d730a57782c6515b48b4998b2
/privacy-comission/privacy-comission/src/main/java/com/connectis/cbpl/service/DocumentURLUtils.java
73e3dbe26817096b80e4045d7150395371f3bacb
[]
no_license
eidos71/privacycomission
https://github.com/eidos71/privacycomission
396f68c6117928f64749faf0734ebc1d467d4879
62328b57d64a3b432f9aa5fdb9be70d555b7e088
refs/heads/master
2016-09-06T06:33:24.573000
2014-03-14T15:55:23
2014-03-14T15:55:23
22,549,263
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.connectis.cbpl.service; import javax.annotation.Resource; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @PropertySource("classpath:${privacy.env}.application.properties") @Scope("singleton") @Component public class DocumentURLUtils { private static final String RESOURCE_URL = "privacy.url"; @Resource private Environment env; public String getDocumentURL(String documentUrlFS) { int pos = documentUrlFS.lastIndexOf("resources"); String relativePath = documentUrlFS.substring(pos, documentUrlFS.length()); relativePath = relativePath.replace("\\", "/"); String documentUrl = env.getRequiredProperty(RESOURCE_URL)+relativePath; return documentUrl; } }
UTF-8
Java
894
java
DocumentURLUtils.java
Java
[]
null
[]
package com.connectis.cbpl.service; import javax.annotation.Resource; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @PropertySource("classpath:${privacy.env}.application.properties") @Scope("singleton") @Component public class DocumentURLUtils { private static final String RESOURCE_URL = "privacy.url"; @Resource private Environment env; public String getDocumentURL(String documentUrlFS) { int pos = documentUrlFS.lastIndexOf("resources"); String relativePath = documentUrlFS.substring(pos, documentUrlFS.length()); relativePath = relativePath.replace("\\", "/"); String documentUrl = env.getRequiredProperty(RESOURCE_URL)+relativePath; return documentUrl; } }
894
0.759508
0.759508
31
26.838709
25.817095
77
false
false
0
0
0
0
0
0
1.193548
false
false
3
4272a5f3252085536de76344e860d0526d1ed295
17,093,969,868,548
a7246e9b0d69b29f656ccc12103fce4365a3f0db
/sources/androidx/appcompat/app/h.java
f2977b1a97715d94e9cd3af22f27802babf06d0d
[]
no_license
dungnguyenBKA/app1-decompile
https://github.com/dungnguyenBKA/app1-decompile
e1343b0505bfc8532409f5a51ddc9ac7ad439e04
5b9aadc0fb75d6f276e7f8ed912b430896989b15
refs/heads/master
2023-07-26T01:41:47.981000
2021-09-10T13:24:12
2021-09-10T13:24:12
405,087,480
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package androidx.appcompat.app; import defpackage.k; public interface h { void onSupportActionModeFinished(k kVar); void onSupportActionModeStarted(k kVar); k onWindowStartingSupportActionMode(k.a aVar); }
UTF-8
Java
222
java
h.java
Java
[]
null
[]
package androidx.appcompat.app; import defpackage.k; public interface h { void onSupportActionModeFinished(k kVar); void onSupportActionModeStarted(k kVar); k onWindowStartingSupportActionMode(k.a aVar); }
222
0.77027
0.77027
11
19.181818
19.483412
50
false
false
0
0
0
0
0
0
0.454545
false
false
3
a3b03b37d8f0013f70f2ed10c1b0ce7ffc5221c1
20,306,605,412,173
288eab39d37d3b7d8ccdd7daf31482bc160c8908
/app/src/main/java/gte/com/itextmosimayor/repository/MessagesRepository.java
660cd38f1663c17b40dbddac1d578456e10fbbfc
[]
no_license
totzk9/iTextMoSiMayor
https://github.com/totzk9/iTextMoSiMayor
2a90a038ca6cb8b6277f63202bad4b245b3d8808
0de618a54991bee2b4e0b5d6c723300a71dd4ba2
refs/heads/master
2020-09-13T15:40:42.308000
2019-11-20T02:38:02
2019-11-20T02:38:02
222,831,706
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gte.com.itextmosimayor.repository; import android.app.Application; import android.util.Log; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import androidx.lifecycle.MutableLiveData; import gte.com.itextmosimayor.constant.Constants; import gte.com.itextmosimayor.database.DatabaseHandler; import gte.com.itextmosimayor.models.MessagesData; import gte.com.itextmosimayor.modules.SingletonRequest; public class MessagesRepository { private DatabaseHandler db; private static MessagesRepository instance; private ArrayList<MessagesData> unassignedDataSet = new ArrayList<>(); private ArrayList<MessagesData> openDataSet = new ArrayList<>(); private ArrayList<MessagesData> importantDataSet = new ArrayList<>(); private ArrayList<MessagesData> dataSetContents = new ArrayList<>(); public static MessagesRepository getInstance() { if (instance == null) instance = new MessagesRepository(); return instance; } public MutableLiveData<List<MessagesData>> getUnassignedMessages(Application application) { setUnassignedMessages(application); MutableLiveData<List<MessagesData>> data = new MutableLiveData<>(); data.setValue(unassignedDataSet); return data; } public MutableLiveData<List<MessagesData>> getOpenMessages(Application application) { setOpenMessages(application); MutableLiveData<List<MessagesData>> data = new MutableLiveData<>(); data.setValue(openDataSet); return data; } public MutableLiveData<List<MessagesData>> getImportantMessages(Application application) { setImportantMessages(application); MutableLiveData<List<MessagesData>> data = new MutableLiveData<>(); data.setValue(importantDataSet); return data; } public MutableLiveData<List<MessagesData>> getUnassignedMessagesData(Application application) { String mobNum; for (int i = 0; i < unassignedDataSet.size(); i++) { mobNum = unassignedDataSet.get(i).getClientMobileNumber(); setUnassignedMessagesData(mobNum, application); } MutableLiveData<List<MessagesData>> data = new MutableLiveData<>(); data.setValue(dataSetContents); return data; } private void setUnassignedMessages(final Application application) { String REQUEST_TAG = Constants.URL + Constants.FETCHUNASSIGNEDMESSAGE + "&MayorID=1"; final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, REQUEST_TAG, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { db = new DatabaseHandler(application); unassignedDataSet.clear(); db.TRUNCATE_UNASSIGNED_MESSAGE(); // Loop through the array elements for (int i = 0; i < response.length(); i++) { // Get current json object JSONObject obj = response.getJSONObject(i); String messageID = obj.getInt("MessageID") + ""; String dateSent = obj.getString("DateSent"); String clientMobileNumber = obj.getString("ClientMobileNumber"); String content = obj.getString("Content"); String mayorID = obj.getInt("MayorID") + ""; String priorityLevel = obj.getString("PriorityLevel"); String isAssigned = obj.getString("isAssigned"); String status = obj.getString("Status"); unassignedDataSet.add(new MessagesData(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status)); db.INSERT_UNASSIGNED_MESSAGE(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status); } } catch (JSONException e) { Log.e("Fail caught", e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("unassignedRepoError", error.getMessage()); } }); SingletonRequest.getInstance(application).addToRequestQueue(request); } private void setOpenMessages(final Application application) { String REQUEST_TAG = Constants.URL + Constants.FETCHOPENMESSAGE + "&MayorID=1"; final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, REQUEST_TAG, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { db = new DatabaseHandler(application); openDataSet.clear(); db.TRUNCATE_OPEN_MESSAGE(); // Loop through the array elements for (int i = 0; i < response.length(); i++) { // Get current json object JSONObject obj = response.getJSONObject(i); String messageID = obj.getInt("MessageID") + ""; String dateSent = obj.getString("DateSent"); String clientMobileNumber = obj.getString("ClientMobileNumber"); String content = obj.getString("Content"); String mayorID = obj.getInt("MayorID") + ""; String priorityLevel = obj.getString("PriorityLevel"); String isAssigned = obj.getString("isAssigned"); String status = obj.getString("Status"); String departmentName = obj.getString("DepartmentName"); openDataSet.add(new MessagesData(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status, departmentName)); db.INSERT_OPEN_MESSAGE(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status, departmentName, ""); } } catch (JSONException e) { Log.e("Fail caught", e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("openRepoError", error.getMessage()); } }); SingletonRequest.getInstance(application).addToRequestQueue(request); } private void setImportantMessages(final Application application) { String REQUEST_TAG = Constants.URL + Constants.FETCHIMPORTANTMESSAGE + "&MayorID=1"; final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, REQUEST_TAG, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { db = new DatabaseHandler(application); importantDataSet.clear(); db.TRUNCATE_IMPORTANT_MESSAGE(); // Loop through the array elements for (int i = 0; i < response.length(); i++) { // Get current json object JSONObject obj = response.getJSONObject(i); String messageID = obj.getInt("MessageID") + ""; String dateSent = obj.getString("DateSent"); String clientMobileNumber = obj.getString("ClientMobileNumber"); String content = obj.getString("Content"); String mayorID = obj.getInt("MayorID") + ""; String priorityLevel = obj.getString("PriorityLevel"); String isAssigned = obj.getInt("isAssigned") + ""; String status = obj.getString("Status"); String departmentName = obj.getString("DepartmentName"); importantDataSet.add(new MessagesData(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status, departmentName)); db.INSERT_IMPORTANT_MESSAGE(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status, departmentName, ""); } } catch (JSONException e) { Log.e("Fail caught", e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("importantRepoError", error.getMessage()); } }); SingletonRequest.getInstance(application).addToRequestQueue(request); } private void setUnassignedMessagesData(String mobileNumber, Application application) { String REQUEST_TAG = Constants.URL + Constants.FETCHUNASSIGNEDMESSAGETHREAD + "&MayorID=1" + "&ClientMobileNumber=" + mobileNumber; final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, REQUEST_TAG, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { if (response.toString().length() > 3) { try { // Loop through the array elements for (int i = 0; i < response.length(); i++) { // Get current json object JSONObject obj = response.getJSONObject(i); String messageID = obj.getInt("MessageID") + ""; String dateSent = obj.getString("DateSent"); String clientMobileNumber = obj.getString("ClientMobileNumber"); String content = obj.getString("Content"); String mayorID = obj.getInt("MayorID") + ""; String priorityLevel = obj.getString("PriorityLevel"); String isAssigned = obj.getInt("isAssigned") + ""; String status = obj.getString("Status"); boolean doesContain = false; for (int j = 0; j < dataSetContents.size(); j++) { if ((dataSetContents.get(j).getMessageID().equals(messageID))) doesContain = true; } if (!doesContain) { dataSetContents.add(new MessagesData(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status)); db.INSERT_MESSAGE(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status); } } } catch (JSONException e) { Log.e("Fail caught", e.toString()); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("error history", "" + error.getMessage()); } }); SingletonRequest.getInstance(application).addToRequestQueue(request); } }
UTF-8
Java
11,780
java
MessagesRepository.java
Java
[]
null
[]
package gte.com.itextmosimayor.repository; import android.app.Application; import android.util.Log; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import androidx.lifecycle.MutableLiveData; import gte.com.itextmosimayor.constant.Constants; import gte.com.itextmosimayor.database.DatabaseHandler; import gte.com.itextmosimayor.models.MessagesData; import gte.com.itextmosimayor.modules.SingletonRequest; public class MessagesRepository { private DatabaseHandler db; private static MessagesRepository instance; private ArrayList<MessagesData> unassignedDataSet = new ArrayList<>(); private ArrayList<MessagesData> openDataSet = new ArrayList<>(); private ArrayList<MessagesData> importantDataSet = new ArrayList<>(); private ArrayList<MessagesData> dataSetContents = new ArrayList<>(); public static MessagesRepository getInstance() { if (instance == null) instance = new MessagesRepository(); return instance; } public MutableLiveData<List<MessagesData>> getUnassignedMessages(Application application) { setUnassignedMessages(application); MutableLiveData<List<MessagesData>> data = new MutableLiveData<>(); data.setValue(unassignedDataSet); return data; } public MutableLiveData<List<MessagesData>> getOpenMessages(Application application) { setOpenMessages(application); MutableLiveData<List<MessagesData>> data = new MutableLiveData<>(); data.setValue(openDataSet); return data; } public MutableLiveData<List<MessagesData>> getImportantMessages(Application application) { setImportantMessages(application); MutableLiveData<List<MessagesData>> data = new MutableLiveData<>(); data.setValue(importantDataSet); return data; } public MutableLiveData<List<MessagesData>> getUnassignedMessagesData(Application application) { String mobNum; for (int i = 0; i < unassignedDataSet.size(); i++) { mobNum = unassignedDataSet.get(i).getClientMobileNumber(); setUnassignedMessagesData(mobNum, application); } MutableLiveData<List<MessagesData>> data = new MutableLiveData<>(); data.setValue(dataSetContents); return data; } private void setUnassignedMessages(final Application application) { String REQUEST_TAG = Constants.URL + Constants.FETCHUNASSIGNEDMESSAGE + "&MayorID=1"; final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, REQUEST_TAG, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { db = new DatabaseHandler(application); unassignedDataSet.clear(); db.TRUNCATE_UNASSIGNED_MESSAGE(); // Loop through the array elements for (int i = 0; i < response.length(); i++) { // Get current json object JSONObject obj = response.getJSONObject(i); String messageID = obj.getInt("MessageID") + ""; String dateSent = obj.getString("DateSent"); String clientMobileNumber = obj.getString("ClientMobileNumber"); String content = obj.getString("Content"); String mayorID = obj.getInt("MayorID") + ""; String priorityLevel = obj.getString("PriorityLevel"); String isAssigned = obj.getString("isAssigned"); String status = obj.getString("Status"); unassignedDataSet.add(new MessagesData(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status)); db.INSERT_UNASSIGNED_MESSAGE(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status); } } catch (JSONException e) { Log.e("Fail caught", e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("unassignedRepoError", error.getMessage()); } }); SingletonRequest.getInstance(application).addToRequestQueue(request); } private void setOpenMessages(final Application application) { String REQUEST_TAG = Constants.URL + Constants.FETCHOPENMESSAGE + "&MayorID=1"; final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, REQUEST_TAG, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { db = new DatabaseHandler(application); openDataSet.clear(); db.TRUNCATE_OPEN_MESSAGE(); // Loop through the array elements for (int i = 0; i < response.length(); i++) { // Get current json object JSONObject obj = response.getJSONObject(i); String messageID = obj.getInt("MessageID") + ""; String dateSent = obj.getString("DateSent"); String clientMobileNumber = obj.getString("ClientMobileNumber"); String content = obj.getString("Content"); String mayorID = obj.getInt("MayorID") + ""; String priorityLevel = obj.getString("PriorityLevel"); String isAssigned = obj.getString("isAssigned"); String status = obj.getString("Status"); String departmentName = obj.getString("DepartmentName"); openDataSet.add(new MessagesData(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status, departmentName)); db.INSERT_OPEN_MESSAGE(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status, departmentName, ""); } } catch (JSONException e) { Log.e("Fail caught", e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("openRepoError", error.getMessage()); } }); SingletonRequest.getInstance(application).addToRequestQueue(request); } private void setImportantMessages(final Application application) { String REQUEST_TAG = Constants.URL + Constants.FETCHIMPORTANTMESSAGE + "&MayorID=1"; final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, REQUEST_TAG, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { db = new DatabaseHandler(application); importantDataSet.clear(); db.TRUNCATE_IMPORTANT_MESSAGE(); // Loop through the array elements for (int i = 0; i < response.length(); i++) { // Get current json object JSONObject obj = response.getJSONObject(i); String messageID = obj.getInt("MessageID") + ""; String dateSent = obj.getString("DateSent"); String clientMobileNumber = obj.getString("ClientMobileNumber"); String content = obj.getString("Content"); String mayorID = obj.getInt("MayorID") + ""; String priorityLevel = obj.getString("PriorityLevel"); String isAssigned = obj.getInt("isAssigned") + ""; String status = obj.getString("Status"); String departmentName = obj.getString("DepartmentName"); importantDataSet.add(new MessagesData(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status, departmentName)); db.INSERT_IMPORTANT_MESSAGE(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status, departmentName, ""); } } catch (JSONException e) { Log.e("Fail caught", e.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("importantRepoError", error.getMessage()); } }); SingletonRequest.getInstance(application).addToRequestQueue(request); } private void setUnassignedMessagesData(String mobileNumber, Application application) { String REQUEST_TAG = Constants.URL + Constants.FETCHUNASSIGNEDMESSAGETHREAD + "&MayorID=1" + "&ClientMobileNumber=" + mobileNumber; final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, REQUEST_TAG, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { if (response.toString().length() > 3) { try { // Loop through the array elements for (int i = 0; i < response.length(); i++) { // Get current json object JSONObject obj = response.getJSONObject(i); String messageID = obj.getInt("MessageID") + ""; String dateSent = obj.getString("DateSent"); String clientMobileNumber = obj.getString("ClientMobileNumber"); String content = obj.getString("Content"); String mayorID = obj.getInt("MayorID") + ""; String priorityLevel = obj.getString("PriorityLevel"); String isAssigned = obj.getInt("isAssigned") + ""; String status = obj.getString("Status"); boolean doesContain = false; for (int j = 0; j < dataSetContents.size(); j++) { if ((dataSetContents.get(j).getMessageID().equals(messageID))) doesContain = true; } if (!doesContain) { dataSetContents.add(new MessagesData(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status)); db.INSERT_MESSAGE(messageID, dateSent, clientMobileNumber, content, mayorID, priorityLevel, isAssigned, status); } } } catch (JSONException e) { Log.e("Fail caught", e.toString()); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("error history", "" + error.getMessage()); } }); SingletonRequest.getInstance(application).addToRequestQueue(request); } }
11,780
0.579202
0.578268
227
50.898678
36.354389
173
false
false
0
0
0
0
0
0
0.969163
false
false
3
9fc745b4265d3fee7b4bc35b1eb06707c58dacef
30,210,799,983,967
ba78ab1f53e17a757bd03656691a69d237a6758b
/src/test/java/com/korg/entity/deserializer/PaymentMethodsDeserializer.java
5e31c33d45edba34bbe25a1934b60721d84f14bd
[]
no_license
kaps-git/wd-test-framework
https://github.com/kaps-git/wd-test-framework
982638f5ad6bb7ba878ac92d63ef7eefa614ddb5
2b9b6071b330a5d90c253096f09aff8d535d722d
refs/heads/master
2021-01-18T23:50:11.689000
2017-06-09T01:29:54
2017-06-09T01:29:54
46,761,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.korg.entity.deserializer; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.korg.entity.PaymentMethod; public class PaymentMethodsDeserializer implements JsonDeserializer { @Override ////eclipse Preference->Java->Compiler "Compiler compliance level". You must choose "1.6" or higher for this annotation to work. public PaymentMethod deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final JsonObject jsonObject = json.getAsJsonObject(); final PaymentMethod paymentMethod = new PaymentMethod(); paymentMethod.setCcType(jsonObject.get("cctype").getAsString()); paymentMethod.setCcNumber(jsonObject.get("ccNumber").getAsString()); paymentMethod.setCvv(jsonObject.get("cvv").getAsString()); paymentMethod.setExpiryMonth(jsonObject.get("expiryMonth").getAsString()); paymentMethod.setExpiryYear(jsonObject.get("expiryYear").getAsString()); return paymentMethod; } }//end class
UTF-8
Java
1,216
java
PaymentMethodsDeserializer.java
Java
[]
null
[]
package com.korg.entity.deserializer; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.korg.entity.PaymentMethod; public class PaymentMethodsDeserializer implements JsonDeserializer { @Override ////eclipse Preference->Java->Compiler "Compiler compliance level". You must choose "1.6" or higher for this annotation to work. public PaymentMethod deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final JsonObject jsonObject = json.getAsJsonObject(); final PaymentMethod paymentMethod = new PaymentMethod(); paymentMethod.setCcType(jsonObject.get("cctype").getAsString()); paymentMethod.setCcNumber(jsonObject.get("ccNumber").getAsString()); paymentMethod.setCvv(jsonObject.get("cvv").getAsString()); paymentMethod.setExpiryMonth(jsonObject.get("expiryMonth").getAsString()); paymentMethod.setExpiryYear(jsonObject.get("expiryYear").getAsString()); return paymentMethod; } }//end class
1,216
0.786184
0.784539
27
44.037037
34.99892
139
false
false
0
0
0
0
0
0
1.148148
false
false
3
7d49eaf3652bf30d4dff23b1d97da3837f094dc9
20,418,274,575,393
75367f9ea2fd6cde4840cfeabaf02c3c26abacb9
/spring/src/main/java/study/spring/aop/HelloWorldAspect2.java
8f5f6eb6da23ed8c3f0ecd40423d2ca04a2ac941
[]
no_license
kshine/spring
https://github.com/kshine/spring
f9271ccaf00863c3d5a98bc399b8f62c9c2616fb
8f3e18ef1ca503bd085d35b3441ebc6151072788
refs/heads/master
2016-09-24T20:30:38.020000
2016-09-23T08:59:50
2016-09-23T08:59:50
68,094,212
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package study.spring.aop; import org.aspectj.lang.annotation.Aspect; @Aspect public class HelloWorldAspect2 { }
UTF-8
Java
124
java
HelloWorldAspect2.java
Java
[]
null
[]
package study.spring.aop; import org.aspectj.lang.annotation.Aspect; @Aspect public class HelloWorldAspect2 { }
124
0.733871
0.725806
8
13.5
15.835088
42
false
false
0
0
0
0
0
0
0.375
false
false
3
2cc418d8c254b473727ca436647dc1f8355b3a0e
7,937,099,575,158
c66b6325ac34672abd3cfa40402879df5fd3a04a
/app/src/main/java/nsu/fit/g14201/marchenko/phoenix/recordrepository/RecordLocalRepoStateListener.java
c324c3c65dca0ed6af983a21d32748bd28c3d4af
[]
no_license
AnnMir/Phoenix-public-version
https://github.com/AnnMir/Phoenix-public-version
656b67dd315aeb9e5021b951a24ea93334acb0cd
cfeedcec6225984b771e6155c7a8dadd461443b5
refs/heads/master
2023-01-05T09:01:49.420000
2020-11-03T10:17:12
2020-11-03T10:17:12
309,661,265
0
0
null
false
2020-11-03T11:24:36
2020-11-03T11:13:18
2020-11-03T11:22:00
2020-11-03T11:24:14
0
0
0
0
Java
false
false
package nsu.fit.g14201.marchenko.phoenix.recordrepository; public class RecordLocalRepoStateListener { }
UTF-8
Java
107
java
RecordLocalRepoStateListener.java
Java
[]
null
[]
package nsu.fit.g14201.marchenko.phoenix.recordrepository; public class RecordLocalRepoStateListener { }
107
0.841121
0.794393
5
20.4
25.032778
58
false
false
0
0
0
0
0
0
0.2
false
false
3
858cc042289280d6864354ebf9bf36203732bc24
15,410,342,721,846
ee9db88b6a6d3baf22f96fed97d34b9d6e9f7d4a
/src/com/web/Process.java
8221f8db3bdfdd22a63113185dccedae24b44289
[]
no_license
confiself/Phone
https://github.com/confiself/Phone
bce58c9b9050af95ee6cff7a0fa8ec55fd5a6645
f4f80c4c30958bc91adce87b9f9520fc23fc2c4f
refs/heads/master
2021-05-16T13:35:02.779000
2017-10-01T02:26:59
2017-10-01T02:26:59
105,413,972
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.web; import java.io.IOException; import java.util.Random; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTable; import com.ui.Mobile; public class Process extends CommonInfo implements Runnable{ private int id,guessRow; private String cookie; private String cid; private String phone; private JTable table; private JButton btnSet; private JLabel labelProcess; Process(int id,JButton btnSet,JTable table,JLabel labelProcess){ this.id=id; this.btnSet=btnSet; this.table=table; this.labelProcess=labelProcess; phone=CommonInfo.successInfo.get(id).phone; cookie=CommonInfo.successInfo.get(id).cookie; cid=CommonInfo.successInfo.get(id).cid; guessRow=CommonInfo.successInfo.get(id).guessRow; } public void run(){ String result=""; String tmp; for(int i=0;i<4;i++){ tmp=guess(); if(tmp!="") result+=tmp+"|"; } if(result=="")tmp="猜完|没一个中!"; else tmp="猜中了|"+result; synchronized(Mobile.lock){ table.setValueAt(tmp, guessRow, 3); Mobile.processFinish++; } // if(result!=""){ synchronized(Mobile.lockFile){ try { Mobile.bufferWriterGuess.write(phone+"----"+tmp+"\r\n"); Mobile.bufferWriterGuess.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //} processStartNew(); } private void processStartNew(){ int diff=Mobile.processThreadNum-(Mobile.processCurrent-Mobile.processFinish); while(Mobile.processCurrent<CommonInfo.successNum && diff>0){ CommonInfo.processThread.get(Mobile.processCurrent).start(); Mobile.processCurrent++; diff--; } String result=Mobile.processFinish+"/"+CommonInfo.successNum; Mobile.labelProcess.setText(result); if(Mobile.loginFinish==CommonInfo.accountNum && Mobile.processFinish==CommonInfo.successNum){ labelProcess.setText("猜完!"); btnSet.setEnabled(false); } } public String guess(){ String num=getNum(); String url="https://clientaccess.10086.cn:9043/leadeon-cmcc-events/api/guess/lottery?"+cookie+";Comment=SessionServer-cmcc;Path=/;Secure"; String param="{\"cid\":\"[cid]\",\"en\":\"0\",\"t\":\"[cook];Comment=SessionServer-cmcc;Path=/;Secure\",\"sn\":\"\",\"cv\":\"2.1.0\",\"st\":\"1\",\"sv\":\"4.4.2\",\"sp\":\"\",\"reqBody\":{\"numb\":#}}"; param=param.replace("[cook]", cookie); param=param.replace("[cid]", cid); param=param.replace("#", num); HttpRequest httpRequest=new HttpRequest(url); httpRequest.setRequestProperty("Content-Type","application/Json"); httpRequest.setRequestProperty("x-forwarded-for", getIP()); httpRequest.setRequestProperty("client_ip", getIP()); String result=httpRequest.sendPost(param); if(result.indexOf("恭喜您获得") != -1){ int pos=result.indexOf("msg"); result=result.substring(pos+6); pos=result.indexOf("\""); result=result.substring(0,pos); result.replace("恭喜您获得:", ""); } else{ result=""; } System.out.println(result); return result; } private String getNum(){ ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String js="function getNumber() {var c = 99;var b = 3;var a = 10;var d = generateGuessNumber(c, b, a);return d.start+\"|\"+d.end;}"; js+="function generateGuessNumber(c, b, a) {var d = {};d.start = getRandomNum(10, c - a);d.end = getRandomNum(d.start + b, d.start + a); d.end = getRandomNum(d.start + b, d.start + a);return d;}"; js+="function getRandomNum(c, a) { var b = a - c;var d = Math.random();return (c + Math.round(d * b));}"; String num=""; try { engine.eval(js); Invocable inv = (Invocable) engine; num=(String)inv.invokeFunction("getNumber"); System.out.println(num); } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } int pos=num.indexOf("|"); int value=Integer.valueOf(num.substring(0,pos)); num=String.valueOf(value+1); return num; } private String getIP(){ Random random=new Random(id); String ip=String.valueOf(Math.abs(random.nextInt())%254)+1; ip+="."+String.valueOf(Math.abs(random.nextInt())%254)+1; ip+="."+String.valueOf(Math.abs(random.nextInt())%254)+1; ip+="."+String.valueOf(Math.abs(random.nextInt())%254)+1; return ip; } }
GB18030
Java
4,701
java
Process.java
Java
[]
null
[]
package com.web; import java.io.IOException; import java.util.Random; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTable; import com.ui.Mobile; public class Process extends CommonInfo implements Runnable{ private int id,guessRow; private String cookie; private String cid; private String phone; private JTable table; private JButton btnSet; private JLabel labelProcess; Process(int id,JButton btnSet,JTable table,JLabel labelProcess){ this.id=id; this.btnSet=btnSet; this.table=table; this.labelProcess=labelProcess; phone=CommonInfo.successInfo.get(id).phone; cookie=CommonInfo.successInfo.get(id).cookie; cid=CommonInfo.successInfo.get(id).cid; guessRow=CommonInfo.successInfo.get(id).guessRow; } public void run(){ String result=""; String tmp; for(int i=0;i<4;i++){ tmp=guess(); if(tmp!="") result+=tmp+"|"; } if(result=="")tmp="猜完|没一个中!"; else tmp="猜中了|"+result; synchronized(Mobile.lock){ table.setValueAt(tmp, guessRow, 3); Mobile.processFinish++; } // if(result!=""){ synchronized(Mobile.lockFile){ try { Mobile.bufferWriterGuess.write(phone+"----"+tmp+"\r\n"); Mobile.bufferWriterGuess.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //} processStartNew(); } private void processStartNew(){ int diff=Mobile.processThreadNum-(Mobile.processCurrent-Mobile.processFinish); while(Mobile.processCurrent<CommonInfo.successNum && diff>0){ CommonInfo.processThread.get(Mobile.processCurrent).start(); Mobile.processCurrent++; diff--; } String result=Mobile.processFinish+"/"+CommonInfo.successNum; Mobile.labelProcess.setText(result); if(Mobile.loginFinish==CommonInfo.accountNum && Mobile.processFinish==CommonInfo.successNum){ labelProcess.setText("猜完!"); btnSet.setEnabled(false); } } public String guess(){ String num=getNum(); String url="https://clientaccess.10086.cn:9043/leadeon-cmcc-events/api/guess/lottery?"+cookie+";Comment=SessionServer-cmcc;Path=/;Secure"; String param="{\"cid\":\"[cid]\",\"en\":\"0\",\"t\":\"[cook];Comment=SessionServer-cmcc;Path=/;Secure\",\"sn\":\"\",\"cv\":\"2.1.0\",\"st\":\"1\",\"sv\":\"4.4.2\",\"sp\":\"\",\"reqBody\":{\"numb\":#}}"; param=param.replace("[cook]", cookie); param=param.replace("[cid]", cid); param=param.replace("#", num); HttpRequest httpRequest=new HttpRequest(url); httpRequest.setRequestProperty("Content-Type","application/Json"); httpRequest.setRequestProperty("x-forwarded-for", getIP()); httpRequest.setRequestProperty("client_ip", getIP()); String result=httpRequest.sendPost(param); if(result.indexOf("恭喜您获得") != -1){ int pos=result.indexOf("msg"); result=result.substring(pos+6); pos=result.indexOf("\""); result=result.substring(0,pos); result.replace("恭喜您获得:", ""); } else{ result=""; } System.out.println(result); return result; } private String getNum(){ ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String js="function getNumber() {var c = 99;var b = 3;var a = 10;var d = generateGuessNumber(c, b, a);return d.start+\"|\"+d.end;}"; js+="function generateGuessNumber(c, b, a) {var d = {};d.start = getRandomNum(10, c - a);d.end = getRandomNum(d.start + b, d.start + a); d.end = getRandomNum(d.start + b, d.start + a);return d;}"; js+="function getRandomNum(c, a) { var b = a - c;var d = Math.random();return (c + Math.round(d * b));}"; String num=""; try { engine.eval(js); Invocable inv = (Invocable) engine; num=(String)inv.invokeFunction("getNumber"); System.out.println(num); } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } int pos=num.indexOf("|"); int value=Integer.valueOf(num.substring(0,pos)); num=String.valueOf(value+1); return num; } private String getIP(){ Random random=new Random(id); String ip=String.valueOf(Math.abs(random.nextInt())%254)+1; ip+="."+String.valueOf(Math.abs(random.nextInt())%254)+1; ip+="."+String.valueOf(Math.abs(random.nextInt())%254)+1; ip+="."+String.valueOf(Math.abs(random.nextInt())%254)+1; return ip; } }
4,701
0.663802
0.653276
134
32.738808
31.660025
204
false
false
0
0
0
0
0
0
3.104478
false
false
3
b808f1e267fd052643e004321f58f90c06c424cb
7,679,401,541,828
33b0dc64176b0f8800be00f44ee6ccded7f92a6f
/src/main/java/com/pompey/upms/config/ShardingDataSourceConfig.java
71352adb23cef297055f449763ee64ae5138a6b9
[]
no_license
PompeyXu/pompey-upms
https://github.com/PompeyXu/pompey-upms
8ffdf7dfaf949f195ebcf6775f4f32654a824ba5
dd031f57b134eec10ae5215719f72961bbd76ebe
refs/heads/master
2022-06-26T04:10:06.113000
2019-08-03T07:26:53
2019-08-03T07:26:53
179,809,511
4
0
null
false
2022-06-17T02:19:38
2019-04-06T08:47:27
2020-05-14T10:21:03
2022-06-17T02:19:38
230
3
0
1
Java
false
false
package com.pompey.upms.config; import java.sql.SQLException; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.pool.DruidDataSource; import com.google.common.collect.Maps; import io.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory; /** * 数据源配置 * * @author PompeyXu * @date 2019-04-20 18:39 */ @Configuration @EnableConfigurationProperties(ShardingMasterSlaveConfig.class) @ConditionalOnProperty({"sharding.jdbc.data-sources.ds_master.url", "sharding.jdbc.master-slave-rule.master-data-source-name"}) public class ShardingDataSourceConfig { private static final Logger logger = LoggerFactory.getLogger(ShardingDataSourceConfig.class); private final ShardingMasterSlaveConfig shardingMasterSlaveConfig; public ShardingDataSourceConfig(ShardingMasterSlaveConfig shardingMasterSlaveConfig) { this.shardingMasterSlaveConfig = shardingMasterSlaveConfig; } /** * 配置数据源 * @throws SQLException */ @Bean(name = "masterSlaveDataSource") public DataSource masterSlaveDataSource() throws SQLException { shardingMasterSlaveConfig.getDataSources().forEach((k,v)->configDruidDataSource(v)); Map<String, DataSource> dataSourceMap = Maps.newHashMap(); dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources()); DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, shardingMasterSlaveConfig.getMasterSlaveRule(), Maps.newHashMap(), new Properties()); logger.info("masterSlaveDataSource config complete"); return dataSource; } /** * 配置事物管理器 */ // @Bean(name = "transactionManager") // public DataSourceTransactionManager transactionManager() { // return new DataSourceTransactionManager(dataSource()); // } private void configDruidDataSource(DruidDataSource dataSource) { DruidDataSource druidParams = shardingMasterSlaveConfig.getDruidDataSource(); dataSource.setMaxActive(druidParams.getMaxActive()); dataSource.setInitialSize(druidParams.getInitialSize()); dataSource.setMaxWait(druidParams.getMaxWait()); dataSource.setMinIdle(druidParams.getMinIdle()); dataSource.setTimeBetweenEvictionRunsMillis(druidParams.getTimeBetweenEvictionRunsMillis()); dataSource.setMinEvictableIdleTimeMillis(druidParams.getMinEvictableIdleTimeMillis()); dataSource.setValidationQuery(druidParams.getValidationQuery()); dataSource.setTestWhileIdle(druidParams.isTestWhileIdle()); dataSource.setTestOnBorrow(druidParams.isTestOnBorrow()); dataSource.setTestOnReturn(druidParams.isTestOnReturn()); dataSource.setPoolPreparedStatements(druidParams.isPoolPreparedStatements()); dataSource.setMaxOpenPreparedStatements(druidParams.getMaxOpenPreparedStatements()); dataSource.setUseGlobalDataSourceStat(druidParams.isUseGlobalDataSourceStat()); try { dataSource.setFilters("stat,wall,slf4j"); } catch (SQLException e) { logger.error("druid configuration initialization filter", e); } } }
UTF-8
Java
3,384
java
ShardingDataSourceConfig.java
Java
[ { "context": "aveDataSourceFactory;\n\n/**\n * 数据源配置\n * \n * @author PompeyXu\n * @date 2019-04-20 18:39\n */\n@Configuration\n@Ena", "end": 736, "score": 0.9970923662185669, "start": 728, "tag": "NAME", "value": "PompeyXu" } ]
null
[]
package com.pompey.upms.config; import java.sql.SQLException; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.pool.DruidDataSource; import com.google.common.collect.Maps; import io.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory; /** * 数据源配置 * * @author PompeyXu * @date 2019-04-20 18:39 */ @Configuration @EnableConfigurationProperties(ShardingMasterSlaveConfig.class) @ConditionalOnProperty({"sharding.jdbc.data-sources.ds_master.url", "sharding.jdbc.master-slave-rule.master-data-source-name"}) public class ShardingDataSourceConfig { private static final Logger logger = LoggerFactory.getLogger(ShardingDataSourceConfig.class); private final ShardingMasterSlaveConfig shardingMasterSlaveConfig; public ShardingDataSourceConfig(ShardingMasterSlaveConfig shardingMasterSlaveConfig) { this.shardingMasterSlaveConfig = shardingMasterSlaveConfig; } /** * 配置数据源 * @throws SQLException */ @Bean(name = "masterSlaveDataSource") public DataSource masterSlaveDataSource() throws SQLException { shardingMasterSlaveConfig.getDataSources().forEach((k,v)->configDruidDataSource(v)); Map<String, DataSource> dataSourceMap = Maps.newHashMap(); dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources()); DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, shardingMasterSlaveConfig.getMasterSlaveRule(), Maps.newHashMap(), new Properties()); logger.info("masterSlaveDataSource config complete"); return dataSource; } /** * 配置事物管理器 */ // @Bean(name = "transactionManager") // public DataSourceTransactionManager transactionManager() { // return new DataSourceTransactionManager(dataSource()); // } private void configDruidDataSource(DruidDataSource dataSource) { DruidDataSource druidParams = shardingMasterSlaveConfig.getDruidDataSource(); dataSource.setMaxActive(druidParams.getMaxActive()); dataSource.setInitialSize(druidParams.getInitialSize()); dataSource.setMaxWait(druidParams.getMaxWait()); dataSource.setMinIdle(druidParams.getMinIdle()); dataSource.setTimeBetweenEvictionRunsMillis(druidParams.getTimeBetweenEvictionRunsMillis()); dataSource.setMinEvictableIdleTimeMillis(druidParams.getMinEvictableIdleTimeMillis()); dataSource.setValidationQuery(druidParams.getValidationQuery()); dataSource.setTestWhileIdle(druidParams.isTestWhileIdle()); dataSource.setTestOnBorrow(druidParams.isTestOnBorrow()); dataSource.setTestOnReturn(druidParams.isTestOnReturn()); dataSource.setPoolPreparedStatements(druidParams.isPoolPreparedStatements()); dataSource.setMaxOpenPreparedStatements(druidParams.getMaxOpenPreparedStatements()); dataSource.setUseGlobalDataSourceStat(druidParams.isUseGlobalDataSourceStat()); try { dataSource.setFilters("stat,wall,slf4j"); } catch (SQLException e) { logger.error("druid configuration initialization filter", e); } } }
3,384
0.817612
0.813134
86
37.953487
34.795719
172
false
false
0
0
0
0
0
0
1.534884
false
false
3
c74559bbece27c22d075da860baa64a13be8c627
7,344,394,144,577
6df5d712d79c42a7810c99e88744d94efe0810be
/SoftServe/src/ChangePanelEvent.java
56832af39cdb0aa882c2c23942fafc992a4a6854
[]
no_license
charberg/CarletonSoftServeComp
https://github.com/charberg/CarletonSoftServeComp
6303872f99b1b63286de739a03423b6de53bd781
aa096d80569d0e268f3be2dd88c687134ff1311f
refs/heads/master
2016-08-04T17:51:26.858000
2015-02-06T00:14:44
2015-02-06T00:14:44
24,818,868
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import javax.swing.JPanel; public class ChangePanelEvent extends EventObject{ /** * */ private static final long serialVersionUID = 1L; public ChangePanelEvent(Object source, String c){ super(source); } public void changePanel(JPanel panel){ //ChangePanelEvent e = new ChangePanelEvent(this); } }
UTF-8
Java
361
java
ChangePanelEvent.java
Java
[]
null
[]
import java.util.*; import javax.swing.JPanel; public class ChangePanelEvent extends EventObject{ /** * */ private static final long serialVersionUID = 1L; public ChangePanelEvent(Object source, String c){ super(source); } public void changePanel(JPanel panel){ //ChangePanelEvent e = new ChangePanelEvent(this); } }
361
0.67867
0.6759
19
16.894737
19.941744
52
false
false
0
0
0
0
0
0
1.105263
false
false
3
5834ebc37ceac826a431742fd32e282c758f59a0
8,899,172,264,277
6967e402b349e4387a2e7d40d86e3ded716b9da8
/Game/src/Editor/comp/FileField.java
c2f63b5245ff1a2880971d2b9ce48fd9d2e9a245
[]
no_license
tariqbroadnax/Project
https://github.com/tariqbroadnax/Project
3f5358634cb1a8c13a0158788291b191dd37c592
be10f1ae226224271b5a29fc6467d581fe0d4cf8
refs/heads/master
2021-01-11T01:04:52.470000
2017-03-06T23:14:11
2017-03-06T23:14:11
70,843,203
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Editor.comp; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import Editor.TextField; public class FileField extends Form implements ActionListener { private File file; private JFileChooser chooser; private TextField lbl; public FileField() { this(null); } public FileField(File file) { lbl = new TextField("Hello"); JButton btn = new JButton("Browse"); chooser = new JFileChooser(); lbl.setEditable(false); lbl.setMaximumSize(new Dimension(0, 0)); addField(lbl, 0, 0, 1); addComponent(btn, 1, 0, 1); btn.addActionListener(this); setFile(file); //label.setEditable(false); } public void chooseFile() { int option = chooser.showOpenDialog(null); if(option == chooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); setFile(file); } } public void setFile(File file) { this.file = file; if(file == null) lbl.setText(" "); else { String fileName = file.getAbsolutePath(); lbl.setText(fileName); } repaint(); } public void setFileFilter(FileFilter filter) { chooser.setFileFilter(filter); } public File getFile() { return file; } @Override public void actionPerformed(ActionEvent e) { chooseFile(); notifyListeners(); } }
UTF-8
Java
1,458
java
FileField.java
Java
[]
null
[]
package Editor.comp; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import Editor.TextField; public class FileField extends Form implements ActionListener { private File file; private JFileChooser chooser; private TextField lbl; public FileField() { this(null); } public FileField(File file) { lbl = new TextField("Hello"); JButton btn = new JButton("Browse"); chooser = new JFileChooser(); lbl.setEditable(false); lbl.setMaximumSize(new Dimension(0, 0)); addField(lbl, 0, 0, 1); addComponent(btn, 1, 0, 1); btn.addActionListener(this); setFile(file); //label.setEditable(false); } public void chooseFile() { int option = chooser.showOpenDialog(null); if(option == chooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); setFile(file); } } public void setFile(File file) { this.file = file; if(file == null) lbl.setText(" "); else { String fileName = file.getAbsolutePath(); lbl.setText(fileName); } repaint(); } public void setFileFilter(FileFilter filter) { chooser.setFileFilter(filter); } public File getFile() { return file; } @Override public void actionPerformed(ActionEvent e) { chooseFile(); notifyListeners(); } }
1,458
0.683128
0.677641
92
14.847826
14.626461
47
false
false
0
0
0
0
0
0
1.76087
false
false
3
c0688f4aeb90543eafc10f42a458562719574151
18,296,560,697,388
2bc029672579ea8fd2da412d95faf73014f19fac
/src/com/adkms/blokersi/libs/Biurwa.java
a88debe64705107675f50ea47aafcd227583a412
[]
no_license
bamboleho/Blokersi
https://github.com/bamboleho/Blokersi
2285c0332ac8065156abdd74d6ae3cb591581f25
8509544cc8a35cacf2989df3e9b04815a23b5ab4
refs/heads/master
2016-09-16T04:58:02.237000
2014-01-29T17:14:12
2014-01-29T17:14:12
14,232,546
1
0
null
false
2014-01-07T16:02:02
2013-11-08T12:33:00
2014-01-07T16:02:02
2014-01-07T16:02:02
6,429
0
1
0
Java
null
null
/** * @file Biurwa.java * @author Kamil Bojes */ package com.adkms.blokersi.libs; /** * Klasa reprezentujaca jednostke Biurwa * @author Kamil Bojes */ public class Biurwa extends Officials { /** * Konstruktor, ustawiajacy parametry klasy */ public Biurwa() { super(4, 5, 0, 1, 5, false, "Biurwa", 5, 0, 100, "biurwa"); } }
UTF-8
Java
384
java
Biurwa.java
Java
[ { "context": "/**\r\n * @file Biurwa.java\r\n * @author Kamil Bojes\r\n */\r\n\r\npackage com.adkms.blokersi.libs;\r\n\r\n/**\r\n", "end": 49, "score": 0.9998842477798462, "start": 38, "tag": "NAME", "value": "Kamil Bojes" }, { "context": " Klasa reprezentujaca jednostke Biurwa\r\n * @author Kamil Bojes\r\n */\r\npublic class Biurwa extends Officials\r\n{\r\n ", "end": 163, "score": 0.9998753666877747, "start": 152, "tag": "NAME", "value": "Kamil Bojes" } ]
null
[]
/** * @file Biurwa.java * @author <NAME> */ package com.adkms.blokersi.libs; /** * Klasa reprezentujaca jednostke Biurwa * @author <NAME> */ public class Biurwa extends Officials { /** * Konstruktor, ustawiajacy parametry klasy */ public Biurwa() { super(4, 5, 0, 1, 5, false, "Biurwa", 5, 0, 100, "biurwa"); } }
374
0.572917
0.546875
21
16.380953
18.219498
67
false
false
0
0
0
0
0
0
0.619048
false
false
3
c90f22790880a630f1f0c38f912e4685dac6b8d9
2,920,577,805,707
7b012f90212549bb413260ac48aec776f6401f29
/Spring_Hai/SpringBootThymeleft/src/main/java/com/example/thymeleafdemo/model/Student.java
cb31d7d999db4bf199e0baf900fa81e1127a7177
[]
no_license
thaibinh204/isl_java_k01
https://github.com/thaibinh204/isl_java_k01
acbf834e78fdc2d2b6170af8ff7625f6c1d18a6b
5e12476b7a84abc3ef6635aa2774baac241a37fb
refs/heads/master
2022-11-26T03:44:53.523000
2020-08-08T01:25:55
2020-08-08T01:25:55
265,229,307
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.thymeleafdemo.model; import java.util.Date; 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 = "students") public class Student { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "full_name") private String fullName; @Column(name = "birthday") private Date birthday; @Column(name = "math") private double math; @Column(name = "literature") private double literature; @Column(name = "english") private double english; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public double getMath() { return math; } public void setMath(double math) { this.math = math; } public double getLiterature() { return literature; } public void setLiterature(double literature) { this.literature = literature; } public double getEnglish() { return english; } public void setEnglish(double english) { this.english = english; } }
UTF-8
Java
1,420
java
Student.java
Java
[]
null
[]
package com.example.thymeleafdemo.model; import java.util.Date; 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 = "students") public class Student { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "full_name") private String fullName; @Column(name = "birthday") private Date birthday; @Column(name = "math") private double math; @Column(name = "literature") private double literature; @Column(name = "english") private double english; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public double getMath() { return math; } public void setMath(double math) { this.math = math; } public double getLiterature() { return literature; } public void setLiterature(double literature) { this.literature = literature; } public double getEnglish() { return english; } public void setEnglish(double english) { this.english = english; } }
1,420
0.719014
0.719014
83
16.108435
14.790922
52
false
false
0
0
0
0
0
0
1.060241
false
false
3
44c59a408425acdd719a21faba5e83b3150e3e27
24,678,882,149,289
173256744b5ecb238acfdc97a594acd6dd84710a
/DataDiplayerAdepter.java
86cccd5aeac330f15e995a182f9b1638337e61b3
[]
no_license
JayHelaiya/viewPager_with_economist
https://github.com/JayHelaiya/viewPager_with_economist
a229d3f14bd55d85ef81b972f3b30f9e5e6e6ef2
aed62dacc0707922b1f8e1612e3b1c7a7058b06a
refs/heads/master
2021-01-19T04:02:28.808000
2016-07-11T09:25:16
2016-07-11T09:25:16
63,054,531
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android_7.viewpagerexample; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; /** * Created by android-7 on 9/6/16. */ public class DataDiplayerAdepter extends PagerAdapter{ Context context; ArrayList<Country> countryList; LayoutInflater inflater; public DataDiplayerAdepter(Context context, ArrayList<Country> countryList) { this.context = context; this.countryList = countryList; } @Override public int getCount() { return countryList.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == ((RelativeLayout) object); } @Override public Object instantiateItem(ViewGroup container, int position) { TextView txtrank; TextView txtcountry; TextView txtpopulation; ImageView imgflag; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.viewpager_main, container, false); txtrank = (TextView) itemView.findViewById(R.id.tv_rank_value); txtcountry = (TextView) itemView.findViewById(R.id.tv_country_value); txtpopulation = (TextView) itemView.findViewById(R.id.tv_population_value); imgflag = (ImageView) itemView.findViewById(R.id.flagOfCountry); txtrank.setText(countryList.get(position).getRank()+""); txtcountry.setText(countryList.get(position).getCountry_name()); txtpopulation.setText(countryList.get(position).getPopulation().toString()); imgflag.setImageResource(countryList.get(position).getFlag()); ((ViewPager) container).addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((RelativeLayout) object); } }
UTF-8
Java
2,260
java
DataDiplayerAdepter.java
Java
[ { "context": "w;\n\nimport java.util.ArrayList;\n\n/**\n * Created by android-7 on 9/6/16.\n */\npublic class DataDiplayerAdepter ", "end": 446, "score": 0.9991800785064697, "start": 437, "tag": "USERNAME", "value": "android-7" } ]
null
[]
package com.example.android_7.viewpagerexample; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; /** * Created by android-7 on 9/6/16. */ public class DataDiplayerAdepter extends PagerAdapter{ Context context; ArrayList<Country> countryList; LayoutInflater inflater; public DataDiplayerAdepter(Context context, ArrayList<Country> countryList) { this.context = context; this.countryList = countryList; } @Override public int getCount() { return countryList.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == ((RelativeLayout) object); } @Override public Object instantiateItem(ViewGroup container, int position) { TextView txtrank; TextView txtcountry; TextView txtpopulation; ImageView imgflag; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.viewpager_main, container, false); txtrank = (TextView) itemView.findViewById(R.id.tv_rank_value); txtcountry = (TextView) itemView.findViewById(R.id.tv_country_value); txtpopulation = (TextView) itemView.findViewById(R.id.tv_population_value); imgflag = (ImageView) itemView.findViewById(R.id.flagOfCountry); txtrank.setText(countryList.get(position).getRank()+""); txtcountry.setText(countryList.get(position).getCountry_name()); txtpopulation.setText(countryList.get(position).getPopulation().toString()); imgflag.setImageResource(countryList.get(position).getFlag()); ((ViewPager) container).addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((RelativeLayout) object); } }
2,260
0.703097
0.699558
73
29.958904
26.738939
84
false
false
0
0
0
0
0
0
0.589041
false
false
3
ba6402e0eafd11ef2ab06c4fe964de79f3665934
21,595,095,610,600
ccc5adcb71b3b595cb02d34c100a019382323107
/src/main/java/com/example/demo/controller/UserController.java
3806f55d9d2b04e5295b0c2622d3196379197e12
[]
no_license
PasserByJia/spring-shiro
https://github.com/PasserByJia/spring-shiro
dd959f601e61f02f09056cff241cc55bf276b3e8
7692b4c6b7e4fac231fa974480cd46e20b759ded
refs/heads/master
2020-03-26T17:48:50.169000
2018-10-17T15:09:19
2018-10-17T15:09:19
145,182,349
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.controller; import com.example.demo.domain.User; import com.example.demo.util.Common; import com.example.demo.util.ResponseUtil; import org.apache.shiro.SecurityUtils; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class UserController extends BasicController { @RequestMapping(value = "/changePassword", method = RequestMethod.PUT) public Map<String, Object> changePassword(@RequestBody Map map){ String newPassword = (String)map.get("password"); String username = (String) SecurityUtils.getSubject().getPrincipal(); User user = userService.findByUsername(username); user.setPassword(newPassword); try{ userService.update(user,username); }catch (Exception e){ return ResponseUtil.errorResponse(Common.Error_500,"修改密码失败",null); } return ResponseUtil.successResponse(Common.Error_001,"修改密码成功请重新登录!"); } }
UTF-8
Java
1,213
java
UserController.java
Java
[ { "context": "indByUsername(username);\n user.setPassword(newPassword);\n try{\n userService.update(use", "end": 910, "score": 0.8990018367767334, "start": 899, "tag": "PASSWORD", "value": "newPassword" } ]
null
[]
package com.example.demo.controller; import com.example.demo.domain.User; import com.example.demo.util.Common; import com.example.demo.util.ResponseUtil; import org.apache.shiro.SecurityUtils; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class UserController extends BasicController { @RequestMapping(value = "/changePassword", method = RequestMethod.PUT) public Map<String, Object> changePassword(@RequestBody Map map){ String newPassword = (String)map.get("password"); String username = (String) SecurityUtils.getSubject().getPrincipal(); User user = userService.findByUsername(username); user.setPassword(<PASSWORD>); try{ userService.update(user,username); }catch (Exception e){ return ResponseUtil.errorResponse(Common.Error_500,"修改密码失败",null); } return ResponseUtil.successResponse(Common.Error_001,"修改密码成功请重新登录!"); } }
1,212
0.747664
0.742566
29
39.586208
25.632034
77
false
false
0
0
0
0
0
0
0.793103
false
false
3
62ede982872640d7ed04d646fb0cf6e7d2596532
5,351,529,309,053
641e77f33ad8fa499cc36b661e3c24917bc47f96
/timesheetNew/src/server/essp/timesheet/outwork/logic/LgAccount.java
de0b2fd151b529efe10ff27c4a958890ce7aa2f6
[]
no_license
stonethink/essp
https://github.com/stonethink/essp
43203bba6d95438eca7e47a071beba32dc7c2db1
10267cd3af60fc06631a7ff4b7fd855f7143f271
refs/heads/master
2021-04-12T10:07:27.792000
2018-04-22T03:18:02
2018-04-22T03:18:02
126,622,326
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package server.essp.timesheet.outwork.logic; import java.util.List; import net.sf.hibernate.HibernateException; import db.essp.timesheet.TsAccount; import db.essp.timesheet.TsCodeValue; import db.essp.timesheet.TsOutworkerPrivilege; import server.essp.framework.logic.AbstractESSPLogic; import server.framework.common.BusinessException; import server.framework.taglib.util.SelectList; public class LgAccount extends AbstractESSPLogic { public String getNameByDeptId(String deptId) { try { List list = this.getDbAccessor().getSession() .createQuery("from TsAccount where account_Id = :accountId order by account_id") .setString("accountId", deptId) .list(); if(list != null && list.size() > 0) { return ((TsAccount)list.get(0)).getAccountName(); } } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listAccount", "list account by deptId error", e); } return deptId; } public synchronized List listPrivilegeDeptByLoginId(String loginId) { List list; String hql = "from TsOutworkerPrivilege where lower(login_id) = lower(:loginId)"; try { list = this.getDbAccessor().getSession() .createQuery(hql) .setString("loginId", loginId) .list(); } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listAccount", "list privilege dept error", e); } return list; } public List listAccountByDeptId(String deptId) { List list = null; try { list = this.getDbAccessor().getSession() .createQuery("from TsAccount where org_code = :orgId and account_Status = 'N' order by account_id") .setString("orgId", deptId) .list(); } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listAccount", "list account by deptId error", e); } return list; } public List listLaborByAcntRid(Long acntRid) { List list = null; String hql = "from TsLaborResource where account_Rid= :acntRid"; try { list = this.getDbAccessor().getSession() .createQuery(hql).setLong("acntRid", acntRid) .list(); } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listLabor", "list labor by deptId error", e); } return list; } public List listCodeByCodeTypeRid(Long codeTypeRid) { List list = null; String hql = "select v from TsCodeValue v " + ",TsCodeRelation r where v.rid = r.valueRid " + " and r.typeRid = :typeRid"; try { list = this.getDbAccessor().getSession() .createQuery(hql).setLong("typeRid", codeTypeRid) .list(); } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listcode", "list code by deptId error", e); } leafFilter(list); return list; } /** * 过滤TsCodeValue列表,只留下叶子节点 * @param list */ private void leafFilter(List list) { String hql = "from TsCodeValue where parent_rid = :pRid "; try { for(int i = 0; i < list.size(); i ++) { TsCodeValue value = (TsCodeValue)list.get(i); List children = this.getDbAccessor().getSession() .createQuery(hql).setLong("pRid", value.getRid()) .list(); if(children != null && children.size() > 0) { list.remove(i); } } } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.leafFilter", "list leaf filter error", e); } } public TsAccount getTsAccount(Long rid) { return (TsAccount) this.getDbAccessor().load(TsAccount.class, rid); } public String getAccountOrgCode(Long acntRid) { TsAccount acnt = getTsAccount(acntRid); if(acnt == null) { return ""; } else { return acnt.getOrgCode(); } } public static void main(String args[]) { LgAccount lg = new LgAccount(); List privilegeList = lg.listPrivilegeDeptByLoginId("WH0607014"); for (int i = 0; i < privilegeList.size(); i++) { TsOutworkerPrivilege bean = (TsOutworkerPrivilege)privilegeList.get(i); System.out.println(bean.getAcntId()+ " -- " + bean.getAcntName()); } } }
GB18030
Java
4,091
java
LgAccount.java
Java
[]
null
[]
package server.essp.timesheet.outwork.logic; import java.util.List; import net.sf.hibernate.HibernateException; import db.essp.timesheet.TsAccount; import db.essp.timesheet.TsCodeValue; import db.essp.timesheet.TsOutworkerPrivilege; import server.essp.framework.logic.AbstractESSPLogic; import server.framework.common.BusinessException; import server.framework.taglib.util.SelectList; public class LgAccount extends AbstractESSPLogic { public String getNameByDeptId(String deptId) { try { List list = this.getDbAccessor().getSession() .createQuery("from TsAccount where account_Id = :accountId order by account_id") .setString("accountId", deptId) .list(); if(list != null && list.size() > 0) { return ((TsAccount)list.get(0)).getAccountName(); } } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listAccount", "list account by deptId error", e); } return deptId; } public synchronized List listPrivilegeDeptByLoginId(String loginId) { List list; String hql = "from TsOutworkerPrivilege where lower(login_id) = lower(:loginId)"; try { list = this.getDbAccessor().getSession() .createQuery(hql) .setString("loginId", loginId) .list(); } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listAccount", "list privilege dept error", e); } return list; } public List listAccountByDeptId(String deptId) { List list = null; try { list = this.getDbAccessor().getSession() .createQuery("from TsAccount where org_code = :orgId and account_Status = 'N' order by account_id") .setString("orgId", deptId) .list(); } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listAccount", "list account by deptId error", e); } return list; } public List listLaborByAcntRid(Long acntRid) { List list = null; String hql = "from TsLaborResource where account_Rid= :acntRid"; try { list = this.getDbAccessor().getSession() .createQuery(hql).setLong("acntRid", acntRid) .list(); } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listLabor", "list labor by deptId error", e); } return list; } public List listCodeByCodeTypeRid(Long codeTypeRid) { List list = null; String hql = "select v from TsCodeValue v " + ",TsCodeRelation r where v.rid = r.valueRid " + " and r.typeRid = :typeRid"; try { list = this.getDbAccessor().getSession() .createQuery(hql).setLong("typeRid", codeTypeRid) .list(); } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.listcode", "list code by deptId error", e); } leafFilter(list); return list; } /** * 过滤TsCodeValue列表,只留下叶子节点 * @param list */ private void leafFilter(List list) { String hql = "from TsCodeValue where parent_rid = :pRid "; try { for(int i = 0; i < list.size(); i ++) { TsCodeValue value = (TsCodeValue)list.get(i); List children = this.getDbAccessor().getSession() .createQuery(hql).setLong("pRid", value.getRid()) .list(); if(children != null && children.size() > 0) { list.remove(i); } } } catch (Exception e) { log.error(e); throw new BusinessException("error.logic.LgAccount.leafFilter", "list leaf filter error", e); } } public TsAccount getTsAccount(Long rid) { return (TsAccount) this.getDbAccessor().load(TsAccount.class, rid); } public String getAccountOrgCode(Long acntRid) { TsAccount acnt = getTsAccount(acntRid); if(acnt == null) { return ""; } else { return acnt.getOrgCode(); } } public static void main(String args[]) { LgAccount lg = new LgAccount(); List privilegeList = lg.listPrivilegeDeptByLoginId("WH0607014"); for (int i = 0; i < privilegeList.size(); i++) { TsOutworkerPrivilege bean = (TsOutworkerPrivilege)privilegeList.get(i); System.out.println(bean.getAcntId()+ " -- " + bean.getAcntName()); } } }
4,091
0.679862
0.676912
142
27.640844
23.490286
102
false
false
0
0
0
0
0
0
2.570423
false
false
3
0f94e367257f1b07439f60c9c4ad8b4c7415ceac
9,895,604,710,222
6b9588d36a20f37323724d39cf196feb31dc3103
/skycloset_malware/src/com/facebook/f/a/a/f.java
6f039cae406a2a073bbcc82b073faaf789b5882a
[]
no_license
won21kr/Malware_Project_Skycloset
https://github.com/won21kr/Malware_Project_Skycloset
f7728bef47c0b231528fdf002e3da4fea797e466
1ad90be1a68a4e9782a81ef1490f107489429c32
refs/heads/master
2022-12-07T11:27:48.119000
2019-12-16T21:39:19
2019-12-16T21:39:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.f.a.a; import android.content.Context; import android.content.res.Resources; import com.facebook.common.b.f; import com.facebook.common.d.e; import com.facebook.common.d.l; import com.facebook.f.b.a; import com.facebook.f.c.d; import com.facebook.imagepipeline.d.p; import com.facebook.imagepipeline.f.g; import com.facebook.imagepipeline.f.j; import com.facebook.imagepipeline.i.a; import java.util.Set; public class f extends Object implements l<e> { private final Context a; private final g b; private final g c; private final Set<d> d; public f(Context paramContext, b paramb) { this(paramContext, j.a(), paramb); } public f(Context paramContext, j paramj, b paramb) { this(paramContext, paramj, null, paramb); } public f(Context paramContext, j paramj, Set<d> paramSet, b paramb) { this.a = paramContext; this.b = paramj.h(); if (paramb != null && paramb.b() != null) { g1 = paramb.b(); } else { g1 = new g(); } this.c = g1; g g1 = this.c; Resources resources = paramContext.getResources(); a a1 = a.a(); a a2 = paramj.b(paramContext); f f1 = f.b(); p p = this.b.d(); paramj = null; if (paramb != null) { e e = paramb.a(); } else { paramContext = null; } if (paramb != null) l1 = paramb.c(); g1.a(resources, a1, a2, f1, p, paramContext, l1); this.d = paramSet; } public e a() { return new e(this.a, this.c, this.b, this.d); } }
UTF-8
Java
1,504
java
f.java
Java
[]
null
[]
package com.facebook.f.a.a; import android.content.Context; import android.content.res.Resources; import com.facebook.common.b.f; import com.facebook.common.d.e; import com.facebook.common.d.l; import com.facebook.f.b.a; import com.facebook.f.c.d; import com.facebook.imagepipeline.d.p; import com.facebook.imagepipeline.f.g; import com.facebook.imagepipeline.f.j; import com.facebook.imagepipeline.i.a; import java.util.Set; public class f extends Object implements l<e> { private final Context a; private final g b; private final g c; private final Set<d> d; public f(Context paramContext, b paramb) { this(paramContext, j.a(), paramb); } public f(Context paramContext, j paramj, b paramb) { this(paramContext, paramj, null, paramb); } public f(Context paramContext, j paramj, Set<d> paramSet, b paramb) { this.a = paramContext; this.b = paramj.h(); if (paramb != null && paramb.b() != null) { g1 = paramb.b(); } else { g1 = new g(); } this.c = g1; g g1 = this.c; Resources resources = paramContext.getResources(); a a1 = a.a(); a a2 = paramj.b(paramContext); f f1 = f.b(); p p = this.b.d(); paramj = null; if (paramb != null) { e e = paramb.a(); } else { paramContext = null; } if (paramb != null) l1 = paramb.c(); g1.a(resources, a1, a2, f1, p, paramContext, l1); this.d = paramSet; } public e a() { return new e(this.a, this.c, this.b, this.d); } }
1,504
0.629654
0.621011
57
25.385965
20.204876
98
false
false
0
0
0
0
0
0
1
false
false
3
3a2bc5557a034496869b487edd8800db062e583b
21,723,944,640,753
88a0e2ae46040a6852d87bf12653c95ecbdb1c52
/src/main/java/code_samples/algorithm/BinarySearch.java
ee69822a85613bd515eb888818230808e90bbf64
[]
no_license
naelir/code_samples
https://github.com/naelir/code_samples
1fa2c08b46830703c3d6e6ce10201b3d501053d5
991c57de8c6d6ccda6e3d443d74edec51652b13a
refs/heads/master
2020-03-07T03:26:38.947000
2019-03-24T13:03:47
2019-03-24T13:03:47
127,235,590
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package code_samples.algorithm; public class BinarySearch { private final int[] array; public BinarySearch(final int[] array) { this.array = array; } public int search(final int toFind, final int left, final int right) { if (right >= left) { final int middle = left + (right - left) / 2; if (this.array[middle] == toFind) return middle; else if (this.array[middle] > toFind) return this.search(toFind, left, middle - 1); else return this.search(toFind, middle + 1, right); } return -1; } }
UTF-8
Java
550
java
BinarySearch.java
Java
[]
null
[]
package code_samples.algorithm; public class BinarySearch { private final int[] array; public BinarySearch(final int[] array) { this.array = array; } public int search(final int toFind, final int left, final int right) { if (right >= left) { final int middle = left + (right - left) / 2; if (this.array[middle] == toFind) return middle; else if (this.array[middle] > toFind) return this.search(toFind, left, middle - 1); else return this.search(toFind, middle + 1, right); } return -1; } }
550
0.632727
0.625455
22
23.09091
20.194304
71
false
false
0
0
0
0
0
0
2.318182
false
false
3
831b11fa94b2f7c2b407ff1df10741909365b997
38,869,454,061,689
2d5c4791438c457da1dc78e18bdfc32f2d0da18a
/eiff-framework-test-parent/eiff-framework-test/src/main/java/com/eiff/framework/test/automock/MockInfo.java
dca21e30f2ef1670cb226b88d4f58ecb9a13b2b4
[]
no_license
mazhaohui0710/cool-framework
https://github.com/mazhaohui0710/cool-framework
632bb9fabc407d3b8cd9274c6168c3ebf95aab98
c801e3096ea8f87cdc15b3057ed55e00e0240197
refs/heads/master
2021-09-21T00:21:48.760000
2018-08-17T10:11:28
2018-08-17T10:11:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eiff.framework.test.automock; import java.util.Set; import com.eiff.framework.test.automock.group.MockClazPack; import com.eiff.framework.test.automock.vo.MockBeanDefinition; public abstract class MockInfo { public abstract Set<MockBeanDefinition> getIncludeList(); public abstract Set<MockBeanDefinition> getIncludeParentList(); public abstract Set<MockBeanDefinition> getExcludeList(); public abstract Set<MockBeanDefinition> getExcludeParentList(); public MockInfo(MockClazPack mockClazPack) { mergeBeanDefine(mockClazPack.getInclude(), this.getIncludeList()); mergeBeanDefine(mockClazPack.getIncludeParent(), this.getIncludeParentList()); mergeBeanDefine(mockClazPack.getExclude(), this.getExcludeList()); mergeBeanDefine(mockClazPack.getExcludeParent(), this.getExcludeParentList()); } private void mergeBeanDefine(Set<MockBeanDefinition> dest, Set<MockBeanDefinition> origin) { if (origin != null) { for (MockBeanDefinition define : origin) { try { Class.forName(define.getClassName()); dest.add(define); } catch (Exception e) { } } } } }
UTF-8
Java
1,114
java
MockInfo.java
Java
[]
null
[]
package com.eiff.framework.test.automock; import java.util.Set; import com.eiff.framework.test.automock.group.MockClazPack; import com.eiff.framework.test.automock.vo.MockBeanDefinition; public abstract class MockInfo { public abstract Set<MockBeanDefinition> getIncludeList(); public abstract Set<MockBeanDefinition> getIncludeParentList(); public abstract Set<MockBeanDefinition> getExcludeList(); public abstract Set<MockBeanDefinition> getExcludeParentList(); public MockInfo(MockClazPack mockClazPack) { mergeBeanDefine(mockClazPack.getInclude(), this.getIncludeList()); mergeBeanDefine(mockClazPack.getIncludeParent(), this.getIncludeParentList()); mergeBeanDefine(mockClazPack.getExclude(), this.getExcludeList()); mergeBeanDefine(mockClazPack.getExcludeParent(), this.getExcludeParentList()); } private void mergeBeanDefine(Set<MockBeanDefinition> dest, Set<MockBeanDefinition> origin) { if (origin != null) { for (MockBeanDefinition define : origin) { try { Class.forName(define.getClassName()); dest.add(define); } catch (Exception e) { } } } } }
1,114
0.770198
0.770198
36
29.944445
29.582224
93
false
false
0
0
0
0
0
0
1.861111
false
false
3
30487f014d9ebc88a644ae3f1d75e92335bd7f3e
12,120,397,771,966
e8e2a833a95c169d688f4570b9a259c1c1247568
/src/leetCode/repository/No1014BestSightseeingPair.java
c14ab8425801c48df0bb0d753e85d064883f3af9
[]
no_license
jiangxiewei/acm
https://github.com/jiangxiewei/acm
dba53b600dd1bca3de8e49a9cb56927dba11a4dd
2e53c59ce30e6c74d04c3ebf527acd9296be20e3
refs/heads/master
2023-09-05T03:57:31.851000
2023-08-18T04:10:15
2023-08-18T04:10:15
139,950,859
7
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetCode.repository; /** * 输入:[8,1,5,2,6] * 输出:11 * 解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 * * @author jiang * @date 2020/6/17 */ public class No1014BestSightseeingPair { public static void main(String[] args) { No1014BestSightseeingPair pair = new No1014BestSightseeingPair(); System.out.println(pair.maxScoreSightseeingPair(new int[]{8, 1, 5, 2, 6})); } /** * 思路: * 我们的目标是 f(i,j)=A[i] + A[j] + i - j , i<j * <br/> * 我们可以变形成 f(i,j) = A[i] + i + (A[j]-j) = g(i) + h(j) * <br/> * 然后(可以画图看看)发现,对于every j,只需要找到最大的g(i)即可. 故遍历j期间,记录下g(i)max即可 */ public int maxScoreSightseeingPair(int[] a) { int targetMax = Integer.MIN_VALUE, preMax; preMax = a[0]; for (int i = 1; i < a.length; i++) { targetMax = Math.max(a[i] - i + preMax, targetMax); preMax = Math.max(a[i] + i, preMax); } return targetMax; } }
UTF-8
Java
1,081
java
No1014BestSightseeingPair.java
Java
[ { "context": " + A[j] + i - j = 8 + 5 + 0 - 2 = 11\n *\n * @author jiang\n * @date 2020/6/17\n */\npublic class No1014BestSig", "end": 141, "score": 0.9981968402862549, "start": 136, "tag": "USERNAME", "value": "jiang" } ]
null
[]
package leetCode.repository; /** * 输入:[8,1,5,2,6] * 输出:11 * 解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 * * @author jiang * @date 2020/6/17 */ public class No1014BestSightseeingPair { public static void main(String[] args) { No1014BestSightseeingPair pair = new No1014BestSightseeingPair(); System.out.println(pair.maxScoreSightseeingPair(new int[]{8, 1, 5, 2, 6})); } /** * 思路: * 我们的目标是 f(i,j)=A[i] + A[j] + i - j , i<j * <br/> * 我们可以变形成 f(i,j) = A[i] + i + (A[j]-j) = g(i) + h(j) * <br/> * 然后(可以画图看看)发现,对于every j,只需要找到最大的g(i)即可. 故遍历j期间,记录下g(i)max即可 */ public int maxScoreSightseeingPair(int[] a) { int targetMax = Integer.MIN_VALUE, preMax; preMax = a[0]; for (int i = 1; i < a.length; i++) { targetMax = Math.max(a[i] - i + preMax, targetMax); preMax = Math.max(a[i] + i, preMax); } return targetMax; } }
1,081
0.52322
0.480908
36
25.916666
24.421501
83
false
false
0
0
0
0
0
0
0.805556
false
false
3
0980f5aa9b85cf5737fbc325adb4218f11865da9
39,384,850,119,031
f5500eb3911517a05fb58513d3567ed270406fe2
/quadribol-api/src/main/java/quadribolapi/controller/EquipeController.java
6ac691409c11051ddf0ab13f1e8268b33adc5423
[]
no_license
lucasnlima/quadribol_cup
https://github.com/lucasnlima/quadribol_cup
4df38910b41628a0891fbba6661bba39a7ea1a59
a8dfbbf571cc1249203df4545c3dff4258770131
refs/heads/main
2023-03-26T12:37:40.464000
2021-03-24T22:20:48
2021-03-24T22:20:48
328,840,879
1
1
null
false
2021-03-24T22:19:30
2021-01-12T01:44:03
2021-03-24T20:39:44
2021-03-24T22:19:28
3,227
1
1
0
Java
false
false
package quadribolapi.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import quadribolapi.domain.Time; import quadribolapi.repository.TimeRepository; @RestController @CrossOrigin(origins = "*", allowedHeaders = "*") @RequestMapping("/times") public class EquipeController { @Autowired private TimeRepository timeRepository; @GetMapping public List<Time> getTime() { return timeRepository.findAll(); } @GetMapping("/{nome}") public Time getEquipes(@PathVariable String nome) { return timeRepository.getEquipeByNome(nome); } @PostMapping public Time createEquipe(@RequestBody Time time) { return timeRepository.save(time); } }
UTF-8
Java
1,130
java
EquipeController.java
Java
[]
null
[]
package quadribolapi.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import quadribolapi.domain.Time; import quadribolapi.repository.TimeRepository; @RestController @CrossOrigin(origins = "*", allowedHeaders = "*") @RequestMapping("/times") public class EquipeController { @Autowired private TimeRepository timeRepository; @GetMapping public List<Time> getTime() { return timeRepository.findAll(); } @GetMapping("/{nome}") public Time getEquipes(@PathVariable String nome) { return timeRepository.getEquipeByNome(nome); } @PostMapping public Time createEquipe(@RequestBody Time time) { return timeRepository.save(time); } }
1,130
0.806195
0.806195
39
27.97436
22.917339
62
false
false
0
0
0
0
0
0
1
false
false
3
c1dd6a9c61280ee6537b822805e25c45c1c10bf9
39,341,900,431,585
5169a31d0ece0effa81203f65222ed9d5f2e1179
/src/main/java/com/ckp/test/facade/SubClassC.java
dfae6a9a82bed23ce4e75326f58efbe6dbf1846e
[]
no_license
yuweiqwe/DesignPattern
https://github.com/yuweiqwe/DesignPattern
d6414f50a3ea8f6e31544cea3abb620bfc6fa3cf
c037a5a29db27f2040edf19ee0b4d9488ff95d94
refs/heads/master
2023-02-19T19:34:49.822000
2023-02-09T07:59:55
2023-02-09T07:59:55
117,545,096
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ckp.test.facade; public class SubClassC { public void doSomethingC(){ System.out.println("SubClassC doSomethingC"); } }
UTF-8
Java
140
java
SubClassC.java
Java
[]
null
[]
package com.ckp.test.facade; public class SubClassC { public void doSomethingC(){ System.out.println("SubClassC doSomethingC"); } }
140
0.728571
0.728571
9
14.555555
16.506639
47
false
false
0
0
0
0
0
0
0.777778
false
false
3
b7dd43e94ee2a55a4ba263316f2ed51933528266
36,919,538,902,846
71a10512bf20614e71fbcaf0f11137308a631105
/common/src/main/java/common/datatypes/Item.java
9d6e2d8bb120d8aabb074dc2a2529961ccea9cca
[]
no_license
largecats/flink-learning
https://github.com/largecats/flink-learning
79adb551a80e18e425bffdd2c0b82d33004e644d
3b5877e54ab9ff2eab2414c095ed0811329f1a5b
refs/heads/main
2023-07-09T07:22:21.224000
2021-08-17T10:34:58
2021-08-17T10:34:58
357,517,432
1
0
null
false
2021-06-25T03:23:03
2021-04-13T10:46:10
2021-06-25T03:17:57
2021-06-25T03:23:02
138
0
0
0
Java
false
false
package common.datatypes; import common.utils.DataGenerator; import java.io.Serializable; public class Item implements Serializable { public Item() { DataGenerator g = new DataGenerator(0L); // dummy rideId this.color = new Color(g.color()); this.shape = new Shape(g.shape()); } public Item(Color color, Shape shape) { this.color = color; this.shape = shape; } public Color color; public Shape shape; public Color getColor() { return color; } public Shape getShape() { return shape; } public long getEventTime() { return System.currentTimeMillis(); } }
UTF-8
Java
673
java
Item.java
Java
[]
null
[]
package common.datatypes; import common.utils.DataGenerator; import java.io.Serializable; public class Item implements Serializable { public Item() { DataGenerator g = new DataGenerator(0L); // dummy rideId this.color = new Color(g.color()); this.shape = new Shape(g.shape()); } public Item(Color color, Shape shape) { this.color = color; this.shape = shape; } public Color color; public Shape shape; public Color getColor() { return color; } public Shape getShape() { return shape; } public long getEventTime() { return System.currentTimeMillis(); } }
673
0.61367
0.612184
33
19.39394
17.259058
64
false
false
0
0
0
0
0
0
0.424242
false
false
3
bfe8c4a83357cab3bee38941e0cd592abb6f1383
37,976,100,855,344
dd4878c975858ec16bbe4f0af97cf2017e032f4e
/sexyvc/app/src/main/java/com/qtin/sexyvc/ui/main/fragInvestor/di/FragInvestorComponent.java
252280aae5f447c5993a064cac840ee06cd754f4
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
yuchunheyuyuyu/testSexyvc
https://github.com/yuchunheyuyuyu/testSexyvc
21a31ac8639272bfeae10269818c664a129944e6
53695e6ab325f0fff8f23316df9d50572e3b4cdd
refs/heads/master
2021-04-26T23:51:10.769000
2017-10-09T02:11:45
2017-10-09T02:11:45
123,869,771
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qtin.sexyvc.ui.main.fragInvestor.di; import com.jess.arms.di.scope.FragmentScope; import com.qtin.sexyvc.common.AppComponent; import com.qtin.sexyvc.ui.main.fragInvestor.FragInvestor; import dagger.Component; /** * Created by ls on 17/4/26. */ @FragmentScope @Component(modules = FragInvestorModule.class,dependencies = AppComponent.class) public interface FragInvestorComponent { void inject(FragInvestor fragProject); }
UTF-8
Java
442
java
FragInvestorComponent.java
Java
[ { "context": "estor;\nimport dagger.Component;\n\n/**\n * Created by ls on 17/4/26.\n */\n@FragmentScope\n@Component(modules", "end": 243, "score": 0.7344153523445129, "start": 241, "tag": "USERNAME", "value": "ls" } ]
null
[]
package com.qtin.sexyvc.ui.main.fragInvestor.di; import com.jess.arms.di.scope.FragmentScope; import com.qtin.sexyvc.common.AppComponent; import com.qtin.sexyvc.ui.main.fragInvestor.FragInvestor; import dagger.Component; /** * Created by ls on 17/4/26. */ @FragmentScope @Component(modules = FragInvestorModule.class,dependencies = AppComponent.class) public interface FragInvestorComponent { void inject(FragInvestor fragProject); }
442
0.79638
0.785068
15
28.466667
23.835175
80
false
false
0
0
0
0
0
0
0.466667
false
false
3
8668c13f876452156039139bdc81b328d068b612
39,402,029,989,469
74b1bb9f79433e9e16d034adf04573e2911a0213
/common/adudewithapc/goodorevil/weapon/ItemHolySword.java
42b4182232dac1253306b0b2b6d983c473eafbbb
[]
no_license
adudewithapc/Good-Or-Evil-Mod
https://github.com/adudewithapc/Good-Or-Evil-Mod
dde9d8bd82479e0a43779f332338df19b1dc1a91
49ab9f36cac00fcc9e06de77b4f3288eca97193e
refs/heads/master
2016-09-07T22:03:39.834000
2014-04-12T07:44:14
2014-04-12T07:44:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package adudewithapc.goodorevil.weapon; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.item.EnumToolMaterial; import net.minecraft.item.ItemSword; import adudewithapc.goodorevil.GOE_Main; public class ItemHolySword extends ItemSword { public ItemHolySword(int par1, EnumToolMaterial par2EnumToolMaterial) { super(par1, par2EnumToolMaterial); this.setCreativeTab(GOE_Main.tabGoodWeapons); } public void registerIcons(IconRegister iconRegister) { itemIcon = iconRegister.registerIcon("GoodOrEvil:holysword"); } }
UTF-8
Java
558
java
ItemHolySword.java
Java
[]
null
[]
package adudewithapc.goodorevil.weapon; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.item.EnumToolMaterial; import net.minecraft.item.ItemSword; import adudewithapc.goodorevil.GOE_Main; public class ItemHolySword extends ItemSword { public ItemHolySword(int par1, EnumToolMaterial par2EnumToolMaterial) { super(par1, par2EnumToolMaterial); this.setCreativeTab(GOE_Main.tabGoodWeapons); } public void registerIcons(IconRegister iconRegister) { itemIcon = iconRegister.registerIcon("GoodOrEvil:holysword"); } }
558
0.820789
0.81362
18
30
24.986664
72
false
false
0
0
0
0
0
0
1.111111
false
false
3
ac681c2cb4b9ec523a7bcef6f60c183a832bac7c
34,909,494,230,604
e6be822e98295eef1b3b686372e1fae96eff3ed9
/src/com/test/Main_System_Test.java
22e25bc075afc69231343eede00203c465e8fe12
[]
no_license
GongchunDing/ATM_System_SQL
https://github.com/GongchunDing/ATM_System_SQL
cc244c25f1129e9afa19a40fa17fa28d1f36e4e4
e781eb6cd5f209626203cc9937a8756323be3062
refs/heads/master
2021-09-02T11:51:41.048000
2018-01-02T09:36:40
2018-01-02T09:36:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test; import com.menu.StartMenu; import java.sql.SQLException; public class Main_System_Test { /** * 测试主函数 */ public static void main(String[] args) throws SQLException { StartMenu menu=new StartMenu(); menu.start(); } }
UTF-8
Java
258
java
Main_System_Test.java
Java
[]
null
[]
package com.test; import com.menu.StartMenu; import java.sql.SQLException; public class Main_System_Test { /** * 测试主函数 */ public static void main(String[] args) throws SQLException { StartMenu menu=new StartMenu(); menu.start(); } }
258
0.697581
0.697581
16
14.5
16.874537
61
false
false
0
0
0
0
0
0
0.875
false
false
3
ce1bedccd54621383f9ea691902c5f8571416c8e
36,876,589,235,842
9d43bd809794732b99d091c912b4939b729a80fd
/src/test/java/com/yq/web/jsoup/JsoupTest.java
68686f061cdf65a233bd7c7c64efed8c60ff0abf
[]
no_license
qsyyke/javaweb-donation-system
https://github.com/qsyyke/javaweb-donation-system
16185de3ad8f689a56b62e35402d2715aff42258
55f5a9c90dbe723f04a6a085a72a8e4ffaf6d4b8
refs/heads/master
2023-06-18T20:59:16.970000
2021-07-14T11:58:24
2021-07-14T11:58:24
385,883,186
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yq.web.jsoup; import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.HtmlPage; import org.junit.Test; import java.net.URL; /** * @Author 程钦义 vipblogs.cn * @Version 1.0 */ public class JsoupTest { @Test public void test1() throws Exception { String keyWord = "Jsoup"; URL url = new URL("https://www.baidu.com/sugrec?p=3&json=1&prod=pc&from=pc_web&sugsid=33800,33822,31253,34004,33675,33607,26350&req=2&csor=5&cb=jQuery110203314006852831428_1621129582252&_=1621129582258&wd="+keyWord); com.gargoylesoftware.htmlunit.WebClient client = new com.gargoylesoftware.htmlunit.WebClient(BrowserVersion.CHROME); client.getOptions().setThrowExceptionOnScriptError(false); client.getOptions().setThrowExceptionOnFailingStatusCode(false); client.getOptions().setJavaScriptEnabled(true); client.getOptions().setCssEnabled(false); client.setAjaxController(new NicelyResynchronizingAjaxController()); client.waitForBackgroundJavaScript(300); TextPage page = client.getPage(url); System.out.println(page.getContent()); } @Test public void test2() { } }
UTF-8
Java
1,204
java
JsoupTest.java
Java
[ { "context": "junit.Test;\n\nimport java.net.URL;\n\n/**\n * @Author 程钦义 vipblogs.cn\n * @Version 1.0\n */\npublic class Jsou", "end": 183, "score": 0.9997566342353821, "start": 180, "tag": "NAME", "value": "程钦义" }, { "context": "t1() throws Exception {\n String keyWord = \"Jsoup\";\n URL url = new URL(\"https://www.baidu.co", "end": 325, "score": 0.8323541879653931, "start": 320, "tag": "KEY", "value": "Jsoup" } ]
null
[]
package com.yq.web.jsoup; import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.HtmlPage; import org.junit.Test; import java.net.URL; /** * @Author 程钦义 vipblogs.cn * @Version 1.0 */ public class JsoupTest { @Test public void test1() throws Exception { String keyWord = "Jsoup"; URL url = new URL("https://www.baidu.com/sugrec?p=3&json=1&prod=pc&from=pc_web&sugsid=33800,33822,31253,34004,33675,33607,26350&req=2&csor=5&cb=jQuery110203314006852831428_1621129582252&_=1621129582258&wd="+keyWord); com.gargoylesoftware.htmlunit.WebClient client = new com.gargoylesoftware.htmlunit.WebClient(BrowserVersion.CHROME); client.getOptions().setThrowExceptionOnScriptError(false); client.getOptions().setThrowExceptionOnFailingStatusCode(false); client.getOptions().setJavaScriptEnabled(true); client.getOptions().setCssEnabled(false); client.setAjaxController(new NicelyResynchronizingAjaxController()); client.waitForBackgroundJavaScript(300); TextPage page = client.getPage(url); System.out.println(page.getContent()); } @Test public void test2() { } }
1,204
0.717028
0.639399
37
31.378378
42.565277
224
false
false
0
0
0
0
0
0
0.594595
false
false
3
9fdbc8eef9cee78630bfa0a252a1e18972b71cd4
19,353,122,678,875
e8b04f5611f387a36e9c7edece57102b578fc565
/source_code/whitebug/Simple Home Automation Source Code/Angar/app/src/main/java/com/dennismwebia/angar/activities/DeviceActionActivity.java
ad8dcb474dc40da741ed977033accce2dd21e691
[]
no_license
perumaluniversal/whitebug
https://github.com/perumaluniversal/whitebug
ecacf373553575316b088284c23bd89ca293eedb
f4f54f031fb0204427ded99f3b438e750ebaca23
refs/heads/main
2023-02-19T00:20:07.881000
2021-01-15T07:58:33
2021-01-15T07:58:33
329,844,357
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dennismwebia.angar.activities; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SwitchCompat; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.TextView; import com.dennismwebia.angar.R; import com.dennismwebia.angar.adapters.AirConditionerListAdapter; import com.dennismwebia.angar.adapters.LightsListAdapter; import com.dennismwebia.angar.data.Data; import com.dennismwebia.angar.utils.Common; import com.dennismwebia.angar.utils.Utils; import com.dennismwebia.angar.views.TxtSemiBold; import org.json.JSONObject; import java.math.RoundingMode; import java.text.DecimalFormat; public class DeviceActionActivity extends AppCompatActivity { public static StatusAsyncTask statusthread; public TxtSemiBold txtbatteryvoltage; public TxtSemiBold txttemperature; public TxtSemiBold txtrunning; public com.dennismwebia.angar.views.Btn btnrefresh; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device_action); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarDeviceAction); Utils utils = new Utils(this, this); getExtraData(utils, toolbar); txtbatteryvoltage = findViewById(R.id.txtbatteryvoltage); txttemperature = findViewById(R.id.txttemperature); txtrunning = findViewById(R.id.txtrunning); btnrefresh = findViewById(R.id.btnrefresh); btnrefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Refresh(); } }); } private void getExtraData(Utils utils, Toolbar toolbar) { Intent intent = getIntent(); if (intent.getExtras() != null) { Bundle bundle = intent.getExtras(); if (bundle.containsKey("device_group")) { String device_group = bundle.getString("device_group"); utils.initToolbar(toolbar, device_group, DashboardActivity.class); initDeviceList(device_group); } } } private void initDeviceList(String deviceGroup) { Data data = new Data(); RecyclerView listDevices = (RecyclerView) findViewById(R.id.listDevices); listDevices.setHasFixedSize(true); listDevices.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); if (deviceGroup.contains("Lights")) { LightsListAdapter lightsListAdapter = new LightsListAdapter(this, data.lights()); listDevices.setAdapter(lightsListAdapter); } else if (deviceGroup.contains("Air Condition")) { AirConditionerListAdapter airConditionerListAdapter = new AirConditionerListAdapter(this, data.airConditioners()); listDevices.setAdapter(airConditionerListAdapter); } Refresh(); } private void Refresh() { Common.progress = ProgressDialog.show(this, "White Bug", "Getting Status.. Please wait"); DeviceActionActivity.statusthread = new StatusAsyncTask(); DeviceActionActivity.statusthread.execute(""); } private class StatusAsyncTask extends AsyncTask<String,Void,String> { @Override protected String doInBackground(String... urls) { try { return Common.GetControlStatus(); } catch (Exception ee) { Log.d("StatusAsyncTask" , ee.getMessage()); } return ""; } @Override protected void onPostExecute(String result) { //call printer code try { //14.176923076923078||39.7'C(thersold)||SOLAR Common.progress.dismiss(); String[] resarray = result.split("\\|\\|"); DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); txtbatteryvoltage.setText(df.format(Double.parseDouble(resarray[0])) + " Volt"); txttemperature.setText(resarray[1]); txtrunning.setText(resarray[2]); //switch state RecyclerView listDevices = (RecyclerView) findViewById(R.id.listDevices); int counter = listDevices.getChildCount(); JSONObject jdata = new JSONObject(resarray[3]); int i; for(i = 0; i<counter; i++) { String code = ((TextView)listDevices.getChildAt(i).findViewById(R.id.dataid)).getText().toString(); String sdata = jdata.getString(code); if(sdata!=null) { if(sdata.equals("1")) ((SwitchCompat)listDevices.getChildAt(i).findViewById(R.id.switchDevice)).setChecked(true); else ((SwitchCompat)listDevices.getChildAt(i).findViewById(R.id.switchDevice)).setChecked(false); } } } catch (Exception ee) { Log.d("Error Print call:", ee.getMessage()); } } } }
UTF-8
Java
5,688
java
DeviceActionActivity.java
Java
[]
null
[]
package com.dennismwebia.angar.activities; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SwitchCompat; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.TextView; import com.dennismwebia.angar.R; import com.dennismwebia.angar.adapters.AirConditionerListAdapter; import com.dennismwebia.angar.adapters.LightsListAdapter; import com.dennismwebia.angar.data.Data; import com.dennismwebia.angar.utils.Common; import com.dennismwebia.angar.utils.Utils; import com.dennismwebia.angar.views.TxtSemiBold; import org.json.JSONObject; import java.math.RoundingMode; import java.text.DecimalFormat; public class DeviceActionActivity extends AppCompatActivity { public static StatusAsyncTask statusthread; public TxtSemiBold txtbatteryvoltage; public TxtSemiBold txttemperature; public TxtSemiBold txtrunning; public com.dennismwebia.angar.views.Btn btnrefresh; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device_action); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarDeviceAction); Utils utils = new Utils(this, this); getExtraData(utils, toolbar); txtbatteryvoltage = findViewById(R.id.txtbatteryvoltage); txttemperature = findViewById(R.id.txttemperature); txtrunning = findViewById(R.id.txtrunning); btnrefresh = findViewById(R.id.btnrefresh); btnrefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Refresh(); } }); } private void getExtraData(Utils utils, Toolbar toolbar) { Intent intent = getIntent(); if (intent.getExtras() != null) { Bundle bundle = intent.getExtras(); if (bundle.containsKey("device_group")) { String device_group = bundle.getString("device_group"); utils.initToolbar(toolbar, device_group, DashboardActivity.class); initDeviceList(device_group); } } } private void initDeviceList(String deviceGroup) { Data data = new Data(); RecyclerView listDevices = (RecyclerView) findViewById(R.id.listDevices); listDevices.setHasFixedSize(true); listDevices.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); if (deviceGroup.contains("Lights")) { LightsListAdapter lightsListAdapter = new LightsListAdapter(this, data.lights()); listDevices.setAdapter(lightsListAdapter); } else if (deviceGroup.contains("Air Condition")) { AirConditionerListAdapter airConditionerListAdapter = new AirConditionerListAdapter(this, data.airConditioners()); listDevices.setAdapter(airConditionerListAdapter); } Refresh(); } private void Refresh() { Common.progress = ProgressDialog.show(this, "White Bug", "Getting Status.. Please wait"); DeviceActionActivity.statusthread = new StatusAsyncTask(); DeviceActionActivity.statusthread.execute(""); } private class StatusAsyncTask extends AsyncTask<String,Void,String> { @Override protected String doInBackground(String... urls) { try { return Common.GetControlStatus(); } catch (Exception ee) { Log.d("StatusAsyncTask" , ee.getMessage()); } return ""; } @Override protected void onPostExecute(String result) { //call printer code try { //14.176923076923078||39.7'C(thersold)||SOLAR Common.progress.dismiss(); String[] resarray = result.split("\\|\\|"); DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); txtbatteryvoltage.setText(df.format(Double.parseDouble(resarray[0])) + " Volt"); txttemperature.setText(resarray[1]); txtrunning.setText(resarray[2]); //switch state RecyclerView listDevices = (RecyclerView) findViewById(R.id.listDevices); int counter = listDevices.getChildCount(); JSONObject jdata = new JSONObject(resarray[3]); int i; for(i = 0; i<counter; i++) { String code = ((TextView)listDevices.getChildAt(i).findViewById(R.id.dataid)).getText().toString(); String sdata = jdata.getString(code); if(sdata!=null) { if(sdata.equals("1")) ((SwitchCompat)listDevices.getChildAt(i).findViewById(R.id.switchDevice)).setChecked(true); else ((SwitchCompat)listDevices.getChildAt(i).findViewById(R.id.switchDevice)).setChecked(false); } } } catch (Exception ee) { Log.d("Error Print call:", ee.getMessage()); } } } }
5,688
0.627813
0.622187
161
34.329193
28.666161
126
false
false
0
0
0
0
0
0
0.621118
false
false
3
4f13c14ee94320d952859573ba13cd4ce95e0cfd
35,656,818,527,960
aba62c417bc268909a00dc82ce53a15fd91fbbdd
/src/formula/FormulaParser.java
796132bc1d4bb728df6386b72771688ad0a6c208
[]
no_license
fractalic/lab9-fall2015
https://github.com/fractalic/lab9-fall2015
fea1200c1f01d20540c31d7080eb48d4930b8370
332a452fd7315f15395f3def2b8310a2a63fd557
refs/heads/master
2021-01-17T20:56:41.798000
2015-11-16T00:23:30
2015-11-16T00:23:30
45,564,078
0
0
null
true
2015-11-04T20:01:33
2015-11-04T20:01:33
2015-11-03T00:15:26
2015-10-27T17:18:28
1,395
0
0
0
null
null
null
// Generated from Formula.g4 by ANTLR 4.4 package formula; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class FormulaParser extends Parser { static { RuntimeMetaData.checkVersion("4.4", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int TRUE=1, FALSE=2, AND=3, NOT=4, WHITESPACE=5; public static final String[] tokenNames = { "<INVALID>", "TRUE", "FALSE", "'&'", "'!'", "WHITESPACE" }; public static final int RULE_formula = 0, RULE_conjunction = 1, RULE_negation = 2, RULE_literal = 3; public static final String[] ruleNames = { "formula", "conjunction", "negation", "literal" }; @Override public String getGrammarFileName() { return "Formula.g4"; } @Override public String[] getTokenNames() { return tokenNames; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } // This method makes the lexer or parser stop running if it encounters // invalid input and throw a RuntimeException. public void reportErrorsAsExceptions() { //removeErrorListeners(); addErrorListener(new ExceptionThrowingErrorListener()); } private static class ExceptionThrowingErrorListener extends BaseErrorListener { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new RuntimeException(msg); } } public FormulaParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class FormulaContext extends ParserRuleContext { public TerminalNode EOF() { return getToken(FormulaParser.EOF, 0); } public ConjunctionContext conjunction() { return getRuleContext(ConjunctionContext.class,0); } public FormulaContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_formula; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).enterFormula(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).exitFormula(this); } } public final FormulaContext formula() throws RecognitionException { FormulaContext _localctx = new FormulaContext(_ctx, getState()); enterRule(_localctx, 0, RULE_formula); try { enterOuterAlt(_localctx, 1); { setState(8); conjunction(0); setState(9); match(EOF); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ConjunctionContext extends ParserRuleContext { public NegationContext negation() { return getRuleContext(NegationContext.class,0); } public List<ConjunctionContext> conjunction() { return getRuleContexts(ConjunctionContext.class); } public TerminalNode AND() { return getToken(FormulaParser.AND, 0); } public ConjunctionContext conjunction(int i) { return getRuleContext(ConjunctionContext.class,i); } public ConjunctionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_conjunction; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).enterConjunction(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).exitConjunction(this); } } public final ConjunctionContext conjunction() throws RecognitionException { return conjunction(0); } private ConjunctionContext conjunction(int _p) throws RecognitionException { ParserRuleContext _parentctx = _ctx; int _parentState = getState(); ConjunctionContext _localctx = new ConjunctionContext(_ctx, _parentState); ConjunctionContext _prevctx = _localctx; int _startState = 2; enterRecursionRule(_localctx, 2, RULE_conjunction, _p); try { int _alt; enterOuterAlt(_localctx, 1); { { setState(12); negation(); } _ctx.stop = _input.LT(-1); setState(19); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,0,_ctx); while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { if ( _parseListeners!=null ) triggerExitRuleEvent(); _prevctx = _localctx; { { _localctx = new ConjunctionContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_conjunction); setState(14); if (!(precpred(_ctx, 2))) throw new FailedPredicateException(this, "precpred(_ctx, 2)"); setState(15); match(AND); setState(16); conjunction(3); } } } setState(21); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,0,_ctx); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { unrollRecursionContexts(_parentctx); } return _localctx; } public static class NegationContext extends ParserRuleContext { public TerminalNode NOT() { return getToken(FormulaParser.NOT, 0); } public LiteralContext literal() { return getRuleContext(LiteralContext.class,0); } public NegationContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_negation; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).enterNegation(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).exitNegation(this); } } public final NegationContext negation() throws RecognitionException { NegationContext _localctx = new NegationContext(_ctx, getState()); enterRule(_localctx, 4, RULE_negation); try { setState(25); switch (_input.LA(1)) { case TRUE: case FALSE: enterOuterAlt(_localctx, 1); { setState(22); literal(); } break; case NOT: enterOuterAlt(_localctx, 2); { setState(23); match(NOT); setState(24); literal(); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class LiteralContext extends ParserRuleContext { public TerminalNode FALSE() { return getToken(FormulaParser.FALSE, 0); } public TerminalNode TRUE() { return getToken(FormulaParser.TRUE, 0); } public LiteralContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_literal; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).enterLiteral(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).exitLiteral(this); } } public final LiteralContext literal() throws RecognitionException { LiteralContext _localctx = new LiteralContext(_ctx, getState()); enterRule(_localctx, 6, RULE_literal); int _la; try { enterOuterAlt(_localctx, 1); { setState(27); _la = _input.LA(1); if ( !(_la==TRUE || _la==FALSE) ) { _errHandler.recoverInline(this); } consume(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) { switch (ruleIndex) { case 1: return conjunction_sempred((ConjunctionContext)_localctx, predIndex); } return true; } private boolean conjunction_sempred(ConjunctionContext _localctx, int predIndex) { switch (predIndex) { case 0: return precpred(_ctx, 2); } return true; } public static final String _serializedATN = "\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\7 \4\2\t\2\4\3\t"+ "\3\4\4\t\4\4\5\t\5\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\7\3\24\n\3\f\3"+ "\16\3\27\13\3\3\4\3\4\3\4\5\4\34\n\4\3\5\3\5\3\5\2\3\4\6\2\4\6\b\2\3\3"+ "\2\3\4\35\2\n\3\2\2\2\4\r\3\2\2\2\6\33\3\2\2\2\b\35\3\2\2\2\n\13\5\4\3"+ "\2\13\f\7\2\2\3\f\3\3\2\2\2\r\16\b\3\1\2\16\17\5\6\4\2\17\25\3\2\2\2\20"+ "\21\f\4\2\2\21\22\7\5\2\2\22\24\5\4\3\5\23\20\3\2\2\2\24\27\3\2\2\2\25"+ "\23\3\2\2\2\25\26\3\2\2\2\26\5\3\2\2\2\27\25\3\2\2\2\30\34\5\b\5\2\31"+ "\32\7\6\2\2\32\34\5\b\5\2\33\30\3\2\2\2\33\31\3\2\2\2\34\7\3\2\2\2\35"+ "\36\t\2\2\2\36\t\3\2\2\2\4\25\33"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
UTF-8
Java
10,024
java
FormulaParser.java
Java
[]
null
[]
// Generated from Formula.g4 by ANTLR 4.4 package formula; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class FormulaParser extends Parser { static { RuntimeMetaData.checkVersion("4.4", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int TRUE=1, FALSE=2, AND=3, NOT=4, WHITESPACE=5; public static final String[] tokenNames = { "<INVALID>", "TRUE", "FALSE", "'&'", "'!'", "WHITESPACE" }; public static final int RULE_formula = 0, RULE_conjunction = 1, RULE_negation = 2, RULE_literal = 3; public static final String[] ruleNames = { "formula", "conjunction", "negation", "literal" }; @Override public String getGrammarFileName() { return "Formula.g4"; } @Override public String[] getTokenNames() { return tokenNames; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } // This method makes the lexer or parser stop running if it encounters // invalid input and throw a RuntimeException. public void reportErrorsAsExceptions() { //removeErrorListeners(); addErrorListener(new ExceptionThrowingErrorListener()); } private static class ExceptionThrowingErrorListener extends BaseErrorListener { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new RuntimeException(msg); } } public FormulaParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class FormulaContext extends ParserRuleContext { public TerminalNode EOF() { return getToken(FormulaParser.EOF, 0); } public ConjunctionContext conjunction() { return getRuleContext(ConjunctionContext.class,0); } public FormulaContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_formula; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).enterFormula(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).exitFormula(this); } } public final FormulaContext formula() throws RecognitionException { FormulaContext _localctx = new FormulaContext(_ctx, getState()); enterRule(_localctx, 0, RULE_formula); try { enterOuterAlt(_localctx, 1); { setState(8); conjunction(0); setState(9); match(EOF); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ConjunctionContext extends ParserRuleContext { public NegationContext negation() { return getRuleContext(NegationContext.class,0); } public List<ConjunctionContext> conjunction() { return getRuleContexts(ConjunctionContext.class); } public TerminalNode AND() { return getToken(FormulaParser.AND, 0); } public ConjunctionContext conjunction(int i) { return getRuleContext(ConjunctionContext.class,i); } public ConjunctionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_conjunction; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).enterConjunction(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).exitConjunction(this); } } public final ConjunctionContext conjunction() throws RecognitionException { return conjunction(0); } private ConjunctionContext conjunction(int _p) throws RecognitionException { ParserRuleContext _parentctx = _ctx; int _parentState = getState(); ConjunctionContext _localctx = new ConjunctionContext(_ctx, _parentState); ConjunctionContext _prevctx = _localctx; int _startState = 2; enterRecursionRule(_localctx, 2, RULE_conjunction, _p); try { int _alt; enterOuterAlt(_localctx, 1); { { setState(12); negation(); } _ctx.stop = _input.LT(-1); setState(19); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,0,_ctx); while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { if ( _parseListeners!=null ) triggerExitRuleEvent(); _prevctx = _localctx; { { _localctx = new ConjunctionContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_conjunction); setState(14); if (!(precpred(_ctx, 2))) throw new FailedPredicateException(this, "precpred(_ctx, 2)"); setState(15); match(AND); setState(16); conjunction(3); } } } setState(21); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,0,_ctx); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { unrollRecursionContexts(_parentctx); } return _localctx; } public static class NegationContext extends ParserRuleContext { public TerminalNode NOT() { return getToken(FormulaParser.NOT, 0); } public LiteralContext literal() { return getRuleContext(LiteralContext.class,0); } public NegationContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_negation; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).enterNegation(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).exitNegation(this); } } public final NegationContext negation() throws RecognitionException { NegationContext _localctx = new NegationContext(_ctx, getState()); enterRule(_localctx, 4, RULE_negation); try { setState(25); switch (_input.LA(1)) { case TRUE: case FALSE: enterOuterAlt(_localctx, 1); { setState(22); literal(); } break; case NOT: enterOuterAlt(_localctx, 2); { setState(23); match(NOT); setState(24); literal(); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class LiteralContext extends ParserRuleContext { public TerminalNode FALSE() { return getToken(FormulaParser.FALSE, 0); } public TerminalNode TRUE() { return getToken(FormulaParser.TRUE, 0); } public LiteralContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_literal; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).enterLiteral(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FormulaListener ) ((FormulaListener)listener).exitLiteral(this); } } public final LiteralContext literal() throws RecognitionException { LiteralContext _localctx = new LiteralContext(_ctx, getState()); enterRule(_localctx, 6, RULE_literal); int _la; try { enterOuterAlt(_localctx, 1); { setState(27); _la = _input.LA(1); if ( !(_la==TRUE || _la==FALSE) ) { _errHandler.recoverInline(this); } consume(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) { switch (ruleIndex) { case 1: return conjunction_sempred((ConjunctionContext)_localctx, predIndex); } return true; } private boolean conjunction_sempred(ConjunctionContext _localctx, int predIndex) { switch (predIndex) { case 0: return precpred(_ctx, 2); } return true; } public static final String _serializedATN = "\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\7 \4\2\t\2\4\3\t"+ "\3\4\4\t\4\4\5\t\5\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\7\3\24\n\3\f\3"+ "\16\3\27\13\3\3\4\3\4\3\4\5\4\34\n\4\3\5\3\5\3\5\2\3\4\6\2\4\6\b\2\3\3"+ "\2\3\4\35\2\n\3\2\2\2\4\r\3\2\2\2\6\33\3\2\2\2\b\35\3\2\2\2\n\13\5\4\3"+ "\2\13\f\7\2\2\3\f\3\3\2\2\2\r\16\b\3\1\2\16\17\5\6\4\2\17\25\3\2\2\2\20"+ "\21\f\4\2\2\21\22\7\5\2\2\22\24\5\4\3\5\23\20\3\2\2\2\24\27\3\2\2\2\25"+ "\23\3\2\2\2\25\26\3\2\2\2\26\5\3\2\2\2\27\25\3\2\2\2\30\34\5\b\5\2\31"+ "\32\7\6\2\2\32\34\5\b\5\2\33\30\3\2\2\2\33\31\3\2\2\2\34\7\3\2\2\2\35"+ "\36\t\2\2\2\36\t\3\2\2\2\4\25\33"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
10,024
0.692837
0.655826
316
30.724684
27.131598
97
false
false
0
0
48
0.004789
0
0
2.740506
false
false
3
b6baab1f3859c1fa2fe9b61b98356ca1088b4a99
39,599,598,470,661
3a1b817888933d52d6b23aaeae000c283d7906e0
/src/view/ViewLevel.java
c257d633e2e0bf160d7e5cf962f066394430613f
[ "MIT" ]
permissive
thibauth01/Mastermind
https://github.com/thibauth01/Mastermind
2dbfd43bf197d8f5fd35ab62b0910e2915a7444d
ccc4c10d7d7365bc1cbdda0f6650691c300a1330
refs/heads/master
2020-08-11T23:20:15.893000
2018-12-21T14:41:56
2018-12-21T14:41:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package view; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.border.EmptyBorder; import model.ModelGame; import java.awt.GridBagLayout; import javax.swing.JButton; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import java.awt.Font; /** * @author BOHYN Gauthier * @author HERMANT Thibaut * @author MEYERS Humbert * La vue du jeu en GUI pour le choix du niveau */ public class ViewLevel extends JFrame implements ActionListener { ModelGame GameControllerGui = new ModelGame(); private JPanel contentPane; private JTextField textField; private JLabel Title,lblEncoderLadresseIp,lblHardh,lblNormaln,lblEasye,lbErreur; private JButton btnEnter; String temp=""; /** * Launch the application. * @param args les paramètres du jeu. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ViewLevel frame = new ViewLevel(); frame.setVisible(true); frame.setTitle("Number Mastermind"); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ViewLevel() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 400, 400); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); GridBagLayout gbl_contentPane = new GridBagLayout(); gbl_contentPane.columnWidths = new int[]{0, 0, 0}; gbl_contentPane.rowHeights = new int[]{10, 90, 20, 50, 50, 20, 20,20, 80}; gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 0.0}; gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; contentPane.setLayout(gbl_contentPane); Title = new JLabel("Number Mastermind"); Title.setHorizontalAlignment(SwingConstants.LEFT); Title.setFont(new Font("Lucida Grande", Font.PLAIN, 37)); GridBagConstraints gbc_Title = new GridBagConstraints(); gbc_Title.gridwidth = 3; gbc_Title.insets = new Insets(0, 0, 5, 0); gbc_Title.gridx = 0; gbc_Title.gridy = 1; contentPane.add(Title, gbc_Title); lblEncoderLadresseIp = new JLabel("Please enter your difficulty:"); lblEncoderLadresseIp.setFont(new Font("Lucida Grande", Font.PLAIN, 20)); GridBagConstraints gbc_lblEncoderLadresseIp = new GridBagConstraints(); gbc_lblEncoderLadresseIp.anchor = GridBagConstraints.SOUTHWEST; gbc_lblEncoderLadresseIp.gridwidth = 3; gbc_lblEncoderLadresseIp.insets = new Insets(0, 0, 5, 0); gbc_lblEncoderLadresseIp.gridx = 0; gbc_lblEncoderLadresseIp.gridy = 3; contentPane.add(lblEncoderLadresseIp, gbc_lblEncoderLadresseIp); btnEnter = new JButton("Enter"); btnEnter.setFont(new Font("Lucida Grande", Font.PLAIN, 17)); GridBagConstraints gbc_btnEnter = new GridBagConstraints(); gbc_btnEnter.insets = new Insets(0, 0, 5, 5); gbc_btnEnter.gridx = 0; gbc_btnEnter.gridy = 4; contentPane.add(btnEnter, gbc_btnEnter); btnEnter.addActionListener(this); JRootPane rootPane = SwingUtilities.getRootPane(btnEnter); rootPane.setDefaultButton(btnEnter); rootPane.setVisible(true); textField = new JTextField(); textField.setColumns(10); GridBagConstraints gbc_textField = new GridBagConstraints(); gbc_textField.insets = new Insets(0, 0, 5, 5); gbc_textField.fill = GridBagConstraints.HORIZONTAL; gbc_textField.gridx = 1; gbc_textField.gridy = 4; contentPane.add(textField, gbc_textField); setVisible(true); textField.requestFocus(); lblHardh = new JLabel("Hard = 'H' 5 chances"); GridBagConstraints gbc_lblHardh = new GridBagConstraints(); gbc_lblHardh.anchor = GridBagConstraints.WEST; gbc_lblHardh.insets = new Insets(0, 0, 5, 5); gbc_lblHardh.gridx = 1; gbc_lblHardh.gridy = 5; contentPane.add(lblHardh, gbc_lblHardh); lblNormaln = new JLabel("Normal = 'N' 9 chances"); GridBagConstraints gbc_lblNormaln = new GridBagConstraints(); gbc_lblNormaln.anchor = GridBagConstraints.WEST; gbc_lblNormaln.insets = new Insets(0, 0, 5, 5); gbc_lblNormaln.gridx = 1; gbc_lblNormaln.gridy = 6; contentPane.add(lblNormaln, gbc_lblNormaln); lblEasye = new JLabel("Easy = 'E' 12 chances"); GridBagConstraints gbc_lblEasye = new GridBagConstraints(); gbc_lblEasye.anchor = GridBagConstraints.WEST; gbc_lblEasye.insets = new Insets(0, 0, 5, 5); gbc_lblEasye.gridx = 1; gbc_lblEasye.gridy = 7; contentPane.add(lblEasye, gbc_lblEasye); lbErreur = new JLabel(""); lbErreur.setFont(new Font("Lucida Grande", Font.PLAIN, 15)); GridBagConstraints gbc_lbErreur = new GridBagConstraints(); gbc_lbErreur.anchor = GridBagConstraints.WEST; gbc_lbErreur.insets = new Insets(0, 0, 0, 5); gbc_lbErreur.gridx = 1; gbc_lbErreur.gridy = 8; contentPane.add(lbErreur, gbc_lbErreur); } @Override public void actionPerformed(ActionEvent e) { switch(e.getActionCommand()){ case"Enter": ViewGameSolo ViewGameSolo = new ViewGameSolo(); if(!(GameControllerGui.isLevelCorrect(textField.getText()))){ lbErreur.setText("Value no correct"); textField.setText(""); } else { ViewGameSolo.levelSolo = GameControllerGui.levelSolo(textField.getText()); ViewGameSolo.setVisible(true); this.dispose(); } break; } } }
UTF-8
Java
5,535
java
ViewLevel.java
Java
[ { "context": "ngUtilities;\nimport java.awt.Font;\n\n/**\n * @author BOHYN Gauthier\n * @author HERMANT Thibaut\n * @author MEYERS Humb", "end": 564, "score": 0.9998660087585449, "start": 550, "tag": "NAME", "value": "BOHYN Gauthier" }, { "context": "wt.Font;\n\n/**\n * @author BOHYN Gauthier\n * @author HERMANT Thibaut\n * @author MEYERS Humbert\n * La vue du jeu en GUI", "end": 591, "score": 0.9998582601547241, "start": 576, "tag": "NAME", "value": "HERMANT Thibaut" }, { "context": "HYN Gauthier\n * @author HERMANT Thibaut\n * @author MEYERS Humbert\n * La vue du jeu en GUI pour le choix du niveau\n ", "end": 617, "score": 0.9998593330383301, "start": 603, "tag": "NAME", "value": "MEYERS Humbert" } ]
null
[]
package view; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.border.EmptyBorder; import model.ModelGame; import java.awt.GridBagLayout; import javax.swing.JButton; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import java.awt.Font; /** * @author <NAME> * @author <NAME> * @author <NAME> * La vue du jeu en GUI pour le choix du niveau */ public class ViewLevel extends JFrame implements ActionListener { ModelGame GameControllerGui = new ModelGame(); private JPanel contentPane; private JTextField textField; private JLabel Title,lblEncoderLadresseIp,lblHardh,lblNormaln,lblEasye,lbErreur; private JButton btnEnter; String temp=""; /** * Launch the application. * @param args les paramètres du jeu. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ViewLevel frame = new ViewLevel(); frame.setVisible(true); frame.setTitle("Number Mastermind"); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ViewLevel() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 400, 400); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); GridBagLayout gbl_contentPane = new GridBagLayout(); gbl_contentPane.columnWidths = new int[]{0, 0, 0}; gbl_contentPane.rowHeights = new int[]{10, 90, 20, 50, 50, 20, 20,20, 80}; gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 0.0}; gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; contentPane.setLayout(gbl_contentPane); Title = new JLabel("Number Mastermind"); Title.setHorizontalAlignment(SwingConstants.LEFT); Title.setFont(new Font("Lucida Grande", Font.PLAIN, 37)); GridBagConstraints gbc_Title = new GridBagConstraints(); gbc_Title.gridwidth = 3; gbc_Title.insets = new Insets(0, 0, 5, 0); gbc_Title.gridx = 0; gbc_Title.gridy = 1; contentPane.add(Title, gbc_Title); lblEncoderLadresseIp = new JLabel("Please enter your difficulty:"); lblEncoderLadresseIp.setFont(new Font("Lucida Grande", Font.PLAIN, 20)); GridBagConstraints gbc_lblEncoderLadresseIp = new GridBagConstraints(); gbc_lblEncoderLadresseIp.anchor = GridBagConstraints.SOUTHWEST; gbc_lblEncoderLadresseIp.gridwidth = 3; gbc_lblEncoderLadresseIp.insets = new Insets(0, 0, 5, 0); gbc_lblEncoderLadresseIp.gridx = 0; gbc_lblEncoderLadresseIp.gridy = 3; contentPane.add(lblEncoderLadresseIp, gbc_lblEncoderLadresseIp); btnEnter = new JButton("Enter"); btnEnter.setFont(new Font("Lucida Grande", Font.PLAIN, 17)); GridBagConstraints gbc_btnEnter = new GridBagConstraints(); gbc_btnEnter.insets = new Insets(0, 0, 5, 5); gbc_btnEnter.gridx = 0; gbc_btnEnter.gridy = 4; contentPane.add(btnEnter, gbc_btnEnter); btnEnter.addActionListener(this); JRootPane rootPane = SwingUtilities.getRootPane(btnEnter); rootPane.setDefaultButton(btnEnter); rootPane.setVisible(true); textField = new JTextField(); textField.setColumns(10); GridBagConstraints gbc_textField = new GridBagConstraints(); gbc_textField.insets = new Insets(0, 0, 5, 5); gbc_textField.fill = GridBagConstraints.HORIZONTAL; gbc_textField.gridx = 1; gbc_textField.gridy = 4; contentPane.add(textField, gbc_textField); setVisible(true); textField.requestFocus(); lblHardh = new JLabel("Hard = 'H' 5 chances"); GridBagConstraints gbc_lblHardh = new GridBagConstraints(); gbc_lblHardh.anchor = GridBagConstraints.WEST; gbc_lblHardh.insets = new Insets(0, 0, 5, 5); gbc_lblHardh.gridx = 1; gbc_lblHardh.gridy = 5; contentPane.add(lblHardh, gbc_lblHardh); lblNormaln = new JLabel("Normal = 'N' 9 chances"); GridBagConstraints gbc_lblNormaln = new GridBagConstraints(); gbc_lblNormaln.anchor = GridBagConstraints.WEST; gbc_lblNormaln.insets = new Insets(0, 0, 5, 5); gbc_lblNormaln.gridx = 1; gbc_lblNormaln.gridy = 6; contentPane.add(lblNormaln, gbc_lblNormaln); lblEasye = new JLabel("Easy = 'E' 12 chances"); GridBagConstraints gbc_lblEasye = new GridBagConstraints(); gbc_lblEasye.anchor = GridBagConstraints.WEST; gbc_lblEasye.insets = new Insets(0, 0, 5, 5); gbc_lblEasye.gridx = 1; gbc_lblEasye.gridy = 7; contentPane.add(lblEasye, gbc_lblEasye); lbErreur = new JLabel(""); lbErreur.setFont(new Font("Lucida Grande", Font.PLAIN, 15)); GridBagConstraints gbc_lbErreur = new GridBagConstraints(); gbc_lbErreur.anchor = GridBagConstraints.WEST; gbc_lbErreur.insets = new Insets(0, 0, 0, 5); gbc_lbErreur.gridx = 1; gbc_lbErreur.gridy = 8; contentPane.add(lbErreur, gbc_lbErreur); } @Override public void actionPerformed(ActionEvent e) { switch(e.getActionCommand()){ case"Enter": ViewGameSolo ViewGameSolo = new ViewGameSolo(); if(!(GameControllerGui.isLevelCorrect(textField.getText()))){ lbErreur.setText("Value no correct"); textField.setText(""); } else { ViewGameSolo.levelSolo = GameControllerGui.levelSolo(textField.getText()); ViewGameSolo.setVisible(true); this.dispose(); } break; } } }
5,510
0.718648
0.696422
172
31.174419
21.317474
84
false
false
0
0
0
0
0
0
2.819767
false
false
3
d2ed507b79c5b65e11591851b13156631138be5e
26,877,905,361,277
d3197e32327401ab7736a3f9bdf61b9c48439f72
/app/src/main/java/com/cafedroid/gpstrackerapp/JoinCircleActivity.java
925fc53d07db4f56cdcc14df6c13f9ff5289c638
[]
no_license
rachitbhutani1998/GPS-Tracker
https://github.com/rachitbhutani1998/GPS-Tracker
78a6bcbdd898d5ae72cfc9c1c9fd57f27788eecb
42701da91a44fdcd15666b879c553261a7b3a9e8
refs/heads/master
2020-04-13T04:19:08.998000
2018-12-24T06:22:49
2018-12-24T06:22:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cafedroid.gpstrackerapp; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; import com.goodiebag.pinview.Pinview; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; 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.Query; import com.google.firebase.database.ValueEventListener; public class JoinCircleActivity extends AppCompatActivity { Pinview pinview; DatabaseReference reference,currentReference,circleReference; FirebaseUser user; FirebaseAuth auth; String current_user_id,join_user_id; String name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_join_circle); auth = FirebaseAuth.getInstance(); user = auth.getCurrentUser(); pinview = findViewById(R.id.pinview); reference = FirebaseDatabase.getInstance().getReference().child("Users"); currentReference = FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid()); current_user_id= user.getUid(); name = user.getDisplayName(); } public void submitButton(View v){ Query query =reference.orderByChild("code").equalTo(pinview.getValue()); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ for(DataSnapshot childss: dataSnapshot.getChildren()) { join_user_id = childss.getKey(); circleReference = FirebaseDatabase.getInstance().getReference().child("Users") .child(join_user_id).child("circleMembers"); CircleJoin circleJoin = new CircleJoin(current_user_id); CircleJoin circleJoin1 = new CircleJoin(join_user_id); circleReference.child(current_user_id).setValue(name) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(getApplicationContext(), "User joined Successfully", Toast.LENGTH_SHORT).show(); } } }); } } else{ Toast.makeText(JoinCircleActivity.this, "Invalid Circle Code", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
UTF-8
Java
3,433
java
JoinCircleActivity.java
Java
[ { "context": "package com.cafedroid.gpstrackerapp;\n\nimport android.support.annotation", "end": 21, "score": 0.5682480931282043, "start": 17, "tag": "USERNAME", "value": "roid" } ]
null
[]
package com.cafedroid.gpstrackerapp; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; import com.goodiebag.pinview.Pinview; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; 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.Query; import com.google.firebase.database.ValueEventListener; public class JoinCircleActivity extends AppCompatActivity { Pinview pinview; DatabaseReference reference,currentReference,circleReference; FirebaseUser user; FirebaseAuth auth; String current_user_id,join_user_id; String name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_join_circle); auth = FirebaseAuth.getInstance(); user = auth.getCurrentUser(); pinview = findViewById(R.id.pinview); reference = FirebaseDatabase.getInstance().getReference().child("Users"); currentReference = FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid()); current_user_id= user.getUid(); name = user.getDisplayName(); } public void submitButton(View v){ Query query =reference.orderByChild("code").equalTo(pinview.getValue()); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ for(DataSnapshot childss: dataSnapshot.getChildren()) { join_user_id = childss.getKey(); circleReference = FirebaseDatabase.getInstance().getReference().child("Users") .child(join_user_id).child("circleMembers"); CircleJoin circleJoin = new CircleJoin(current_user_id); CircleJoin circleJoin1 = new CircleJoin(join_user_id); circleReference.child(current_user_id).setValue(name) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(getApplicationContext(), "User joined Successfully", Toast.LENGTH_SHORT).show(); } } }); } } else{ Toast.makeText(JoinCircleActivity.this, "Invalid Circle Code", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
3,433
0.617244
0.616662
102
32.666668
31.456579
139
false
false
0
0
0
0
0
0
0.490196
false
false
3
2bb784fe1779073d256f426bb816f68a8e092bb8
14,568,529,112,472
6470df0bb53db4726bea6bf564d1febd7e025936
/BBS-src/com/laoer/bbscs/service/mail/TemplateMail.java
c31e894924de1060b5a80fec28b0ba6b1fab5bcd
[]
no_license
yunlugu/yunluyuan-bbs
https://github.com/yunlugu/yunluyuan-bbs
3d9a8069f4eb1843859a8dff117680037d2ec471
9d3121246c2b65a371e129c7b34f6680c748f319
refs/heads/master
2021-01-24T01:29:54.622000
2018-02-25T06:43:51
2018-02-25T06:43:51
122,812,187
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.laoer.bbscs.service.mail; import freemarker.template.*; import java.io.*; import java.util.*; import javax.mail.internet.InternetAddress; import org.apache.commons.mail.*; import org.apache.commons.logging.*; //import org.springframework.core.io.*; import com.laoer.bbscs.service.config.SysConfig; import com.laoer.bbscs.comm.*; public class TemplateMail { private static final Log logger = LogFactory.getLog(TemplateMail.class); private Configuration tempConfiguration = new Configuration(); private HtmlEmail htmlEmail; private SysConfig sysConfig; public SysConfig getSysConfig() { return sysConfig; } public void setSysConfig(SysConfig sysConfig) { this.sysConfig = sysConfig; } public HtmlEmail getHtmlEmail() { return htmlEmail; } public void setHtmlEmail(HtmlEmail htmlEmail) { this.htmlEmail = htmlEmail; } public Configuration getTempConfiguration() { return tempConfiguration; } public void setTempConfiguration(Configuration tempConfiguration) { this.tempConfiguration = tempConfiguration; } public void init() throws Exception { this.htmlEmail = new HtmlEmail(); if (this.getSysConfig().getSmtpAuth() == 1) { DefaultAuthenticator defaultAuthenticator = new DefaultAuthenticator( this.getSysConfig().getSmtpUser(), this.getSysConfig() .getSmtpPasswd()); this.getHtmlEmail().setAuthenticator(defaultAuthenticator); } this.getHtmlEmail().setHostName(this.getSysConfig().getSmtpServer()); this.getHtmlEmail().setSmtpPort(this.getSysConfig().getSmtpPort()); this.getHtmlEmail().setFrom(this.getSysConfig().getSenderEmail()); this.getHtmlEmail().setTextMsg( "Your email client does not support HTML messages"); this.getHtmlEmail().setCharset(Constant.CHARSET); this.getTempConfiguration().setDirectoryForTemplateLoading(new File(Constant.ROOTPATH + Constant.FTL_PATH)); //ClassPathResource cpr = new ClassPathResource("/templates/"); //System.out.println(cpr.getFile()); //this.getTempConfiguration().setDirectoryForTemplateLoading(cpr.getFile()); this.getTempConfiguration().setDefaultEncoding(Constant.CHARSET); this.getTempConfiguration().setNumberFormat("0.##########"); } public void sendMailFromTemplate(String to, String subject, String ftlName, Map root, Locale locale) { try { //this.init(); this.getTempConfiguration().setLocale(locale); this.getHtmlEmail().setSubject(subject); Template temp = this.getTempConfiguration().getTemplate(ftlName); StringWriter sw = new StringWriter(); temp.process(root, sw); this.getHtmlEmail().setHtmlMsg(sw.toString()); List<InternetAddress> list=new ArrayList<InternetAddress>(); list.add(new InternetAddress(to)); //this.getHtmlEmail().addTo(to); this.getHtmlEmail().setTo(list); this.getHtmlEmail().send(); sw.flush(); } catch (Exception e) { logger.error(e); } } }
UTF-8
Java
2,983
java
TemplateMail.java
Java
[]
null
[]
package com.laoer.bbscs.service.mail; import freemarker.template.*; import java.io.*; import java.util.*; import javax.mail.internet.InternetAddress; import org.apache.commons.mail.*; import org.apache.commons.logging.*; //import org.springframework.core.io.*; import com.laoer.bbscs.service.config.SysConfig; import com.laoer.bbscs.comm.*; public class TemplateMail { private static final Log logger = LogFactory.getLog(TemplateMail.class); private Configuration tempConfiguration = new Configuration(); private HtmlEmail htmlEmail; private SysConfig sysConfig; public SysConfig getSysConfig() { return sysConfig; } public void setSysConfig(SysConfig sysConfig) { this.sysConfig = sysConfig; } public HtmlEmail getHtmlEmail() { return htmlEmail; } public void setHtmlEmail(HtmlEmail htmlEmail) { this.htmlEmail = htmlEmail; } public Configuration getTempConfiguration() { return tempConfiguration; } public void setTempConfiguration(Configuration tempConfiguration) { this.tempConfiguration = tempConfiguration; } public void init() throws Exception { this.htmlEmail = new HtmlEmail(); if (this.getSysConfig().getSmtpAuth() == 1) { DefaultAuthenticator defaultAuthenticator = new DefaultAuthenticator( this.getSysConfig().getSmtpUser(), this.getSysConfig() .getSmtpPasswd()); this.getHtmlEmail().setAuthenticator(defaultAuthenticator); } this.getHtmlEmail().setHostName(this.getSysConfig().getSmtpServer()); this.getHtmlEmail().setSmtpPort(this.getSysConfig().getSmtpPort()); this.getHtmlEmail().setFrom(this.getSysConfig().getSenderEmail()); this.getHtmlEmail().setTextMsg( "Your email client does not support HTML messages"); this.getHtmlEmail().setCharset(Constant.CHARSET); this.getTempConfiguration().setDirectoryForTemplateLoading(new File(Constant.ROOTPATH + Constant.FTL_PATH)); //ClassPathResource cpr = new ClassPathResource("/templates/"); //System.out.println(cpr.getFile()); //this.getTempConfiguration().setDirectoryForTemplateLoading(cpr.getFile()); this.getTempConfiguration().setDefaultEncoding(Constant.CHARSET); this.getTempConfiguration().setNumberFormat("0.##########"); } public void sendMailFromTemplate(String to, String subject, String ftlName, Map root, Locale locale) { try { //this.init(); this.getTempConfiguration().setLocale(locale); this.getHtmlEmail().setSubject(subject); Template temp = this.getTempConfiguration().getTemplate(ftlName); StringWriter sw = new StringWriter(); temp.process(root, sw); this.getHtmlEmail().setHtmlMsg(sw.toString()); List<InternetAddress> list=new ArrayList<InternetAddress>(); list.add(new InternetAddress(to)); //this.getHtmlEmail().addTo(to); this.getHtmlEmail().setTo(list); this.getHtmlEmail().send(); sw.flush(); } catch (Exception e) { logger.error(e); } } }
2,983
0.723098
0.722427
97
28.752577
25.692884
110
false
false
0
0
0
0
0
0
1.927835
false
false
3
50e6a6df4cf9f0916414d3ccdca0551e78837647
15,247,133,951,930
f66dfe35a66fd66853773816e91373dc8f264297
/src/main/java/string/StringDemo4.java
88742213754fa13f417733e39316f0ea0b37423e
[]
no_license
fyjjhy/demo
https://github.com/fyjjhy/demo
fe312c51d2da806ae68ae1d3dc39803c5a3cc3f1
0ea5873894a18abdf2dfd9091e5b6efe0962a888
refs/heads/master
2020-04-25T21:32:27.763000
2019-10-21T15:32:12
2019-10-21T15:32:12
173,082,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package string; /** * <Description> 将一个基本数据类型转为字符串<br> *【方式】 * 1.基本数据类型.toString() -- 快 * 2.String.valueOf(数据) -- 次之 * 3.数据+"" --慢 * @author 付永杰<br> * @version 1.0<br> * @taskId <br> * @CreateDate 2019/4/12 * @see string <br> * @since V1.0<br> */ public class StringDemo4 { private static final int SUM = 100000; public static void main(String[] args) { long startTime1 = System.currentTimeMillis(); System.out.println("测试方式1:基本数据类型.toString() 开始执行!"); for (int i = 0; i < SUM; i++) { String str = Integer.toString(i); } System.out.println("测试方式1:基本数据类型.toString() 结束执行!" + (System.currentTimeMillis() - startTime1)); long startTime2 = System.currentTimeMillis(); System.out.println("测试方式2:String.valueOf(数据) 开始执行!"); for (int i = 0; i < SUM; i++) { String str = String.valueOf(i); } System.out.println("测试方式2:String.valueOf(数据) 结束执行!" + (System.currentTimeMillis() - startTime2)); long startTime3 = System.currentTimeMillis(); System.out.println("测试方式3:数据+'' 开始执行!"); for (int i = 0; i < SUM; i++) { String str = i + ""; } System.out.println("测试方式3:数据+'' 结束执行!" + (System.currentTimeMillis() - startTime3)); } }
UTF-8
Java
1,390
java
StringDemo4.java
Java
[ { "context": "tring.valueOf(数据) -- 次之\n * 3.数据+\"\" --慢\n * @author 付永杰<br>\n * @version 1.0<br>\n * @taskId <br>\n * @Creat", "end": 151, "score": 0.9997063279151917, "start": 148, "tag": "NAME", "value": "付永杰" } ]
null
[]
package string; /** * <Description> 将一个基本数据类型转为字符串<br> *【方式】 * 1.基本数据类型.toString() -- 快 * 2.String.valueOf(数据) -- 次之 * 3.数据+"" --慢 * @author 付永杰<br> * @version 1.0<br> * @taskId <br> * @CreateDate 2019/4/12 * @see string <br> * @since V1.0<br> */ public class StringDemo4 { private static final int SUM = 100000; public static void main(String[] args) { long startTime1 = System.currentTimeMillis(); System.out.println("测试方式1:基本数据类型.toString() 开始执行!"); for (int i = 0; i < SUM; i++) { String str = Integer.toString(i); } System.out.println("测试方式1:基本数据类型.toString() 结束执行!" + (System.currentTimeMillis() - startTime1)); long startTime2 = System.currentTimeMillis(); System.out.println("测试方式2:String.valueOf(数据) 开始执行!"); for (int i = 0; i < SUM; i++) { String str = String.valueOf(i); } System.out.println("测试方式2:String.valueOf(数据) 结束执行!" + (System.currentTimeMillis() - startTime2)); long startTime3 = System.currentTimeMillis(); System.out.println("测试方式3:数据+'' 开始执行!"); for (int i = 0; i < SUM; i++) { String str = i + ""; } System.out.println("测试方式3:数据+'' 结束执行!" + (System.currentTimeMillis() - startTime3)); } }
1,390
0.639078
0.608362
42
26.904762
25.037886
99
false
false
0
0
0
0
0
0
1.47619
false
false
3
e379ee6228e96f23be1ae75784812b36d87e1aea
28,595,892,260,359
ad77897212015ef59b2b5fd28956d1410dd0a332
/src/test/java/com/lamfire/jmongo/test/entity/GeoEntity.java
a0940f72dd96f48096405c18d7e549963fe48ac1
[]
no_license
lamfire/jmongo-3
https://github.com/lamfire/jmongo-3
525f2cb2fd037b955f001dbce122fe7876ca84e6
8d52764357ede9e3bff432d0a7747802f4f3f361
refs/heads/master
2023-01-12T16:01:26.695000
2022-12-28T06:36:27
2022-12-28T06:36:27
131,264,924
4
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lamfire.jmongo.test.entity; import com.lamfire.jmongo.annotations.Entity; import com.lamfire.jmongo.annotations.Id; import com.lamfire.jmongo.annotations.Indexed; import com.lamfire.jmongo.utils.IndexDirection; /** * Created by linfan on 2017/8/9. */ @Entity public class GeoEntity { @Id private String id; private String name; @Indexed(IndexDirection.GEO2D) private double[] location; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double[] getLocation() { return location; } public void setLocation(double[] location) { this.location = location; } }
UTF-8
Java
832
java
GeoEntity.java
Java
[ { "context": "re.jmongo.utils.IndexDirection;\n\n/**\n * Created by linfan on 2017/8/9.\n */\n@Entity\npublic class GeoEntity {", "end": 249, "score": 0.9996840953826904, "start": 243, "tag": "USERNAME", "value": "linfan" } ]
null
[]
package com.lamfire.jmongo.test.entity; import com.lamfire.jmongo.annotations.Entity; import com.lamfire.jmongo.annotations.Id; import com.lamfire.jmongo.annotations.Indexed; import com.lamfire.jmongo.utils.IndexDirection; /** * Created by linfan on 2017/8/9. */ @Entity public class GeoEntity { @Id private String id; private String name; @Indexed(IndexDirection.GEO2D) private double[] location; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double[] getLocation() { return location; } public void setLocation(double[] location) { this.location = location; } }
832
0.641827
0.633413
44
17.90909
16.265997
48
false
false
0
0
0
0
0
0
0.318182
false
false
3
e24531e330dfd600bd7b4cff64f9895fbd91b527
21,577,915,760,846
e5df68e21177611c4bb952a864e82e3beb71793b
/src/main/java/collection/ArrayListNewConcept.java
93d3f99403664320379263e42bf29aaf9dc6d867
[]
no_license
arjunkumayan/JavaLearningScope
https://github.com/arjunkumayan/JavaLearningScope
a84f6347a4abe80d28c398069adc305a68101a0a
cf9e6add0e904639b7874a527d0c1ba114b15230
refs/heads/master
2022-12-28T12:24:42.961000
2020-09-24T14:35:27
2020-09-24T14:35:27
258,993,061
0
0
null
false
2020-10-13T21:30:53
2020-04-26T09:42:49
2020-09-24T14:33:59
2020-10-13T21:30:52
85,769
0
0
1
Java
false
false
package collection; import java.util.ArrayList; import java.util.Iterator; /** * * @author asingh6766 * */ public class ArrayListNewConcept { public static <E> void main(String[] args) { // ArrayList - it is dynamic array int a[]=new int[2]; // static array - it will indexOutOfBound exception if try to use the value at a[4] // size is fixed // Dynamic array- ArrayList // 1. can contain duplicate values // 2- it maintain insertion order // 3. Not synchronized - not thread safe // 4/ allows random access because it allows/stores values on the basis of index ArrayList arr=new ArrayList(); arr.add(10); arr.add(20); arr.add(30); arr.add(70); System.out.println(arr.size()); arr.add(40); arr.add(50); arr.add(50); arr.add("arjun"); arr.add('e'); arr.add(13.4f); System.out.println(arr.size()); System.out.println(arr.get(6)+" "+arr.get(5)); for(int i=0;i<arr.size();i++) { System.out.println("ArrayList values are: "+arr.get(i)); } ArrayList<Integer> arr1=new ArrayList<Integer>(); arr1.add(100); //arr1.add("selenium"); ArrayList<String> arr2=new ArrayList<String>(); arr2.add("Arjun"); ArrayList<E> arr5=new ArrayList<E>(); // I can store user defined class object also EmployeeDetails e1=new EmployeeDetails("Arjun",26,"QA"); EmployeeDetails e2=new EmployeeDetails("Naveen",29,"Dev"); EmployeeDetails e3=new EmployeeDetails("Sameer",26,"Java"); ArrayList<EmployeeDetails> alist=new ArrayList<EmployeeDetails>(); alist.add(e1); alist.add(e2); alist.add(e3); Iterator<EmployeeDetails> it=alist.iterator(); while(it.hasNext()) { EmployeeDetails empd=it.next(); System.out.println(empd.name+" "+empd.dept+" "+empd.age); } ArrayList<String> ar6=new ArrayList<String>(); ar6.add("amol"); ar6.add("jay"); ArrayList<String> ar7=new ArrayList<String>(); ar7.addAll(ar6); System.out.println(ar6.size()); } }
UTF-8
Java
1,944
java
ArrayListNewConcept.java
Java
[ { "context": "ist;\nimport java.util.Iterator;\n/**\n * \n * @author asingh6766\n *\n */\n\npublic class ArrayListNewConcept {\n\n\tpubl", "end": 105, "score": 0.9996875524520874, "start": 95, "tag": "USERNAME", "value": "asingh6766" }, { "context": "add(40);\n\t\tarr.add(50);\n\t\tarr.add(50);\n\t\tarr.add(\"arjun\");\n\t\tarr.add('e');\n\t\tarr.add(13.4f);\n\t\t\n\t\tSystem.", "end": 786, "score": 0.9990708231925964, "start": 781, "tag": "NAME", "value": "arjun" }, { "context": "t<String> arr2=new ArrayList<String>();\narr2.add(\"Arjun\");\n\nArrayList<E> arr5=new ArrayList<E>();\n\n\n\t\t\n\t\t", "end": 1167, "score": 0.9996358156204224, "start": 1162, "tag": "NAME", "value": "Arjun" }, { "context": "ect also\n\nEmployeeDetails e1=new EmployeeDetails(\"Arjun\",26,\"QA\");\nEmployeeDetails e2=new EmployeeDetails", "end": 1309, "score": 0.9998400211334229, "start": 1304, "tag": "NAME", "value": "Arjun" }, { "context": "26,\"QA\");\nEmployeeDetails e2=new EmployeeDetails(\"Naveen\",29,\"Dev\");\nEmployeeDetails e3=new EmployeeDetail", "end": 1367, "score": 0.9998065829277039, "start": 1361, "tag": "NAME", "value": "Naveen" }, { "context": "9,\"Dev\");\nEmployeeDetails e3=new EmployeeDetails(\"Sameer\",26,\"Java\");\n\n\t\t\n\t\n\t\n\tArrayList<EmployeeDetails> ", "end": 1426, "score": 0.9998177289962769, "start": 1420, "tag": "NAME", "value": "Sameer" }, { "context": "st<String> ar6=new ArrayList<String>();\n\tar6.add(\"amol\");\n\tar6.add(\"jay\");\n\t\n\tArrayList<String> ar7=new ", "end": 1810, "score": 0.9975982904434204, "start": 1806, "tag": "NAME", "value": "amol" }, { "context": " ArrayList<String>();\n\tar6.add(\"amol\");\n\tar6.add(\"jay\");\n\t\n\tArrayList<String> ar7=new ArrayList<String>", "end": 1827, "score": 0.9994753003120422, "start": 1824, "tag": "NAME", "value": "jay" } ]
null
[]
package collection; import java.util.ArrayList; import java.util.Iterator; /** * * @author asingh6766 * */ public class ArrayListNewConcept { public static <E> void main(String[] args) { // ArrayList - it is dynamic array int a[]=new int[2]; // static array - it will indexOutOfBound exception if try to use the value at a[4] // size is fixed // Dynamic array- ArrayList // 1. can contain duplicate values // 2- it maintain insertion order // 3. Not synchronized - not thread safe // 4/ allows random access because it allows/stores values on the basis of index ArrayList arr=new ArrayList(); arr.add(10); arr.add(20); arr.add(30); arr.add(70); System.out.println(arr.size()); arr.add(40); arr.add(50); arr.add(50); arr.add("arjun"); arr.add('e'); arr.add(13.4f); System.out.println(arr.size()); System.out.println(arr.get(6)+" "+arr.get(5)); for(int i=0;i<arr.size();i++) { System.out.println("ArrayList values are: "+arr.get(i)); } ArrayList<Integer> arr1=new ArrayList<Integer>(); arr1.add(100); //arr1.add("selenium"); ArrayList<String> arr2=new ArrayList<String>(); arr2.add("Arjun"); ArrayList<E> arr5=new ArrayList<E>(); // I can store user defined class object also EmployeeDetails e1=new EmployeeDetails("Arjun",26,"QA"); EmployeeDetails e2=new EmployeeDetails("Naveen",29,"Dev"); EmployeeDetails e3=new EmployeeDetails("Sameer",26,"Java"); ArrayList<EmployeeDetails> alist=new ArrayList<EmployeeDetails>(); alist.add(e1); alist.add(e2); alist.add(e3); Iterator<EmployeeDetails> it=alist.iterator(); while(it.hasNext()) { EmployeeDetails empd=it.next(); System.out.println(empd.name+" "+empd.dept+" "+empd.age); } ArrayList<String> ar6=new ArrayList<String>(); ar6.add("amol"); ar6.add("jay"); ArrayList<String> ar7=new ArrayList<String>(); ar7.addAll(ar6); System.out.println(ar6.size()); } }
1,944
0.666152
0.636317
97
19.041237
21.46871
105
false
false
0
0
0
0
0
0
1.556701
false
false
3
91746d9e925dc445d209e2e8eb183d50a4b9d06b
18,605,798,348,132
6fd85e764f97890d7e34d3956834622127b13a2e
/src/main/java/view/FrameViewer.java
b8da099894faeaab0058a36723be9570cd4de201
[ "MIT" ]
permissive
vokor/code-analyzer
https://github.com/vokor/code-analyzer
45e418d3f39e37433f3417b576c9d6d36b51a6e2
5a0077bfab62e3217492428278c8e8cae3f0bf7b
refs/heads/master
2022-12-13T20:15:34.660000
2020-09-13T14:44:37
2020-09-13T14:44:37
294,909,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package view; import analyzer.TreeInfo; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.components.JBTextArea; import com.intellij.ui.treeStructure.Tree; import model.PsiTreeModel; import javax.swing.*; import java.awt.*; public class FrameViewer { private PsiTreeModel treeModel; private TreeInfo treeInfo; public FrameViewer(PsiTreeModel treeModel, TreeInfo treeInfo) { this.treeInfo = treeInfo; this.treeModel = treeModel; } public void setVisible() { if (!treeModel.isValid((PsiElement) treeModel.getRoot())) return; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("Code analyzer"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); Tree tree = new Tree(treeModel); JBScrollPane treeView = new JBScrollPane(tree); JBTextArea textField = new JBTextArea(); textField.setText(showInfo()); panel.add(treeView, BorderLayout.CENTER); panel.add(textField, BorderLayout.SOUTH); //Add content to the window. frame.add(panel); //Display the window. frame.pack(); frame.setVisible(true); frame.setLocationRelativeTo(null); } private String showInfo() { String dec = String.format("Number of variable declarations: %s\n", treeInfo.getDeclareElement().getCounter()); String acc = String.format("Number of variable calls: %s\n", treeInfo.getAccessElement().getCounter()); String thr = String.format("Number of exceptions thrown: %s\n", treeInfo.getThrowElement().getCounter()); return dec + acc + thr; } }
UTF-8
Java
2,026
java
FrameViewer.java
Java
[]
null
[]
package view; import analyzer.TreeInfo; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.components.JBTextArea; import com.intellij.ui.treeStructure.Tree; import model.PsiTreeModel; import javax.swing.*; import java.awt.*; public class FrameViewer { private PsiTreeModel treeModel; private TreeInfo treeInfo; public FrameViewer(PsiTreeModel treeModel, TreeInfo treeInfo) { this.treeInfo = treeInfo; this.treeModel = treeModel; } public void setVisible() { if (!treeModel.isValid((PsiElement) treeModel.getRoot())) return; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("Code analyzer"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); Tree tree = new Tree(treeModel); JBScrollPane treeView = new JBScrollPane(tree); JBTextArea textField = new JBTextArea(); textField.setText(showInfo()); panel.add(treeView, BorderLayout.CENTER); panel.add(textField, BorderLayout.SOUTH); //Add content to the window. frame.add(panel); //Display the window. frame.pack(); frame.setVisible(true); frame.setLocationRelativeTo(null); } private String showInfo() { String dec = String.format("Number of variable declarations: %s\n", treeInfo.getDeclareElement().getCounter()); String acc = String.format("Number of variable calls: %s\n", treeInfo.getAccessElement().getCounter()); String thr = String.format("Number of exceptions thrown: %s\n", treeInfo.getThrowElement().getCounter()); return dec + acc + thr; } }
2,026
0.657947
0.657947
63
31.15873
26.567797
119
false
false
0
0
0
0
0
0
0.650794
false
false
3
18b4f3b0d4e66fa7cb63784c4fde8cd2c81b5e43
31,636,729,106,580
2edc856463e76566da7d148ad72ab326720467da
/semantics/Values.java
c75df255f650c3b1c8ac6ddc96e3d9fe0b8edd28
[]
no_license
dextract/ic
https://github.com/dextract/ic
bd59639908b978a9ceb778f755a7a67a0b2150c5
d221c3816d0f2abda87efd5a887a30f5857ea61e
refs/heads/master
2016-08-03T10:41:40.070000
2014-06-16T15:45:57
2014-06-16T15:45:57
31,874,418
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package semantics; public class Values { public static boolean toBool(Value value) throws EvaluationException { if( value instanceof BooleanValue ) { return ((BooleanValue)value).value; } else throw new EvaluationException(); } public static int toInt(Value value) throws EvaluationException { if( value instanceof IntegerValue ) { return ((IntegerValue)value).value; } else throw new EvaluationException(); } public static Value newInt(int value) { return new IntegerValue(value); } public static Value newBool(boolean value) { if( value ) return BooleanValue.true_value; else return BooleanValue.false_value; } public static Value newRef(Value value) { return new RefValue(value); } public static Value newUndefined() { return new UndefinedValue(); } public static Value newUnit() { return new UnitValue(); } public static RefValue toRef(Value value) throws EvaluationException { if( value instanceof RefValue ) { return (RefValue) value; } else throw new EvaluationException(); } public static ClosureValue toClosure(Value value) throws EvaluationException { if( value instanceof ClosureValue ) { return (ClosureValue) value; } else throw new EvaluationException(); } public static RecordValue toRecord(Value value) throws EvaluationException { if( value instanceof RecordValue ) { return (RecordValue) value; } else throw new EvaluationException(); } public static ListValue toList(Value value) throws EvaluationException { if( value instanceof ListValue ) { return (ListValue) value; } else throw new EvaluationException(); } public static Value newString(String value) { return new StringValue(value); } public static Value fromStringToVal(String p) { Value tmp = null; if(p.equals("int")) tmp = Values.newInt(0); else if(p.equals("bool")) tmp = Values.newBool(false); else if(p.equals("string")) tmp = Values.newString(""); else if(p.startsWith("fun")) tmp = new ClosureValue(null, null, null); return tmp; } }
UTF-8
Java
2,072
java
Values.java
Java
[]
null
[]
package semantics; public class Values { public static boolean toBool(Value value) throws EvaluationException { if( value instanceof BooleanValue ) { return ((BooleanValue)value).value; } else throw new EvaluationException(); } public static int toInt(Value value) throws EvaluationException { if( value instanceof IntegerValue ) { return ((IntegerValue)value).value; } else throw new EvaluationException(); } public static Value newInt(int value) { return new IntegerValue(value); } public static Value newBool(boolean value) { if( value ) return BooleanValue.true_value; else return BooleanValue.false_value; } public static Value newRef(Value value) { return new RefValue(value); } public static Value newUndefined() { return new UndefinedValue(); } public static Value newUnit() { return new UnitValue(); } public static RefValue toRef(Value value) throws EvaluationException { if( value instanceof RefValue ) { return (RefValue) value; } else throw new EvaluationException(); } public static ClosureValue toClosure(Value value) throws EvaluationException { if( value instanceof ClosureValue ) { return (ClosureValue) value; } else throw new EvaluationException(); } public static RecordValue toRecord(Value value) throws EvaluationException { if( value instanceof RecordValue ) { return (RecordValue) value; } else throw new EvaluationException(); } public static ListValue toList(Value value) throws EvaluationException { if( value instanceof ListValue ) { return (ListValue) value; } else throw new EvaluationException(); } public static Value newString(String value) { return new StringValue(value); } public static Value fromStringToVal(String p) { Value tmp = null; if(p.equals("int")) tmp = Values.newInt(0); else if(p.equals("bool")) tmp = Values.newBool(false); else if(p.equals("string")) tmp = Values.newString(""); else if(p.startsWith("fun")) tmp = new ClosureValue(null, null, null); return tmp; } }
2,072
0.713803
0.71332
89
22.292135
21.122543
79
false
false
0
0
0
0
0
0
1.865169
false
false
3
32aee1cb5e22b14e924e706725c7e1383c33df4e
6,073,083,770,921
a973c986e79162fc7c5fbbf0753dbd60b732b397
/src/main/java/com/huayu/service/ForumService.java
f90c9fa3841861bbfeeb90afe0c232ed2260ae49
[]
no_license
wangpintao/crmxiangmu
https://github.com/wangpintao/crmxiangmu
2ac961a02c4d2a862bac1cb5c846af68a30998ce
27f5a526a06604854010ed97f363156b17700927
refs/heads/master
2022-12-11T07:54:48.336000
2020-09-14T01:44:31
2020-09-14T01:44:31
290,995,827
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huayu.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.util.StringUtil; import com.huayu.layuiUtils.Stulayui; import com.huayu.mapper.ForumMapper; import com.huayu.mapper.PermissionMapper; import com.huayu.pojo.Forum; import com.huayu.pojo.Permission; import com.huayu.service.imp.IForumServiceImp; import com.huayu.service.imp.IPermissionServiceImp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class ForumService extends ServiceImpl<ForumMapper, Forum> implements IForumServiceImp { @Autowired private ForumMapper forumMapper; @Override public Integer updateone(Forum forum) { return forumMapper.updateone(forum); } @Override public Integer updateone1(Forum forum) { return forumMapper.updateone1(forum); } @Override public Integer updateone2(Forum forum) { return forumMapper.updateone2(forum); } @Override public Stulayui queryall(Integer page,Integer limit,Forum forum) { Stulayui stulayui=new Stulayui(); Page page1 = PageHelper.startPage(page,limit); QueryWrapper queryWrapper=new QueryWrapper(); queryWrapper.eq("for_forid",0); if(forum!=null){ if(!StringUtil.isEmpty(forum.getForLabel())){ if(forum.getForLabel().equals("for_theme")){ queryWrapper.like(forum.getForLabel(),forum.getForClassify()); }else if(forum.getForLabel().equals("for_author")){ queryWrapper.like(forum.getForLabel(),forum.getForClassify()); }else if(forum.getForLabel().equals("for_label")){ queryWrapper.like(forum.getForLabel(),forum.getForClassify()); }else if(forum.getForLabel().equals("for_click")){ queryWrapper.eq(forum.getForLabel(),forum.getForClassify()); }else if(forum.getForLabel().equals("for_reply")){ queryWrapper.eq(forum.getForLabel(),forum.getForClassify()); } } } List<Forum> list=forumMapper.selectList(queryWrapper); if(list.size()>0){ stulayui.setCode(0); stulayui.setMsg("查询成功"); stulayui.setCount(Integer.valueOf(String.valueOf(page1.getTotal()))); stulayui.setData(list); }else{ stulayui.setCode(1); stulayui.setMsg("无数据"); } return stulayui; } }
UTF-8
Java
2,886
java
ForumService.java
Java
[]
null
[]
package com.huayu.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.util.StringUtil; import com.huayu.layuiUtils.Stulayui; import com.huayu.mapper.ForumMapper; import com.huayu.mapper.PermissionMapper; import com.huayu.pojo.Forum; import com.huayu.pojo.Permission; import com.huayu.service.imp.IForumServiceImp; import com.huayu.service.imp.IPermissionServiceImp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class ForumService extends ServiceImpl<ForumMapper, Forum> implements IForumServiceImp { @Autowired private ForumMapper forumMapper; @Override public Integer updateone(Forum forum) { return forumMapper.updateone(forum); } @Override public Integer updateone1(Forum forum) { return forumMapper.updateone1(forum); } @Override public Integer updateone2(Forum forum) { return forumMapper.updateone2(forum); } @Override public Stulayui queryall(Integer page,Integer limit,Forum forum) { Stulayui stulayui=new Stulayui(); Page page1 = PageHelper.startPage(page,limit); QueryWrapper queryWrapper=new QueryWrapper(); queryWrapper.eq("for_forid",0); if(forum!=null){ if(!StringUtil.isEmpty(forum.getForLabel())){ if(forum.getForLabel().equals("for_theme")){ queryWrapper.like(forum.getForLabel(),forum.getForClassify()); }else if(forum.getForLabel().equals("for_author")){ queryWrapper.like(forum.getForLabel(),forum.getForClassify()); }else if(forum.getForLabel().equals("for_label")){ queryWrapper.like(forum.getForLabel(),forum.getForClassify()); }else if(forum.getForLabel().equals("for_click")){ queryWrapper.eq(forum.getForLabel(),forum.getForClassify()); }else if(forum.getForLabel().equals("for_reply")){ queryWrapper.eq(forum.getForLabel(),forum.getForClassify()); } } } List<Forum> list=forumMapper.selectList(queryWrapper); if(list.size()>0){ stulayui.setCode(0); stulayui.setMsg("查询成功"); stulayui.setCount(Integer.valueOf(String.valueOf(page1.getTotal()))); stulayui.setData(list); }else{ stulayui.setCode(1); stulayui.setMsg("无数据"); } return stulayui; } }
2,886
0.67305
0.669568
76
36.789474
25.407373
95
false
false
0
0
0
0
0
0
0.644737
false
false
3
6112e21dca8338ad208315eff20693a1d93efa8a
1,331,439,887,157
24870d2ff6705f38424e879d14fe40ee15a003f8
/src/com/example/tema2si/ArrayAdapterAppInfo.java
9a336813f44b35186e2dc455e35e8901aaa8ed10
[]
no_license
cbotogan/Tema2SI
https://github.com/cbotogan/Tema2SI
9cc92f44c7041905a606f7b37bcebbe68973eeae
312d9692d724a36170930b76c115ce896793a68b
refs/heads/master
2021-05-26T17:43:07.130000
2014-01-17T18:37:53
2014-01-17T18:37:53
15,935,688
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.tema2si; import java.text.DecimalFormat; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class ArrayAdapterAppInfo extends ArrayAdapter<PowerEvent> { Context context; ArrayList<PowerEvent> rows; public ArrayAdapterAppInfo(Context context, ArrayList<PowerEvent> rows) { super(context, R.layout.app_info_row, rows); this.context = context; this.rows = rows; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.app_info_row, parent, false); DecimalFormat df = new DecimalFormat("##.##"); TextView textView = (TextView) rowView.findViewById(R.id.cputime); textView.setText(Long.toString(rows.get(position).getCpuTime())); textView = (TextView) rowView.findViewById(R.id.energycpu); textView.setText(df.format(rows.get(position).getPowerCPU())); textView = (TextView) rowView.findViewById(R.id.gpstime); textView.setText(Long.toString(rows.get(position).getGpsTime())); textView = (TextView) rowView.findViewById(R.id.energygps); textView.setText(df.format(rows.get(position).getPowerGPS())); textView = (TextView) rowView.findViewById(R.id.appName); textView.setText(rows.get(position).getAppName()); textView = (TextView) rowView.findViewById(R.id.uid); textView.setText(rows.get(position).getUid()); textView = (TextView) rowView.findViewById(R.id.packageName); textView.setText(rows.get(position).getDefaultPackageName()); textView = (TextView) rowView.findViewById(R.id.bytessent); textView.setText(Long.toString(rows.get(position).getBytesSent())); textView = (TextView) rowView.findViewById(R.id.bytesreceived); textView.setText(Long.toString(rows.get(position).getBytesReceived())); textView = (TextView) rowView.findViewById(R.id.energywifi); textView.setText(df.format(rows.get(position).getPowerTCP())); return rowView; } }
UTF-8
Java
2,255
java
ArrayAdapterAppInfo.java
Java
[]
null
[]
package com.example.tema2si; import java.text.DecimalFormat; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class ArrayAdapterAppInfo extends ArrayAdapter<PowerEvent> { Context context; ArrayList<PowerEvent> rows; public ArrayAdapterAppInfo(Context context, ArrayList<PowerEvent> rows) { super(context, R.layout.app_info_row, rows); this.context = context; this.rows = rows; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.app_info_row, parent, false); DecimalFormat df = new DecimalFormat("##.##"); TextView textView = (TextView) rowView.findViewById(R.id.cputime); textView.setText(Long.toString(rows.get(position).getCpuTime())); textView = (TextView) rowView.findViewById(R.id.energycpu); textView.setText(df.format(rows.get(position).getPowerCPU())); textView = (TextView) rowView.findViewById(R.id.gpstime); textView.setText(Long.toString(rows.get(position).getGpsTime())); textView = (TextView) rowView.findViewById(R.id.energygps); textView.setText(df.format(rows.get(position).getPowerGPS())); textView = (TextView) rowView.findViewById(R.id.appName); textView.setText(rows.get(position).getAppName()); textView = (TextView) rowView.findViewById(R.id.uid); textView.setText(rows.get(position).getUid()); textView = (TextView) rowView.findViewById(R.id.packageName); textView.setText(rows.get(position).getDefaultPackageName()); textView = (TextView) rowView.findViewById(R.id.bytessent); textView.setText(Long.toString(rows.get(position).getBytesSent())); textView = (TextView) rowView.findViewById(R.id.bytesreceived); textView.setText(Long.toString(rows.get(position).getBytesReceived())); textView = (TextView) rowView.findViewById(R.id.energywifi); textView.setText(df.format(rows.get(position).getPowerTCP())); return rowView; } }
2,255
0.75388
0.753437
68
32.161766
27.236767
74
false
false
0
0
0
0
0
0
2.073529
false
false
3
61088638a2e2f3642692d2e3b213ccc2d48a43d9
22,969,485,136,632
7f4aa0a33ae92be8c89ab84ac1b35cbd763a40d4
/app/src/main/java/com/mooo/ziggypop/candconline/LadderStats.java
b8138672298edb65a82591bb996b9c37517b22b1
[]
no_license
hgzimmerman/CnC-Online-Spymaster
https://github.com/hgzimmerman/CnC-Online-Spymaster
3ac38f7f9ac3bede614ea052618384b57e380954
1e4499571c786e3853746fb7dd3a71310c964962
refs/heads/master
2021-05-30T13:08:32.708000
2016-02-02T18:28:03
2016-02-02T18:28:03
34,024,721
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mooo.ziggypop.candconline; import android.app.Activity; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; /** * Created by ziggypop on 1/15/16. * LadderStats are used to display data from the ladder view */ public class LadderStats implements Parcelable { private final String nickname; private final int rankOneVsOne; private final String ladderWinOverLoss; private final int elo; private final int games; private final int wins; private final int losses; private final int disconnects; private final int desyncs; public LadderStats(String nickname, int rankOneVsOne, String ladderWinOverLoss, int elo, int games, int wins, int losses, int disconnects, int desyncs){ this.nickname = nickname; this. rankOneVsOne = rankOneVsOne; this.ladderWinOverLoss = ladderWinOverLoss; this.elo = elo; this.games = games; this. wins = wins; this.losses = losses; this.disconnects = disconnects; this.desyncs = desyncs; } protected LadderStats(Parcel in) { nickname = in.readString(); rankOneVsOne = in.readInt(); ladderWinOverLoss = in.readString(); elo = in.readInt(); games = in.readInt(); wins = in.readInt(); losses = in.readInt(); disconnects = in.readInt(); desyncs = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(nickname); dest.writeInt(rankOneVsOne); dest.writeString(ladderWinOverLoss); dest.writeInt(elo); dest.writeInt(games); dest.writeInt(wins); dest.writeInt(losses); dest.writeInt(disconnects); dest.writeInt(desyncs); } @SuppressWarnings("unused") public static final Parcelable.Creator<LadderStats> CREATOR = new Parcelable.Creator<LadderStats>() { @Override public LadderStats createFromParcel(Parcel in) { return new LadderStats(in); } @Override public LadderStats[] newArray(int size) { return new LadderStats[size]; } }; private static class LadderStatsViewHolder extends RecyclerView.ViewHolder { final TextView nameView; final TextView rankOneVsOneView; final TextView ladderWinOverLossView; final TextView eloView; final TextView gamesView; final TextView winsView; final TextView lossesView; final TextView disconnectsView; final TextView desyncsView; public LadderStatsViewHolder(View itemView) { super(itemView); nameView = (TextView) itemView.findViewById(R.id.ladder_stat_name); rankOneVsOneView = (TextView) itemView.findViewById(R.id.ladder_stat_rank_one_vs_one); ladderWinOverLossView = (TextView) itemView.findViewById(R.id.ladder_stat_win_over_loss); eloView = (TextView) itemView.findViewById(R.id.ladder_stat_elo); gamesView = (TextView) itemView.findViewById(R.id.ladder_stat_games); winsView = (TextView) itemView.findViewById(R.id.ladder_stat_wins); lossesView = (TextView) itemView.findViewById(R.id.ladder_stat_losses); disconnectsView = (TextView) itemView.findViewById(R.id.ladder_stat_disconnects); desyncsView = (TextView) itemView.findViewById(R.id.ladder_stat_desyncs); } } public static class StatsAdapter extends RecyclerView.Adapter<LadderStatsViewHolder> { public ArrayList<LadderStats> myStats; public StatsAdapter(ArrayList<LadderStats> ladderStats) { this.myStats = ladderStats; } @Override public LadderStatsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup cardView = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.player_card, null); RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); cardView.setLayoutParams(lp); View statsView = LayoutInflater.from(parent.getContext()).inflate(R.layout.stats_ladder_layout, null); cardView.addView(statsView); return new LadderStatsViewHolder(cardView); } @Override public void onBindViewHolder(LadderStatsViewHolder holder, int position) { final LadderStats playerStats = myStats.get(position); holder.nameView.setText(playerStats.nickname); holder.rankOneVsOneView.setText(String.format("%d", playerStats.rankOneVsOne)); holder.ladderWinOverLossView.setText(playerStats.ladderWinOverLoss); holder.eloView.setText(String.format("%d", playerStats.elo )); holder.gamesView.setText(String.format("%d", playerStats.games )); holder.winsView.setText(String.format("%d", playerStats.wins )); holder.lossesView.setText(String.format("%d", playerStats.losses )); holder.disconnectsView.setText(String.format("%d", playerStats.disconnects )); holder.desyncsView.setText(String.format("%d", playerStats.desyncs )); } @Override public int getItemCount() { return myStats.size(); } } public static class LadderStatsFragment extends RecyclerViewFragment { private static final String TAG = "StatsFragment"; protected RecyclerView mRecyclerView; protected StatsAdapter mAdapter; protected RecyclerView.LayoutManager mLayoutManager; protected ArrayList<LadderStats> mDataset; @Override public void onCreate(Bundle bundle){ super.onCreate(bundle); Log.v(TAG, "onCreate called"); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); llm.setOrientation(LinearLayoutManager.VERTICAL); View rootView = getActivity().getLayoutInflater().inflate(R.layout.fragment_list_view, null, false); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(llm); mDataset = new ArrayList<>(); mAdapter = new StatsAdapter(mDataset); Log.v(TAG, "setting the adapter for player"); mRecyclerView.setAdapter( mAdapter ); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); mDataset = new ArrayList<>(); Log.v(TAG, "onCreateView Called"); View rootView = inflater.inflate(R.layout.fragment_list_view, container, false); rootView.setTag(TAG); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view); // LinearLayoutManager is used here, this will layout the elements in a similar fashion // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how // elements are laid out. mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setHasFixedSize(true); setRecyclerViewLayoutManager(mRecyclerView); mRecyclerView.addItemDecoration(new RecyclerViewFragment.VerticalSpaceItemDecoration( (int) getResources().getDimension(R.dimen.recycle_spacing))); mAdapter = new StatsAdapter(mDataset); // Set CustomAdapter as the adapter for RecyclerView. Log.v(TAG, "setting the adapter for player"); mRecyclerView.setAdapter(mAdapter); return rootView; } public void setData(final ArrayList<LadderStats> data, final Activity activity){ if(!isAdded()) mAdapter = new StatsAdapter(mDataset); activity.runOnUiThread(new Runnable() { @Override public void run() { Log.v(TAG, "Setting data"); if (mDataset == null){ mDataset = new ArrayList<>(); } mDataset.clear(); mDataset.addAll(data); mAdapter.notifyDataSetChanged(); } }); } } }
UTF-8
Java
8,910
java
LadderStats.java
Java
[ { "context": "w;\n\nimport java.util.ArrayList;\n\n/**\n * Created by ziggypop on 1/15/16.\n * LadderStats are used to display da", "end": 458, "score": 0.9996405243873596, "start": 450, "tag": "USERNAME", "value": "ziggypop" } ]
null
[]
package com.mooo.ziggypop.candconline; import android.app.Activity; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; /** * Created by ziggypop on 1/15/16. * LadderStats are used to display data from the ladder view */ public class LadderStats implements Parcelable { private final String nickname; private final int rankOneVsOne; private final String ladderWinOverLoss; private final int elo; private final int games; private final int wins; private final int losses; private final int disconnects; private final int desyncs; public LadderStats(String nickname, int rankOneVsOne, String ladderWinOverLoss, int elo, int games, int wins, int losses, int disconnects, int desyncs){ this.nickname = nickname; this. rankOneVsOne = rankOneVsOne; this.ladderWinOverLoss = ladderWinOverLoss; this.elo = elo; this.games = games; this. wins = wins; this.losses = losses; this.disconnects = disconnects; this.desyncs = desyncs; } protected LadderStats(Parcel in) { nickname = in.readString(); rankOneVsOne = in.readInt(); ladderWinOverLoss = in.readString(); elo = in.readInt(); games = in.readInt(); wins = in.readInt(); losses = in.readInt(); disconnects = in.readInt(); desyncs = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(nickname); dest.writeInt(rankOneVsOne); dest.writeString(ladderWinOverLoss); dest.writeInt(elo); dest.writeInt(games); dest.writeInt(wins); dest.writeInt(losses); dest.writeInt(disconnects); dest.writeInt(desyncs); } @SuppressWarnings("unused") public static final Parcelable.Creator<LadderStats> CREATOR = new Parcelable.Creator<LadderStats>() { @Override public LadderStats createFromParcel(Parcel in) { return new LadderStats(in); } @Override public LadderStats[] newArray(int size) { return new LadderStats[size]; } }; private static class LadderStatsViewHolder extends RecyclerView.ViewHolder { final TextView nameView; final TextView rankOneVsOneView; final TextView ladderWinOverLossView; final TextView eloView; final TextView gamesView; final TextView winsView; final TextView lossesView; final TextView disconnectsView; final TextView desyncsView; public LadderStatsViewHolder(View itemView) { super(itemView); nameView = (TextView) itemView.findViewById(R.id.ladder_stat_name); rankOneVsOneView = (TextView) itemView.findViewById(R.id.ladder_stat_rank_one_vs_one); ladderWinOverLossView = (TextView) itemView.findViewById(R.id.ladder_stat_win_over_loss); eloView = (TextView) itemView.findViewById(R.id.ladder_stat_elo); gamesView = (TextView) itemView.findViewById(R.id.ladder_stat_games); winsView = (TextView) itemView.findViewById(R.id.ladder_stat_wins); lossesView = (TextView) itemView.findViewById(R.id.ladder_stat_losses); disconnectsView = (TextView) itemView.findViewById(R.id.ladder_stat_disconnects); desyncsView = (TextView) itemView.findViewById(R.id.ladder_stat_desyncs); } } public static class StatsAdapter extends RecyclerView.Adapter<LadderStatsViewHolder> { public ArrayList<LadderStats> myStats; public StatsAdapter(ArrayList<LadderStats> ladderStats) { this.myStats = ladderStats; } @Override public LadderStatsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewGroup cardView = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.player_card, null); RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); cardView.setLayoutParams(lp); View statsView = LayoutInflater.from(parent.getContext()).inflate(R.layout.stats_ladder_layout, null); cardView.addView(statsView); return new LadderStatsViewHolder(cardView); } @Override public void onBindViewHolder(LadderStatsViewHolder holder, int position) { final LadderStats playerStats = myStats.get(position); holder.nameView.setText(playerStats.nickname); holder.rankOneVsOneView.setText(String.format("%d", playerStats.rankOneVsOne)); holder.ladderWinOverLossView.setText(playerStats.ladderWinOverLoss); holder.eloView.setText(String.format("%d", playerStats.elo )); holder.gamesView.setText(String.format("%d", playerStats.games )); holder.winsView.setText(String.format("%d", playerStats.wins )); holder.lossesView.setText(String.format("%d", playerStats.losses )); holder.disconnectsView.setText(String.format("%d", playerStats.disconnects )); holder.desyncsView.setText(String.format("%d", playerStats.desyncs )); } @Override public int getItemCount() { return myStats.size(); } } public static class LadderStatsFragment extends RecyclerViewFragment { private static final String TAG = "StatsFragment"; protected RecyclerView mRecyclerView; protected StatsAdapter mAdapter; protected RecyclerView.LayoutManager mLayoutManager; protected ArrayList<LadderStats> mDataset; @Override public void onCreate(Bundle bundle){ super.onCreate(bundle); Log.v(TAG, "onCreate called"); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); llm.setOrientation(LinearLayoutManager.VERTICAL); View rootView = getActivity().getLayoutInflater().inflate(R.layout.fragment_list_view, null, false); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(llm); mDataset = new ArrayList<>(); mAdapter = new StatsAdapter(mDataset); Log.v(TAG, "setting the adapter for player"); mRecyclerView.setAdapter( mAdapter ); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); mDataset = new ArrayList<>(); Log.v(TAG, "onCreateView Called"); View rootView = inflater.inflate(R.layout.fragment_list_view, container, false); rootView.setTag(TAG); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view); // LinearLayoutManager is used here, this will layout the elements in a similar fashion // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how // elements are laid out. mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setHasFixedSize(true); setRecyclerViewLayoutManager(mRecyclerView); mRecyclerView.addItemDecoration(new RecyclerViewFragment.VerticalSpaceItemDecoration( (int) getResources().getDimension(R.dimen.recycle_spacing))); mAdapter = new StatsAdapter(mDataset); // Set CustomAdapter as the adapter for RecyclerView. Log.v(TAG, "setting the adapter for player"); mRecyclerView.setAdapter(mAdapter); return rootView; } public void setData(final ArrayList<LadderStats> data, final Activity activity){ if(!isAdded()) mAdapter = new StatsAdapter(mDataset); activity.runOnUiThread(new Runnable() { @Override public void run() { Log.v(TAG, "Setting data"); if (mDataset == null){ mDataset = new ArrayList<>(); } mDataset.clear(); mDataset.addAll(data); mAdapter.notifyDataSetChanged(); } }); } } }
8,910
0.643547
0.642649
243
35.67078
30.561121
147
false
false
0
0
0
0
0
0
0.674897
false
false
3
5c976834fdb1822801a0fcc3f9bc6085491f285f
13,202,729,474,682
a660c22318303cc78f17d63fbec32149fb9c4883
/app/src/main/java/publikar/salonyelskamonforte/FrecuenteActivity.java
c497c9c1204d9012b2dec1868ce88ff5e045432a
[]
no_license
publikar/Salonyelskamonforte
https://github.com/publikar/Salonyelskamonforte
c707ccaaccde87252e9f09a5ca252b5c06e0f51f
e02e2aad5b8d5755150ecbec63a83ccec869b0a3
refs/heads/master
2021-01-18T20:02:22.217000
2017-07-15T16:31:32
2017-07-15T16:31:32
86,928,305
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package publikar.salonyelskamonforte; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import Util.DatosUsuario; import WebService.RequestMethod; import WebService.RestClient; import WebService.WebUrl; public class FrecuenteActivity extends AppCompatActivity { CheckBox chk1,chk2,chk3,chk4,chk5,chk6; RestClient restClient; Boolean passwordok=false,check1=false,check2=false,check3=false,check4=false,check5=false, check6=false; DatosUsuario datosusuario; int nvisitas=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_frecuente); chk1=(CheckBox)findViewById(R.id.checkBox1); chk2=(CheckBox)findViewById(R.id.checkBox2); chk3=(CheckBox)findViewById(R.id.checkBox3); chk4=(CheckBox)findViewById(R.id.checkBox4); chk5=(CheckBox)findViewById(R.id.checkBox5); chk6=(CheckBox)findViewById(R.id.checkBox6); datosusuario=new DatosUsuario(FrecuenteActivity.this); revisarvisitas(); chk1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check1=true; showInputDialog(); } }); chk2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check2=true; showInputDialog(); } }); chk3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check3=true; showInputDialog(); } }); chk4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check4=true; showInputDialog(); } }); chk5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check5=true; showInputDialog(); } }); chk6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check6=true; showInputDialog(); } }); } private void revisarvisitas() { if(Util.Util.checkInternetConnection(FrecuenteActivity.this)) { //Consulta al servidor cuántas visitas tiene el usuario ProgressDialog progressDialog = new ProgressDialog(FrecuenteActivity.this); progressDialog.setMessage("Consultando, por favor espere..."); ConsultarVisitasTask consultarVisitasTask = new ConsultarVisitasTask(progressDialog, FrecuenteActivity.this); consultarVisitasTask.execute(); }else { nvisitas=datosusuario.getUserVisit(); } } protected void showInputDialog() { LayoutInflater layoutInflater = LayoutInflater.from(FrecuenteActivity.this); View promptView = layoutInflater.inflate(R.layout.input_dialog, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(FrecuenteActivity.this); alertDialogBuilder.setView(promptView); final EditText etxtpassword = (EditText) promptView.findViewById(R.id.editText); // setup a dialog window alertDialogBuilder.setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //Validar admin if(!etxtpassword.getText().toString().matches("")) { restClient = new RestClient(WebUrl.webUrl + "loginadmin.php"); restClient.clearAddHeader(); restClient.clearAddParam(); restClient.AddParam("password", etxtpassword.getText().toString()); //Verificar password de administrador ProgressDialog progressDialog = new ProgressDialog(FrecuenteActivity.this); progressDialog.setMessage("Consultando, por favor espere..."); ConsultarPassTask consultarPassTask = new ConsultarPassTask(progressDialog, FrecuenteActivity.this); consultarPassTask.execute(); }else { dialog.cancel(); uncheck(); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); uncheck(); } }); // create an alert dialog AlertDialog alert = alertDialogBuilder.create(); alert.show(); } private void uncheck() { if(check1) { chk1.setChecked(false); } if(check2) {chk2.setChecked(false);} if(check3) { chk3.setChecked(false); } if(check4) {chk4.setChecked(false);} if(check5) {chk5.setChecked(false);} if(check6) {chk6.setChecked(false);} } //actualiza las visitas en el servidor private boolean insertarVisitas() { restClient = new RestClient(WebUrl.webUrl + "frecuentes.php"); restClient.clearAddHeader(); restClient.clearAddParam(); restClient.AddParam("idcliente",Integer.toString( datosusuario.getUserId())); restClient.AddParam("nvisita",Integer.toString(nvisitas)); try { restClient.Execute(RequestMethod.POST); String res = restClient.getResponse().trim(); if (res.equals("true")) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } //Revisar en el servidor cuantas visitas tiene el usuario private void cargarvisitas() { restClient = new RestClient(WebUrl.webUrl + "verVisitas.php"); restClient.clearAddHeader(); restClient.clearAddParam(); restClient.AddParam("idcliente",Integer.toString( datosusuario.getUserId())); try { restClient.Execute(RequestMethod.POST); JSONArray json = new JSONArray(restClient.getResponse()); if (!json.isNull(0)) { JSONObject job = null; for (int i = 0; i < json.length(); i++) { job = json.getJSONObject(i); } nvisitas=job.getInt("nvisitas"); } } catch (Exception e) { e.printStackTrace(); } } private void bloquearchecks() { chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(false); } public boolean consultapassword() { try { restClient.Execute(RequestMethod.POST); JSONArray json = new JSONArray(restClient.getResponse()); if (!json.isNull(0)) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } public class ConsultarPassTask extends AsyncTask<Void, Void, Void> { private ProgressDialog progressDialog; private Context context; public ConsultarPassTask(ProgressDialog progressDialog, Context context) { this.context = context; this.progressDialog = progressDialog; } @Override protected Void doInBackground(Void... params) { if(consultapassword()) { passwordok=true; }else{passwordok=false;} return null; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if(passwordok) { if(check1) { nvisitas=1; check1=false; } if(check2) { nvisitas=2; check2=false; } if(check3) { nvisitas=3; check3=false; } if(check4) { nvisitas=4; check4=false; } if(check5) { nvisitas=5; check5=false; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(FrecuenteActivity.this); alertDialogBuilder.setTitle("¡Felicidades!"); alertDialogBuilder.setMessage("Tu próximo servicio es gratis"); alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert).show(); } if(check6) {nvisitas=0; check6=false; } if(insertarVisitas()) { Toast.makeText(FrecuenteActivity.this,"Visita registrada",Toast.LENGTH_SHORT).show(); datosusuario.setUserVisit(nvisitas); revisarvisitas(); }else { Toast.makeText(FrecuenteActivity.this,"La visita no fue registrada. Intente nuevamente", Toast.LENGTH_SHORT).show(); } }else { //Si el password no es correcto despalomea el check uncheck(); Toast.makeText(FrecuenteActivity.this,"Password incorrecto",Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } } public class ConsultarVisitasTask extends AsyncTask<Void, Void, Void> { private ProgressDialog progressDialog; private Context context; public ConsultarVisitasTask(ProgressDialog progressDialog, Context context) { this.context = context; this.progressDialog = progressDialog; } @Override protected Void doInBackground(Void... params) { cargarvisitas(); return null; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); switch(nvisitas) { case 0: bloquearchecks(); break; case 1: chk1.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(true); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(false); break; case 2: chk1.setChecked(true); chk2.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(true); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(false); break; case 3: chk1.setChecked(true); chk2.setChecked(true); chk3.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(true); chk5.setEnabled(false); chk6.setEnabled(false); break; case 4: chk1.setChecked(true); chk2.setChecked(true); chk3.setChecked(true); chk4.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(true); chk6.setEnabled(false); break; case 5: chk1.setChecked(true); chk2.setChecked(true); chk3.setChecked(true); chk4.setChecked(true); chk5.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(true); break; case 6: chk1.setChecked(true); chk2.setChecked(true); chk3.setChecked(true); chk4.setChecked(true); chk5.setChecked(true); chk6.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(false); break; } //Guarde en shared preferences las visitas datosusuario.setUserVisit(nvisitas); progressDialog.dismiss(); } } }
UTF-8
Java
14,558
java
FrecuenteActivity.java
Java
[ { "context": " restClient.AddParam(\"password\", etxtpassword.getText().toString());\n//Verificar password de ad", "end": 4442, "score": 0.7748593091964722, "start": 4430, "tag": "PASSWORD", "value": "etxtpassword" } ]
null
[]
package publikar.salonyelskamonforte; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import Util.DatosUsuario; import WebService.RequestMethod; import WebService.RestClient; import WebService.WebUrl; public class FrecuenteActivity extends AppCompatActivity { CheckBox chk1,chk2,chk3,chk4,chk5,chk6; RestClient restClient; Boolean passwordok=false,check1=false,check2=false,check3=false,check4=false,check5=false, check6=false; DatosUsuario datosusuario; int nvisitas=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_frecuente); chk1=(CheckBox)findViewById(R.id.checkBox1); chk2=(CheckBox)findViewById(R.id.checkBox2); chk3=(CheckBox)findViewById(R.id.checkBox3); chk4=(CheckBox)findViewById(R.id.checkBox4); chk5=(CheckBox)findViewById(R.id.checkBox5); chk6=(CheckBox)findViewById(R.id.checkBox6); datosusuario=new DatosUsuario(FrecuenteActivity.this); revisarvisitas(); chk1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check1=true; showInputDialog(); } }); chk2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check2=true; showInputDialog(); } }); chk3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check3=true; showInputDialog(); } }); chk4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check4=true; showInputDialog(); } }); chk5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check5=true; showInputDialog(); } }); chk6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { check6=true; showInputDialog(); } }); } private void revisarvisitas() { if(Util.Util.checkInternetConnection(FrecuenteActivity.this)) { //Consulta al servidor cuántas visitas tiene el usuario ProgressDialog progressDialog = new ProgressDialog(FrecuenteActivity.this); progressDialog.setMessage("Consultando, por favor espere..."); ConsultarVisitasTask consultarVisitasTask = new ConsultarVisitasTask(progressDialog, FrecuenteActivity.this); consultarVisitasTask.execute(); }else { nvisitas=datosusuario.getUserVisit(); } } protected void showInputDialog() { LayoutInflater layoutInflater = LayoutInflater.from(FrecuenteActivity.this); View promptView = layoutInflater.inflate(R.layout.input_dialog, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(FrecuenteActivity.this); alertDialogBuilder.setView(promptView); final EditText etxtpassword = (EditText) promptView.findViewById(R.id.editText); // setup a dialog window alertDialogBuilder.setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //Validar admin if(!etxtpassword.getText().toString().matches("")) { restClient = new RestClient(WebUrl.webUrl + "loginadmin.php"); restClient.clearAddHeader(); restClient.clearAddParam(); restClient.AddParam("password", <PASSWORD>.getText().toString()); //Verificar password de administrador ProgressDialog progressDialog = new ProgressDialog(FrecuenteActivity.this); progressDialog.setMessage("Consultando, por favor espere..."); ConsultarPassTask consultarPassTask = new ConsultarPassTask(progressDialog, FrecuenteActivity.this); consultarPassTask.execute(); }else { dialog.cancel(); uncheck(); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); uncheck(); } }); // create an alert dialog AlertDialog alert = alertDialogBuilder.create(); alert.show(); } private void uncheck() { if(check1) { chk1.setChecked(false); } if(check2) {chk2.setChecked(false);} if(check3) { chk3.setChecked(false); } if(check4) {chk4.setChecked(false);} if(check5) {chk5.setChecked(false);} if(check6) {chk6.setChecked(false);} } //actualiza las visitas en el servidor private boolean insertarVisitas() { restClient = new RestClient(WebUrl.webUrl + "frecuentes.php"); restClient.clearAddHeader(); restClient.clearAddParam(); restClient.AddParam("idcliente",Integer.toString( datosusuario.getUserId())); restClient.AddParam("nvisita",Integer.toString(nvisitas)); try { restClient.Execute(RequestMethod.POST); String res = restClient.getResponse().trim(); if (res.equals("true")) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } //Revisar en el servidor cuantas visitas tiene el usuario private void cargarvisitas() { restClient = new RestClient(WebUrl.webUrl + "verVisitas.php"); restClient.clearAddHeader(); restClient.clearAddParam(); restClient.AddParam("idcliente",Integer.toString( datosusuario.getUserId())); try { restClient.Execute(RequestMethod.POST); JSONArray json = new JSONArray(restClient.getResponse()); if (!json.isNull(0)) { JSONObject job = null; for (int i = 0; i < json.length(); i++) { job = json.getJSONObject(i); } nvisitas=job.getInt("nvisitas"); } } catch (Exception e) { e.printStackTrace(); } } private void bloquearchecks() { chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(false); } public boolean consultapassword() { try { restClient.Execute(RequestMethod.POST); JSONArray json = new JSONArray(restClient.getResponse()); if (!json.isNull(0)) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } public class ConsultarPassTask extends AsyncTask<Void, Void, Void> { private ProgressDialog progressDialog; private Context context; public ConsultarPassTask(ProgressDialog progressDialog, Context context) { this.context = context; this.progressDialog = progressDialog; } @Override protected Void doInBackground(Void... params) { if(consultapassword()) { passwordok=true; }else{passwordok=false;} return null; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if(passwordok) { if(check1) { nvisitas=1; check1=false; } if(check2) { nvisitas=2; check2=false; } if(check3) { nvisitas=3; check3=false; } if(check4) { nvisitas=4; check4=false; } if(check5) { nvisitas=5; check5=false; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(FrecuenteActivity.this); alertDialogBuilder.setTitle("¡Felicidades!"); alertDialogBuilder.setMessage("Tu próximo servicio es gratis"); alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert).show(); } if(check6) {nvisitas=0; check6=false; } if(insertarVisitas()) { Toast.makeText(FrecuenteActivity.this,"Visita registrada",Toast.LENGTH_SHORT).show(); datosusuario.setUserVisit(nvisitas); revisarvisitas(); }else { Toast.makeText(FrecuenteActivity.this,"La visita no fue registrada. Intente nuevamente", Toast.LENGTH_SHORT).show(); } }else { //Si el password no es correcto despalomea el check uncheck(); Toast.makeText(FrecuenteActivity.this,"Password incorrecto",Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } } public class ConsultarVisitasTask extends AsyncTask<Void, Void, Void> { private ProgressDialog progressDialog; private Context context; public ConsultarVisitasTask(ProgressDialog progressDialog, Context context) { this.context = context; this.progressDialog = progressDialog; } @Override protected Void doInBackground(Void... params) { cargarvisitas(); return null; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); switch(nvisitas) { case 0: bloquearchecks(); break; case 1: chk1.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(true); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(false); break; case 2: chk1.setChecked(true); chk2.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(true); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(false); break; case 3: chk1.setChecked(true); chk2.setChecked(true); chk3.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(true); chk5.setEnabled(false); chk6.setEnabled(false); break; case 4: chk1.setChecked(true); chk2.setChecked(true); chk3.setChecked(true); chk4.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(true); chk6.setEnabled(false); break; case 5: chk1.setChecked(true); chk2.setChecked(true); chk3.setChecked(true); chk4.setChecked(true); chk5.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(true); break; case 6: chk1.setChecked(true); chk2.setChecked(true); chk3.setChecked(true); chk4.setChecked(true); chk5.setChecked(true); chk6.setChecked(true); chk1.setEnabled(false); chk2.setEnabled(false); chk3.setEnabled(false); chk4.setEnabled(false); chk5.setEnabled(false); chk6.setEnabled(false); break; } //Guarde en shared preferences las visitas datosusuario.setUserVisit(nvisitas); progressDialog.dismiss(); } } }
14,556
0.519272
0.509584
478
29.449791
23.333416
109
false
false
0
0
0
0
0
0
0.546025
false
false
3
48924f278fbd89ee7539b005b771d2cd0aeb299f
3,040,836,852,910
9b92cd11f428f430fddf73a94b62bae528f0e33b
/Java Fundamentals/Java OOP/04. Interfaces and Abstraction/01. Interfaces and Abstraction - Lab/src/P08_MooD_3/Archangel.java
b6385303c588d5b0f1268d6b46ed01ba122eb79e
[ "MIT" ]
permissive
GabrielGardev/soft-uni
https://github.com/GabrielGardev/soft-uni
02533a5ddd3ebe450b3e84c27cc09910239fd5cb
785e3e726087232e1e516c4325772dd168487a3a
refs/heads/master
2020-04-18T09:09:47.821000
2020-04-16T14:10:28
2020-04-16T14:10:28
167,424,615
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package P08_MooD_3; public class Archangel extends Character<String> { private static final String CHARACTER_TYPE = "Archangel"; Archangel(String username, int level, Integer specialPoints) { super(username, CHARACTER_TYPE, level, specialPoints); } @Override public String toString() { return super.toString() + System.lineSeparator() + this.getSpecialPoints().intValue() * this.getLevel(); } }
UTF-8
Java
471
java
Archangel.java
Java
[]
null
[]
package P08_MooD_3; public class Archangel extends Character<String> { private static final String CHARACTER_TYPE = "Archangel"; Archangel(String username, int level, Integer specialPoints) { super(username, CHARACTER_TYPE, level, specialPoints); } @Override public String toString() { return super.toString() + System.lineSeparator() + this.getSpecialPoints().intValue() * this.getLevel(); } }
471
0.645435
0.639066
17
26.705883
25.872458
71
false
false
0
0
0
0
0
0
0.529412
false
false
3
eedb1271b07d83eac5cbfba309a71ab42408346f
15,522,011,828,045
3a6495b060dcc0c2ccaaf263aaab059f108cbdba
/LOP/src/test/java/com/LorealPages_TestCases/BeautyGenius.java
9ab71f2cc30e549f3772da8cd5937ead2f956ea6
[]
no_license
johnm323/LOP
https://github.com/johnm323/LOP
8e52f0391cd7e3c58c5681a4b50dd97b2f59a5e4
076f63de98c2707dc6d41516748bca3fc3ff62e5
refs/heads/master
2020-05-18T00:38:53.474000
2019-05-03T07:20:15
2019-05-03T07:20:15
184,068,139
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.LorealPages_TestCases; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import com.LorealPages.BaseClass; import com.LorealPages.BeautyGenius_Page; public class BeautyGenius extends BaseClass { @Test(priority = 55) public void verifybeautyGeniusIcon() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Icon"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusIcon(); logger.info("Verified Beauty Genius Icon successfully"); } @Test(priority = 56) public void verifybeautyGeniusLogo() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Header"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusLogo(); logger.info("Verified Beauty Genius Header successfully"); } @Test(priority = 57) public void verifybeautyGeniusHeader() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Description"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusHeader(); logger.info("Verified Beauty Genius Description successfully"); } @Test(priority = 58) public void verifybeautyGeniusRegistrationForm() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Form"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusRegistrationForm(); logger.info("Verified Beauty Genius Form successfully"); } @Test(priority = 59) public void verifymenExpertProductGrid() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Registration Buttons"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusRegistrationButtons(); logger.info("Verified Beauty Genius Registration Buttons successfully"); } }
UTF-8
Java
2,168
java
BeautyGenius.java
Java
[]
null
[]
package com.LorealPages_TestCases; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import com.LorealPages.BaseClass; import com.LorealPages.BeautyGenius_Page; public class BeautyGenius extends BaseClass { @Test(priority = 55) public void verifybeautyGeniusIcon() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Icon"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusIcon(); logger.info("Verified Beauty Genius Icon successfully"); } @Test(priority = 56) public void verifybeautyGeniusLogo() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Header"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusLogo(); logger.info("Verified Beauty Genius Header successfully"); } @Test(priority = 57) public void verifybeautyGeniusHeader() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Description"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusHeader(); logger.info("Verified Beauty Genius Description successfully"); } @Test(priority = 58) public void verifybeautyGeniusRegistrationForm() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Form"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusRegistrationForm(); logger.info("Verified Beauty Genius Form successfully"); } @Test(priority = 59) public void verifymenExpertProductGrid() throws InterruptedException { logger = report.createTest("Verify Beauty Genius Registration Buttons"); BeautyGenius_Page beautygenius = PageFactory.initElements(driver, BeautyGenius_Page.class); beautygenius.verifybeautyGeniusRegistrationButtons(); logger.info("Verified Beauty Genius Registration Buttons successfully"); } }
2,168
0.770295
0.765683
70
28.971428
32.043262
93
false
false
0
0
0
0
0
0
1.214286
false
false
3
7490dea03ff90e3ec79cd04855c7f57b98307947
35,175,782,154,303
e0148bce73e77c087dbc71e006dfad71e4578b0a
/fanweHybridLive/src/main/java/com/fanwe/live/adapter/viewholder/MsgTextViewHolder.java
67711033f17dff4df7c661c30199474059332403
[]
no_license
kingdzdz/FanweLive1
https://github.com/kingdzdz/FanweLive1
84dc9c86c6b803d27b2036a5147cc834f9d6b4fb
d127db1c1cc31d6a4c08e8644d10556889ea92e1
refs/heads/master
2020-04-24T20:24:22.951000
2019-02-23T17:31:45
2019-02-23T17:31:45
172,242,273
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fanwe.live.adapter.viewholder; import android.view.View; import com.fanwe.library.adapter.SDRecyclerAdapter; import com.fanwe.library.utils.SDResourcesUtil; import com.fanwe.live.LiveInformation; import com.fanwe.live.R; import com.fanwe.live.common.AppRuntimeWorker; import com.fanwe.live.model.custommsg.CustomMsg; import com.fanwe.live.model.custommsg.CustomMsgText; import com.fanwe.live.model.custommsg.MsgModel; /** * 文字消息 */ public class MsgTextViewHolder extends MsgViewHolder { public MsgTextViewHolder(View itemView) { super(itemView); } @Override protected void bindCustomMsg(int position, CustomMsg customMsg) { appendUserInfo(customMsg.getSender()); // 内容 int textColor = 0; if (customMsg.getSender().getUser_id().equals(LiveInformation.getInstance().getCreaterId())) { // 主播 textColor = SDResourcesUtil.getColor(R.color.main_color); } else if(customMsg.getSender().getUser_id().equals(AppRuntimeWorker.getLoginUserID())){ //自己 textColor = SDResourcesUtil.getColor(R.color.live_msg_text_creater); } else{ textColor = SDResourcesUtil.getColor(R.color.main_color); } appendContent(getText(), textColor); setUserInfoClickListener(tv_content); } protected String getText() { CustomMsgText msg = (CustomMsgText) customMsg; return msg.getText(); } }
UTF-8
Java
1,518
java
MsgTextViewHolder.java
Java
[]
null
[]
package com.fanwe.live.adapter.viewholder; import android.view.View; import com.fanwe.library.adapter.SDRecyclerAdapter; import com.fanwe.library.utils.SDResourcesUtil; import com.fanwe.live.LiveInformation; import com.fanwe.live.R; import com.fanwe.live.common.AppRuntimeWorker; import com.fanwe.live.model.custommsg.CustomMsg; import com.fanwe.live.model.custommsg.CustomMsgText; import com.fanwe.live.model.custommsg.MsgModel; /** * 文字消息 */ public class MsgTextViewHolder extends MsgViewHolder { public MsgTextViewHolder(View itemView) { super(itemView); } @Override protected void bindCustomMsg(int position, CustomMsg customMsg) { appendUserInfo(customMsg.getSender()); // 内容 int textColor = 0; if (customMsg.getSender().getUser_id().equals(LiveInformation.getInstance().getCreaterId())) { // 主播 textColor = SDResourcesUtil.getColor(R.color.main_color); } else if(customMsg.getSender().getUser_id().equals(AppRuntimeWorker.getLoginUserID())){ //自己 textColor = SDResourcesUtil.getColor(R.color.live_msg_text_creater); } else{ textColor = SDResourcesUtil.getColor(R.color.main_color); } appendContent(getText(), textColor); setUserInfoClickListener(tv_content); } protected String getText() { CustomMsgText msg = (CustomMsgText) customMsg; return msg.getText(); } }
1,518
0.673565
0.672897
53
27.264151
26.255745
100
false
false
0
0
0
0
0
0
0.415094
false
false
3
b5e5a07e4a06bf84862126913dc0c7d42b979054
2,662,879,786,763
1d619a6ab8eb2e14dec0c4ba365f30e9d72b4668
/wp-cp-m5/src/java/jp/chinaportal/portal/JapanManDAO.java
ef2fbdb1a1e8d8fd6e3e55b6e91c11f1f675ccdf
[]
no_license
websketch/all_project
https://github.com/websketch/all_project
a6554e705f398d0beb83b8e089d2c4a0cbe4ea0b
f8da7b02aaf2b7bd374e133a76bed11f9a72efa6
refs/heads/master
2020-05-26T05:49:57.435000
2012-08-11T06:28:56
2012-08-11T06:28:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jp.chinaportal.portal; import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import jp.chinaportal.portal.common.CommonUtil; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import com.chinaportal.portal.login.LoginMAN; import com.mediazone.bean.User; import com.mediazone.man.BaseManTransaction; import com.mediazone.man.UserInfoTransaction; import com.mediazone.man.bean.ManResponseBean; import com.mediazone.man.form.UserRegisterForm; public class JapanManDAO extends BaseManTransaction { private static final Logger logs = LogsFile.getLogs(JapanManDAO.class .getName()); /* * (non-Javadoc) * * @see com.mediazone.man.BaseManTransaction#mapResponseToBean(org.jdom.Document) */ protected List mapResponseToBean(Document doc) { // TODO Auto-generated method stub return null; } public User getMANUserInfo(String userId) throws Exception { User user = new User(); UserInfoTransaction userInfoTransaction = new UserInfoTransaction(); String userInfo = userInfoTransaction.getUserInfo(userId); if (!CommonUtil.checkEmptyString(userInfo)) { SAXBuilder parser = new SAXBuilder(); Document document = null; try { document = parser.build(new StringReader(userInfo)); } catch (JDOMException e) { logs.log(Level.SEVERE, "ERROR: " + "getMANUserInfo()" + " " + e.toString()); } catch (IOException e) { logs.log(Level.WARNING, "ERROR: " + "getMANUserInfo()" + " " + e.toString()); } String MANCrmId = document.getRootElement().getAttributeValue( "CrmId"); String MANEmail = document.getRootElement().getAttributeValue( "Email"); String MANUserId = document.getRootElement().getAttributeValue( "UserId"); String MANName = document.getRootElement() .getAttributeValue("Name"); String MANEmailNotify = document.getRootElement() .getAttributeValue("EmailNotify"); user.setLoginName(MANEmail); user.setManUserId(MANUserId); user.setName(MANName); if ( MANEmailNotify != null && MANEmailNotify.equals("on")) { user.setStatus(new Integer(1)); } else { user.setStatus(new Integer(0)); } } return user; } /** * Bean properties to set UserId SecurePassword SecurePin PinPayment * PinAmount PinMenu PinPG PinPGRate Name LeadId EmailNotify etc ReturnUrl * TermsAgree Email Language * * @param bean * @param response * code */ public ManResponseBean registerUser(UserRegisterForm bean) throws Exception { String url = "/services/RegisterUser"; /* * UserId SecurePassword SecurePin PinPayment PinAmount PinMenu PinPG * PinPGRate Name LeadId EmailNotify etc ReturnUrl TermsAgree Email * Language */ NameValuePair[] params = { new NameValuePair("UserId", bean.getUserId()), new NameValuePair("SecurePassword", bean.getSecurePassword()), new NameValuePair("SecurePin", bean.getSecurePin()), new NameValuePair("PinPayment", bean.getPinPayment()), new NameValuePair("PinAmount", bean.getPinAmount()), new NameValuePair("PinMenu", bean.getPinMenu()), new NameValuePair("PinPG", bean.getPinPG()), new NameValuePair("PinPGRate", bean.getPinPGRate()), new NameValuePair("FirstName", bean.getFirstName()), new NameValuePair("LastName", bean.getLastName()), new NameValuePair("Name", bean.getFirstName() + " " + bean.getLastName()), new NameValuePair("LeadId", bean.getLeadId()), new NameValuePair("EmailNotify", bean.getEmailNotify()), new NameValuePair("etc", bean.getEtc()), new NameValuePair("ReturnUrl", bean.getReturnUrl()), new NameValuePair("TermsAgree", bean.getTermsAgree()), new NameValuePair("Question", bean.getQuestion()), new NameValuePair("Answer", bean.getAnswer()), new NameValuePair("Language", bean.getLanguage()), new NameValuePair("Email", bean.getEmail()) }; ManResponseBean response = handlePOSTRequest(url, params, null); return response; } }
UTF-8
Java
5,000
java
JapanManDAO.java
Java
[ { "context": "lue(\"EmailNotify\");\n user.setLoginName(MANEmail);\n user.setManUserId(MANUserId);\n", "end": 2522, "score": 0.5913752913475037, "start": 2519, "tag": "NAME", "value": "MAN" }, { "context": "setManUserId(MANUserId);\n user.setName(MANName);\n if ( MANEmailNotify != null && MANE", "end": 2604, "score": 0.9007517695426941, "start": 2597, "tag": "NAME", "value": "MANName" } ]
null
[]
package jp.chinaportal.portal; import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import jp.chinaportal.portal.common.CommonUtil; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import com.chinaportal.portal.login.LoginMAN; import com.mediazone.bean.User; import com.mediazone.man.BaseManTransaction; import com.mediazone.man.UserInfoTransaction; import com.mediazone.man.bean.ManResponseBean; import com.mediazone.man.form.UserRegisterForm; public class JapanManDAO extends BaseManTransaction { private static final Logger logs = LogsFile.getLogs(JapanManDAO.class .getName()); /* * (non-Javadoc) * * @see com.mediazone.man.BaseManTransaction#mapResponseToBean(org.jdom.Document) */ protected List mapResponseToBean(Document doc) { // TODO Auto-generated method stub return null; } public User getMANUserInfo(String userId) throws Exception { User user = new User(); UserInfoTransaction userInfoTransaction = new UserInfoTransaction(); String userInfo = userInfoTransaction.getUserInfo(userId); if (!CommonUtil.checkEmptyString(userInfo)) { SAXBuilder parser = new SAXBuilder(); Document document = null; try { document = parser.build(new StringReader(userInfo)); } catch (JDOMException e) { logs.log(Level.SEVERE, "ERROR: " + "getMANUserInfo()" + " " + e.toString()); } catch (IOException e) { logs.log(Level.WARNING, "ERROR: " + "getMANUserInfo()" + " " + e.toString()); } String MANCrmId = document.getRootElement().getAttributeValue( "CrmId"); String MANEmail = document.getRootElement().getAttributeValue( "Email"); String MANUserId = document.getRootElement().getAttributeValue( "UserId"); String MANName = document.getRootElement() .getAttributeValue("Name"); String MANEmailNotify = document.getRootElement() .getAttributeValue("EmailNotify"); user.setLoginName(MANEmail); user.setManUserId(MANUserId); user.setName(MANName); if ( MANEmailNotify != null && MANEmailNotify.equals("on")) { user.setStatus(new Integer(1)); } else { user.setStatus(new Integer(0)); } } return user; } /** * Bean properties to set UserId SecurePassword SecurePin PinPayment * PinAmount PinMenu PinPG PinPGRate Name LeadId EmailNotify etc ReturnUrl * TermsAgree Email Language * * @param bean * @param response * code */ public ManResponseBean registerUser(UserRegisterForm bean) throws Exception { String url = "/services/RegisterUser"; /* * UserId SecurePassword SecurePin PinPayment PinAmount PinMenu PinPG * PinPGRate Name LeadId EmailNotify etc ReturnUrl TermsAgree Email * Language */ NameValuePair[] params = { new NameValuePair("UserId", bean.getUserId()), new NameValuePair("SecurePassword", bean.getSecurePassword()), new NameValuePair("SecurePin", bean.getSecurePin()), new NameValuePair("PinPayment", bean.getPinPayment()), new NameValuePair("PinAmount", bean.getPinAmount()), new NameValuePair("PinMenu", bean.getPinMenu()), new NameValuePair("PinPG", bean.getPinPG()), new NameValuePair("PinPGRate", bean.getPinPGRate()), new NameValuePair("FirstName", bean.getFirstName()), new NameValuePair("LastName", bean.getLastName()), new NameValuePair("Name", bean.getFirstName() + " " + bean.getLastName()), new NameValuePair("LeadId", bean.getLeadId()), new NameValuePair("EmailNotify", bean.getEmailNotify()), new NameValuePair("etc", bean.getEtc()), new NameValuePair("ReturnUrl", bean.getReturnUrl()), new NameValuePair("TermsAgree", bean.getTermsAgree()), new NameValuePair("Question", bean.getQuestion()), new NameValuePair("Answer", bean.getAnswer()), new NameValuePair("Language", bean.getLanguage()), new NameValuePair("Email", bean.getEmail()) }; ManResponseBean response = handlePOSTRequest(url, params, null); return response; } }
5,000
0.6096
0.6092
126
38.682541
25.526411
85
false
false
0
0
0
0
0
0
0.690476
false
false
3
bb1bd3f973d7e33485c59f755855e3fc9578f8d4
2,662,879,786,864
0427cb18b043377af0ca09bdf4df3807b028468b
/src/main/java/io/quarkus/nmtTracker/RuntimeEnvironmentResource.java
68ae46c8f9a3084d0d934a669b02f6a05d166376
[]
no_license
c00ler/nmt-tracker
https://github.com/c00ler/nmt-tracker
f8c7c2906bbeba89e367ba10c983391b12533875
640ef956ef3f74870e27ffac40a5e9c89c3776f8
refs/heads/main
2023-05-29T09:43:52.839000
2021-06-16T09:11:38
2021-06-16T09:11:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.quarkus.nmtTracker; import io.quarkus.nmtTracker.environment.Environment; import io.smallrye.mutiny.Uni; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; @Path("/environment") public class RuntimeEnvironmentResource extends BaseResource { @Inject Environment environment; @GET @Path("/processes") @Produces(MediaType.APPLICATION_JSON) public List<String> listProcesses() throws Exception { AtomicReference<List<String>> runningProcesses = new AtomicReference<>(); environment.getProcesses(processes -> { runningProcesses.set(processes); latch.countDown(); } ); if (waitFor(latch)) { return runningProcesses.get(); } else { throw new Exception("Timedout waiting for list of processes"); } } }
UTF-8
Java
1,222
java
RuntimeEnvironmentResource.java
Java
[]
null
[]
package io.quarkus.nmtTracker; import io.quarkus.nmtTracker.environment.Environment; import io.smallrye.mutiny.Uni; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; @Path("/environment") public class RuntimeEnvironmentResource extends BaseResource { @Inject Environment environment; @GET @Path("/processes") @Produces(MediaType.APPLICATION_JSON) public List<String> listProcesses() throws Exception { AtomicReference<List<String>> runningProcesses = new AtomicReference<>(); environment.getProcesses(processes -> { runningProcesses.set(processes); latch.countDown(); } ); if (waitFor(latch)) { return runningProcesses.get(); } else { throw new Exception("Timedout waiting for list of processes"); } } }
1,222
0.691489
0.691489
47
25
21.282297
81
false
false
0
0
0
0
0
0
0.468085
false
false
3
646256877508834facff45bbf3006a72df2a16cd
29,351,806,509,255
aab6030f81fcd2bd4a20801cac0b0e1bd8e12d9e
/src/剑指offer/no51_60/Print_60.java
2f252b82dc8eecacdb35cb9110adf7e25d86fc21
[]
no_license
yunyun2017/algorithm
https://github.com/yunyun2017/algorithm
9b32a7bd755de071efce974d4544f49c013ce3c4
b5ff2a948e67ebd9c179c2be732e8b16f4a3d00b
refs/heads/master
2021-06-17T18:32:41.825000
2019-08-21T07:55:54
2019-08-21T07:55:54
141,140,469
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package 剑指offer.no51_60; import 剑指offer.commonWidgets.ListNode; import 剑指offer.commonWidgets.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class Print_60 { ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> seq = new ArrayList<>(); if (pRoot == null) return seq; Queue<TreeNode> queue1 = new LinkedList<>(); Queue<TreeNode> queue2 = new LinkedList<>(); queue1.offer(pRoot); while (!queue1.isEmpty() || !queue2.isEmpty()) { ArrayList<Integer> row1 = new ArrayList<>(); while (!queue1.isEmpty()) { TreeNode node = queue1.poll(); row1.add(node.val); if (node.left != null) queue2.offer(node.left); if (node.right != null) queue2.offer(node.right); } if (row1.size() > 0) seq.add(row1); ArrayList<Integer> row2 = new ArrayList<>(); while (!queue2.isEmpty()) { TreeNode node = queue2.poll(); row2.add(node.val); if (node.left != null) queue1.offer(node.left); if (node.right != null) queue1.offer(node.right); } if (row2.size() > 0) seq.add(row2); } return seq; } public static void main(String[] args) { TreeNode p = new TreeNode(1); p.left = new TreeNode(2); p.right = new TreeNode(3); p.left.left = new TreeNode(4); p.left.right = new TreeNode(5); p.right.left = new TreeNode(6); p.right.right = new TreeNode(7); Print_60 print = new Print_60(); ArrayList<ArrayList<Integer>> list = print.Print(p); } }
UTF-8
Java
1,909
java
Print_60.java
Java
[]
null
[]
package 剑指offer.no51_60; import 剑指offer.commonWidgets.ListNode; import 剑指offer.commonWidgets.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class Print_60 { ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> seq = new ArrayList<>(); if (pRoot == null) return seq; Queue<TreeNode> queue1 = new LinkedList<>(); Queue<TreeNode> queue2 = new LinkedList<>(); queue1.offer(pRoot); while (!queue1.isEmpty() || !queue2.isEmpty()) { ArrayList<Integer> row1 = new ArrayList<>(); while (!queue1.isEmpty()) { TreeNode node = queue1.poll(); row1.add(node.val); if (node.left != null) queue2.offer(node.left); if (node.right != null) queue2.offer(node.right); } if (row1.size() > 0) seq.add(row1); ArrayList<Integer> row2 = new ArrayList<>(); while (!queue2.isEmpty()) { TreeNode node = queue2.poll(); row2.add(node.val); if (node.left != null) queue1.offer(node.left); if (node.right != null) queue1.offer(node.right); } if (row2.size() > 0) seq.add(row2); } return seq; } public static void main(String[] args) { TreeNode p = new TreeNode(1); p.left = new TreeNode(2); p.right = new TreeNode(3); p.left.left = new TreeNode(4); p.left.right = new TreeNode(5); p.right.left = new TreeNode(6); p.right.right = new TreeNode(7); Print_60 print = new Print_60(); ArrayList<ArrayList<Integer>> list = print.Print(p); } }
1,909
0.517132
0.496046
63
29.111111
18.531065
62
false
false
0
0
0
0
0
0
0.555556
false
false
3
a6f5f6e93895fdbe9137e7c8f562cd714f32329d
970,662,617,578
fc62c6ea77426b329429522903d41d9139e0c8a3
/Exchange/src/main/java/com/javamuk/product/persistence/MyProductReadDAO.java
11cbdb5bff9ca9ef007f6a0cce3a47d0dde93e44
[]
no_license
wwwnghks/exchange
https://github.com/wwwnghks/exchange
1b10cca336ab2336c7f6834d45909006f0d7b865
e97a48a66030f4954fd97d2790fc12e4819b01a6
refs/heads/master
2020-03-13T10:29:51.945000
2018-06-18T01:45:31
2018-06-18T01:45:31
131,084,596
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javamuk.product.persistence; import java.util.List; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import com.javamuk.domain.Member; import com.javamuk.domain.Product; @Repository public class MyProductReadDAO { @Inject private SqlSession session; private static String namespace= "com.javamuk.mapper.MyProductMapper"; public List<Product> myProductAll(Member member) { // TODO Auto-generated method stub return session.selectList(namespace+".selectProductAll",member); } public Product myProductOne(Product product) { // TODO Auto-generated method stub return session.selectOne(namespace+".selectProductOne",product); } public Member ownerMember(Product product) { // TODO Auto-generated method stub return session.selectOne(namespace+".selectOwner", product); } public List<Product> locationProduct(Product location_product) { // TODO Auto-generated method stub return session.selectList(namespace+".locationProduct", location_product); } public List<Product> productSearch(Product product) { // TODO Auto-generated method stub return session.selectList(namespace+".searchProduct", product); } }
UTF-8
Java
1,287
java
MyProductReadDAO.java
Java
[]
null
[]
package com.javamuk.product.persistence; import java.util.List; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import com.javamuk.domain.Member; import com.javamuk.domain.Product; @Repository public class MyProductReadDAO { @Inject private SqlSession session; private static String namespace= "com.javamuk.mapper.MyProductMapper"; public List<Product> myProductAll(Member member) { // TODO Auto-generated method stub return session.selectList(namespace+".selectProductAll",member); } public Product myProductOne(Product product) { // TODO Auto-generated method stub return session.selectOne(namespace+".selectProductOne",product); } public Member ownerMember(Product product) { // TODO Auto-generated method stub return session.selectOne(namespace+".selectOwner", product); } public List<Product> locationProduct(Product location_product) { // TODO Auto-generated method stub return session.selectList(namespace+".locationProduct", location_product); } public List<Product> productSearch(Product product) { // TODO Auto-generated method stub return session.selectList(namespace+".searchProduct", product); } }
1,287
0.747475
0.747475
48
24.8125
24.938805
76
false
false
0
0
0
0
0
0
1.1875
false
false
3
7f21e7c913cae895447103c8e69bcf5acd8accce
20,117,626,864,826
3a2256b5ff15b66b0409706a2dd6a953feebb12e
/app/src/main/java/com/sikdev/diplomankas/LoadingActivity.java
8d855e955a01388b4aafa39c2ef3589842ff5a5c
[]
no_license
SergeyVitovskiy/DiplomAnkas
https://github.com/SergeyVitovskiy/DiplomAnkas
04fc2551f71c5e2206704f266b7e1adc1129dd32
6afbe5d6f954d2dda1d475e4a7e294e8fcdcde82
refs/heads/master
2023-04-11T17:13:22.024000
2021-05-14T04:57:52
2021-05-14T04:57:52
367,252,765
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sikdev.diplomankas; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import com.sikdev.diplomankas.Objects.Basket; import com.sikdev.diplomankas.Objects.User; import java.util.Timer; import java.util.TimerTask; public class LoadingActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loading); // Загрузка товаров из корзины Basket.loadSystemBasket(LoadingActivity.this); // Загрузка данных пользователя User.loadSystemBasket(LoadingActivity.this); final int[] tick = {0}; // Таймер задержки на загрузку final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (tick[0] >=2){ timer.cancel(); Intent intent = new Intent(LoadingActivity.this, MainActivity.class); startActivity(intent); } tick[0]++; } }); } },0,1000); } @Override public void onBackPressed() { } }
UTF-8
Java
1,527
java
LoadingActivity.java
Java
[]
null
[]
package com.sikdev.diplomankas; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import com.sikdev.diplomankas.Objects.Basket; import com.sikdev.diplomankas.Objects.User; import java.util.Timer; import java.util.TimerTask; public class LoadingActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loading); // Загрузка товаров из корзины Basket.loadSystemBasket(LoadingActivity.this); // Загрузка данных пользователя User.loadSystemBasket(LoadingActivity.this); final int[] tick = {0}; // Таймер задержки на загрузку final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (tick[0] >=2){ timer.cancel(); Intent intent = new Intent(LoadingActivity.this, MainActivity.class); startActivity(intent); } tick[0]++; } }); } },0,1000); } @Override public void onBackPressed() { } }
1,527
0.565726
0.559532
48
29.291666
20.11525
97
false
false
0
0
0
0
0
0
0.479167
false
false
3
8a5c9e075b266dd0a05d1ffa44ae28cee9561fa2
9,380,208,604,068
b5da1f12618a3f5e877593187373f7dacd1170ad
/src/main/java/com/hlcl/rql/util/as/CategorizePagesMap.java
3db90c7c2b991b43e7f9155cac6fdb1822157f7b
[]
no_license
solutionexchange/Fork-jRQL
https://github.com/solutionexchange/Fork-jRQL
0aa93855277be354e9b354e99220f965b873ffd1
00ed485896d460906c811364134d1771b6ccb8d2
refs/heads/master
2021-01-18T20:07:25.759000
2017-01-03T14:56:11
2017-01-03T14:56:11
86,940,012
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hlcl.rql.util.as; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import com.hlcl.rql.as.Page; import com.hlcl.rql.as.RQLException; /** * @author lejafr * * This class maps a category (simply a string) to a set of pages and provides access to categories and page sets. */ public class CategorizePagesMap { // maps a category string to a set of pages private Map<String, Set<Page>> categoryMap; private boolean freeOccupiedPageMemory; /** * Creates a category page set map. * * @param freeOccupiedPageMemory if true, all added pages will release there internal caches f */ public CategorizePagesMap(boolean freeOccupiedPageMemory) { super(); this.freeOccupiedPageMemory = freeOccupiedPageMemory; // initialize map categoryMap = new HashMap<String, Set<Page>>(); } /** * Adds the given page under the given categories. */ public void add(Page page, java.util.List<String> categories) throws RQLException { for (String category : categories) { add(page, category); } } /** * Adds the given page under the given category. */ public void add(Page page, String category) throws RQLException { Set<Page> setOrNull = getPages(category); // lazy initialize set if (setOrNull == null) { setOrNull = new HashSet<Page>(); categoryMap.put(category, setOrNull); } // reduce memory footprint of page if (freeOccupiedPageMemory) { page.freeOccupiedMemory(); } // add page setOrNull.add(page); } /** * Returns the Set for the given category or null, if this map did not contain pages for given category at all. */ public Set<Page> getPages(String category) throws RQLException { return categoryMap.get(category); } /** * Returns the Set sorted by page headline for the given category or null, if this map did not contain pages for given category at all. */ public SortedSet<Page> getPagesSortedByHeadline(String category) throws RQLException { SortedSet<Page> result = new TreeSet<Page>(new HeadlinePageComparator()); result.addAll(getPages(category)); return result; } /** * Returns true, if this map contains the given category, otherwise false. */ public boolean containsCategory(String category) throws RQLException { return categoryMap.containsKey(category); } /** * Returns all added categories of this map sorted ascending. */ public SortedSet<String> getCategories() throws RQLException { return new TreeSet<String>(categoryMap.keySet()); } }
UTF-8
Java
2,581
java
CategorizePagesMap.java
Java
[ { "context": "port com.hlcl.rql.as.RQLException;\n\n/**\n * @author lejafr\n * \n * This class maps a category (simply a strin", "end": 270, "score": 0.9996235370635986, "start": 264, "tag": "USERNAME", "value": "lejafr" } ]
null
[]
package com.hlcl.rql.util.as; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import com.hlcl.rql.as.Page; import com.hlcl.rql.as.RQLException; /** * @author lejafr * * This class maps a category (simply a string) to a set of pages and provides access to categories and page sets. */ public class CategorizePagesMap { // maps a category string to a set of pages private Map<String, Set<Page>> categoryMap; private boolean freeOccupiedPageMemory; /** * Creates a category page set map. * * @param freeOccupiedPageMemory if true, all added pages will release there internal caches f */ public CategorizePagesMap(boolean freeOccupiedPageMemory) { super(); this.freeOccupiedPageMemory = freeOccupiedPageMemory; // initialize map categoryMap = new HashMap<String, Set<Page>>(); } /** * Adds the given page under the given categories. */ public void add(Page page, java.util.List<String> categories) throws RQLException { for (String category : categories) { add(page, category); } } /** * Adds the given page under the given category. */ public void add(Page page, String category) throws RQLException { Set<Page> setOrNull = getPages(category); // lazy initialize set if (setOrNull == null) { setOrNull = new HashSet<Page>(); categoryMap.put(category, setOrNull); } // reduce memory footprint of page if (freeOccupiedPageMemory) { page.freeOccupiedMemory(); } // add page setOrNull.add(page); } /** * Returns the Set for the given category or null, if this map did not contain pages for given category at all. */ public Set<Page> getPages(String category) throws RQLException { return categoryMap.get(category); } /** * Returns the Set sorted by page headline for the given category or null, if this map did not contain pages for given category at all. */ public SortedSet<Page> getPagesSortedByHeadline(String category) throws RQLException { SortedSet<Page> result = new TreeSet<Page>(new HeadlinePageComparator()); result.addAll(getPages(category)); return result; } /** * Returns true, if this map contains the given category, otherwise false. */ public boolean containsCategory(String category) throws RQLException { return categoryMap.containsKey(category); } /** * Returns all added categories of this map sorted ascending. */ public SortedSet<String> getCategories() throws RQLException { return new TreeSet<String>(categoryMap.keySet()); } }
2,581
0.726463
0.726463
95
26.168421
29.713598
136
false
false
0
0
0
0
0
0
1.389474
false
false
3
89f44640191373e1c5706448d078e8efbb693e68
27,487,790,755,894
62000a806728a1fe411840cd2427aed42c0bb7fa
/BOJ/_1_Silver/Level_2/a1058_친구.java
e461d2e9cf5d3d92a89aa36ea3ed9f91f0ee569e
[]
no_license
younwony/wony
https://github.com/younwony/wony
9e885727433668b2b4fbd549d91ac2b85bd59223
30d55efac769ed587f26023be8296954b102022f
refs/heads/master
2022-06-26T00:50:30.775000
2022-06-25T12:10:51
2022-06-25T12:10:51
132,995,347
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package BOJ.src._1_Silver.Level_2; public class a1058_친구 { public static void main(String[] args) { } }
UTF-8
Java
118
java
a1058_친구.java
Java
[]
null
[]
package BOJ.src._1_Silver.Level_2; public class a1058_친구 { public static void main(String[] args) { } }
118
0.649123
0.596491
7
15.285714
16.951311
44
false
false
0
0
0
0
0
0
0.142857
false
false
3
15a552b2f989905970cd16e268dfc8cb268d6525
33,706,903,387,191
82c47316be365b4bf9e0ac621307ae35398888ad
/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/customrule/CustomRuleInitializer.java
1129eab833fca2c3dac2d8204d080d17e7af8958
[ "Apache-2.0" ]
permissive
astamuse/asta4d
https://github.com/astamuse/asta4d
94e68c3f218adbbce10c66842e578b9f43d3cb8b
9273956311941948966555cd3579362a282a1ffa
refs/heads/develop
2023-08-30T01:16:52.108000
2019-02-07T04:34:57
2019-02-07T04:34:57
7,204,443
183
75
null
false
2020-02-11T03:37:00
2012-12-17T12:30:57
2020-02-05T06:11:20
2019-02-07T04:34:58
17,688
163
60
16
Java
false
false
package com.astamuse.asta4d.sample.customrule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleInitializer; public class CustomRuleInitializer implements UrlMappingRuleInitializer<CustomRuleSet> { @Override public void initUrlMappingRules(CustomRuleSet rules) { rules.add("/", "index.html").id("top").group("somegroup"); rules.add("/index.html").reMapTo("top"); rules.add("/gohandler").group("handler-group").handler(new Object() { public void handler() { System.out.println(""); } }).forward("handlerResult.html"); } }
UTF-8
Java
621
java
CustomRuleInitializer.java
Java
[]
null
[]
package com.astamuse.asta4d.sample.customrule; import com.astamuse.asta4d.web.dispatch.mapping.UrlMappingRuleInitializer; public class CustomRuleInitializer implements UrlMappingRuleInitializer<CustomRuleSet> { @Override public void initUrlMappingRules(CustomRuleSet rules) { rules.add("/", "index.html").id("top").group("somegroup"); rules.add("/index.html").reMapTo("top"); rules.add("/gohandler").group("handler-group").handler(new Object() { public void handler() { System.out.println(""); } }).forward("handlerResult.html"); } }
621
0.661836
0.658615
17
35.529411
29.325993
88
false
false
0
0
0
0
0
0
0.411765
false
false
3
14e3be3164a56b01682d2348fb9f04989f8b1250
9,148,280,403,327
6a53157e39224e2acce48dbb032216ef3542967b
/fiabilite/testUnitaires/src/item/tests/ItemTest.java
0c78d36aa57f4504f494174d0d09b7464a724362
[]
no_license
laiaga/M2_TPs
https://github.com/laiaga/M2_TPs
3d68a454bc73991774acadd41abe3ee1dc03940d
ae1b3d039ba858aa4fb53dbdb041e9da565f5ec5
refs/heads/master
2021-01-11T05:06:34.952000
2016-12-01T15:46:13
2016-12-01T15:46:13
68,611,558
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package item.tests; import org.junit.After; import org.junit.Test; import org.junit.Before; import org.junit.Assert; import item.Item; public class ItemTest { private Item cheapItem; private Item cheapItemBis; private Item expensiveItem; @Before public void setUp() throws Exception { cheapItem = new Item("cheap", 4.2f); cheapItemBis = new Item("cheap", 4.2f); expensiveItem = new Item("expensive", 6.2f); } @After public void tearDown() throws Exception { cheapItem = null; cheapItemBis = null; expensiveItem = null; } @Test public void testGetPrice() { Assert.assertEquals(4.2f, cheapItem.getPrice(),0.001); } @Test public void testGreaterThanPrice() { Assert.assertEquals(true, expensiveItem.greaterThanPrice(cheapItem)); Assert.assertEquals(false, expensiveItem.greaterThanPrice(expensiveItem)); Assert.assertEquals(false, cheapItem.greaterThanPrice(expensiveItem)); } @Test public void testLessThanPrice() { Assert.assertEquals(false, expensiveItem.lessThanPrice(cheapItem)); Assert.assertEquals(false, expensiveItem.lessThanPrice(expensiveItem)); Assert.assertEquals(true, cheapItem.lessThanPrice(expensiveItem)); } @Test public void testLessEqualPrice() { Assert.assertEquals(false, expensiveItem.lessEqualPrice(cheapItem)); Assert.assertEquals(true, expensiveItem.lessEqualPrice(expensiveItem)); Assert.assertEquals(true, cheapItem.lessEqualPrice(expensiveItem)); } @Test public void testIsSameArticle() { Assert.assertEquals(true, cheapItem.isSameArticle(cheapItemBis)); Assert.assertEquals(false, cheapItem.isSameArticle(expensiveItem)); } }
UTF-8
Java
1,624
java
ItemTest.java
Java
[]
null
[]
package item.tests; import org.junit.After; import org.junit.Test; import org.junit.Before; import org.junit.Assert; import item.Item; public class ItemTest { private Item cheapItem; private Item cheapItemBis; private Item expensiveItem; @Before public void setUp() throws Exception { cheapItem = new Item("cheap", 4.2f); cheapItemBis = new Item("cheap", 4.2f); expensiveItem = new Item("expensive", 6.2f); } @After public void tearDown() throws Exception { cheapItem = null; cheapItemBis = null; expensiveItem = null; } @Test public void testGetPrice() { Assert.assertEquals(4.2f, cheapItem.getPrice(),0.001); } @Test public void testGreaterThanPrice() { Assert.assertEquals(true, expensiveItem.greaterThanPrice(cheapItem)); Assert.assertEquals(false, expensiveItem.greaterThanPrice(expensiveItem)); Assert.assertEquals(false, cheapItem.greaterThanPrice(expensiveItem)); } @Test public void testLessThanPrice() { Assert.assertEquals(false, expensiveItem.lessThanPrice(cheapItem)); Assert.assertEquals(false, expensiveItem.lessThanPrice(expensiveItem)); Assert.assertEquals(true, cheapItem.lessThanPrice(expensiveItem)); } @Test public void testLessEqualPrice() { Assert.assertEquals(false, expensiveItem.lessEqualPrice(cheapItem)); Assert.assertEquals(true, expensiveItem.lessEqualPrice(expensiveItem)); Assert.assertEquals(true, cheapItem.lessEqualPrice(expensiveItem)); } @Test public void testIsSameArticle() { Assert.assertEquals(true, cheapItem.isSameArticle(cheapItemBis)); Assert.assertEquals(false, cheapItem.isSameArticle(expensiveItem)); } }
1,624
0.768473
0.761084
60
26.066668
25.405293
76
false
false
0
0
0
0
0
0
1.733333
false
false
3
940ecdcea6c7d124786357c306ac2a1dcc48a441
14,328,010,963,199
0ade1cf5b58621df288915b3790a4ecd797a6c84
/src/main/java/org/elasticsearch/action/bench/BenchmarkSettings.java
e0efa3cf5cb324e05c2a0045f10b4dfce2f7ac32
[ "Apache-2.0" ]
permissive
sarvex/elasticsearch
https://github.com/sarvex/elasticsearch
dd2fa074889a309bc78870710901eb485d026074
d5b378170ded14084a283b8a6fec51788bd33fd3
refs/heads/master
2023-05-26T09:12:44.442000
2023-05-03T03:11:25
2023-05-03T03:11:25
32,274,228
0
0
Apache-2.0
true
2023-05-03T03:11:26
2015-03-15T17:34:58
2023-05-03T03:05:32
2023-05-03T03:11:25
88,346
0
0
0
Java
false
false
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.action.bench; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Settings that define how a benchmark should be executed. */ public class BenchmarkSettings implements Streamable { public static final int DEFAULT_CONCURRENCY = 5; public static final int DEFAULT_ITERATIONS = 5; public static final int DEFAULT_MULTIPLIER = 1000; public static final int DEFAULT_NUM_SLOWEST = 1; public static final boolean DEFAULT_WARMUP = true; public static final SearchType DEFAULT_SEARCH_TYPE = SearchType.DEFAULT; public static final double[] DEFAULT_PERCENTILES = { 10, 25, 50, 75, 90, 99 }; private int concurrency = DEFAULT_CONCURRENCY; private int iterations = DEFAULT_ITERATIONS; private int multiplier = DEFAULT_MULTIPLIER; private int numSlowest = DEFAULT_NUM_SLOWEST; private boolean warmup = DEFAULT_WARMUP; private SearchType searchType = DEFAULT_SEARCH_TYPE; private ClearIndicesCacheRequest clearCaches = null; private ClearCachesSettings clearCachesSettings = null; private String[] indices = Strings.EMPTY_ARRAY; private String[] types = Strings.EMPTY_ARRAY; private List<SearchRequest> searchRequests = new ArrayList<>(); private boolean concurrencyFinalized = false; private boolean iterationsFinalized = false; private boolean multiplierFinalized = false; private boolean numSlowestFinalized = false; private boolean warmupFinalized = false; private boolean searchTypeFinalized = false; private boolean clearCachesSettingsFinalized = false; private boolean allowCacheClearing = true; /** * List of indices to execute on * @return Indices */ public String[] indices() { return indices; } /** * Sets the indices to execute on * @param indices Indices */ public void indices(String[] indices) { this.indices = (indices == null) ? Strings.EMPTY_ARRAY : indices; } /** * List of types to execute on * @return Types */ public String[] types() { return types; } /** * Sets the types to execute on * @param types Types */ public void types(String[] types) { this.types = (types == null) ? Strings.EMPTY_ARRAY : types; } /** * Gets the concurrency level * @return Concurrency */ public int concurrency() { return concurrency; } /** * Sets the concurrency level; determines how many threads will be executing the competition concurrently. * @param concurrency Concurrency * @param finalize If true, value cannot be overwritten by subsequent calls */ public void concurrency(int concurrency, boolean finalize) { if (concurrencyFinalized) { return; } this.concurrency = concurrency; concurrencyFinalized = finalize; } /** * How many times to the competition. * @return Iterations */ public int iterations() { return iterations; } /** * How many times to run the competition. Requests will be executed a total of (iterations * multiplier). * @param iterations Iterations * @param finalize If true, value cannot be overwritten by subsequent calls */ public void iterations(int iterations, boolean finalize) { if (iterationsFinalized) { return; } this.iterations = iterations; iterationsFinalized = finalize; } /** * Gets the multiplier * @return Multiplier */ public int multiplier() { return multiplier; } /** * Sets the multiplier. The multiplier determines how many times each iteration will be run. * @param multiplier Multiplier * @param finalize If true, value cannot be overwritten by subsequent calls */ public void multiplier(int multiplier, boolean finalize) { if (multiplierFinalized) { return; } this.multiplier = multiplier; multiplierFinalized = finalize; } /** * Gets number of slow requests to track * @return Number of slow requests to track */ public int numSlowest() { return numSlowest; } /** * How many slow requests to track * @param numSlowest Number of slow requests to track * @param finalize If true, value cannot be overwritten by subsequent calls */ public void numSlowest(int numSlowest, boolean finalize) { if (numSlowestFinalized) { return; } this.numSlowest = numSlowest; numSlowestFinalized = finalize; } /** * Whether to run a warmup search request * @return True/false */ public boolean warmup() { return warmup; } /** * Whether to run a warmup search request * @param warmup True/false * @param finalize If true, value cannot be overwritten by subsequent calls */ public void warmup(boolean warmup, boolean finalize) { if (warmupFinalized) { return; } this.warmup = warmup; warmupFinalized = finalize; } /** * Gets the search type * @return Search type */ public SearchType searchType() { return searchType; } /** * Sets the search type * @param searchType Search type * @param finalize If true, value cannot be overwritten by subsequent calls */ public void searchType(SearchType searchType, boolean finalize) { if (searchTypeFinalized) { return; } this.searchType = searchType; searchTypeFinalized = finalize; } /** * Gets the list of search requests to benchmark * @return Search requests */ public List<SearchRequest> searchRequests() { return searchRequests; } /** * Adds a search request to benchmark * @param searchRequest Search request */ public void addSearchRequest(SearchRequest... searchRequest) { searchRequests.addAll(Arrays.asList(searchRequest)); } /** * Gets the clear caches request * @return The clear caches request */ public ClearIndicesCacheRequest clearCaches() { return clearCaches; } public boolean allowCacheClearing() { return allowCacheClearing; } public void allowCacheClearing(boolean allowCacheClearing) { this.allowCacheClearing = allowCacheClearing; } /** * Gets the clear caches settings * @return Clear caches settings */ public ClearCachesSettings clearCachesSettings() { return clearCachesSettings; } /** * Sets the clear caches settings * @param clearCachesSettings Clear caches settings * @param finalize If true, value cannot be overwritten by subsequent calls */ public void clearCachesSettings(ClearCachesSettings clearCachesSettings, boolean finalize) { if (clearCachesSettingsFinalized) { return; } this.clearCachesSettings = clearCachesSettings; clearCachesSettingsFinalized = finalize; } /** * Builds a clear cache request from the settings */ public void buildClearCachesRequestFromSettings() { clearCaches = new ClearIndicesCacheRequest(indices); clearCaches.filterCache(clearCachesSettings.filterCache); clearCaches.fieldDataCache(clearCachesSettings.fieldDataCache); clearCaches.idCache(clearCachesSettings.idCache); clearCaches.recycler(clearCachesSettings.recyclerCache); clearCaches.fields(clearCachesSettings.fields); clearCaches.filterKeys(clearCachesSettings.filterKeys); } public void buildSearchRequestsFromSettings() { for (SearchRequest searchRequest : searchRequests) { searchRequest.indices(indices); searchRequest.types(types); searchRequest.searchType(searchType); } } /** * Merge another settings object with this one, ignoring fields which have been finalized. * This is a convenience so that a global settings object can cascade it's settings * down to specific competitors w/o inadvertently overwriting anything that has already been set. * @param otherSettings The settings to merge into this */ public void merge(BenchmarkSettings otherSettings) { if (!concurrencyFinalized) { concurrency = otherSettings.concurrency; } if (!iterationsFinalized) { iterations = otherSettings.iterations; } if (!multiplierFinalized) { multiplier = otherSettings.multiplier; } if (!numSlowestFinalized) { numSlowest = otherSettings.numSlowest; } if (!warmupFinalized) { warmup = otherSettings.warmup; } if (!searchTypeFinalized) { searchType = otherSettings.searchType; } if (!clearCachesSettingsFinalized) { clearCachesSettings = otherSettings.clearCachesSettings; } } public static class ClearCachesSettings { private boolean filterCache = false; private boolean fieldDataCache = false; private boolean idCache = false; private boolean recyclerCache = false; private String[] fields = null; private String[] filterKeys = null; public void filterCache(boolean filterCache) { this.filterCache = filterCache; } public void fieldDataCache(boolean fieldDataCache) { this.fieldDataCache = fieldDataCache; } public void idCache(boolean idCache) { this.idCache = idCache; } public void recycler(boolean recyclerCache) { this.recyclerCache = recyclerCache; } public void fields(String[] fields) { this.fields = fields; } public void filterKeys(String[] filterKeys) { this.filterKeys = filterKeys; } } @Override public void readFrom(StreamInput in) throws IOException { concurrency = in.readVInt(); iterations = in.readVInt(); multiplier = in.readVInt(); numSlowest = in.readVInt(); warmup = in.readBoolean(); indices = in.readStringArray(); types = in.readStringArray(); searchType = SearchType.fromId(in.readByte()); clearCaches = in.readOptionalStreamable(new ClearIndicesCacheRequest()); final int size = in.readVInt(); for (int i = 0; i < size; i++) { SearchRequest searchRequest = new SearchRequest(); searchRequest.readFrom(in); searchRequests.add(searchRequest); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(concurrency); out.writeVInt(iterations); out.writeVInt(multiplier); out.writeVInt(numSlowest); out.writeBoolean(warmup); out.writeStringArray(indices); out.writeStringArray(types); out.writeByte(searchType.id()); out.writeOptionalStreamable(clearCaches); out.writeVInt(searchRequests.size()); for (SearchRequest searchRequest : searchRequests) { searchRequest.writeTo(out); } } }
UTF-8
Java
12,704
java
BenchmarkSettings.java
Java
[]
null
[]
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.action.bench; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Settings that define how a benchmark should be executed. */ public class BenchmarkSettings implements Streamable { public static final int DEFAULT_CONCURRENCY = 5; public static final int DEFAULT_ITERATIONS = 5; public static final int DEFAULT_MULTIPLIER = 1000; public static final int DEFAULT_NUM_SLOWEST = 1; public static final boolean DEFAULT_WARMUP = true; public static final SearchType DEFAULT_SEARCH_TYPE = SearchType.DEFAULT; public static final double[] DEFAULT_PERCENTILES = { 10, 25, 50, 75, 90, 99 }; private int concurrency = DEFAULT_CONCURRENCY; private int iterations = DEFAULT_ITERATIONS; private int multiplier = DEFAULT_MULTIPLIER; private int numSlowest = DEFAULT_NUM_SLOWEST; private boolean warmup = DEFAULT_WARMUP; private SearchType searchType = DEFAULT_SEARCH_TYPE; private ClearIndicesCacheRequest clearCaches = null; private ClearCachesSettings clearCachesSettings = null; private String[] indices = Strings.EMPTY_ARRAY; private String[] types = Strings.EMPTY_ARRAY; private List<SearchRequest> searchRequests = new ArrayList<>(); private boolean concurrencyFinalized = false; private boolean iterationsFinalized = false; private boolean multiplierFinalized = false; private boolean numSlowestFinalized = false; private boolean warmupFinalized = false; private boolean searchTypeFinalized = false; private boolean clearCachesSettingsFinalized = false; private boolean allowCacheClearing = true; /** * List of indices to execute on * @return Indices */ public String[] indices() { return indices; } /** * Sets the indices to execute on * @param indices Indices */ public void indices(String[] indices) { this.indices = (indices == null) ? Strings.EMPTY_ARRAY : indices; } /** * List of types to execute on * @return Types */ public String[] types() { return types; } /** * Sets the types to execute on * @param types Types */ public void types(String[] types) { this.types = (types == null) ? Strings.EMPTY_ARRAY : types; } /** * Gets the concurrency level * @return Concurrency */ public int concurrency() { return concurrency; } /** * Sets the concurrency level; determines how many threads will be executing the competition concurrently. * @param concurrency Concurrency * @param finalize If true, value cannot be overwritten by subsequent calls */ public void concurrency(int concurrency, boolean finalize) { if (concurrencyFinalized) { return; } this.concurrency = concurrency; concurrencyFinalized = finalize; } /** * How many times to the competition. * @return Iterations */ public int iterations() { return iterations; } /** * How many times to run the competition. Requests will be executed a total of (iterations * multiplier). * @param iterations Iterations * @param finalize If true, value cannot be overwritten by subsequent calls */ public void iterations(int iterations, boolean finalize) { if (iterationsFinalized) { return; } this.iterations = iterations; iterationsFinalized = finalize; } /** * Gets the multiplier * @return Multiplier */ public int multiplier() { return multiplier; } /** * Sets the multiplier. The multiplier determines how many times each iteration will be run. * @param multiplier Multiplier * @param finalize If true, value cannot be overwritten by subsequent calls */ public void multiplier(int multiplier, boolean finalize) { if (multiplierFinalized) { return; } this.multiplier = multiplier; multiplierFinalized = finalize; } /** * Gets number of slow requests to track * @return Number of slow requests to track */ public int numSlowest() { return numSlowest; } /** * How many slow requests to track * @param numSlowest Number of slow requests to track * @param finalize If true, value cannot be overwritten by subsequent calls */ public void numSlowest(int numSlowest, boolean finalize) { if (numSlowestFinalized) { return; } this.numSlowest = numSlowest; numSlowestFinalized = finalize; } /** * Whether to run a warmup search request * @return True/false */ public boolean warmup() { return warmup; } /** * Whether to run a warmup search request * @param warmup True/false * @param finalize If true, value cannot be overwritten by subsequent calls */ public void warmup(boolean warmup, boolean finalize) { if (warmupFinalized) { return; } this.warmup = warmup; warmupFinalized = finalize; } /** * Gets the search type * @return Search type */ public SearchType searchType() { return searchType; } /** * Sets the search type * @param searchType Search type * @param finalize If true, value cannot be overwritten by subsequent calls */ public void searchType(SearchType searchType, boolean finalize) { if (searchTypeFinalized) { return; } this.searchType = searchType; searchTypeFinalized = finalize; } /** * Gets the list of search requests to benchmark * @return Search requests */ public List<SearchRequest> searchRequests() { return searchRequests; } /** * Adds a search request to benchmark * @param searchRequest Search request */ public void addSearchRequest(SearchRequest... searchRequest) { searchRequests.addAll(Arrays.asList(searchRequest)); } /** * Gets the clear caches request * @return The clear caches request */ public ClearIndicesCacheRequest clearCaches() { return clearCaches; } public boolean allowCacheClearing() { return allowCacheClearing; } public void allowCacheClearing(boolean allowCacheClearing) { this.allowCacheClearing = allowCacheClearing; } /** * Gets the clear caches settings * @return Clear caches settings */ public ClearCachesSettings clearCachesSettings() { return clearCachesSettings; } /** * Sets the clear caches settings * @param clearCachesSettings Clear caches settings * @param finalize If true, value cannot be overwritten by subsequent calls */ public void clearCachesSettings(ClearCachesSettings clearCachesSettings, boolean finalize) { if (clearCachesSettingsFinalized) { return; } this.clearCachesSettings = clearCachesSettings; clearCachesSettingsFinalized = finalize; } /** * Builds a clear cache request from the settings */ public void buildClearCachesRequestFromSettings() { clearCaches = new ClearIndicesCacheRequest(indices); clearCaches.filterCache(clearCachesSettings.filterCache); clearCaches.fieldDataCache(clearCachesSettings.fieldDataCache); clearCaches.idCache(clearCachesSettings.idCache); clearCaches.recycler(clearCachesSettings.recyclerCache); clearCaches.fields(clearCachesSettings.fields); clearCaches.filterKeys(clearCachesSettings.filterKeys); } public void buildSearchRequestsFromSettings() { for (SearchRequest searchRequest : searchRequests) { searchRequest.indices(indices); searchRequest.types(types); searchRequest.searchType(searchType); } } /** * Merge another settings object with this one, ignoring fields which have been finalized. * This is a convenience so that a global settings object can cascade it's settings * down to specific competitors w/o inadvertently overwriting anything that has already been set. * @param otherSettings The settings to merge into this */ public void merge(BenchmarkSettings otherSettings) { if (!concurrencyFinalized) { concurrency = otherSettings.concurrency; } if (!iterationsFinalized) { iterations = otherSettings.iterations; } if (!multiplierFinalized) { multiplier = otherSettings.multiplier; } if (!numSlowestFinalized) { numSlowest = otherSettings.numSlowest; } if (!warmupFinalized) { warmup = otherSettings.warmup; } if (!searchTypeFinalized) { searchType = otherSettings.searchType; } if (!clearCachesSettingsFinalized) { clearCachesSettings = otherSettings.clearCachesSettings; } } public static class ClearCachesSettings { private boolean filterCache = false; private boolean fieldDataCache = false; private boolean idCache = false; private boolean recyclerCache = false; private String[] fields = null; private String[] filterKeys = null; public void filterCache(boolean filterCache) { this.filterCache = filterCache; } public void fieldDataCache(boolean fieldDataCache) { this.fieldDataCache = fieldDataCache; } public void idCache(boolean idCache) { this.idCache = idCache; } public void recycler(boolean recyclerCache) { this.recyclerCache = recyclerCache; } public void fields(String[] fields) { this.fields = fields; } public void filterKeys(String[] filterKeys) { this.filterKeys = filterKeys; } } @Override public void readFrom(StreamInput in) throws IOException { concurrency = in.readVInt(); iterations = in.readVInt(); multiplier = in.readVInt(); numSlowest = in.readVInt(); warmup = in.readBoolean(); indices = in.readStringArray(); types = in.readStringArray(); searchType = SearchType.fromId(in.readByte()); clearCaches = in.readOptionalStreamable(new ClearIndicesCacheRequest()); final int size = in.readVInt(); for (int i = 0; i < size; i++) { SearchRequest searchRequest = new SearchRequest(); searchRequest.readFrom(in); searchRequests.add(searchRequest); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(concurrency); out.writeVInt(iterations); out.writeVInt(multiplier); out.writeVInt(numSlowest); out.writeBoolean(warmup); out.writeStringArray(indices); out.writeStringArray(types); out.writeByte(searchType.id()); out.writeOptionalStreamable(clearCaches); out.writeVInt(searchRequests.size()); for (SearchRequest searchRequest : searchRequests) { searchRequest.writeTo(out); } } }
12,704
0.651921
0.650032
394
31.243654
24.28075
110
false
false
0
0
0
0
0
0
0.395939
false
false
3
805bd80c9852d44a8084b5104c4dc9cd7b78f737
14,328,010,962,830
96eda3e04a3876c0eee4f4e9c6629ade3e40a656
/barghos-core-api/src/main/java/module-info.java
71fabc0750e6b90ec4887a75b9cc3c2dcf173729
[ "MIT" ]
permissive
picatrix1899/barghos
https://github.com/picatrix1899/barghos
6098a017492b60f738709930ca6ea090f1c4b578
8f9941b23d87b8d1723d11292f2b0ae01ffd5ea7
refs/heads/master
2023-04-03T05:46:12.697000
2023-03-19T19:13:31
2023-03-19T19:13:31
284,809,724
0
0
MIT
false
2022-10-20T19:25:13
2020-08-03T21:21:10
2022-01-29T23:34:30
2022-10-20T19:25:12
2,959
0
0
0
Java
false
false
/** * This section defines the module "org.barghos.core.api". * * @author picatrix1899 */ module org.barghos.core.api { requires org.barghos.annotation; exports org.barghos.core.api; exports org.barghos.core.api.flag; exports org.barghos.core.api.math; exports org.barghos.core.api.metrics; exports org.barghos.core.api.nio.buffer; exports org.barghos.core.api.pool; exports org.barghos.core.api.reflect; exports org.barghos.core.api.util; exports org.barghos.core.api.util.function; exports org.barghos.core.api.util.timer; opens org.barghos.core.api; opens org.barghos.core.api.flag; opens org.barghos.core.api.math; opens org.barghos.core.api.metrics; opens org.barghos.core.api.nio.buffer; opens org.barghos.core.api.pool; opens org.barghos.core.api.reflect; opens org.barghos.core.api.util; opens org.barghos.core.api.util.function; opens org.barghos.core.api.util.timer; }
UTF-8
Java
908
java
module-info.java
Java
[ { "context": " the module \"org.barghos.core.api\".\n * \n * @author picatrix1899\n */\nmodule org.barghos.core.api\n{\n\trequires org.b", "end": 90, "score": 0.9995065331459045, "start": 78, "tag": "USERNAME", "value": "picatrix1899" } ]
null
[]
/** * This section defines the module "org.barghos.core.api". * * @author picatrix1899 */ module org.barghos.core.api { requires org.barghos.annotation; exports org.barghos.core.api; exports org.barghos.core.api.flag; exports org.barghos.core.api.math; exports org.barghos.core.api.metrics; exports org.barghos.core.api.nio.buffer; exports org.barghos.core.api.pool; exports org.barghos.core.api.reflect; exports org.barghos.core.api.util; exports org.barghos.core.api.util.function; exports org.barghos.core.api.util.timer; opens org.barghos.core.api; opens org.barghos.core.api.flag; opens org.barghos.core.api.math; opens org.barghos.core.api.metrics; opens org.barghos.core.api.nio.buffer; opens org.barghos.core.api.pool; opens org.barghos.core.api.reflect; opens org.barghos.core.api.util; opens org.barghos.core.api.util.function; opens org.barghos.core.api.util.timer; }
908
0.763216
0.758811
31
28.32258
15.448953
58
false
false
0
0
0
0
0
0
1.419355
false
false
3
8c4c1721ebee9fa3bfdc56c777ce4931c9f7f4e4
22,668,837,401,843
cafe855bf63895c35de2ee56ca3c8d847c1c0902
/leetCode/lwc/0101-0200/lc_114.java
ba3eb27075d489a7c4f9a96581b6241e06336910
[]
no_license
fukunee/shamenote
https://github.com/fukunee/shamenote
5e2771e28a27ac711efe31c1c05340043e151544
3b3d6a430aacd5d816a59fb6dc61097e13b89a80
refs/heads/master
2020-07-24T15:19:25.376000
2020-06-05T06:39:42
2020-06-05T06:39:42
207,966,709
2
1
null
false
2019-09-30T15:36:55
2019-09-12T04:46:29
2019-09-30T03:04:05
2019-09-30T15:36:55
141,470
0
1
0
CSS
false
false
package solution2; /** * @author lwc * @date 2019/10/29 9:01 */ public class U114 { public void flatten(TreeNode root){ if(root == null) return; flatten(root.left); flatten(root.right); TreeNode rHead = root.right; root.right = root.left; root.left = null; while(root.right != null) root = root.right; root.right = rHead; } }
UTF-8
Java
426
java
lc_114.java
Java
[ { "context": "package solution2;\r\n\r\n/**\r\n * @author lwc\r\n * @date 2019/10/29 9:01\r\n */\r\npublic class U114", "end": 41, "score": 0.9996551871299744, "start": 38, "tag": "USERNAME", "value": "lwc" } ]
null
[]
package solution2; /** * @author lwc * @date 2019/10/29 9:01 */ public class U114 { public void flatten(TreeNode root){ if(root == null) return; flatten(root.left); flatten(root.right); TreeNode rHead = root.right; root.right = root.left; root.left = null; while(root.right != null) root = root.right; root.right = rHead; } }
426
0.532864
0.497653
21
18.285715
15.200698
52
false
false
0
0
0
0
0
0
0.428571
false
false
3
cb014758fe69ac1b4d904f5942fb236c1bc66ee9
24,421,184,069,033
38cac366fdee30eee6131b8b64d0ff6da8879002
/src/com/droidfad/data/ObjectManager.java
fc7d42bc95164fb9f7047882c1579d307c7b1c7e
[ "Apache-2.0" ]
permissive
jglufke/droidfad_base
https://github.com/jglufke/droidfad_base
da7a12d40724dddecba8d07d688ca1e70f22b7e7
6912e22a5691e5c259f7671707d17edddccd6836
refs/heads/master
2016-09-15T19:37:47.817000
2014-03-31T17:50:53
2014-03-31T17:50:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.droidfad.data; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Vector; import com.droidfad.classloading.ClazzFinder; import com.droidfad.data.ACategory.Category; import com.droidfad.data.ADao.AttributesEnum; import com.droidfad.iframework.event.IEvent; import com.droidfad.iframework.event.IEvent.DataType; import com.droidfad.iframework.event.IEvent.EventType; import com.droidfad.iframework.event.IEventPublisher; import com.droidfad.persistency.Persistency; import com.droidfad.util.LogWrapper; import com.droidfad.util.ReflectionUtil; /** Copyright 2014 Jens Glufke Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ class ObjectManager { private static final Byte BYTE0 = 0; private static final Double DOUBLE0 = 0D; private volatile static IEventPublisher eventBroadcaster; private static final Float FLOAT0 = 0F; private static ObjectManager instance; private static final Integer INT0 = 0; private static final int KEY_BOOL = 7; private static final int KEY_BYTE = 0; private static final int KEY_DOUBLE = 5; private static final int KEY_FLOAT = 4; private static final int KEY_INT = 2; private static final int KEY_LONG = 3; private static final int KEY_SHORT = 1; private static final int KEY_STRING = 6; private static final String LOGTAG = ObjectManager.class.getSimpleName(); private static final Long LONG0 = 0L; private static final Short SHORT0 = 0; private static HashMap<Class<?>, Integer> typeKeyMap = null; private static final String TYPENAME = ObjectManager.class.getSimpleName(); static { typeKeyMap = new HashMap<Class<?>, Integer>(); typeKeyMap.put(byte.class, KEY_BYTE); typeKeyMap.put(Byte.class, KEY_BYTE); typeKeyMap.put(short.class, KEY_SHORT); typeKeyMap.put(Short.class, KEY_SHORT); typeKeyMap.put(int.class, KEY_INT); typeKeyMap.put(Integer.class, KEY_INT); typeKeyMap.put(long.class, KEY_LONG); typeKeyMap.put(Long.class, KEY_LONG); typeKeyMap.put(float.class, KEY_FLOAT); typeKeyMap.put(Float.class, KEY_FLOAT); typeKeyMap.put(double.class, KEY_DOUBLE); typeKeyMap.put(Double.class, KEY_DOUBLE); typeKeyMap.put(String.class, KEY_STRING); typeKeyMap.put(boolean.class, KEY_BOOL); typeKeyMap.put(Boolean.class, KEY_BOOL); } protected static synchronized ObjectManager getImpl() { if(instance == null) { instance = new ObjectManager(); } return instance; } public static void main(String[] args) { String lFilename = "\\data\\data\\com.glufke.android\\databases\\pers\\153\\237\\133\\6\\TestReference_2\\TestReference_2\\SourceType\\val"; File lFile = new File(lFilename); lFile.getParentFile().mkdirs(); } protected static synchronized void setImpl(ObjectManager pImpl) { instance = pImpl; } /** * key - type * key - name * key - attributeName * value - attribute value */ private HashMap<String, HashMap<String, HashMap<String, Object>>> cache = new HashMap<String, HashMap<String,HashMap<String, Object>>>(); /** * key - type name which is the simple name of the class * value - classname */ HashMap<String, String> classNameMap = null; /** * key - simple class name * key - instance name * value - reference to instance */ HashMap<String, HashMap<String, ADao>> objectCache = null; private ReflectionUtil reflectionUtil = new ReflectionUtil(); private HashMap<String, Class<? extends ADao>> typeNameToDaoMap; protected ObjectManager(){} /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#clear() */ protected synchronized void clear() { if(objectCache != null && !objectCache.isEmpty()) { for(Entry<String, HashMap<String, ADao>> lEntry : new Vector<Entry<String, HashMap<String, ADao>>>(objectCache.entrySet())) { HashMap<String, ADao> lEntryMap = lEntry.getValue(); if(lEntryMap != null && !lEntryMap.isEmpty()) { for(ADao lObject : new Vector<ADao>(lEntryMap.values())) { unregisterObject(lObject); } } } } Persistency.getInstance().delete(); objectCache = null; } protected void clearCache() { clearCache(null, null); } /** * * delete all entries in internal cache that have the category * pCategory. If pCategory is null all entries in the cache are * deleted. If pToBeClearedTypeSet is not null, only the types * that are containtedin pToBeClearedTypeSet are cleared from * the cache. The conditions for pCategory and pToBeClearedTypeSet are * AND connected. * @param pCategory * @param pToBeClearedTypeSet * */ protected void clearCache(Category pCategory, HashSet<String> pToBeClearedTypeSet) { HashSet<String> lCategoryTypeSet = null; if(pCategory != null) { lCategoryTypeSet = new HashSet<String>(); for(Class<?> lSubClass : ClazzFinder.findSubclasses(ADao.class)) { ACategory lCategoryAnnotation = lSubClass.getAnnotation(ACategory.class); if(lCategoryAnnotation != null) { if(pCategory.equals(lCategoryAnnotation.category())) { lCategoryTypeSet.add(lSubClass.getSimpleName()); } } } } if(objectCache != null && !objectCache.isEmpty()) { for(Entry<String, HashMap<String, ADao>> lEntry : new Vector<Entry<String, HashMap<String, ADao>>>(objectCache.entrySet())) { String lDaoType = lEntry.getKey(); /** * only delete the entry if pCategory was null or * if lDaoType has the correct ACategory annotation */ if(lCategoryTypeSet == null || lCategoryTypeSet.contains(lDaoType)) { if(pToBeClearedTypeSet == null || pToBeClearedTypeSet.contains(lDaoType)) { HashMap<String, ADao> lEntryMap = lEntry.getValue(); if(lEntryMap != null && !lEntryMap.isEmpty()) { for(ADao lObject : new Vector<ADao>(lEntryMap.values())) { removeObjectFromCache(lObject); } } } } } } if(pCategory == null && pToBeClearedTypeSet == null) { objectCache = null; cache.clear(); } } /** * ********************************************<br> * * @param pType * @param pName * @return * * ********************************************<br> */ protected ADao createInstance(Class<? extends ADao> pType, String pName) { ADao lObject = null; /** * get the class name of the pType */ if(pType != null && !AReferenceType.class.isAssignableFrom(pType)) { String lClassName = pType.getName(); try { Constructor<? extends ADao> lConstructor = reflectionUtil.getConstructor(pType, new Class[]{ String.class }); if(lConstructor != null) { lObject = lConstructor.newInstance(pName); } else { LogWrapper.e(TYPENAME, "class:" + lClassName + " does not have a constructor with a single string as parameter"); } } catch (IllegalArgumentException e) { LogWrapper.e(TYPENAME, "could not create:" + lClassName + " e:" + e.getMessage()); } catch (InstantiationException e) { LogWrapper.e(TYPENAME, "could not create:" + lClassName + " e:" + e.getMessage()); } catch (IllegalAccessException e) { LogWrapper.e(TYPENAME, "could not create:" + lClassName + " e:" + e.getMessage()); } catch (InvocationTargetException e) { LogWrapper.e(TYPENAME, "could not create:" + lClassName + " e:" + e.getMessage(), e); } } return lObject; } /** * * @param pCategory * @param pExportFile * @throws IOException * */ public void exportData(Category pCategory, File pExportFile) throws IOException { Persistency.getInstance().exportData(pCategory, pExportFile); } /** * ********************************************<br> * * @param pType * @param pName * @param pAttributeName * @param pValue * * ********************************************<br> */ private void fireDataSet(final Class<? extends ADao> pType, final String pName, final AttributesEnum pAttribute, final Object pValue) { IEvent lEvent = eventBroadcaster.createEvent( this, DataType.object, EventType.updated, pType, pName, this, pAttribute, null, pValue); eventBroadcaster.publish(lEvent); } /** * ********************************************<br> * * @param pType * @param pName * * ********************************************<br> */ private void fireObjectCreated(final Class<? extends ADao> pType, final String pName) { IEvent lEvent = eventBroadcaster.createEvent(this, DataType.object, EventType.created, pType, pName, this, null, null, null); eventBroadcaster.publish(lEvent); } /** * ********************************************<br> * * @param pType * @param pName * * ********************************************<br> */ private void fireObjectDeleted(final Class<? extends ADao> pType, final String pName) { IEvent lEvent = eventBroadcaster.createEvent(this, DataType.object, EventType.deleted, pType, pName, this, null, null, null); eventBroadcaster.publish(lEvent); } /** * * @param pTypeName * @return * */ public synchronized Class<? extends ADao> getDaoClassFromTypeName(String pTypeName) { if(typeNameToDaoMap == null) { initObjectCache(); } Class<? extends ADao> lDaoClass = typeNameToDaoMap.get(pTypeName); return lDaoClass; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#getObject(java.lang.Class, java.lang.String) */ protected synchronized <T extends ADao> T getInstance(Class<? extends ADao> pType, String pName) { if(pType == null) { throw new IllegalArgumentException("parameter pObjectClass must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } T lObject = getObjectFromCache(pType, pName); if(lObject == null) { lObject = getObjectFromDataBase(pType, pName); } return lObject; } /** * * @param pType * @param pName * */ private <T extends ADao> T getObjectFromDataBase(Class<? extends ADao> pType, String pName) { ADao lReturnObject = null; HashSet<String> lNameSet = Persistency.getInstance().getPersistedInstanceNameSet(pType); if(lNameSet.contains(pName)) { lReturnObject = createInstance(pType, pName); } return (T) lReturnObject; } /** * * @param pType * @param pName * */ @SuppressWarnings("unchecked") private <T extends ADao> Vector<T> getObjectsFromDataBase(Class<? extends ADao> pType) { Vector<T> lReturnList = new Vector<T>(); for(String lObjectName : Persistency.getInstance().getPersistedInstanceNameSet(pType)) { /** * check if the object already exists */ T lObject = getObjectFromCache(pType, lObjectName); if(lObject == null) { lObject = (T) createInstance(pType, lObjectName); } lReturnList.add(lObject); } return lReturnList; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#getInstances(java.lang.String) */ @SuppressWarnings("unchecked") protected synchronized <T extends ADao> Vector<T> getInstances(Class<? extends ADao> pType) { Vector<T> lInstanceList = null; if(objectCache == null) { initObjectCache(); } HashMap<String,ADao> lInstanceMap = null; if(pType != null) { lInstanceMap = objectCache.get(pType.getSimpleName()); if(lInstanceMap != null) { Collection<ADao> lObjectList = lInstanceMap.values(); lInstanceList = new Vector<T>(lObjectList.size()); for(ADao lObject : lInstanceMap.values()) { lInstanceList.add((T) lObject); } } else { System.out.println(); } } if(lInstanceList == null) { lInstanceList = new Vector<T>(0); } return lInstanceList; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#getObject(java.lang.String, java.lang.String) */ protected synchronized <T extends ADao> T getObject(Class<? extends ADao> pType, String pName) { if(pType == null) { throw new IllegalArgumentException("parameter pObjectType must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } T lObject = getObjectFromCache(pType, pName); return lObject; } /** * ********************************************<br> * @param pType * @param lTypeName * @param pName * @return * * ********************************************<br> */ @SuppressWarnings("unchecked") private <T extends ADao> T getObjectFromCache(final Class<? extends ADao> pType, final String pName) { if(objectCache == null) { /** * if the object cache is not yet instantiated, read all * available information from database */ initObjectCache(); } T lObject = null; ADao lCachedObject = null; String lTypeName = pType.getSimpleName(); HashMap<String, ADao> lInstanceMap = objectCache.get(lTypeName); if(lInstanceMap != null) { lCachedObject = lInstanceMap.get(pName); } if(lCachedObject != null) { if(pType == null || pType.equals(lCachedObject.getClass())) { lObject = (T) lCachedObject; } else { throw new IllegalArgumentException("request object class: "+pType+" is different to stored:" + pType.getName() + " stored:" + lCachedObject.getClass().getName()); } } return lObject; } /** * ********************************************<br> * * @return * * ********************************************<br> */ public Vector<Class<? extends ADao>> getObjectTypeList() { HashSet<Class<? extends ADao>> lSubClassSet = ClazzFinder.findSubclasses(ADao.class); return new Vector<Class<? extends ADao>>(lSubClassSet); } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#getValue(java.lang.Class, java.lang.String, com.droidfad.data.ADao.AttributesEnum) */ protected synchronized <T> T getValue(Class<? extends ADao> pType, String pName, AttributesEnum pAttribute) { if(pType == null) { throw new IllegalArgumentException("parameter pClass must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } if(pAttribute == null) { throw new IllegalArgumentException("parameter pAttribute must not be null"); } ADao lObject = getObject(pType, pName); Class<?> lAttributeType = reflectionUtil.getAttributeType(pType, pAttribute.toString(), null); if(lAttributeType == null) { throw new IllegalArgumentException("not getter implemented for attribute:" + pAttribute); } T lValue = null; if(lObject != null) { String lAttributeName = pAttribute.toString(); lValue = getValueFromCache(cache, pType, pName, lAttributeName); if(lValue == null && isPersistent(pType, lAttributeName)) { lValue = getValueFromDataBase(pType, pName, lAttributeType, lAttributeName); setValueToCache(cache, pType, pName, lAttributeName, lValue); } } else { LogWrapper.w(LOGTAG, "getValue:" + pType + "." + pName + " object is not registered"); } lValue = handleNullValue(lAttributeType, lValue); return lValue; } /** * ********************************************<br> * * @param pType * @param pName * @param pAttributeName * @return * * ********************************************<br> */ @SuppressWarnings("unchecked") private <T> T getValueFromCache(final HashMap<String, HashMap<String, HashMap<String, Object>>> pCache, final Class<? extends ADao> pType, final String pName, final String pAttributeName) { T lValue = null; HashMap<String,HashMap<String,Object>> lInstanceMap = pCache.get(pType.getSimpleName()); if(lInstanceMap != null) { HashMap<String, Object> lAttributeMap = lInstanceMap.get(pName); if(lAttributeMap != null) { lValue = (T) lAttributeMap.get(pAttributeName); } } return lValue; } /** * * ********************************************<br> * * @param <T> * @param pType * @param pName * @param pAttributeType * @param pAttributeName * @return * * ********************************************<br> */ private <T> T getValueFromDataBase(final Class<? extends ADao> pType, final String pName, final Class<?> pAttributeType, final String pAttributeName) { T lValue = null; try { lValue = Persistency.getInstance().getValueFromFile(pType, pName, pAttributeName, pAttributeType); } catch (IOException e) { String lMessage = "could not get value to attribute:" + pType + "." + pName + "." + pAttributeName + " e:" + e.getMessage(); LogWrapper.e(LOGTAG, lMessage); throw new RuntimeException(lMessage); } return lValue; } /** * ********************************************<br> * * @param pAttributeType * @param pValue * @return * * ********************************************<br> */ @SuppressWarnings("unchecked") private <T> T handleNullValue(final Class<?> pAttributeType, final T pValue) { T lValue = pValue; if(pValue == null) { Integer lKey = typeKeyMap.get(pAttributeType); if(lKey == null) { lKey = Integer.MAX_VALUE; } switch(lKey) { case KEY_BYTE: lValue = (T) BYTE0; break; case KEY_SHORT: lValue = (T) SHORT0; break; case KEY_INT: lValue = (T) INT0; break; case KEY_LONG: lValue = (T) LONG0; break; case KEY_FLOAT: lValue = (T) FLOAT0; break; case KEY_DOUBLE: lValue = (T) DOUBLE0; break; case KEY_BOOL: lValue = (T) Boolean.FALSE; break; case KEY_STRING: break; default: // LogWrapper.w(LOGTAG, "unhandled key:" + lKey + " for type:" + pAttributeType.getSimpleName()); } } return lValue; } /** * * @param pImportFile * @throws IOException * */ public void importData(File pImportFile) throws IOException { /** * objectManager has to know which ADao subclasses have been * imported to delete the cache for the respective classes */ HashSet<String> lLoadedTypeSet = Persistency.getInstance().importData(pImportFile); clearCache(null, lLoadedTypeSet); /** * load the information of the loaded data into the object cache */ for(String lTypeName : lLoadedTypeSet) { Class<? extends ADao> lType = typeNameToDaoMap.get(lTypeName); Vector<ADao> lLoadedObjectList = getObjectsFromDataBase(lType); } } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#init() */ protected void init() { eventBroadcaster.removeAllSubscribers(); clearCache(null, null); } /** * * ********************************************<br> * * read the type information and the instance names * from the database and fill objectCache with it * * ********************************************<br> */ private void initObjectCache() { objectCache = new HashMap<String, HashMap<String,ADao>>(); typeNameToDaoMap = new HashMap<String, Class<? extends ADao>>(); HashSet<Class<? extends ADao>> lDaoTypeList = ClazzFinder.findSubclasses(ADao.class); for(Class<? extends ADao> lDaoType : lDaoTypeList) { String lDaoTypeName = lDaoType.getSimpleName(); HashSet<String> lInstanceNameSet = Persistency.getInstance().getPersistedInstanceNameSet(lDaoType); HashMap<String, ADao> lInstanceMap = new HashMap<String, ADao>(); objectCache.put(lDaoTypeName, lInstanceMap); typeNameToDaoMap.put(lDaoTypeName, lDaoType); for(String lName : lInstanceNameSet) { ADao lObject = createInstance(lDaoType, lName); if(lObject != null) { lInstanceMap.put(lName, lObject); } } } } /** * ********************************************<br> * * @param pType * @param pAttribute * @return * * ********************************************<br> */ protected boolean isPersistent(Class<? extends ADao> pClass, String pAttributeName) { boolean lIsPersistent = reflectionUtil.hasAnnotation(pClass, pAttributeName, Persistent.class); return lIsPersistent; } /** * * ********************************************<br> * * @param <T> * @param pObject * @param pObjectClass * @param pName * * ********************************************<br> */ private <T extends ADao> void putObjectToCache(T pObject, Class<? extends ADao> pObjectClass, String pName) { if(objectCache == null) { initObjectCache(); } String lTypeName = pObjectClass.getSimpleName(); HashMap<String, ADao> lInstanceMap = objectCache.get(lTypeName); if(lInstanceMap == null) { lInstanceMap = new HashMap<String, ADao>(); objectCache.put(lTypeName, lInstanceMap); } ADao lOldObject = lInstanceMap.put(pName, pObject); if(lOldObject == null) { /** * put the new object to persistency */ writeInstanceToDataBase(pName, pObject); } else { /** * change back the partialTopic of lInstanceMap */ lInstanceMap.put(pName, pObject); throw new IllegalArgumentException("object of type:" + lTypeName + " with name:" + pName + " already exists"); } } /** * ********************************************<br> * * @param pAObject * @param pName * * ********************************************<br> */ protected synchronized void registerObject(ADao pAObject, String pName) { if(pAObject == null) { throw new IllegalArgumentException("parameter pAObject must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } Class<? extends ADao> lClass = pAObject.getClass(); putObjectToCache(pAObject, lClass, pName); if(!(pAObject instanceof AReferenceType)) { fireObjectCreated(pAObject.getClass(), pName); } }; private <T extends ADao> void removeObjectFromCache(T pObject) { String lType = pObject.getType(); String lName = pObject.getName(); if(objectCache != null) { HashMap<String, ADao> lInstanceMap = objectCache.get(lType); if(lInstanceMap != null) { lInstanceMap.remove(lName); if(lInstanceMap.isEmpty()) { objectCache.remove(lType); } } } if(cache != null) { HashMap<String, HashMap<String, Object>> lInstanceMap = cache.get(lType); if(lInstanceMap != null) { lInstanceMap.remove(lName); } } } /** * ********************************************<br> * * @param pService * * ********************************************<br> */ protected synchronized void setEventBroadcaster(IEventPublisher pService) { eventBroadcaster = pService; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#setValue(java.lang.Class, java.lang.String, com.droidfad.data.ADao.AttributesEnum, java.lang.Object) */ protected synchronized void setValue(final Class<? extends ADao> pType, final String pName, final AttributesEnum pAttribute, final Object pValue) { if(pType == null) { throw new IllegalArgumentException("parameter pClass must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } if(pAttribute == null) { throw new IllegalArgumentException("parameter pAttribute must not be null"); } /** * only set a value if the object is registered and available. * */ ADao lObject = getObject(pType, pName); if(lObject != null) { String lAttributeName = pAttribute.toString(); boolean lValueChanged = setValueToCache(cache, pType, pName, lAttributeName, pValue); if(lValueChanged && isPersistent(pType, lAttributeName)) { /** * only write the data to database if the value actually changed */ writeValueToDatabase(pType, pName, lAttributeName, pValue); } fireDataSet(pType, pName, pAttribute, pValue); } else { LogWrapper.w(LOGTAG, "setValue:" + pType.getSimpleName() + "." + pName + " object does not exist"); } } /** * ********************************************<br> * @param pCache * * @param pType * @param pName * @param pAttributeName * * ********************************************<br> */ private boolean setValueToCache(HashMap<String, HashMap<String, HashMap<String, Object>>> pCache, final Class<? extends ADao> pType, final String pName, final String pAttributeName, final Object pValue) { HashMap<String,HashMap<String,Object>> lInstanceMap = pCache.get(pType.getSimpleName()); if(lInstanceMap == null) { lInstanceMap = new HashMap<String, HashMap<String,Object>>(); pCache.put(pType.getSimpleName(), lInstanceMap); } HashMap<String, Object> lAttributeMap = lInstanceMap.get(pName); if(lAttributeMap == null) { lAttributeMap = new HashMap<String, Object>(); lInstanceMap.put(pName, lAttributeMap); } boolean lValueChanged = false; Object lOldValue = lAttributeMap.put(pAttributeName, pValue); if(pValue == null) { lValueChanged = lOldValue != null; } else { lValueChanged = !pValue.equals(lOldValue); } return lValueChanged; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#unregisterObject(T) */ protected synchronized <T extends ADao> void unregisterObject(T pObject) { if(pObject != null) { Persistency.getInstance().removeInstance(pObject.getClass(), pObject.getName()); /** * delete the attribute cache */ removeObjectFromCache(pObject); if(!(pObject instanceof AReferenceType)) { fireObjectDeleted(pObject.getClass(), pObject.getName()); } pObject.isValid = false; } } /** * * * @param pName * @param pObject * */ private void writeInstanceToDataBase(String pName, ADao pObject) { if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } if(pObject == null) { throw new IllegalArgumentException("parameter pObject must not be null"); } Class<? extends ADao> lType = pObject.getClass(); List<String> lAttributeNameList = reflectionUtil.getPersistentAttributeNames(pObject.getClass(), null); String lAttributeName = null; Object lValue = null; if(lAttributeNameList.isEmpty()) { lAttributeName = Persistency.DUMMY_ATTRIBUTE_NAME; lValue = ""; } else { lAttributeName = lAttributeNameList.get(0); lValue = reflectionUtil.invokeGetter(pObject, lAttributeName, null); } try { Persistency.getInstance().writeValueToFile(lType, pName, lAttributeName, lValue); } catch (IOException e) { LogWrapper.e(LOGTAG, "could not write attribute:" + lType.getSimpleName() + "." + pName + "." + lAttributeName); } } /** * ********************************************<br> * * @param pType * @param pName * @param pAttributeName * @throws IOException * * ********************************************<br> */ private void writeValueToDatabase(Class<? extends ADao> pType, String pName, String pAttributeName, Object pValue) { if(pType == null) { throw new IllegalArgumentException("parameter pType must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } if(pAttributeName == null) { throw new IllegalArgumentException("parameter pAttributeName must not be null"); } if(pValue != null) { try { Persistency.getInstance().writeValueToFile(pType, pName, pAttributeName, pValue); } catch (IOException e) { LogWrapper.e(LOGTAG, ("could not set value to file for:" + pType + "." + pName + "." + pAttributeName + "=" + pValue)); } } } /** * * @param pPrintWriter * */ public void dumpPersistency(PrintWriter pPrintWriter) { Persistency.getInstance().dump(pPrintWriter); } }
UTF-8
Java
28,130
java
ObjectManager.java
Java
[ { "context": ".droidfad.util.ReflectionUtil;\n\n/**\nCopyright 2014 Jens Glufke\n\nLicensed under the Apache License, Version 2.0 (", "end": 864, "score": 0.9996756315231323, "start": 853, "tag": "NAME", "value": "Jens Glufke" } ]
null
[]
/** * */ package com.droidfad.data; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Vector; import com.droidfad.classloading.ClazzFinder; import com.droidfad.data.ACategory.Category; import com.droidfad.data.ADao.AttributesEnum; import com.droidfad.iframework.event.IEvent; import com.droidfad.iframework.event.IEvent.DataType; import com.droidfad.iframework.event.IEvent.EventType; import com.droidfad.iframework.event.IEventPublisher; import com.droidfad.persistency.Persistency; import com.droidfad.util.LogWrapper; import com.droidfad.util.ReflectionUtil; /** Copyright 2014 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ class ObjectManager { private static final Byte BYTE0 = 0; private static final Double DOUBLE0 = 0D; private volatile static IEventPublisher eventBroadcaster; private static final Float FLOAT0 = 0F; private static ObjectManager instance; private static final Integer INT0 = 0; private static final int KEY_BOOL = 7; private static final int KEY_BYTE = 0; private static final int KEY_DOUBLE = 5; private static final int KEY_FLOAT = 4; private static final int KEY_INT = 2; private static final int KEY_LONG = 3; private static final int KEY_SHORT = 1; private static final int KEY_STRING = 6; private static final String LOGTAG = ObjectManager.class.getSimpleName(); private static final Long LONG0 = 0L; private static final Short SHORT0 = 0; private static HashMap<Class<?>, Integer> typeKeyMap = null; private static final String TYPENAME = ObjectManager.class.getSimpleName(); static { typeKeyMap = new HashMap<Class<?>, Integer>(); typeKeyMap.put(byte.class, KEY_BYTE); typeKeyMap.put(Byte.class, KEY_BYTE); typeKeyMap.put(short.class, KEY_SHORT); typeKeyMap.put(Short.class, KEY_SHORT); typeKeyMap.put(int.class, KEY_INT); typeKeyMap.put(Integer.class, KEY_INT); typeKeyMap.put(long.class, KEY_LONG); typeKeyMap.put(Long.class, KEY_LONG); typeKeyMap.put(float.class, KEY_FLOAT); typeKeyMap.put(Float.class, KEY_FLOAT); typeKeyMap.put(double.class, KEY_DOUBLE); typeKeyMap.put(Double.class, KEY_DOUBLE); typeKeyMap.put(String.class, KEY_STRING); typeKeyMap.put(boolean.class, KEY_BOOL); typeKeyMap.put(Boolean.class, KEY_BOOL); } protected static synchronized ObjectManager getImpl() { if(instance == null) { instance = new ObjectManager(); } return instance; } public static void main(String[] args) { String lFilename = "\\data\\data\\com.glufke.android\\databases\\pers\\153\\237\\133\\6\\TestReference_2\\TestReference_2\\SourceType\\val"; File lFile = new File(lFilename); lFile.getParentFile().mkdirs(); } protected static synchronized void setImpl(ObjectManager pImpl) { instance = pImpl; } /** * key - type * key - name * key - attributeName * value - attribute value */ private HashMap<String, HashMap<String, HashMap<String, Object>>> cache = new HashMap<String, HashMap<String,HashMap<String, Object>>>(); /** * key - type name which is the simple name of the class * value - classname */ HashMap<String, String> classNameMap = null; /** * key - simple class name * key - instance name * value - reference to instance */ HashMap<String, HashMap<String, ADao>> objectCache = null; private ReflectionUtil reflectionUtil = new ReflectionUtil(); private HashMap<String, Class<? extends ADao>> typeNameToDaoMap; protected ObjectManager(){} /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#clear() */ protected synchronized void clear() { if(objectCache != null && !objectCache.isEmpty()) { for(Entry<String, HashMap<String, ADao>> lEntry : new Vector<Entry<String, HashMap<String, ADao>>>(objectCache.entrySet())) { HashMap<String, ADao> lEntryMap = lEntry.getValue(); if(lEntryMap != null && !lEntryMap.isEmpty()) { for(ADao lObject : new Vector<ADao>(lEntryMap.values())) { unregisterObject(lObject); } } } } Persistency.getInstance().delete(); objectCache = null; } protected void clearCache() { clearCache(null, null); } /** * * delete all entries in internal cache that have the category * pCategory. If pCategory is null all entries in the cache are * deleted. If pToBeClearedTypeSet is not null, only the types * that are containtedin pToBeClearedTypeSet are cleared from * the cache. The conditions for pCategory and pToBeClearedTypeSet are * AND connected. * @param pCategory * @param pToBeClearedTypeSet * */ protected void clearCache(Category pCategory, HashSet<String> pToBeClearedTypeSet) { HashSet<String> lCategoryTypeSet = null; if(pCategory != null) { lCategoryTypeSet = new HashSet<String>(); for(Class<?> lSubClass : ClazzFinder.findSubclasses(ADao.class)) { ACategory lCategoryAnnotation = lSubClass.getAnnotation(ACategory.class); if(lCategoryAnnotation != null) { if(pCategory.equals(lCategoryAnnotation.category())) { lCategoryTypeSet.add(lSubClass.getSimpleName()); } } } } if(objectCache != null && !objectCache.isEmpty()) { for(Entry<String, HashMap<String, ADao>> lEntry : new Vector<Entry<String, HashMap<String, ADao>>>(objectCache.entrySet())) { String lDaoType = lEntry.getKey(); /** * only delete the entry if pCategory was null or * if lDaoType has the correct ACategory annotation */ if(lCategoryTypeSet == null || lCategoryTypeSet.contains(lDaoType)) { if(pToBeClearedTypeSet == null || pToBeClearedTypeSet.contains(lDaoType)) { HashMap<String, ADao> lEntryMap = lEntry.getValue(); if(lEntryMap != null && !lEntryMap.isEmpty()) { for(ADao lObject : new Vector<ADao>(lEntryMap.values())) { removeObjectFromCache(lObject); } } } } } } if(pCategory == null && pToBeClearedTypeSet == null) { objectCache = null; cache.clear(); } } /** * ********************************************<br> * * @param pType * @param pName * @return * * ********************************************<br> */ protected ADao createInstance(Class<? extends ADao> pType, String pName) { ADao lObject = null; /** * get the class name of the pType */ if(pType != null && !AReferenceType.class.isAssignableFrom(pType)) { String lClassName = pType.getName(); try { Constructor<? extends ADao> lConstructor = reflectionUtil.getConstructor(pType, new Class[]{ String.class }); if(lConstructor != null) { lObject = lConstructor.newInstance(pName); } else { LogWrapper.e(TYPENAME, "class:" + lClassName + " does not have a constructor with a single string as parameter"); } } catch (IllegalArgumentException e) { LogWrapper.e(TYPENAME, "could not create:" + lClassName + " e:" + e.getMessage()); } catch (InstantiationException e) { LogWrapper.e(TYPENAME, "could not create:" + lClassName + " e:" + e.getMessage()); } catch (IllegalAccessException e) { LogWrapper.e(TYPENAME, "could not create:" + lClassName + " e:" + e.getMessage()); } catch (InvocationTargetException e) { LogWrapper.e(TYPENAME, "could not create:" + lClassName + " e:" + e.getMessage(), e); } } return lObject; } /** * * @param pCategory * @param pExportFile * @throws IOException * */ public void exportData(Category pCategory, File pExportFile) throws IOException { Persistency.getInstance().exportData(pCategory, pExportFile); } /** * ********************************************<br> * * @param pType * @param pName * @param pAttributeName * @param pValue * * ********************************************<br> */ private void fireDataSet(final Class<? extends ADao> pType, final String pName, final AttributesEnum pAttribute, final Object pValue) { IEvent lEvent = eventBroadcaster.createEvent( this, DataType.object, EventType.updated, pType, pName, this, pAttribute, null, pValue); eventBroadcaster.publish(lEvent); } /** * ********************************************<br> * * @param pType * @param pName * * ********************************************<br> */ private void fireObjectCreated(final Class<? extends ADao> pType, final String pName) { IEvent lEvent = eventBroadcaster.createEvent(this, DataType.object, EventType.created, pType, pName, this, null, null, null); eventBroadcaster.publish(lEvent); } /** * ********************************************<br> * * @param pType * @param pName * * ********************************************<br> */ private void fireObjectDeleted(final Class<? extends ADao> pType, final String pName) { IEvent lEvent = eventBroadcaster.createEvent(this, DataType.object, EventType.deleted, pType, pName, this, null, null, null); eventBroadcaster.publish(lEvent); } /** * * @param pTypeName * @return * */ public synchronized Class<? extends ADao> getDaoClassFromTypeName(String pTypeName) { if(typeNameToDaoMap == null) { initObjectCache(); } Class<? extends ADao> lDaoClass = typeNameToDaoMap.get(pTypeName); return lDaoClass; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#getObject(java.lang.Class, java.lang.String) */ protected synchronized <T extends ADao> T getInstance(Class<? extends ADao> pType, String pName) { if(pType == null) { throw new IllegalArgumentException("parameter pObjectClass must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } T lObject = getObjectFromCache(pType, pName); if(lObject == null) { lObject = getObjectFromDataBase(pType, pName); } return lObject; } /** * * @param pType * @param pName * */ private <T extends ADao> T getObjectFromDataBase(Class<? extends ADao> pType, String pName) { ADao lReturnObject = null; HashSet<String> lNameSet = Persistency.getInstance().getPersistedInstanceNameSet(pType); if(lNameSet.contains(pName)) { lReturnObject = createInstance(pType, pName); } return (T) lReturnObject; } /** * * @param pType * @param pName * */ @SuppressWarnings("unchecked") private <T extends ADao> Vector<T> getObjectsFromDataBase(Class<? extends ADao> pType) { Vector<T> lReturnList = new Vector<T>(); for(String lObjectName : Persistency.getInstance().getPersistedInstanceNameSet(pType)) { /** * check if the object already exists */ T lObject = getObjectFromCache(pType, lObjectName); if(lObject == null) { lObject = (T) createInstance(pType, lObjectName); } lReturnList.add(lObject); } return lReturnList; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#getInstances(java.lang.String) */ @SuppressWarnings("unchecked") protected synchronized <T extends ADao> Vector<T> getInstances(Class<? extends ADao> pType) { Vector<T> lInstanceList = null; if(objectCache == null) { initObjectCache(); } HashMap<String,ADao> lInstanceMap = null; if(pType != null) { lInstanceMap = objectCache.get(pType.getSimpleName()); if(lInstanceMap != null) { Collection<ADao> lObjectList = lInstanceMap.values(); lInstanceList = new Vector<T>(lObjectList.size()); for(ADao lObject : lInstanceMap.values()) { lInstanceList.add((T) lObject); } } else { System.out.println(); } } if(lInstanceList == null) { lInstanceList = new Vector<T>(0); } return lInstanceList; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#getObject(java.lang.String, java.lang.String) */ protected synchronized <T extends ADao> T getObject(Class<? extends ADao> pType, String pName) { if(pType == null) { throw new IllegalArgumentException("parameter pObjectType must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } T lObject = getObjectFromCache(pType, pName); return lObject; } /** * ********************************************<br> * @param pType * @param lTypeName * @param pName * @return * * ********************************************<br> */ @SuppressWarnings("unchecked") private <T extends ADao> T getObjectFromCache(final Class<? extends ADao> pType, final String pName) { if(objectCache == null) { /** * if the object cache is not yet instantiated, read all * available information from database */ initObjectCache(); } T lObject = null; ADao lCachedObject = null; String lTypeName = pType.getSimpleName(); HashMap<String, ADao> lInstanceMap = objectCache.get(lTypeName); if(lInstanceMap != null) { lCachedObject = lInstanceMap.get(pName); } if(lCachedObject != null) { if(pType == null || pType.equals(lCachedObject.getClass())) { lObject = (T) lCachedObject; } else { throw new IllegalArgumentException("request object class: "+pType+" is different to stored:" + pType.getName() + " stored:" + lCachedObject.getClass().getName()); } } return lObject; } /** * ********************************************<br> * * @return * * ********************************************<br> */ public Vector<Class<? extends ADao>> getObjectTypeList() { HashSet<Class<? extends ADao>> lSubClassSet = ClazzFinder.findSubclasses(ADao.class); return new Vector<Class<? extends ADao>>(lSubClassSet); } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#getValue(java.lang.Class, java.lang.String, com.droidfad.data.ADao.AttributesEnum) */ protected synchronized <T> T getValue(Class<? extends ADao> pType, String pName, AttributesEnum pAttribute) { if(pType == null) { throw new IllegalArgumentException("parameter pClass must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } if(pAttribute == null) { throw new IllegalArgumentException("parameter pAttribute must not be null"); } ADao lObject = getObject(pType, pName); Class<?> lAttributeType = reflectionUtil.getAttributeType(pType, pAttribute.toString(), null); if(lAttributeType == null) { throw new IllegalArgumentException("not getter implemented for attribute:" + pAttribute); } T lValue = null; if(lObject != null) { String lAttributeName = pAttribute.toString(); lValue = getValueFromCache(cache, pType, pName, lAttributeName); if(lValue == null && isPersistent(pType, lAttributeName)) { lValue = getValueFromDataBase(pType, pName, lAttributeType, lAttributeName); setValueToCache(cache, pType, pName, lAttributeName, lValue); } } else { LogWrapper.w(LOGTAG, "getValue:" + pType + "." + pName + " object is not registered"); } lValue = handleNullValue(lAttributeType, lValue); return lValue; } /** * ********************************************<br> * * @param pType * @param pName * @param pAttributeName * @return * * ********************************************<br> */ @SuppressWarnings("unchecked") private <T> T getValueFromCache(final HashMap<String, HashMap<String, HashMap<String, Object>>> pCache, final Class<? extends ADao> pType, final String pName, final String pAttributeName) { T lValue = null; HashMap<String,HashMap<String,Object>> lInstanceMap = pCache.get(pType.getSimpleName()); if(lInstanceMap != null) { HashMap<String, Object> lAttributeMap = lInstanceMap.get(pName); if(lAttributeMap != null) { lValue = (T) lAttributeMap.get(pAttributeName); } } return lValue; } /** * * ********************************************<br> * * @param <T> * @param pType * @param pName * @param pAttributeType * @param pAttributeName * @return * * ********************************************<br> */ private <T> T getValueFromDataBase(final Class<? extends ADao> pType, final String pName, final Class<?> pAttributeType, final String pAttributeName) { T lValue = null; try { lValue = Persistency.getInstance().getValueFromFile(pType, pName, pAttributeName, pAttributeType); } catch (IOException e) { String lMessage = "could not get value to attribute:" + pType + "." + pName + "." + pAttributeName + " e:" + e.getMessage(); LogWrapper.e(LOGTAG, lMessage); throw new RuntimeException(lMessage); } return lValue; } /** * ********************************************<br> * * @param pAttributeType * @param pValue * @return * * ********************************************<br> */ @SuppressWarnings("unchecked") private <T> T handleNullValue(final Class<?> pAttributeType, final T pValue) { T lValue = pValue; if(pValue == null) { Integer lKey = typeKeyMap.get(pAttributeType); if(lKey == null) { lKey = Integer.MAX_VALUE; } switch(lKey) { case KEY_BYTE: lValue = (T) BYTE0; break; case KEY_SHORT: lValue = (T) SHORT0; break; case KEY_INT: lValue = (T) INT0; break; case KEY_LONG: lValue = (T) LONG0; break; case KEY_FLOAT: lValue = (T) FLOAT0; break; case KEY_DOUBLE: lValue = (T) DOUBLE0; break; case KEY_BOOL: lValue = (T) Boolean.FALSE; break; case KEY_STRING: break; default: // LogWrapper.w(LOGTAG, "unhandled key:" + lKey + " for type:" + pAttributeType.getSimpleName()); } } return lValue; } /** * * @param pImportFile * @throws IOException * */ public void importData(File pImportFile) throws IOException { /** * objectManager has to know which ADao subclasses have been * imported to delete the cache for the respective classes */ HashSet<String> lLoadedTypeSet = Persistency.getInstance().importData(pImportFile); clearCache(null, lLoadedTypeSet); /** * load the information of the loaded data into the object cache */ for(String lTypeName : lLoadedTypeSet) { Class<? extends ADao> lType = typeNameToDaoMap.get(lTypeName); Vector<ADao> lLoadedObjectList = getObjectsFromDataBase(lType); } } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#init() */ protected void init() { eventBroadcaster.removeAllSubscribers(); clearCache(null, null); } /** * * ********************************************<br> * * read the type information and the instance names * from the database and fill objectCache with it * * ********************************************<br> */ private void initObjectCache() { objectCache = new HashMap<String, HashMap<String,ADao>>(); typeNameToDaoMap = new HashMap<String, Class<? extends ADao>>(); HashSet<Class<? extends ADao>> lDaoTypeList = ClazzFinder.findSubclasses(ADao.class); for(Class<? extends ADao> lDaoType : lDaoTypeList) { String lDaoTypeName = lDaoType.getSimpleName(); HashSet<String> lInstanceNameSet = Persistency.getInstance().getPersistedInstanceNameSet(lDaoType); HashMap<String, ADao> lInstanceMap = new HashMap<String, ADao>(); objectCache.put(lDaoTypeName, lInstanceMap); typeNameToDaoMap.put(lDaoTypeName, lDaoType); for(String lName : lInstanceNameSet) { ADao lObject = createInstance(lDaoType, lName); if(lObject != null) { lInstanceMap.put(lName, lObject); } } } } /** * ********************************************<br> * * @param pType * @param pAttribute * @return * * ********************************************<br> */ protected boolean isPersistent(Class<? extends ADao> pClass, String pAttributeName) { boolean lIsPersistent = reflectionUtil.hasAnnotation(pClass, pAttributeName, Persistent.class); return lIsPersistent; } /** * * ********************************************<br> * * @param <T> * @param pObject * @param pObjectClass * @param pName * * ********************************************<br> */ private <T extends ADao> void putObjectToCache(T pObject, Class<? extends ADao> pObjectClass, String pName) { if(objectCache == null) { initObjectCache(); } String lTypeName = pObjectClass.getSimpleName(); HashMap<String, ADao> lInstanceMap = objectCache.get(lTypeName); if(lInstanceMap == null) { lInstanceMap = new HashMap<String, ADao>(); objectCache.put(lTypeName, lInstanceMap); } ADao lOldObject = lInstanceMap.put(pName, pObject); if(lOldObject == null) { /** * put the new object to persistency */ writeInstanceToDataBase(pName, pObject); } else { /** * change back the partialTopic of lInstanceMap */ lInstanceMap.put(pName, pObject); throw new IllegalArgumentException("object of type:" + lTypeName + " with name:" + pName + " already exists"); } } /** * ********************************************<br> * * @param pAObject * @param pName * * ********************************************<br> */ protected synchronized void registerObject(ADao pAObject, String pName) { if(pAObject == null) { throw new IllegalArgumentException("parameter pAObject must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } Class<? extends ADao> lClass = pAObject.getClass(); putObjectToCache(pAObject, lClass, pName); if(!(pAObject instanceof AReferenceType)) { fireObjectCreated(pAObject.getClass(), pName); } }; private <T extends ADao> void removeObjectFromCache(T pObject) { String lType = pObject.getType(); String lName = pObject.getName(); if(objectCache != null) { HashMap<String, ADao> lInstanceMap = objectCache.get(lType); if(lInstanceMap != null) { lInstanceMap.remove(lName); if(lInstanceMap.isEmpty()) { objectCache.remove(lType); } } } if(cache != null) { HashMap<String, HashMap<String, Object>> lInstanceMap = cache.get(lType); if(lInstanceMap != null) { lInstanceMap.remove(lName); } } } /** * ********************************************<br> * * @param pService * * ********************************************<br> */ protected synchronized void setEventBroadcaster(IEventPublisher pService) { eventBroadcaster = pService; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#setValue(java.lang.Class, java.lang.String, com.droidfad.data.ADao.AttributesEnum, java.lang.Object) */ protected synchronized void setValue(final Class<? extends ADao> pType, final String pName, final AttributesEnum pAttribute, final Object pValue) { if(pType == null) { throw new IllegalArgumentException("parameter pClass must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } if(pAttribute == null) { throw new IllegalArgumentException("parameter pAttribute must not be null"); } /** * only set a value if the object is registered and available. * */ ADao lObject = getObject(pType, pName); if(lObject != null) { String lAttributeName = pAttribute.toString(); boolean lValueChanged = setValueToCache(cache, pType, pName, lAttributeName, pValue); if(lValueChanged && isPersistent(pType, lAttributeName)) { /** * only write the data to database if the value actually changed */ writeValueToDatabase(pType, pName, lAttributeName, pValue); } fireDataSet(pType, pName, pAttribute, pValue); } else { LogWrapper.w(LOGTAG, "setValue:" + pType.getSimpleName() + "." + pName + " object does not exist"); } } /** * ********************************************<br> * @param pCache * * @param pType * @param pName * @param pAttributeName * * ********************************************<br> */ private boolean setValueToCache(HashMap<String, HashMap<String, HashMap<String, Object>>> pCache, final Class<? extends ADao> pType, final String pName, final String pAttributeName, final Object pValue) { HashMap<String,HashMap<String,Object>> lInstanceMap = pCache.get(pType.getSimpleName()); if(lInstanceMap == null) { lInstanceMap = new HashMap<String, HashMap<String,Object>>(); pCache.put(pType.getSimpleName(), lInstanceMap); } HashMap<String, Object> lAttributeMap = lInstanceMap.get(pName); if(lAttributeMap == null) { lAttributeMap = new HashMap<String, Object>(); lInstanceMap.put(pName, lAttributeMap); } boolean lValueChanged = false; Object lOldValue = lAttributeMap.put(pAttributeName, pValue); if(pValue == null) { lValueChanged = lOldValue != null; } else { lValueChanged = !pValue.equals(lOldValue); } return lValueChanged; } /* (non-Javadoc) * @see com.droidfad.data.IObjectManager#unregisterObject(T) */ protected synchronized <T extends ADao> void unregisterObject(T pObject) { if(pObject != null) { Persistency.getInstance().removeInstance(pObject.getClass(), pObject.getName()); /** * delete the attribute cache */ removeObjectFromCache(pObject); if(!(pObject instanceof AReferenceType)) { fireObjectDeleted(pObject.getClass(), pObject.getName()); } pObject.isValid = false; } } /** * * * @param pName * @param pObject * */ private void writeInstanceToDataBase(String pName, ADao pObject) { if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } if(pObject == null) { throw new IllegalArgumentException("parameter pObject must not be null"); } Class<? extends ADao> lType = pObject.getClass(); List<String> lAttributeNameList = reflectionUtil.getPersistentAttributeNames(pObject.getClass(), null); String lAttributeName = null; Object lValue = null; if(lAttributeNameList.isEmpty()) { lAttributeName = Persistency.DUMMY_ATTRIBUTE_NAME; lValue = ""; } else { lAttributeName = lAttributeNameList.get(0); lValue = reflectionUtil.invokeGetter(pObject, lAttributeName, null); } try { Persistency.getInstance().writeValueToFile(lType, pName, lAttributeName, lValue); } catch (IOException e) { LogWrapper.e(LOGTAG, "could not write attribute:" + lType.getSimpleName() + "." + pName + "." + lAttributeName); } } /** * ********************************************<br> * * @param pType * @param pName * @param pAttributeName * @throws IOException * * ********************************************<br> */ private void writeValueToDatabase(Class<? extends ADao> pType, String pName, String pAttributeName, Object pValue) { if(pType == null) { throw new IllegalArgumentException("parameter pType must not be null"); } if(pName == null) { throw new IllegalArgumentException("parameter pName must not be null"); } if(pAttributeName == null) { throw new IllegalArgumentException("parameter pAttributeName must not be null"); } if(pValue != null) { try { Persistency.getInstance().writeValueToFile(pType, pName, pAttributeName, pValue); } catch (IOException e) { LogWrapper.e(LOGTAG, ("could not set value to file for:" + pType + "." + pName + "." + pAttributeName + "=" + pValue)); } } } /** * * @param pPrintWriter * */ public void dumpPersistency(PrintWriter pPrintWriter) { Persistency.getInstance().dump(pPrintWriter); } }
28,125
0.645645
0.643939
931
29.214823
29.064487
142
false
false
0
0
0
0
0
0
2.290011
false
false
3
f07f7562deb97f4ba56ed32728478574b626eafc
18,399,639,963,177
21e7da1e6a311e2ae2f777882d8c57d279f5e6e5
/SSGCBD/gestionModelosConsultas/src/gestionmodelosconsultas/sysinfo/people/People_View.java
b35d1030a46000493f6ee39f7f32b52fbf14d8e1
[]
no_license
CDPS/SSGCBD
https://github.com/CDPS/SSGCBD
f286ec6cbc11c1b0d36d3897b3a4480e90bc9b2f
11b290275d8428aab5e95581e95150a32e436de4
refs/heads/master
2018-01-01T10:16:15.869000
2017-03-23T14:44:52
2017-03-23T14:44:52
71,906,506
0
3
null
false
2017-02-23T21:20:43
2016-10-25T14:40:47
2016-10-25T14:42:28
2017-02-23T21:20:43
120,828
0
2
0
Java
null
null
/** */ package gestionmodelosconsultas.sysinfo.people; import gestionmodelosconsultas.sysinfo.Paquete; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>People View</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link gestionmodelosconsultas.sysinfo.people.People_View#getDirectorio <em>Directorio</em>}</li> * <li>{@link gestionmodelosconsultas.sysinfo.people.People_View#getOrganizacion <em>Organizacion</em>}</li> * </ul> * </p> * * @see gestionmodelosconsultas.sysinfo.people.PeoplePackage#getPeople_View() * @model * @generated */ public interface People_View extends Paquete { /** * Returns the value of the '<em><b>Directorio</b></em>' containment reference. * It is bidirectional and its opposite is '{@link gestionmodelosconsultas.sysinfo.people.Directorio#getPeople_View <em>People View</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Directorio</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Directorio</em>' containment reference. * @see #setDirectorio(Directorio) * @see gestionmodelosconsultas.sysinfo.people.PeoplePackage#getPeople_View_Directorio() * @see gestionmodelosconsultas.sysinfo.people.Directorio#getPeople_View * @model opposite="People_View" containment="true" required="true" * @generated */ Directorio getDirectorio(); /** * Sets the value of the '{@link gestionmodelosconsultas.sysinfo.people.People_View#getDirectorio <em>Directorio</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Directorio</em>' containment reference. * @see #getDirectorio() * @generated */ void setDirectorio(Directorio value); /** * Returns the value of the '<em><b>Organizacion</b></em>' containment reference. * It is bidirectional and its opposite is '{@link gestionmodelosconsultas.sysinfo.people.Organizacion#getPeople_View <em>People View</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Organizacion</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Organizacion</em>' containment reference. * @see #setOrganizacion(Organizacion) * @see gestionmodelosconsultas.sysinfo.people.PeoplePackage#getPeople_View_Organizacion() * @see gestionmodelosconsultas.sysinfo.people.Organizacion#getPeople_View * @model opposite="People_View" containment="true" required="true" * @generated */ Organizacion getOrganizacion(); /** * Sets the value of the '{@link gestionmodelosconsultas.sysinfo.people.People_View#getOrganizacion <em>Organizacion</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Organizacion</em>' containment reference. * @see #getOrganizacion() * @generated */ void setOrganizacion(Organizacion value); } // People_View
UTF-8
Java
3,138
java
People_View.java
Java
[]
null
[]
/** */ package gestionmodelosconsultas.sysinfo.people; import gestionmodelosconsultas.sysinfo.Paquete; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>People View</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link gestionmodelosconsultas.sysinfo.people.People_View#getDirectorio <em>Directorio</em>}</li> * <li>{@link gestionmodelosconsultas.sysinfo.people.People_View#getOrganizacion <em>Organizacion</em>}</li> * </ul> * </p> * * @see gestionmodelosconsultas.sysinfo.people.PeoplePackage#getPeople_View() * @model * @generated */ public interface People_View extends Paquete { /** * Returns the value of the '<em><b>Directorio</b></em>' containment reference. * It is bidirectional and its opposite is '{@link gestionmodelosconsultas.sysinfo.people.Directorio#getPeople_View <em>People View</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Directorio</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Directorio</em>' containment reference. * @see #setDirectorio(Directorio) * @see gestionmodelosconsultas.sysinfo.people.PeoplePackage#getPeople_View_Directorio() * @see gestionmodelosconsultas.sysinfo.people.Directorio#getPeople_View * @model opposite="People_View" containment="true" required="true" * @generated */ Directorio getDirectorio(); /** * Sets the value of the '{@link gestionmodelosconsultas.sysinfo.people.People_View#getDirectorio <em>Directorio</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Directorio</em>' containment reference. * @see #getDirectorio() * @generated */ void setDirectorio(Directorio value); /** * Returns the value of the '<em><b>Organizacion</b></em>' containment reference. * It is bidirectional and its opposite is '{@link gestionmodelosconsultas.sysinfo.people.Organizacion#getPeople_View <em>People View</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Organizacion</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Organizacion</em>' containment reference. * @see #setOrganizacion(Organizacion) * @see gestionmodelosconsultas.sysinfo.people.PeoplePackage#getPeople_View_Organizacion() * @see gestionmodelosconsultas.sysinfo.people.Organizacion#getPeople_View * @model opposite="People_View" containment="true" required="true" * @generated */ Organizacion getOrganizacion(); /** * Sets the value of the '{@link gestionmodelosconsultas.sysinfo.people.People_View#getOrganizacion <em>Organizacion</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Organizacion</em>' containment reference. * @see #getOrganizacion() * @generated */ void setOrganizacion(Organizacion value); } // People_View
3,138
0.70204
0.70204
81
37.740742
38.607162
147
false
false
0
0
0
0
0
0
0.740741
false
false
3
3921f1454330c7f6e20691e79d0ae63a5797e2ed
32,341,103,767,702
483d4dd236681769999efbd65090b868b6e7c8e9
/src/main/java/com/myFlink/java/batch/WorldCountJava.java
ca753c672d5df896f9bf39a7503b4e6dde994b33
[]
no_license
Asura7969/myFlink
https://github.com/Asura7969/myFlink
7ee682c5b9ab610f672cc431f9dbadf7978bcd62
67659f9bfad7f8741c8948d426ccbf52e312a884
refs/heads/master
2020-04-09T08:07:29.898000
2019-05-13T10:19:44
2019-05-13T10:19:44
160,183,177
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myFlink.java.batch; import com.myFlink.java.utils.WordCountData; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.util.Collector; import java.util.Arrays; public class WorldCountJava { private static final String INPUT_KEY = "input"; private static final String OUTPUT_KEY = "output"; public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setGlobalJobParameters(params); DataSet<String> text; if(params.has(INPUT_KEY)){ text = env.readTextFile(params.get(INPUT_KEY)); } else { text = WordCountData.getDefaultTextLineDataSet(env); } DataSet<Tuple2<String, Integer>> counts = text.flatMap(new Tokenizer()).groupBy(0) .sum(1); if (params.has(OUTPUT_KEY)) { counts.writeAsCsv(params.get(OUTPUT_KEY), "\n", " "); // execute program env.execute("WordCount Example"); } else { System.out.println("Printing result to stdout. Use --output to specify output path."); counts.print(); } } private static final class Tokenizer implements FlatMapFunction<String,Tuple2<String,Integer>>{ @Override public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception { String[] tokens = value.toLowerCase().split("\\W+"); Arrays.stream(tokens).forEach(token -> { if (token.length() > 0) { out.collect(new Tuple2<>(token, 1)); } }); } } }
UTF-8
Java
1,998
java
WorldCountJava.java
Java
[]
null
[]
package com.myFlink.java.batch; import com.myFlink.java.utils.WordCountData; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.util.Collector; import java.util.Arrays; public class WorldCountJava { private static final String INPUT_KEY = "input"; private static final String OUTPUT_KEY = "output"; public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setGlobalJobParameters(params); DataSet<String> text; if(params.has(INPUT_KEY)){ text = env.readTextFile(params.get(INPUT_KEY)); } else { text = WordCountData.getDefaultTextLineDataSet(env); } DataSet<Tuple2<String, Integer>> counts = text.flatMap(new Tokenizer()).groupBy(0) .sum(1); if (params.has(OUTPUT_KEY)) { counts.writeAsCsv(params.get(OUTPUT_KEY), "\n", " "); // execute program env.execute("WordCount Example"); } else { System.out.println("Printing result to stdout. Use --output to specify output path."); counts.print(); } } private static final class Tokenizer implements FlatMapFunction<String,Tuple2<String,Integer>>{ @Override public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception { String[] tokens = value.toLowerCase().split("\\W+"); Arrays.stream(tokens).forEach(token -> { if (token.length() > 0) { out.collect(new Tuple2<>(token, 1)); } }); } } }
1,998
0.636136
0.631632
58
33.448277
28.152401
100
false
false
0
0
0
0
0
0
0.568965
false
false
3
7016d7e5c9c85e54e647db7ef72d820895301b1c
11,338,713,710,971
370da6f3580f837db6e773c5e9ea976ee00cffd0
/application/src/main/java/com/yxe/application/po/VisitorForm.java
460b2121ed00f17c55920e7c62b74b1b3b554977
[]
no_license
haixingmu/HelloWorld
https://github.com/haixingmu/HelloWorld
45ff903ad302eef4ded89c599802f3b81af075a7
51cee0ca04b5afb3c109f7a73113acc5fa39a318
refs/heads/master
2023-05-05T05:40:22.190000
2022-03-08T01:33:30
2022-03-08T01:33:30
77,194,663
0
0
null
false
2022-06-21T02:20:48
2016-12-23T03:29:09
2022-03-08T01:34:17
2022-06-21T02:20:44
13,726
0
0
3
Java
false
false
package com.yxe.application.po; import java.math.BigDecimal; import java.util.Date; import javax.persistence.*; @Table(name = "T_CAFOS_VISITOR") public class VisitorForm { /** * 主键 */ @Id @Column(name = "XH") private BigDecimal xh; /** * 工号,如果没有就为身份证号 */ @Column(name = "WORKERNO") private String workerno; /** * 姓名 */ @Column(name = "USERNAME") private String username; /** * 性别 */ @Column(name = "SEX") private String sex; /** * 身份证号 */ @Column(name = "ID") private String id; /** * 出生年月 */ @Column(name = "BIRTHDAY") private Date birthday; /** * 居住地址 */ @Column(name = "ADDRESS") private String address; /** * 电话 */ @Column(name = "TEL") private String tel; /** * 身份证照片 */ @Column(name = "PIC") private String pic; /** * 是否有效 */ @Column(name = "YXBZ") private String yxbz; /** * 操作人id */ @Column(name = "OPRID") private String oprid; /** * 操作日期 */ @Column(name = "OPRDATE") private Date oprdate; /** * 最近照片,就为人脸照片 */ @Column(name = "PIC1") private String pic1; /** * 人脸照片 */ @Column(name = "USER_FERET") private String userFeret; /** * 获取主键 * * @return XH - 主键 */ public BigDecimal getXh() { return xh; } /** * 设置主键 * * @param xh 主键 */ public void setXh(BigDecimal xh) { this.xh = xh; } /** * 获取工号,如果没有就为身份证号 * * @return WORKERNO - 工号,如果没有就为身份证号 */ public String getWorkerno() { return workerno; } /** * 设置工号,如果没有就为身份证号 * * @param workerno 工号,如果没有就为身份证号 */ public void setWorkerno(String workerno) { this.workerno = workerno; } /** * 获取姓名 * * @return USERNAME - 姓名 */ public String getUsername() { return username; } /** * 设置姓名 * * @param username 姓名 */ public void setUsername(String username) { this.username = username; } /** * 获取性别 * * @return SEX - 性别 */ public String getSex() { return sex; } /** * 设置性别 * * @param sex 性别 */ public void setSex(String sex) { this.sex = sex; } /** * 获取身份证号 * * @return ID - 身份证号 */ public String getId() { return id; } /** * 设置身份证号 * * @param id 身份证号 */ public void setId(String id) { this.id = id; } /** * 获取出生年月 * * @return BIRTHDAY - 出生年月 */ public Date getBirthday() { return birthday; } /** * 设置出生年月 * * @param birthday 出生年月 */ public void setBirthday(Date birthday) { this.birthday = birthday; } /** * 获取居住地址 * * @return ADDRESS - 居住地址 */ public String getAddress() { return address; } /** * 设置居住地址 * * @param address 居住地址 */ public void setAddress(String address) { this.address = address; } /** * 获取电话 * * @return TEL - 电话 */ public String getTel() { return tel; } /** * 设置电话 * * @param tel 电话 */ public void setTel(String tel) { this.tel = tel; } /** * 获取身份证照片 * * @return PIC - 身份证照片 */ public String getPic() { return pic; } /** * 设置身份证照片 * * @param pic 身份证照片 */ public void setPic(String pic) { this.pic = pic; } /** * 获取是否有效 * * @return YXBZ - 是否有效 */ public String getYxbz() { return yxbz; } /** * 设置是否有效 * * @param yxbz 是否有效 */ public void setYxbz(String yxbz) { this.yxbz = yxbz; } /** * 获取操作人id * * @return OPRID - 操作人id */ public String getOprid() { return oprid; } /** * 设置操作人id * * @param oprid 操作人id */ public void setOprid(String oprid) { this.oprid = oprid; } /** * 获取操作日期 * * @return OPRDATE - 操作日期 */ public Date getOprdate() { return oprdate; } /** * 设置操作日期 * * @param oprdate 操作日期 */ public void setOprdate(Date oprdate) { this.oprdate = oprdate; } /** * 获取最近照片,就为人脸照片 * * @return PIC1 - 最近照片,就为人脸照片 */ public String getPic1() { return pic1; } /** * 设置最近照片,就为人脸照片 * * @param pic1 最近照片,就为人脸照片 */ public void setPic1(String pic1) { this.pic1 = pic1; } /** * 获取人脸照片 * * @return USER_FERET - 人脸照片 */ public String getUserFeret() { return userFeret; } /** * 设置人脸照片 * * @param userFeret 人脸照片 */ public void setUserFeret(String userFeret) { this.userFeret = userFeret; } }
UTF-8
Java
5,860
java
VisitorForm.java
Java
[ { "context": "o;\n\n /**\n * 姓名\n */\n @Column(name = \"USERNAME\")\n private String username;\n\n /**\n * 性别", "end": 413, "score": 0.9868625998497009, "start": 405, "tag": "USERNAME", "value": "USERNAME" }, { "context": "/\n public String getUsername() {\n return username;\n }\n\n /**\n * 设置姓名\n *\n * @param ", "end": 2044, "score": 0.7402110695838928, "start": 2036, "tag": "USERNAME", "value": "username" }, { "context": "e;\n }\n\n /**\n * 设置姓名\n *\n * @param username 姓名\n */\n public void setUsername(String use", "end": 2102, "score": 0.6094231009483337, "start": 2094, "tag": "USERNAME", "value": "username" }, { "context": " /**\n * 设置姓名\n *\n * @param username 姓名\n */\n public void setUsername(String userna", "end": 2105, "score": 0.6020617485046387, "start": 2104, "tag": "USERNAME", "value": "名" }, { "context": "name 姓名\n */\n public void setUsername(String username) {\n this.username = username;\n }\n\n /", "end": 2157, "score": 0.5410125255584717, "start": 2149, "tag": "USERNAME", "value": "username" }, { "context": "sername(String username) {\n this.username = username;\n }\n\n /**\n * 获取性别\n *\n * @return", "end": 2193, "score": 0.9610727429389954, "start": 2185, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.yxe.application.po; import java.math.BigDecimal; import java.util.Date; import javax.persistence.*; @Table(name = "T_CAFOS_VISITOR") public class VisitorForm { /** * 主键 */ @Id @Column(name = "XH") private BigDecimal xh; /** * 工号,如果没有就为身份证号 */ @Column(name = "WORKERNO") private String workerno; /** * 姓名 */ @Column(name = "USERNAME") private String username; /** * 性别 */ @Column(name = "SEX") private String sex; /** * 身份证号 */ @Column(name = "ID") private String id; /** * 出生年月 */ @Column(name = "BIRTHDAY") private Date birthday; /** * 居住地址 */ @Column(name = "ADDRESS") private String address; /** * 电话 */ @Column(name = "TEL") private String tel; /** * 身份证照片 */ @Column(name = "PIC") private String pic; /** * 是否有效 */ @Column(name = "YXBZ") private String yxbz; /** * 操作人id */ @Column(name = "OPRID") private String oprid; /** * 操作日期 */ @Column(name = "OPRDATE") private Date oprdate; /** * 最近照片,就为人脸照片 */ @Column(name = "PIC1") private String pic1; /** * 人脸照片 */ @Column(name = "USER_FERET") private String userFeret; /** * 获取主键 * * @return XH - 主键 */ public BigDecimal getXh() { return xh; } /** * 设置主键 * * @param xh 主键 */ public void setXh(BigDecimal xh) { this.xh = xh; } /** * 获取工号,如果没有就为身份证号 * * @return WORKERNO - 工号,如果没有就为身份证号 */ public String getWorkerno() { return workerno; } /** * 设置工号,如果没有就为身份证号 * * @param workerno 工号,如果没有就为身份证号 */ public void setWorkerno(String workerno) { this.workerno = workerno; } /** * 获取姓名 * * @return USERNAME - 姓名 */ public String getUsername() { return username; } /** * 设置姓名 * * @param username 姓名 */ public void setUsername(String username) { this.username = username; } /** * 获取性别 * * @return SEX - 性别 */ public String getSex() { return sex; } /** * 设置性别 * * @param sex 性别 */ public void setSex(String sex) { this.sex = sex; } /** * 获取身份证号 * * @return ID - 身份证号 */ public String getId() { return id; } /** * 设置身份证号 * * @param id 身份证号 */ public void setId(String id) { this.id = id; } /** * 获取出生年月 * * @return BIRTHDAY - 出生年月 */ public Date getBirthday() { return birthday; } /** * 设置出生年月 * * @param birthday 出生年月 */ public void setBirthday(Date birthday) { this.birthday = birthday; } /** * 获取居住地址 * * @return ADDRESS - 居住地址 */ public String getAddress() { return address; } /** * 设置居住地址 * * @param address 居住地址 */ public void setAddress(String address) { this.address = address; } /** * 获取电话 * * @return TEL - 电话 */ public String getTel() { return tel; } /** * 设置电话 * * @param tel 电话 */ public void setTel(String tel) { this.tel = tel; } /** * 获取身份证照片 * * @return PIC - 身份证照片 */ public String getPic() { return pic; } /** * 设置身份证照片 * * @param pic 身份证照片 */ public void setPic(String pic) { this.pic = pic; } /** * 获取是否有效 * * @return YXBZ - 是否有效 */ public String getYxbz() { return yxbz; } /** * 设置是否有效 * * @param yxbz 是否有效 */ public void setYxbz(String yxbz) { this.yxbz = yxbz; } /** * 获取操作人id * * @return OPRID - 操作人id */ public String getOprid() { return oprid; } /** * 设置操作人id * * @param oprid 操作人id */ public void setOprid(String oprid) { this.oprid = oprid; } /** * 获取操作日期 * * @return OPRDATE - 操作日期 */ public Date getOprdate() { return oprdate; } /** * 设置操作日期 * * @param oprdate 操作日期 */ public void setOprdate(Date oprdate) { this.oprdate = oprdate; } /** * 获取最近照片,就为人脸照片 * * @return PIC1 - 最近照片,就为人脸照片 */ public String getPic1() { return pic1; } /** * 设置最近照片,就为人脸照片 * * @param pic1 最近照片,就为人脸照片 */ public void setPic1(String pic1) { this.pic1 = pic1; } /** * 获取人脸照片 * * @return USER_FERET - 人脸照片 */ public String getUserFeret() { return userFeret; } /** * 设置人脸照片 * * @param userFeret 人脸照片 */ public void setUserFeret(String userFeret) { this.userFeret = userFeret; } }
5,860
0.45693
0.454973
345
13.808696
11.458226
48
false
false
0
0
0
0
0
0
0.133333
false
false
3
2c12e9f7eee24bf433d0e1c058600c837ad0a52e
24,842,090,855,923
ce9fc5e0f0efdbc13ff99d3bd8816ccacb56d788
/Liceo Scientifico 4/Informatica Liceo/Java/projects-workspace/GestioneMagazzinoGUI/src/gestioneMagazzino/ui/GestioneMagazzinoGUI.java
c4077d23c3f97bd5932ea73131955306218a24ed
[]
no_license
FrancescoGhinamo/SchoolFiles
https://github.com/FrancescoGhinamo/SchoolFiles
09b292fa15c4568d3848771312e7b9530da5f2cc
5b88b235dbf050471ed71fe57ff0642204ec2d29
refs/heads/master
2020-04-10T18:34:29.251000
2019-09-05T13:08:03
2019-09-05T13:08:03
161,207,792
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gestioneMagazzino.ui; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import config.Comandi; import eccezioni.MissingDataException; import gestioneMagazzino.dati.Articolo; import gestioneMagazzino.dati.ElencoArticoli; public class GestioneMagazzinoGUI extends JFrame implements ActionListener, ListSelectionListener, Comandi { private static final long serialVersionUID = 3017912850787597385L; private ElencoArticoli elenco; private JLabel lblCodice; private JLabel lblDescrizione; private JLabel lblPrezzo; private JTextField txtCodice; private JTextField txtDescrizione; private JTextField txtPrezzo; private JButton btnAggiungi; private JButton btnVisualizza; private JButton btnOrdina; private JComboBox<String> cmbOrdina; private JCheckBox ckOrdina; private DefaultListModel<Articolo> listModel; private JList<Articolo> outList; public GestioneMagazzinoGUI() { super("Gestione di un magazzino"); setExtendedState(MAXIMIZED_BOTH); elenco = new ElencoArticoli(); initComponents(); } public void initComponents() { lblCodice = new JLabel("Codice prodotto: "); lblDescrizione = new JLabel("Descrizione: "); lblPrezzo = new JLabel("Prezzo: "); txtCodice = new JTextField(30);; txtDescrizione = new JTextField(30); txtPrezzo = new JTextField(30); btnAggiungi = new JButton("Aggiungi prodotto"); btnAggiungi.addActionListener(this); btnVisualizza = new JButton("Visualizza prodotti nel record"); btnVisualizza.addActionListener(this); listModel = new DefaultListModel<Articolo>(); outList = new JList<Articolo>(listModel); outList.addListSelectionListener(this); btnOrdina = new JButton("Ordina per: "); btnOrdina.addActionListener(this); cmbOrdina = new JComboBox<String>(); cmbOrdina.addItem(ORDINA_CODICE); cmbOrdina.addItem(ORDINA_DESCRIZIONE); cmbOrdina.addItem(ORDINA_PREZZO); ckOrdina = new JCheckBox("Auto-update durante il sorting"); JPanel dataIn = new JPanel(); dataIn.setLayout(new GridLayout(6, 2, 3, 3)); dataIn.add(lblCodice); dataIn.add(txtCodice); dataIn.add(lblDescrizione); dataIn.add(txtDescrizione); dataIn.add(lblPrezzo); dataIn.add(txtPrezzo); dataIn.add(btnAggiungi); dataIn.add(btnVisualizza); dataIn.add(btnOrdina); dataIn.add(cmbOrdina); dataIn.add(ckOrdina); JScrollPane out = new JScrollPane(outList); this.setLayout(new BorderLayout()); this.add(dataIn, "North"); this.add(out, "Center"); } public void registraArticoloDaDati() throws MissingDataException { if(txtCodice.getText().equals("") || txtDescrizione.getText().equals("") || txtPrezzo.getText().equals("")) { throw new MissingDataException(); } else { aggiungiArticolo(txtCodice.getText(), txtDescrizione.getText(), Float.parseFloat(txtPrezzo.getText())); txtCodice.setText(""); txtDescrizione.setText(""); txtPrezzo.setText(""); } } public void aggiungiArticolo(String codice, String descrizione, float prezzo) { Articolo _a = new Articolo(codice, descrizione, prezzo); elenco.add(_a); listModel.addElement(_a); } public void visualizzaArticoli() { listModel.clear(); for(Articolo art: elenco) { listModel.addElement(art); } } public void ordinaArticoli() { elenco.oridina((String) cmbOrdina.getSelectedItem()); if(ckOrdina.isSelected()) { visualizzaArticoli(); } } @Override public void actionPerformed(ActionEvent e) { if(e.getSource().equals(btnAggiungi)) { try { registraArticoloDaDati(); } catch (NumberFormatException | MissingDataException e1) { JOptionPane.showMessageDialog(this, e1.getMessage(), "Errore", JOptionPane.ERROR_MESSAGE); } } else if(e.getSource().equals(btnVisualizza)) { visualizzaArticoli(); } else if(e.getSource().equals(btnOrdina)) { ordinaArticoli(); } } @Override public void valueChanged(ListSelectionEvent e) { if(e.getSource().equals(outList)) { int _i = outList.getSelectedIndex(); // System.out.println(_i); try { JOptionPane.showMessageDialog(this, listModel.get(_i).caratteristicheProdotto() , "Infromazioni", JOptionPane.INFORMATION_MESSAGE); } catch(Exception exc) {} outList.clearSelection(); } } public static void main(String[] args) { GestioneMagazzinoGUI gest = new GestioneMagazzinoGUI(); gest.addWindowListener(new WinMan()); gest.setVisible(true); } }
UTF-8
Java
4,937
java
GestioneMagazzinoGUI.java
Java
[]
null
[]
package gestioneMagazzino.ui; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import config.Comandi; import eccezioni.MissingDataException; import gestioneMagazzino.dati.Articolo; import gestioneMagazzino.dati.ElencoArticoli; public class GestioneMagazzinoGUI extends JFrame implements ActionListener, ListSelectionListener, Comandi { private static final long serialVersionUID = 3017912850787597385L; private ElencoArticoli elenco; private JLabel lblCodice; private JLabel lblDescrizione; private JLabel lblPrezzo; private JTextField txtCodice; private JTextField txtDescrizione; private JTextField txtPrezzo; private JButton btnAggiungi; private JButton btnVisualizza; private JButton btnOrdina; private JComboBox<String> cmbOrdina; private JCheckBox ckOrdina; private DefaultListModel<Articolo> listModel; private JList<Articolo> outList; public GestioneMagazzinoGUI() { super("Gestione di un magazzino"); setExtendedState(MAXIMIZED_BOTH); elenco = new ElencoArticoli(); initComponents(); } public void initComponents() { lblCodice = new JLabel("Codice prodotto: "); lblDescrizione = new JLabel("Descrizione: "); lblPrezzo = new JLabel("Prezzo: "); txtCodice = new JTextField(30);; txtDescrizione = new JTextField(30); txtPrezzo = new JTextField(30); btnAggiungi = new JButton("Aggiungi prodotto"); btnAggiungi.addActionListener(this); btnVisualizza = new JButton("Visualizza prodotti nel record"); btnVisualizza.addActionListener(this); listModel = new DefaultListModel<Articolo>(); outList = new JList<Articolo>(listModel); outList.addListSelectionListener(this); btnOrdina = new JButton("Ordina per: "); btnOrdina.addActionListener(this); cmbOrdina = new JComboBox<String>(); cmbOrdina.addItem(ORDINA_CODICE); cmbOrdina.addItem(ORDINA_DESCRIZIONE); cmbOrdina.addItem(ORDINA_PREZZO); ckOrdina = new JCheckBox("Auto-update durante il sorting"); JPanel dataIn = new JPanel(); dataIn.setLayout(new GridLayout(6, 2, 3, 3)); dataIn.add(lblCodice); dataIn.add(txtCodice); dataIn.add(lblDescrizione); dataIn.add(txtDescrizione); dataIn.add(lblPrezzo); dataIn.add(txtPrezzo); dataIn.add(btnAggiungi); dataIn.add(btnVisualizza); dataIn.add(btnOrdina); dataIn.add(cmbOrdina); dataIn.add(ckOrdina); JScrollPane out = new JScrollPane(outList); this.setLayout(new BorderLayout()); this.add(dataIn, "North"); this.add(out, "Center"); } public void registraArticoloDaDati() throws MissingDataException { if(txtCodice.getText().equals("") || txtDescrizione.getText().equals("") || txtPrezzo.getText().equals("")) { throw new MissingDataException(); } else { aggiungiArticolo(txtCodice.getText(), txtDescrizione.getText(), Float.parseFloat(txtPrezzo.getText())); txtCodice.setText(""); txtDescrizione.setText(""); txtPrezzo.setText(""); } } public void aggiungiArticolo(String codice, String descrizione, float prezzo) { Articolo _a = new Articolo(codice, descrizione, prezzo); elenco.add(_a); listModel.addElement(_a); } public void visualizzaArticoli() { listModel.clear(); for(Articolo art: elenco) { listModel.addElement(art); } } public void ordinaArticoli() { elenco.oridina((String) cmbOrdina.getSelectedItem()); if(ckOrdina.isSelected()) { visualizzaArticoli(); } } @Override public void actionPerformed(ActionEvent e) { if(e.getSource().equals(btnAggiungi)) { try { registraArticoloDaDati(); } catch (NumberFormatException | MissingDataException e1) { JOptionPane.showMessageDialog(this, e1.getMessage(), "Errore", JOptionPane.ERROR_MESSAGE); } } else if(e.getSource().equals(btnVisualizza)) { visualizzaArticoli(); } else if(e.getSource().equals(btnOrdina)) { ordinaArticoli(); } } @Override public void valueChanged(ListSelectionEvent e) { if(e.getSource().equals(outList)) { int _i = outList.getSelectedIndex(); // System.out.println(_i); try { JOptionPane.showMessageDialog(this, listModel.get(_i).caratteristicheProdotto() , "Infromazioni", JOptionPane.INFORMATION_MESSAGE); } catch(Exception exc) {} outList.clearSelection(); } } public static void main(String[] args) { GestioneMagazzinoGUI gest = new GestioneMagazzinoGUI(); gest.addWindowListener(new WinMan()); gest.setVisible(true); } }
4,937
0.736682
0.730403
193
24.580311
22.103502
112
false
false
0
0
0
0
0
0
2.160622
false
false
3
08eea24fde9c98e0965d5de92b1e9cfc4187c2f2
15,255,723,885,093
79146177c08e9da2d67e97c1a60887e3a06129ab
/app/src/main/java/com/sg/eyedoctor/consult/advice/activity/DrugAdviceActivity.java
c132d463e4c289a97445e09e25afdc4c79fcd193
[]
no_license
xuyiwanmo/eye
https://github.com/xuyiwanmo/eye
3421ce3bb1c3b6b093fb93e570885fa735074039
37e75fcc3416b5b86222a920a4d2d08201d15b29
refs/heads/master
2020-09-27T21:14:31.274000
2016-09-26T02:58:43
2016-09-26T02:58:43
67,463,383
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sg.eyedoctor.consult.advice.activity; import android.content.Intent; import android.text.InputType; import android.view.View; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.pulltorefresh.handmark.pulltorefresh.library.PullToRefreshBase; import com.pulltorefresh.handmark.pulltorefresh.library.PullToRefreshListView; import com.sg.eyedoctor.R; import com.sg.eyedoctor.common.activity.BaseActivity; import com.sg.eyedoctor.common.impl.DlgEdit; import com.sg.eyedoctor.common.manager.BaseManager; import com.sg.eyedoctor.common.manager.DialogManager; import com.sg.eyedoctor.common.response.BaseRowsResp; import com.sg.eyedoctor.common.utils.AppManager; import com.sg.eyedoctor.common.utils.CommonUtils; import com.sg.eyedoctor.common.utils.LogUtils; import com.sg.eyedoctor.common.utils.NetCallback; import com.sg.eyedoctor.common.view.MyActionbar; import com.sg.eyedoctor.consult.advice.bean.AdviceDrug; import com.sg.eyedoctor.helpUtils.doctorAdvice.adapter.AdviceGrugAdapter; import org.xutils.view.annotation.ContentView; import org.xutils.view.annotation.ViewInject; import java.lang.reflect.Type; import java.util.ArrayList; /** * 建议用药 */ @ContentView(R.layout.activity_drug_advice) public class DrugAdviceActivity extends BaseActivity implements AdviceGrugAdapter.ClickGrug { @ViewInject(R.id.drug_lv) private PullToRefreshListView mRefreshLv; @ViewInject(R.id.actionbar) private MyActionbar mActionbar; private ListView mGrugLv; private AdviceGrugAdapter mAdapter; private ArrayList<AdviceDrug> mDrugs = new ArrayList<>(); private ArrayList<AdviceDrug> mChooseGrugs = new ArrayList<>(); private int mRows = 10; private int mPage = 1; private NetCallback mCallback = new NetCallback(this) { @Override protected void requestOK(String result) { if (CommonUtils.isResultOK(result)) { closeDialog(); Type objectType = new TypeToken<BaseRowsResp<AdviceDrug>>() { }.getType(); BaseRowsResp<AdviceDrug> res = new Gson().fromJson(result, objectType); mDrugs = res.value.rows; for (AdviceDrug grug : mDrugs) { grug.count = 0; } mAdapter.setData(mDrugs); LogUtils.i(mDrugs.size() + ""); } } @Override protected void timeOut() { onTimeOut(); } }; @Override protected void initView() { mRefreshLv.setMode(PullToRefreshBase.Mode.BOTH); mGrugLv = mRefreshLv.getRefreshableView(); mAdapter = new AdviceGrugAdapter(mContext, mDrugs, 0, this); mGrugLv.setAdapter(mAdapter); showdialog(); BaseManager.getShareDrug(mPage + "", mRows + "", "", mCallback); } @Override protected void initListener() { } @Override protected void initActionbar() { mActionbar.setRightTv(R.string.ok, new View.OnClickListener() { @Override public void onClick(View v) { for (AdviceDrug drug : mDrugs) { if (drug.count != 0) { mChooseGrugs.add(drug); } } Intent intent = new Intent(); intent.putParcelableArrayListExtra("data", mChooseGrugs); setResult(RESULT_OK, intent); AppManager.getAppManager().finishActivity(); } }); } @Override public void click(int postion) { AdviceDrug grug = mDrugs.get(postion); grug.count++; LogUtils.i("click: " + grug.count); mAdapter.setData(mDrugs); } @Override public void edit(final int postion, String count) { DialogManager.showEditDlg(DrugAdviceActivity.this, R.string.enter_count, new DlgEdit() { @Override public boolean edit(String text) { if (text == null || text.equals("")) { return true; } AdviceDrug grug = mDrugs.get(postion); grug.count = Integer.valueOf(text); mAdapter.setData(mDrugs); return false; } }, InputType.TYPE_CLASS_NUMBER); } }
UTF-8
Java
4,381
java
DrugAdviceActivity.java
Java
[]
null
[]
package com.sg.eyedoctor.consult.advice.activity; import android.content.Intent; import android.text.InputType; import android.view.View; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.pulltorefresh.handmark.pulltorefresh.library.PullToRefreshBase; import com.pulltorefresh.handmark.pulltorefresh.library.PullToRefreshListView; import com.sg.eyedoctor.R; import com.sg.eyedoctor.common.activity.BaseActivity; import com.sg.eyedoctor.common.impl.DlgEdit; import com.sg.eyedoctor.common.manager.BaseManager; import com.sg.eyedoctor.common.manager.DialogManager; import com.sg.eyedoctor.common.response.BaseRowsResp; import com.sg.eyedoctor.common.utils.AppManager; import com.sg.eyedoctor.common.utils.CommonUtils; import com.sg.eyedoctor.common.utils.LogUtils; import com.sg.eyedoctor.common.utils.NetCallback; import com.sg.eyedoctor.common.view.MyActionbar; import com.sg.eyedoctor.consult.advice.bean.AdviceDrug; import com.sg.eyedoctor.helpUtils.doctorAdvice.adapter.AdviceGrugAdapter; import org.xutils.view.annotation.ContentView; import org.xutils.view.annotation.ViewInject; import java.lang.reflect.Type; import java.util.ArrayList; /** * 建议用药 */ @ContentView(R.layout.activity_drug_advice) public class DrugAdviceActivity extends BaseActivity implements AdviceGrugAdapter.ClickGrug { @ViewInject(R.id.drug_lv) private PullToRefreshListView mRefreshLv; @ViewInject(R.id.actionbar) private MyActionbar mActionbar; private ListView mGrugLv; private AdviceGrugAdapter mAdapter; private ArrayList<AdviceDrug> mDrugs = new ArrayList<>(); private ArrayList<AdviceDrug> mChooseGrugs = new ArrayList<>(); private int mRows = 10; private int mPage = 1; private NetCallback mCallback = new NetCallback(this) { @Override protected void requestOK(String result) { if (CommonUtils.isResultOK(result)) { closeDialog(); Type objectType = new TypeToken<BaseRowsResp<AdviceDrug>>() { }.getType(); BaseRowsResp<AdviceDrug> res = new Gson().fromJson(result, objectType); mDrugs = res.value.rows; for (AdviceDrug grug : mDrugs) { grug.count = 0; } mAdapter.setData(mDrugs); LogUtils.i(mDrugs.size() + ""); } } @Override protected void timeOut() { onTimeOut(); } }; @Override protected void initView() { mRefreshLv.setMode(PullToRefreshBase.Mode.BOTH); mGrugLv = mRefreshLv.getRefreshableView(); mAdapter = new AdviceGrugAdapter(mContext, mDrugs, 0, this); mGrugLv.setAdapter(mAdapter); showdialog(); BaseManager.getShareDrug(mPage + "", mRows + "", "", mCallback); } @Override protected void initListener() { } @Override protected void initActionbar() { mActionbar.setRightTv(R.string.ok, new View.OnClickListener() { @Override public void onClick(View v) { for (AdviceDrug drug : mDrugs) { if (drug.count != 0) { mChooseGrugs.add(drug); } } Intent intent = new Intent(); intent.putParcelableArrayListExtra("data", mChooseGrugs); setResult(RESULT_OK, intent); AppManager.getAppManager().finishActivity(); } }); } @Override public void click(int postion) { AdviceDrug grug = mDrugs.get(postion); grug.count++; LogUtils.i("click: " + grug.count); mAdapter.setData(mDrugs); } @Override public void edit(final int postion, String count) { DialogManager.showEditDlg(DrugAdviceActivity.this, R.string.enter_count, new DlgEdit() { @Override public boolean edit(String text) { if (text == null || text.equals("")) { return true; } AdviceDrug grug = mDrugs.get(postion); grug.count = Integer.valueOf(text); mAdapter.setData(mDrugs); return false; } }, InputType.TYPE_CLASS_NUMBER); } }
4,381
0.635033
0.633661
137
30.919708
23.544044
96
false
false
0
0
0
0
0
0
0.591241
false
false
3
c31d983617ce5bff1d3d92ea42cced0a67c6f586
21,784,074,167,416
0e479bb4dd801b4964e2248b81538c2e73a65c95
/app/src/main/java/com/vsoft/lucas/wisetrackbolivia/MapsSeguimiento.java
b59c16999b6d8d5ecaa5e53edb6310d2ecb596c8
[]
no_license
gabrielmamani/WisetrackBolivia
https://github.com/gabrielmamani/WisetrackBolivia
dc396d3e0bb30e5eb987587be2054f87d30db1b8
3930234b529f768c2759c90e9507b5e1e2556c0a
refs/heads/master
2021-01-19T19:54:21.604000
2017-05-26T13:31:07
2017-05-26T13:31:07
88,459,707
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vsoft.lucas.wisetrackbolivia; import android.Manifest; import android.app.ProgressDialog; import android.content.pm.PackageManager; import android.graphics.Color; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.text.Html; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.vsoft.lucas.wisetrackbolivia.app.AppController; import com.vsoft.lucas.wisetrackbolivia.utils.Const; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.sql.Time; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class MapsSeguimiento extends FragmentActivity implements GoogleMap.OnMarkerClickListener, OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener, GoogleMap.OnInfoWindowLongClickListener, GoogleMap.OnInfoWindowCloseListener { private GoogleMap mMap; private String TAG = MapsSeguimiento.class.getSimpleName(); public String jsonResponse; private Marker mSelectedMarker; private static int[] resource_auto_verde = { R.mipmap.auto_verde_este, R.mipmap.auto_verde_noreste, R.mipmap.auto_verde_noroeste, R.mipmap.auto_verde_norte, R.mipmap.auto_verde_oeste, R.mipmap.auto_verde_sur, R.mipmap.auto_verde_sureste, R.mipmap.auto_verde_suroeste }; private static int[] resource_auto_amarillo = { R.mipmap.auto_amarillo_este, R.mipmap.auto_amarillo_noreste, R.mipmap.auto_amarillo_noroeste, R.mipmap.auto_amarillo_norte, R.mipmap.auto_amarillo_oeste, R.mipmap.auto_amarillo_sur, R.mipmap.auto_amarillo_sureste, R.mipmap.auto_amarillo_suroeste }; private static int[] resource_auto_rojo = { R.mipmap.auto_rojo_este, R.mipmap.auto_rojo_noreste, R.mipmap.auto_rojo_noroeste, R.mipmap.auto_rojo_norte, R.mipmap.auto_rojo_oeste, R.mipmap.auto_rojo_sur, R.mipmap.auto_rojo_sureste, R.mipmap.auto_rojo_suroeste }; private static int[] resource_auto_azul = { R.mipmap.auto_azul_este, R.mipmap.auto_azul_noreste, R.mipmap.auto_azul_noroeste, R.mipmap.auto_azul_norte, R.mipmap.auto_azul_oeste, R.mipmap.auto_azul_sur, R.mipmap.auto_azul_sureste, R.mipmap.auto_azul_suroeste }; private static int[] resource_auto_celeste = { R.mipmap.auto_celeste_este, R.mipmap.auto_celeste_noreste, R.mipmap.auto_celeste_noroeste, R.mipmap.auto_celeste_norte, R.mipmap.auto_celeste_oeste, R.mipmap.auto_celeste_sur, R.mipmap.auto_celeste_sureste, R.mipmap.auto_celeste_suroeste }; private String tag_json_arry = "jarray_req"; private ProgressDialog pDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps_seguimiento); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.getUiSettings().setZoomControlsEnabled(true); Pintar(); mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter()); mMap.setOnMarkerClickListener(this); mMap.setOnInfoWindowClickListener(this); mMap.setOnInfoWindowCloseListener(this); mMap.setOnInfoWindowCloseListener(this); LatLng latLng = new LatLng(-17.128210, -64.714407); CameraUpdate cameraUpdateFactory = CameraUpdateFactory.newLatLngZoom(latLng, 5); mMap.moveCamera(cameraUpdateFactory); //mMap.setMyLocationEnabled(true); //mMap.getUiSettings().setMyLocationButtonEnabled(true); //if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) //{ //mMap.setMyLocationEnabled(true); //mMap.getUiSettings().setMyLocationButtonEnabled(true); //} /* LatLng sydney = new LatLng(-17.767706, -63.115123); final Marker marker = mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in GabrielSentra").icon(BitmapDescriptorFactory.fromResource(R.mipmap.auto_verde_este))); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); // Add a marker in Sydney and move the camera */ } private void showProgressDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideProgressDialog() { if (pDialog.isShowing()) pDialog.hide(); } @Override public boolean onMarkerClick(Marker marker) { mSelectedMarker = marker; return false; } private void Pintar() { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { mMap.clear(); //INICIO JsonArrayRequest JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); try { // Parsing json array response // loop through each json object jsonResponse = ""; for (int i = 0; i < response.length(); i++) { JSONObject trama = (JSONObject) response.get(i); String asimut = trama.getString("Asimut"); String EstadoGPS = trama.getString("EstadoGPS"); String EstadoMotor = trama.getString("EstadoMotor"); String EstadoPuerta = trama.getString("EstadoPuerta"); String FechaGPS = trama.getString("FechaGPS"); String ID = trama.getString("ID"); String IDButton = trama.getString("IDButton"); String IMEI = trama.getString("IMEI"); String Kilometraje = trama.getString("Kilometraje"); String Latitud = trama.getString("Latitud"); String Longitud = trama.getString("Longitud"); String NIT = trama.getString("NIT"); String Nombre = trama.getString("Nombre"); String Nro = trama.getString("Nro"); String NroPlaca = trama.getString("NroPlaca"); String Temperatura = trama.getString("Temperatura"); String Velocidad = trama.getString("Velocidad"); String VoltajeBateria = trama.getString("VoltajeBateria"); String direcciones = trama.getString("direcciones"); String tipov = trama.getString("tipov"); String resultado = "FechaGPS: " + FechaGPS; float rasimut = Float.parseFloat(asimut); int restadomotor = Integer.parseInt(EstadoMotor); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date date = new Date(); try{ date = format.parse(FechaGPS); Log.e("FechaGPS", date.toString()); }catch (ParseException e){ e.printStackTrace(); } int nro = ObtenerEstadoMovil(rasimut, restadomotor, date); /* mMap.addMarker(new MarkerOptions() .position(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud"))) .title("Placa: " + NroPlaca) .snippet(resultado) .icon(BitmapDescriptorFactory.fromResource(nro))); */ if (NroPlaca.equals("4217-UBN")) { mMap.addMarker(new MarkerOptions() .position(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud"))) .title("Placa: " + NroPlaca) .snippet(resultado) .icon(BitmapDescriptorFactory.fromResource(nro))); mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud")))); } else { mMap.addMarker(new MarkerOptions() .position(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud"))) .title("Placa: " + NroPlaca) .snippet(resultado) .icon(BitmapDescriptorFactory.fromResource(nro))); } //mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud")))); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); //hideProgressDialog(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(req, tag_json_arry); // Cancelling request // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_arry); //FIN de JsonArrayRequest } }); } }, 0, 20000); } public int ObtenerEstadoMovil(float result, int restadomotor, Date fechagps) { int resultfinal = 0; int valor = 0; if (result >= 338) { valor = 3; // resource_image_auto[3]; //norte } if(result <= 23){ valor = 3; //resource_image_auto[3]; //norte } if(result > 23 && result < 68){ valor = 1; // resource_image_auto[1]; //noreste } if(result >= 68 && result < 113){ valor = 0; //resource_image_auto[0]; //este } if(result >= 113 && result < 158){ valor = 6; //resource_image_auto[6]; //sureste } if(result >= 158 && result < 203){ valor = 5; //resource_image_auto[5]; //sur } if(result >= 203 && result < 248){ valor = 7; //resource_image_auto[7]; //suroeste } if(result >= 248 && result < 293){ valor =4; // resource_image_auto[4]; //oeste } if(result >= 293 && result < 338){ valor = 2; //resource_image_auto[2]; //noroeste } Date newDate = new Date(); long diff = newDate.getTime() - fechagps.getTime(); //long minutos = (diff/(1000*60))%60; long minutos = (diff/(1000*60)); if(minutos >= 60){ resultfinal = resource_auto_rojo[valor]; } if(minutos >= 30 && minutos < 60){ resultfinal= resource_auto_amarillo[valor]; } if(minutos < 30){ switch (restadomotor){ case 11: resultfinal = resource_auto_azul[valor]; break; case 12: resultfinal = resource_auto_celeste[valor]; break; case 21: resultfinal = resource_auto_verde[valor]; break; case 22: resultfinal = resource_auto_verde[valor]; break; case 41: resultfinal = resource_auto_azul[valor]; break; case 42: resultfinal = resource_auto_celeste[valor]; break; case 1: resultfinal = resource_auto_verde[valor]; break; case 0: resultfinal = resource_auto_azul[valor]; break; default: resultfinal = resource_auto_verde[valor]; break; } } return resultfinal; } @Override public void onInfoWindowClick(Marker marker) { Toast.makeText(this, "Click Info Window", Toast.LENGTH_SHORT).show(); } @Override public void onInfoWindowLongClick(Marker marker) { Toast.makeText(this, "Info Window long click", Toast.LENGTH_SHORT).show(); } @Override public void onInfoWindowClose(Marker marker) { //Toast.makeText(this, "Close Info Window", Toast.LENGTH_SHORT).show(); } class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter { // These are both viewgroups containing an ImageView with id "badge" and two TextViews with id // "title" and "snippet". private final View mWindow; private final View mContents; CustomInfoWindowAdapter() { mWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null); mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null); } @Override public View getInfoWindow(Marker marker) { render(marker, mWindow); return mWindow; } @Override public View getInfoContents(Marker marker) { //render(marker, mWindow); render(marker, mContents); return mContents; } private void render(Marker marker, View view) { int badge; badge = R.mipmap.auto_verde_este; ((ImageView) view.findViewById(R.id.badge)).setImageResource(badge); String title = marker.getTitle(); TextView titleUi = ((TextView) view.findViewById(R.id.title)); if (title != null) { SpannableString titleText = new SpannableString(title); titleText.setSpan(new ForegroundColorSpan(Color.BLUE), 0, titleText.length(), 0); titleUi.setText(titleText); } else { titleUi.setText(""); } String snippet = marker.getSnippet(); TextView snippetUi = ((TextView) view.findViewById(R.id.snippet)); if (snippet != null && snippet.length() > 12) { SpannableString snippetText = new SpannableString(snippet); //snippetText.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 10, 0); snippetText.setSpan(new ForegroundColorSpan(Color.BLACK), 0, snippet.length(), 0); snippetUi.setText(snippetText); } else { snippetUi.setText(""); } } } /* public void onClearMap(View view) { mMap.clear(); } public void onResetMap(View view) { mMap.clear(); //Pintar(); } */ } //gm
UTF-8
Java
19,806
java
MapsSeguimiento.java
Java
[ { "context": " MarkerOptions().position(sydney).title(\"Marker in GabrielSentra\").icon(BitmapDescriptorFactory.fromResource(R.mip", "end": 6370, "score": 0.9830195307731628, "start": 6357, "tag": "NAME", "value": "GabrielSentra" } ]
null
[]
package com.vsoft.lucas.wisetrackbolivia; import android.Manifest; import android.app.ProgressDialog; import android.content.pm.PackageManager; import android.graphics.Color; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.text.Html; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.vsoft.lucas.wisetrackbolivia.app.AppController; import com.vsoft.lucas.wisetrackbolivia.utils.Const; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.sql.Time; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class MapsSeguimiento extends FragmentActivity implements GoogleMap.OnMarkerClickListener, OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener, GoogleMap.OnInfoWindowLongClickListener, GoogleMap.OnInfoWindowCloseListener { private GoogleMap mMap; private String TAG = MapsSeguimiento.class.getSimpleName(); public String jsonResponse; private Marker mSelectedMarker; private static int[] resource_auto_verde = { R.mipmap.auto_verde_este, R.mipmap.auto_verde_noreste, R.mipmap.auto_verde_noroeste, R.mipmap.auto_verde_norte, R.mipmap.auto_verde_oeste, R.mipmap.auto_verde_sur, R.mipmap.auto_verde_sureste, R.mipmap.auto_verde_suroeste }; private static int[] resource_auto_amarillo = { R.mipmap.auto_amarillo_este, R.mipmap.auto_amarillo_noreste, R.mipmap.auto_amarillo_noroeste, R.mipmap.auto_amarillo_norte, R.mipmap.auto_amarillo_oeste, R.mipmap.auto_amarillo_sur, R.mipmap.auto_amarillo_sureste, R.mipmap.auto_amarillo_suroeste }; private static int[] resource_auto_rojo = { R.mipmap.auto_rojo_este, R.mipmap.auto_rojo_noreste, R.mipmap.auto_rojo_noroeste, R.mipmap.auto_rojo_norte, R.mipmap.auto_rojo_oeste, R.mipmap.auto_rojo_sur, R.mipmap.auto_rojo_sureste, R.mipmap.auto_rojo_suroeste }; private static int[] resource_auto_azul = { R.mipmap.auto_azul_este, R.mipmap.auto_azul_noreste, R.mipmap.auto_azul_noroeste, R.mipmap.auto_azul_norte, R.mipmap.auto_azul_oeste, R.mipmap.auto_azul_sur, R.mipmap.auto_azul_sureste, R.mipmap.auto_azul_suroeste }; private static int[] resource_auto_celeste = { R.mipmap.auto_celeste_este, R.mipmap.auto_celeste_noreste, R.mipmap.auto_celeste_noroeste, R.mipmap.auto_celeste_norte, R.mipmap.auto_celeste_oeste, R.mipmap.auto_celeste_sur, R.mipmap.auto_celeste_sureste, R.mipmap.auto_celeste_suroeste }; private String tag_json_arry = "jarray_req"; private ProgressDialog pDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps_seguimiento); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.getUiSettings().setZoomControlsEnabled(true); Pintar(); mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter()); mMap.setOnMarkerClickListener(this); mMap.setOnInfoWindowClickListener(this); mMap.setOnInfoWindowCloseListener(this); mMap.setOnInfoWindowCloseListener(this); LatLng latLng = new LatLng(-17.128210, -64.714407); CameraUpdate cameraUpdateFactory = CameraUpdateFactory.newLatLngZoom(latLng, 5); mMap.moveCamera(cameraUpdateFactory); //mMap.setMyLocationEnabled(true); //mMap.getUiSettings().setMyLocationButtonEnabled(true); //if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) //{ //mMap.setMyLocationEnabled(true); //mMap.getUiSettings().setMyLocationButtonEnabled(true); //} /* LatLng sydney = new LatLng(-17.767706, -63.115123); final Marker marker = mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in GabrielSentra").icon(BitmapDescriptorFactory.fromResource(R.mipmap.auto_verde_este))); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); // Add a marker in Sydney and move the camera */ } private void showProgressDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideProgressDialog() { if (pDialog.isShowing()) pDialog.hide(); } @Override public boolean onMarkerClick(Marker marker) { mSelectedMarker = marker; return false; } private void Pintar() { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { mMap.clear(); //INICIO JsonArrayRequest JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); try { // Parsing json array response // loop through each json object jsonResponse = ""; for (int i = 0; i < response.length(); i++) { JSONObject trama = (JSONObject) response.get(i); String asimut = trama.getString("Asimut"); String EstadoGPS = trama.getString("EstadoGPS"); String EstadoMotor = trama.getString("EstadoMotor"); String EstadoPuerta = trama.getString("EstadoPuerta"); String FechaGPS = trama.getString("FechaGPS"); String ID = trama.getString("ID"); String IDButton = trama.getString("IDButton"); String IMEI = trama.getString("IMEI"); String Kilometraje = trama.getString("Kilometraje"); String Latitud = trama.getString("Latitud"); String Longitud = trama.getString("Longitud"); String NIT = trama.getString("NIT"); String Nombre = trama.getString("Nombre"); String Nro = trama.getString("Nro"); String NroPlaca = trama.getString("NroPlaca"); String Temperatura = trama.getString("Temperatura"); String Velocidad = trama.getString("Velocidad"); String VoltajeBateria = trama.getString("VoltajeBateria"); String direcciones = trama.getString("direcciones"); String tipov = trama.getString("tipov"); String resultado = "FechaGPS: " + FechaGPS; float rasimut = Float.parseFloat(asimut); int restadomotor = Integer.parseInt(EstadoMotor); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date date = new Date(); try{ date = format.parse(FechaGPS); Log.e("FechaGPS", date.toString()); }catch (ParseException e){ e.printStackTrace(); } int nro = ObtenerEstadoMovil(rasimut, restadomotor, date); /* mMap.addMarker(new MarkerOptions() .position(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud"))) .title("Placa: " + NroPlaca) .snippet(resultado) .icon(BitmapDescriptorFactory.fromResource(nro))); */ if (NroPlaca.equals("4217-UBN")) { mMap.addMarker(new MarkerOptions() .position(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud"))) .title("Placa: " + NroPlaca) .snippet(resultado) .icon(BitmapDescriptorFactory.fromResource(nro))); mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud")))); } else { mMap.addMarker(new MarkerOptions() .position(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud"))) .title("Placa: " + NroPlaca) .snippet(resultado) .icon(BitmapDescriptorFactory.fromResource(nro))); } //mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(trama.getDouble("Latitud"), trama.getDouble("Longitud")))); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); //hideProgressDialog(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(req, tag_json_arry); // Cancelling request // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_arry); //FIN de JsonArrayRequest } }); } }, 0, 20000); } public int ObtenerEstadoMovil(float result, int restadomotor, Date fechagps) { int resultfinal = 0; int valor = 0; if (result >= 338) { valor = 3; // resource_image_auto[3]; //norte } if(result <= 23){ valor = 3; //resource_image_auto[3]; //norte } if(result > 23 && result < 68){ valor = 1; // resource_image_auto[1]; //noreste } if(result >= 68 && result < 113){ valor = 0; //resource_image_auto[0]; //este } if(result >= 113 && result < 158){ valor = 6; //resource_image_auto[6]; //sureste } if(result >= 158 && result < 203){ valor = 5; //resource_image_auto[5]; //sur } if(result >= 203 && result < 248){ valor = 7; //resource_image_auto[7]; //suroeste } if(result >= 248 && result < 293){ valor =4; // resource_image_auto[4]; //oeste } if(result >= 293 && result < 338){ valor = 2; //resource_image_auto[2]; //noroeste } Date newDate = new Date(); long diff = newDate.getTime() - fechagps.getTime(); //long minutos = (diff/(1000*60))%60; long minutos = (diff/(1000*60)); if(minutos >= 60){ resultfinal = resource_auto_rojo[valor]; } if(minutos >= 30 && minutos < 60){ resultfinal= resource_auto_amarillo[valor]; } if(minutos < 30){ switch (restadomotor){ case 11: resultfinal = resource_auto_azul[valor]; break; case 12: resultfinal = resource_auto_celeste[valor]; break; case 21: resultfinal = resource_auto_verde[valor]; break; case 22: resultfinal = resource_auto_verde[valor]; break; case 41: resultfinal = resource_auto_azul[valor]; break; case 42: resultfinal = resource_auto_celeste[valor]; break; case 1: resultfinal = resource_auto_verde[valor]; break; case 0: resultfinal = resource_auto_azul[valor]; break; default: resultfinal = resource_auto_verde[valor]; break; } } return resultfinal; } @Override public void onInfoWindowClick(Marker marker) { Toast.makeText(this, "Click Info Window", Toast.LENGTH_SHORT).show(); } @Override public void onInfoWindowLongClick(Marker marker) { Toast.makeText(this, "Info Window long click", Toast.LENGTH_SHORT).show(); } @Override public void onInfoWindowClose(Marker marker) { //Toast.makeText(this, "Close Info Window", Toast.LENGTH_SHORT).show(); } class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter { // These are both viewgroups containing an ImageView with id "badge" and two TextViews with id // "title" and "snippet". private final View mWindow; private final View mContents; CustomInfoWindowAdapter() { mWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null); mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null); } @Override public View getInfoWindow(Marker marker) { render(marker, mWindow); return mWindow; } @Override public View getInfoContents(Marker marker) { //render(marker, mWindow); render(marker, mContents); return mContents; } private void render(Marker marker, View view) { int badge; badge = R.mipmap.auto_verde_este; ((ImageView) view.findViewById(R.id.badge)).setImageResource(badge); String title = marker.getTitle(); TextView titleUi = ((TextView) view.findViewById(R.id.title)); if (title != null) { SpannableString titleText = new SpannableString(title); titleText.setSpan(new ForegroundColorSpan(Color.BLUE), 0, titleText.length(), 0); titleUi.setText(titleText); } else { titleUi.setText(""); } String snippet = marker.getSnippet(); TextView snippetUi = ((TextView) view.findViewById(R.id.snippet)); if (snippet != null && snippet.length() > 12) { SpannableString snippetText = new SpannableString(snippet); //snippetText.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 10, 0); snippetText.setSpan(new ForegroundColorSpan(Color.BLACK), 0, snippet.length(), 0); snippetUi.setText(snippetText); } else { snippetUi.setText(""); } } } /* public void onClearMap(View view) { mMap.clear(); } public void onResetMap(View view) { mMap.clear(); //Pintar(); } */ } //gm
19,806
0.511057
0.503181
477
40.524109
32.147034
185
false
false
0
0
0
0
0
0
0.618449
false
false
3
87eec307c0597808c9d9015a207bcb6727b9219b
14,611,478,759,093
422a51b01d0e723034cb071e9e68debd944a4b55
/src/main/java/com/sckhyt/geodisasters/dto/ProjectQueryParameter.java
65a2aef86fe98c60c8b7567b850afb67b36d9c47
[]
no_license
heylilang/GeoDidasterServer
https://github.com/heylilang/GeoDidasterServer
ddc4c5f7b166d04c7d82880cb48dfd02642d65a9
d12e8289b7f2fa2decd177063eff14d5a45f78aa
refs/heads/master
2020-04-01T17:09:09.363000
2018-10-17T08:22:57
2018-10-17T08:23:04
153,415,599
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sckhyt.geodisasters.dto; import com.sckhyt.geodisasters.model.dtr.ProjectQueryRequest; import io.swagger.annotations.ApiModelProperty; public class ProjectQueryParameter extends PageQueryParameter implements ProjectQueryRequest { @ApiModelProperty(value = "查询结束年度", name = "startYear", required = false) private String startYear; //年度 @ApiModelProperty(value = "查询开始年度", name = "endYear", required = false) private String endYear; //年度 @ApiModelProperty(value = "项目名称", name = "name", required = false) private String name; //项目名称 @ApiModelProperty(value = "区域编码", name = "areaCode", required = false) private String areaCode; //区域编码 @ApiModelProperty(value = "隐患点Id", name = "dangerZoneId", required = false) private Integer dangerZoneId; //隐患点Id @ApiModelProperty(value = "项目类型(GOVERN|PROSPECTING|DANGEROUS|MONITOR|RELOCATE|OTHERS(治理工程|应急抢险|排危除险|专业监测|搬迁避让|其他项目))", name = "projectType", required = true) private String projectType; //项目类型 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getStartYear() { return startYear; } public void setStartYear(String startYear) { this.startYear = startYear; } public String getEndYear() { return endYear; } public void setEndYear(String endYear) { this.endYear = endYear; } public Integer getDangerZoneId() { return dangerZoneId; } public void setDangerZoneId(Integer dangerZoneId) { this.dangerZoneId = dangerZoneId; } public String getProjectType() { return projectType; } public void setProjectType(String projectType) { this.projectType = projectType; } }
UTF-8
Java
2,089
java
ProjectQueryParameter.java
Java
[]
null
[]
package com.sckhyt.geodisasters.dto; import com.sckhyt.geodisasters.model.dtr.ProjectQueryRequest; import io.swagger.annotations.ApiModelProperty; public class ProjectQueryParameter extends PageQueryParameter implements ProjectQueryRequest { @ApiModelProperty(value = "查询结束年度", name = "startYear", required = false) private String startYear; //年度 @ApiModelProperty(value = "查询开始年度", name = "endYear", required = false) private String endYear; //年度 @ApiModelProperty(value = "项目名称", name = "name", required = false) private String name; //项目名称 @ApiModelProperty(value = "区域编码", name = "areaCode", required = false) private String areaCode; //区域编码 @ApiModelProperty(value = "隐患点Id", name = "dangerZoneId", required = false) private Integer dangerZoneId; //隐患点Id @ApiModelProperty(value = "项目类型(GOVERN|PROSPECTING|DANGEROUS|MONITOR|RELOCATE|OTHERS(治理工程|应急抢险|排危除险|专业监测|搬迁避让|其他项目))", name = "projectType", required = true) private String projectType; //项目类型 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getStartYear() { return startYear; } public void setStartYear(String startYear) { this.startYear = startYear; } public String getEndYear() { return endYear; } public void setEndYear(String endYear) { this.endYear = endYear; } public Integer getDangerZoneId() { return dangerZoneId; } public void setDangerZoneId(Integer dangerZoneId) { this.dangerZoneId = dangerZoneId; } public String getProjectType() { return projectType; } public void setProjectType(String projectType) { this.projectType = projectType; } }
2,089
0.674192
0.674192
67
28.089552
28.963554
161
false
false
0
0
0
0
0
0
0.641791
false
false
3
cc81a5b8685faef11a971daf0115cae8baaf9200
4,990,752,000,776
334891e16636fdda2fcf96a75fd16b15384a47ea
/src/main/java/com/hehua/user/localcache/PhoneVersionList.java
db5ba3c18a1a1c687758e21036d7498d3bf21e0c
[]
no_license
hewenjerry/jerry-user
https://github.com/hewenjerry/jerry-user
321d4d5559d2a64a2c3d4b8e6c6a919869c51137
29708a944b906625b51a6ff3e222ed702bc1da3e
refs/heads/master
2017-12-22T07:10:49.203000
2014-11-05T09:05:27
2014-11-05T09:05:27
26,211,532
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hehua.user.localcache; import com.google.common.base.Function; import com.google.common.collect.ListMultimap; import com.google.common.collect.Maps; import com.hehua.commons.Transformers; import com.hehua.user.domain.PhoneVersion; import com.hehua.user.model.AppVer; import org.apache.commons.collections.MapUtils; import org.apache.log4j.Logger; import java.util.*; /** * Created by hesheng on 14-9-28. */ public class PhoneVersionList { private static final Logger log = Logger.getLogger(PhoneVersionList.class); private final List<PhoneVersion> phoneVersionList; private final Map<Long, PhoneVersion> idMapPhoneVersion; private final Map<String, Channels> channelsMap; private final ListMultimap<String, PhoneVersion> channelMapPhoneVerList; public Map<String, Channels> getChannelsMap() { return this.channelsMap; } public class Channels { private List<PhoneVersion> phoneVersionList; private Map<String, PhoneVersion> versionMapPhone; private Map<String, PhoneVersion> upgradeVersionMap; public PhoneVersion getUpdateInfo(SortedMap<String, PhoneVersion> versionMapPV, String version) { if (MapUtils.isEmpty(versionMapPV)) { return getLastPhoneVersion(); } SortedMap<String, PhoneVersion> nextMaps = versionMapPV.tailMap(version); if (MapUtils.isEmpty(nextMaps)) { return getLastPhoneVersion(); } PhoneVersion retVersion = null; List<PhoneVersion> subPhoneList = new ArrayList<>(nextMaps.values()); for (PhoneVersion phoneVersion : subPhoneList) { if (phoneVersion.getForceupdate() == 1) { retVersion = phoneVersion; } } if (retVersion == null) { retVersion = subPhoneList.get(subPhoneList.size() - 1); } PhoneVersion currentPhoneVersion = versionMapPV.get(version); if (currentPhoneVersion.getForceupdate() == 1) { retVersion.setForceupdate(1); } else { retVersion.setForceupdate(0); } return retVersion; } public PhoneVersion getLastPhoneVersion() { return this.phoneVersionList.get(phoneVersionList.size() - 1); } } public PhoneVersionList(List<PhoneVersion> phoneVersionList) { this.phoneVersionList = Collections.unmodifiableList(phoneVersionList); this.idMapPhoneVersion = Transformers.transformAsOneToOneMap(phoneVersionList, PhoneVersion.EXE_IDX); this.channelMapPhoneVerList = Transformers.transformAsListMultimap(phoneVersionList, new Function<PhoneVersion, String>() { @Override public String apply(PhoneVersion phoneVersion) { return phoneVersion.getChannel(); } }); channelsMap = new HashMap<>(); Channels channels = null; for (String channel : channelMapPhoneVerList.keySet()) { channels = new Channels(); channels.phoneVersionList = channelMapPhoneVerList.get(channel); Collections.sort(channels.phoneVersionList, new Comparator<PhoneVersion>() { @Override public int compare(PhoneVersion o1, PhoneVersion o2) { return AppVer.of(o1.getVersion()).compareTo(AppVer.of(o2.getVersion())); } }); channels.versionMapPhone = Transformers.transformAsOneToOneMap(channels.phoneVersionList, PhoneVersion.EXEACT_VERSION); SortedMap<String, PhoneVersion> versionMapPV = Maps.newTreeMap(new Comparator<String>() { @Override public int compare(String str1, String str2) { return AppVer.of(str1).compareTo(AppVer.of(str2)); } }); for (PhoneVersion phoneVersion : channels.phoneVersionList) { try { versionMapPV.put(phoneVersion.getVersion(), phoneVersion); } catch (Exception e) { log.error("phoneVersion is illeage by version=" + phoneVersion.getVersion()); } } channels.upgradeVersionMap = new HashMap<>(); for (Map.Entry<String, PhoneVersion> entry : versionMapPV.entrySet()) { channels.upgradeVersionMap.put(entry.getKey(), channels.getUpdateInfo(versionMapPV, entry.getKey())); } channelsMap.put(channel, channels); } } public PhoneVersion getPhoneVersionById(long id) { return idMapPhoneVersion.get(id); } public List<PhoneVersion> getPhoneVersionAll() { return phoneVersionList; } public List<PhoneVersion> getPhoneVersionBy(String channel) { return channelMapPhoneVerList.get(channel); } public PhoneVersion getCurrentPhoneVersionBy(String channel, String version) { Channels channels = channelsMap.get(channel); if (channels == null) { return null; } return channels.versionMapPhone.get(version); } public PhoneVersion getUpgradePhoneVersionBy(String channel, String version) { Channels channels = channelsMap.get(channel); if (channels == null) { return null; } return channels.upgradeVersionMap.get(version); } }
UTF-8
Java
5,532
java
PhoneVersionList.java
Java
[ { "context": "4j.Logger;\n\nimport java.util.*;\n\n/**\n * Created by hesheng on 14-9-28.\n */\npublic class PhoneVersionList {\n\n", "end": 407, "score": 0.9996373057365417, "start": 400, "tag": "USERNAME", "value": "hesheng" } ]
null
[]
package com.hehua.user.localcache; import com.google.common.base.Function; import com.google.common.collect.ListMultimap; import com.google.common.collect.Maps; import com.hehua.commons.Transformers; import com.hehua.user.domain.PhoneVersion; import com.hehua.user.model.AppVer; import org.apache.commons.collections.MapUtils; import org.apache.log4j.Logger; import java.util.*; /** * Created by hesheng on 14-9-28. */ public class PhoneVersionList { private static final Logger log = Logger.getLogger(PhoneVersionList.class); private final List<PhoneVersion> phoneVersionList; private final Map<Long, PhoneVersion> idMapPhoneVersion; private final Map<String, Channels> channelsMap; private final ListMultimap<String, PhoneVersion> channelMapPhoneVerList; public Map<String, Channels> getChannelsMap() { return this.channelsMap; } public class Channels { private List<PhoneVersion> phoneVersionList; private Map<String, PhoneVersion> versionMapPhone; private Map<String, PhoneVersion> upgradeVersionMap; public PhoneVersion getUpdateInfo(SortedMap<String, PhoneVersion> versionMapPV, String version) { if (MapUtils.isEmpty(versionMapPV)) { return getLastPhoneVersion(); } SortedMap<String, PhoneVersion> nextMaps = versionMapPV.tailMap(version); if (MapUtils.isEmpty(nextMaps)) { return getLastPhoneVersion(); } PhoneVersion retVersion = null; List<PhoneVersion> subPhoneList = new ArrayList<>(nextMaps.values()); for (PhoneVersion phoneVersion : subPhoneList) { if (phoneVersion.getForceupdate() == 1) { retVersion = phoneVersion; } } if (retVersion == null) { retVersion = subPhoneList.get(subPhoneList.size() - 1); } PhoneVersion currentPhoneVersion = versionMapPV.get(version); if (currentPhoneVersion.getForceupdate() == 1) { retVersion.setForceupdate(1); } else { retVersion.setForceupdate(0); } return retVersion; } public PhoneVersion getLastPhoneVersion() { return this.phoneVersionList.get(phoneVersionList.size() - 1); } } public PhoneVersionList(List<PhoneVersion> phoneVersionList) { this.phoneVersionList = Collections.unmodifiableList(phoneVersionList); this.idMapPhoneVersion = Transformers.transformAsOneToOneMap(phoneVersionList, PhoneVersion.EXE_IDX); this.channelMapPhoneVerList = Transformers.transformAsListMultimap(phoneVersionList, new Function<PhoneVersion, String>() { @Override public String apply(PhoneVersion phoneVersion) { return phoneVersion.getChannel(); } }); channelsMap = new HashMap<>(); Channels channels = null; for (String channel : channelMapPhoneVerList.keySet()) { channels = new Channels(); channels.phoneVersionList = channelMapPhoneVerList.get(channel); Collections.sort(channels.phoneVersionList, new Comparator<PhoneVersion>() { @Override public int compare(PhoneVersion o1, PhoneVersion o2) { return AppVer.of(o1.getVersion()).compareTo(AppVer.of(o2.getVersion())); } }); channels.versionMapPhone = Transformers.transformAsOneToOneMap(channels.phoneVersionList, PhoneVersion.EXEACT_VERSION); SortedMap<String, PhoneVersion> versionMapPV = Maps.newTreeMap(new Comparator<String>() { @Override public int compare(String str1, String str2) { return AppVer.of(str1).compareTo(AppVer.of(str2)); } }); for (PhoneVersion phoneVersion : channels.phoneVersionList) { try { versionMapPV.put(phoneVersion.getVersion(), phoneVersion); } catch (Exception e) { log.error("phoneVersion is illeage by version=" + phoneVersion.getVersion()); } } channels.upgradeVersionMap = new HashMap<>(); for (Map.Entry<String, PhoneVersion> entry : versionMapPV.entrySet()) { channels.upgradeVersionMap.put(entry.getKey(), channels.getUpdateInfo(versionMapPV, entry.getKey())); } channelsMap.put(channel, channels); } } public PhoneVersion getPhoneVersionById(long id) { return idMapPhoneVersion.get(id); } public List<PhoneVersion> getPhoneVersionAll() { return phoneVersionList; } public List<PhoneVersion> getPhoneVersionBy(String channel) { return channelMapPhoneVerList.get(channel); } public PhoneVersion getCurrentPhoneVersionBy(String channel, String version) { Channels channels = channelsMap.get(channel); if (channels == null) { return null; } return channels.versionMapPhone.get(version); } public PhoneVersion getUpgradePhoneVersionBy(String channel, String version) { Channels channels = channelsMap.get(channel); if (channels == null) { return null; } return channels.upgradeVersionMap.get(version); } }
5,532
0.627079
0.623464
151
35.635761
30.888065
131
false
false
0
0
0
0
0
0
0.543046
false
false
3
fdc9e43f9b7b22e972e60de60e0f768a55244667
25,503,515,850,174
1906f6d7dd44eeb2445b148978082bc197e84cbe
/src/org/cxb/generics/Test38.java
7956b83fec77776e732b892bf1806c5f5c4f4564
[]
no_license
isChenxb/ThinkingInJava
https://github.com/isChenxb/ThinkingInJava
531c9ca13bb4f6d1383fc58e851f4710afcac4de
4603d3edce845ed6a7bb0dc0f8df7f3733d83b6f
refs/heads/master
2021-01-22T07:23:24.263000
2017-06-24T13:50:14
2017-06-24T13:50:14
81,813,816
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.cxb.generics; class BasicCoffee{ private String type; public BasicCoffee(){} public BasicCoffee(String type){ this.type = type; } public void set(String type){ this.type = type; } public String get(){ return type; } } class CoffeeDecorator extends BasicCoffee{ protected BasicCoffee coffee; public CoffeeDecorator(BasicCoffee coffee){ super(); this.coffee = coffee; } public void set(String type){ coffee.set(type); } public String get(){ return coffee.get(); } } class SteamMilk extends CoffeeDecorator{ public SteamMilk(BasicCoffee coffee){ super(coffee); set(get() + " &SteamMilk"); } } class Foam extends CoffeeDecorator{ public Foam(BasicCoffee coffee){ super(coffee); set(get() + " &Foam"); } } public class Test38 { }
UTF-8
Java
778
java
Test38.java
Java
[]
null
[]
package org.cxb.generics; class BasicCoffee{ private String type; public BasicCoffee(){} public BasicCoffee(String type){ this.type = type; } public void set(String type){ this.type = type; } public String get(){ return type; } } class CoffeeDecorator extends BasicCoffee{ protected BasicCoffee coffee; public CoffeeDecorator(BasicCoffee coffee){ super(); this.coffee = coffee; } public void set(String type){ coffee.set(type); } public String get(){ return coffee.get(); } } class SteamMilk extends CoffeeDecorator{ public SteamMilk(BasicCoffee coffee){ super(coffee); set(get() + " &SteamMilk"); } } class Foam extends CoffeeDecorator{ public Foam(BasicCoffee coffee){ super(coffee); set(get() + " &Foam"); } } public class Test38 { }
778
0.705656
0.703085
43
17.093023
16.164581
54
false
false
0
0
0
0
0
0
1.069767
false
false
3
a44c30b8d22c5489d35c3f4cf9a1438617faf4cf
21,217,138,450,017
55834e04164c5d8c8f39d0dd60bb3f01484fc928
/src/main/java/com/galaxyzeta/blog/util/BloomFilterUtil.java
c36d524eb3f2c0f5cf985765b2140a8321681304
[]
no_license
tanbinh123/SpringbootBlogApi
https://github.com/tanbinh123/SpringbootBlogApi
9bcd8b3afa0a478788c7dc1e12d46d47f5ea47a8
e0a9e69cbff23d843f89d9b92017b48ecfff59e0
refs/heads/master
2023-02-19T13:00:45.697000
2021-01-18T10:39:16
2021-01-18T10:39:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.galaxyzeta.blog.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; @Component /** * 布隆过滤器工具类 */ public class BloomFilterUtil { @Autowired StringRedisTemplate redisTemplate; private static final long FACTOR = 133; /** * 计算给定的 hash */ private Long hash(String toHash, long factor) { long hash = 0; char[] array = toHash.toCharArray(); for(char c: array) { hash = hash * factor + c; } return hash; } /** * 存入 bloomfilter */ public void save(String key, String toHash) { storeHashToBloomFilter(key, this.hash(toHash, FACTOR)); } private void init() { redisTemplate.executePipelined(new RedisCallback<Object>(){ @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); for(int i=0; i<64; i++) { connection.setBit(Constants.REDIS_BLOOM_FILTER_BLOG.getBytes(), i, false); } return null; } }); } /** * 将 String 进行 hash 后,匹配其中每一个 1 所在的位,如果与 Bloomfilter 不一致,说明不存在,直接返回 */ public boolean exists(String key, String toHash) { Long hashed = this.hash(toHash, FACTOR); boolean[] res = new boolean[1]; // 管线操作 redisTemplate.executePipelined(new RedisCallback<Object>(){ @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); long innerHashed = hashed; for(int i=0; i<32; i++, innerHashed >>= 1) { if((innerHashed & 1) == 1 && redisTemplate.opsForValue().getBit(key, i) == false) { res[0] = false; return null; } } res[0] = true; return null; } }); return res[0]; } private void storeHashToBloomFilter(String key, long hash) { // 布隆过滤器初始化 32位 0 if(! redisTemplate.hasKey(key)) { init(); } // 管线操作 redisTemplate.executePipelined(new RedisCallback<Object>(){ @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); long innerhash = hash; for(int i=0; i<32; i++) { if((innerhash & 1) == 1) { connection.setBit(key.getBytes(), i, true); } innerhash >>= 1; } return null; } }); } public static void main(String[] args) { int mask = 1; for(int i=0; i<5; i++) { System.out.println(mask); mask <<= 1; } } }
UTF-8
Java
2,770
java
BloomFilterUtil.java
Java
[]
null
[]
package com.galaxyzeta.blog.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; @Component /** * 布隆过滤器工具类 */ public class BloomFilterUtil { @Autowired StringRedisTemplate redisTemplate; private static final long FACTOR = 133; /** * 计算给定的 hash */ private Long hash(String toHash, long factor) { long hash = 0; char[] array = toHash.toCharArray(); for(char c: array) { hash = hash * factor + c; } return hash; } /** * 存入 bloomfilter */ public void save(String key, String toHash) { storeHashToBloomFilter(key, this.hash(toHash, FACTOR)); } private void init() { redisTemplate.executePipelined(new RedisCallback<Object>(){ @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); for(int i=0; i<64; i++) { connection.setBit(Constants.REDIS_BLOOM_FILTER_BLOG.getBytes(), i, false); } return null; } }); } /** * 将 String 进行 hash 后,匹配其中每一个 1 所在的位,如果与 Bloomfilter 不一致,说明不存在,直接返回 */ public boolean exists(String key, String toHash) { Long hashed = this.hash(toHash, FACTOR); boolean[] res = new boolean[1]; // 管线操作 redisTemplate.executePipelined(new RedisCallback<Object>(){ @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); long innerHashed = hashed; for(int i=0; i<32; i++, innerHashed >>= 1) { if((innerHashed & 1) == 1 && redisTemplate.opsForValue().getBit(key, i) == false) { res[0] = false; return null; } } res[0] = true; return null; } }); return res[0]; } private void storeHashToBloomFilter(String key, long hash) { // 布隆过滤器初始化 32位 0 if(! redisTemplate.hasKey(key)) { init(); } // 管线操作 redisTemplate.executePipelined(new RedisCallback<Object>(){ @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); long innerhash = hash; for(int i=0; i<32; i++) { if((innerhash & 1) == 1) { connection.setBit(key.getBytes(), i, true); } innerhash >>= 1; } return null; } }); } public static void main(String[] args) { int mask = 1; for(int i=0; i<5; i++) { System.out.println(mask); mask <<= 1; } } }
2,770
0.670963
0.659212
116
21.741379
23.200075
88
false
false
0
0
0
0
0
0
2.439655
false
false
9
0f7e4525eabe9ca8e1a5ed13987bee61212f3a05
21,217,138,447,232
65842332c8e5dc1af00f3e2cd9aee78fefa3e7ce
/src/main/java/com/model/onlinebank/BenificiaryDetails.java
435610198b88519a43cadf25a96061def7237e1a
[]
no_license
joshuamax099/BankingMac1
https://github.com/joshuamax099/BankingMac1
2a9b28eeaf71cc61547793a45841912b78b31423
d05dff9f9c4c4045f356141021ba3d69c4ea8983
refs/heads/master
2020-04-08T06:08:38.976000
2018-11-26T00:09:15
2018-11-26T00:09:15
159,087,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.model.onlinebank; public class BenificiaryDetails { //bID number(10) primary key, private long bID; private String name ; private long accNumber; private String IFSC ; private long accId; public long getAccId() { return accId; } public void setAccId(long accId) { this.accId = accId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getAccNumber() { return accNumber; } public void setAccNumber(long accNumber) { this.accNumber = accNumber; } public String getIFSC() { return IFSC; } public void setIFSC(String iFSC) { IFSC = iFSC; } public BenificiaryDetails() { super(); } public long getbID() { return bID; } public void setbID(long bID) { this.bID = bID; } }
UTF-8
Java
843
java
BenificiaryDetails.java
Java
[]
null
[]
package com.model.onlinebank; public class BenificiaryDetails { //bID number(10) primary key, private long bID; private String name ; private long accNumber; private String IFSC ; private long accId; public long getAccId() { return accId; } public void setAccId(long accId) { this.accId = accId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getAccNumber() { return accNumber; } public void setAccNumber(long accNumber) { this.accNumber = accNumber; } public String getIFSC() { return IFSC; } public void setIFSC(String iFSC) { IFSC = iFSC; } public BenificiaryDetails() { super(); } public long getbID() { return bID; } public void setbID(long bID) { this.bID = bID; } }
843
0.642942
0.640569
49
15.244898
12.567419
43
false
false
0
0
0
0
0
0
1.469388
false
false
9
4f58fb4a3dc257e8dcfdf78ae1d5309a71274b52
24,627,342,481,512
b5108164e94308478d8126abc60fe1694cdf082d
/01_Annotation/src/com/cn/test.java
31386ce60b1db8776496f70b50af2dc95b8ef86f
[]
no_license
13669005514/AnntationAndReflection
https://github.com/13669005514/AnntationAndReflection
aec8cd6bcac997a88a5df093670c5a1ea2bcbf35
cb8b46e7e5c7fd67dbd50199c7a86d3840c3b8ae
refs/heads/master
2020-04-08T06:27:10.543000
2018-11-28T12:21:38
2018-11-28T12:21:38
159,097,204
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cn; /** * 内置的三大注解的使用 * @author zhangfx 2018/11/23 */ @MyAnnotation("/xxx") public class test { /** * @Override 覆盖方法的注解 * */ @Override public String toString() { return super.toString(); } /** * @Deprecated 表示过时方法 不建议使用 */ @Deprecated public void test001() { System.out.println("此方法已经过时"); } public static void main(String[] args) { //表示抑制编译错误信息 @SuppressWarnings("All") test test = new test(); test.test001(); } }
UTF-8
Java
641
java
test.java
Java
[ { "context": "package com.cn;\n\n/**\n * 内置的三大注解的使用\n * @author zhangfx 2018/11/23\n */\n@MyAnnotation(\"/xxx\")\npublic class", "end": 53, "score": 0.9996569752693176, "start": 46, "tag": "USERNAME", "value": "zhangfx" } ]
null
[]
package com.cn; /** * 内置的三大注解的使用 * @author zhangfx 2018/11/23 */ @MyAnnotation("/xxx") public class test { /** * @Override 覆盖方法的注解 * */ @Override public String toString() { return super.toString(); } /** * @Deprecated 表示过时方法 不建议使用 */ @Deprecated public void test001() { System.out.println("此方法已经过时"); } public static void main(String[] args) { //表示抑制编译错误信息 @SuppressWarnings("All") test test = new test(); test.test001(); } }
641
0.528131
0.502722
36
14.305555
12.894485
44
false
false
0
0
0
0
0
0
0.138889
false
false
9
d0cdfe05f477a74f57b68f40137309b5e4832e97
12,283,606,479,624
05dfb68b96519fff003e864a0c5822a334c26bcd
/member/src/main/java/com/yxlg/member/service/IMemberLoginService.java
19755c79fe8c1046024346bb2b319ce2ac44d4d1
[ "MIT" ]
permissive
prilo21/yxlg
https://github.com/prilo21/yxlg
187a37c4c9e8f53247c896bf605af5cb14d58b08
a192d9f2b031949fe872d48d4545acfaec8bcb0d
refs/heads/master
2021-07-10T09:09:00.877000
2017-10-07T08:22:55
2017-10-07T08:22:55
106,081,060
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * IMemberLoginService.java * * Created Date: 2015年5月7日 * * Copyright (c) Yuandian Technologies Co., Ltd. * * This software is the confidential and proprietary information of * Yuandian Technologies Co., Ltd. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in accordance * with the terms of the license agreement you entered into with * Yuandian Technologies Co., Ltd. */ package com.yxlg.member.service; import org.springframework.http.ResponseEntity; import com.alibaba.fastjson.JSONObject; import com.yxlg.base.member.dto.MemberLoginDto; import com.yxlg.base.member.dto.MemberLoginWeixinDto; import com.yxlg.base.member.entity.Member; import com.yxlg.base.util.Result; /** * @author Michael.Sun * @version <br> * <p> * 用户登录接口类 * </p> */ public interface IMemberLoginService { /** * 用户登录入口 * * @param member * @return */ public ResponseEntity<Result> login(MemberLoginDto memberLoginDto, String identify); /** * 用户注销 * @param member * @return */ public ResponseEntity<Result> logout(Member member); /** * 用户通过短信验证码登录同时注册 * @param member * @return */ public ResponseEntity<Result> registerMemberByValidateCode(MemberLoginDto memberDto, String identify); /** * 2016-08-01 alisa.yang 第三方登录 * 登录方式:qq,微博,微信;token是自动登录的唯一验证方式,如果token和数据库不匹配,需要使用完整信息进行重新登录,那么登录分为以下步骤: * * 1. token, 验证是否已登录过 * 如果已登录过(说明授权成功并且有此会员),直接返回会员信息 * 如果是首次通过授权登录,则需要返回APP输入手机号绑定会员;并且手机号通过普通验证码之后才可以进行下一步 * 2. 输入手机号和openid及相应token,进行登录 * 如果手机号已注册,直接绑定 * 如果手机号未注册,拿到微信(或qq或微博)的简单信息进行注册,然后绑定 * @param dto * @param identify * @return */ public ResponseEntity<Result> weiXinLogin(MemberLoginWeixinDto dto, String identify); /** * 通过token登录 * @param token * @return */ public ResponseEntity<Result> loginByAuthToken(JSONObject token, String loginUserToken); }
UTF-8
Java
2,432
java
IMemberLoginService.java
Java
[ { "context": "\nimport com.yxlg.base.util.Result;\n\n/**\n * @author Michael.Sun\n * @version <br>\n * <p>\n * 用户登录", "end": 778, "score": 0.9997949600219727, "start": 767, "tag": "NAME", "value": "Michael.Sun" } ]
null
[]
/* * IMemberLoginService.java * * Created Date: 2015年5月7日 * * Copyright (c) Yuandian Technologies Co., Ltd. * * This software is the confidential and proprietary information of * Yuandian Technologies Co., Ltd. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in accordance * with the terms of the license agreement you entered into with * Yuandian Technologies Co., Ltd. */ package com.yxlg.member.service; import org.springframework.http.ResponseEntity; import com.alibaba.fastjson.JSONObject; import com.yxlg.base.member.dto.MemberLoginDto; import com.yxlg.base.member.dto.MemberLoginWeixinDto; import com.yxlg.base.member.entity.Member; import com.yxlg.base.util.Result; /** * @author Michael.Sun * @version <br> * <p> * 用户登录接口类 * </p> */ public interface IMemberLoginService { /** * 用户登录入口 * * @param member * @return */ public ResponseEntity<Result> login(MemberLoginDto memberLoginDto, String identify); /** * 用户注销 * @param member * @return */ public ResponseEntity<Result> logout(Member member); /** * 用户通过短信验证码登录同时注册 * @param member * @return */ public ResponseEntity<Result> registerMemberByValidateCode(MemberLoginDto memberDto, String identify); /** * 2016-08-01 alisa.yang 第三方登录 * 登录方式:qq,微博,微信;token是自动登录的唯一验证方式,如果token和数据库不匹配,需要使用完整信息进行重新登录,那么登录分为以下步骤: * * 1. token, 验证是否已登录过 * 如果已登录过(说明授权成功并且有此会员),直接返回会员信息 * 如果是首次通过授权登录,则需要返回APP输入手机号绑定会员;并且手机号通过普通验证码之后才可以进行下一步 * 2. 输入手机号和openid及相应token,进行登录 * 如果手机号已注册,直接绑定 * 如果手机号未注册,拿到微信(或qq或微博)的简单信息进行注册,然后绑定 * @param dto * @param identify * @return */ public ResponseEntity<Result> weiXinLogin(MemberLoginWeixinDto dto, String identify); /** * 通过token登录 * @param token * @return */ public ResponseEntity<Result> loginByAuthToken(JSONObject token, String loginUserToken); }
2,432
0.717098
0.708808
80
23.137501
25.62018
103
false
false
0
0
0
0
0
0
0.925
false
false
9
a9fc18e0d4a06e18f0a930ac7aecfe693ff104db
31,370,441,142,550
91e510da9661b3ed10f2b79680eac3c3e26d313a
/src/main/java/com/dominiccobo/bruneluni/cs2004tsp/utils/AlgorithmAnalysisLogger.java
1b1f20f42540223ab499eb55f9bcb3d79592762f
[]
no_license
dominiccobo/CS2004-Heuristic-Search
https://github.com/dominiccobo/CS2004-Heuristic-Search
4091f873c33ae0ac2864a8d15f89cf5135bfdad5
a7ea6667e8a499ccf38ca867d5eafd63fe1701bb
refs/heads/master
2020-03-18T09:48:50.873000
2018-05-23T14:26:58
2018-05-23T14:26:58
134,581,285
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dominiccobo.bruneluni.cs2004tsp.utils; import org.apache.commons.lang3.SystemUtils; import java.io.*; /** * Implementation of a simple logger enabling logging of algorithm execution times, with their names * and respective input sizes. * * @author Dominic Cobo (contact@dominiccobo.com) */ public class AlgorithmAnalysisLogger { /** * File to write the logged values to. */ private File logFile; /** * Writer handler */ private PrintWriter printWriter; /** * Name of the algorithm being tested. */ private String algorithmName; /** * Headers to log */ private String[] columnHeaders; /** * Constructor for preventing non parameterized instantiation of model. */ @SuppressWarnings("unused") private AlgorithmAnalysisLogger() { throw new IllegalArgumentException("No args constructors are not permitted."); } /** * Simple constructor initiating a logger. * @param algorithmName the name of the algorithm to log. */ public AlgorithmAnalysisLogger(String algorithmName, String[] columnHeaders) { this.algorithmName = algorithmName; this.columnHeaders = columnHeaders; this.setLogFile(algorithmName); this.init(); } /** * Initialise the log file. * * Creates a new file if the log file does not exist, else if it exists, opens it in append mode. */ @SuppressWarnings("all") private void init() { final String logHeaders = String.join(",", columnHeaders)+"\n"; try { if(!logFile.exists()) { logFile.createNewFile(); printWriter = new PrintWriter(logFile); printWriter.write(logHeaders); } else { printWriter = new PrintWriter(new BufferedWriter( new FileWriter(logFile, true) )); } } catch (IOException e) { e.printStackTrace(); } } /** * Establishes the log file directory as the desktop depending on the environment in which it is executed. * * (Tested on Windows 10, OSX Capitan and Debian) * * @param algorithmName the algorithm filename to log. */ private void setLogFile(String algorithmName) { // windows if(SystemUtils.IS_OS_WINDOWS) { this.logFile = new File(System.getProperty("user.home") + "/Desktop/" + algorithmName + ".csv"); } // mac else if(SystemUtils.IS_OS_MAC) { this.logFile = new File( "/Users/" + System.getProperty("user.name") +"/desktop/" + algorithmName + ".csv" ); } // unix else if(SystemUtils.IS_OS_UNIX) { this.logFile = new File( System.getProperty("user.home") + "/Desktop/" + algorithmName + ".csv" ); } else { throw new RuntimeException("Unable to determine OS"); } } /** * Log an item. * * @param logItems the array of String columns to append */ public void insertLog(String logItems[]) { if(logItems.length != columnHeaders.length) { throw new IllegalArgumentException( "The number of items logged, must match the expected " + columnHeaders.length + " items" ); } final String entry = String.join(",", logItems) + "\n"; printWriter.print(entry); } /** * Close the print writer connection. */ public void close() { printWriter.close(); } }
UTF-8
Java
3,683
java
AlgorithmAnalysisLogger.java
Java
[ { "context": "names\n * and respective input sizes.\n *\n * @author Dominic Cobo (contact@dominiccobo.com)\n */\npublic class Algori", "end": 279, "score": 0.9998638033866882, "start": 267, "tag": "NAME", "value": "Dominic Cobo" }, { "context": "spective input sizes.\n *\n * @author Dominic Cobo (contact@dominiccobo.com)\n */\npublic class AlgorithmAnalysisLogger {\n\n ", "end": 304, "score": 0.9999315738677979, "start": 281, "tag": "EMAIL", "value": "contact@dominiccobo.com" } ]
null
[]
package com.dominiccobo.bruneluni.cs2004tsp.utils; import org.apache.commons.lang3.SystemUtils; import java.io.*; /** * Implementation of a simple logger enabling logging of algorithm execution times, with their names * and respective input sizes. * * @author <NAME> (<EMAIL>) */ public class AlgorithmAnalysisLogger { /** * File to write the logged values to. */ private File logFile; /** * Writer handler */ private PrintWriter printWriter; /** * Name of the algorithm being tested. */ private String algorithmName; /** * Headers to log */ private String[] columnHeaders; /** * Constructor for preventing non parameterized instantiation of model. */ @SuppressWarnings("unused") private AlgorithmAnalysisLogger() { throw new IllegalArgumentException("No args constructors are not permitted."); } /** * Simple constructor initiating a logger. * @param algorithmName the name of the algorithm to log. */ public AlgorithmAnalysisLogger(String algorithmName, String[] columnHeaders) { this.algorithmName = algorithmName; this.columnHeaders = columnHeaders; this.setLogFile(algorithmName); this.init(); } /** * Initialise the log file. * * Creates a new file if the log file does not exist, else if it exists, opens it in append mode. */ @SuppressWarnings("all") private void init() { final String logHeaders = String.join(",", columnHeaders)+"\n"; try { if(!logFile.exists()) { logFile.createNewFile(); printWriter = new PrintWriter(logFile); printWriter.write(logHeaders); } else { printWriter = new PrintWriter(new BufferedWriter( new FileWriter(logFile, true) )); } } catch (IOException e) { e.printStackTrace(); } } /** * Establishes the log file directory as the desktop depending on the environment in which it is executed. * * (Tested on Windows 10, OSX Capitan and Debian) * * @param algorithmName the algorithm filename to log. */ private void setLogFile(String algorithmName) { // windows if(SystemUtils.IS_OS_WINDOWS) { this.logFile = new File(System.getProperty("user.home") + "/Desktop/" + algorithmName + ".csv"); } // mac else if(SystemUtils.IS_OS_MAC) { this.logFile = new File( "/Users/" + System.getProperty("user.name") +"/desktop/" + algorithmName + ".csv" ); } // unix else if(SystemUtils.IS_OS_UNIX) { this.logFile = new File( System.getProperty("user.home") + "/Desktop/" + algorithmName + ".csv" ); } else { throw new RuntimeException("Unable to determine OS"); } } /** * Log an item. * * @param logItems the array of String columns to append */ public void insertLog(String logItems[]) { if(logItems.length != columnHeaders.length) { throw new IllegalArgumentException( "The number of items logged, must match the expected " + columnHeaders.length + " items" ); } final String entry = String.join(",", logItems) + "\n"; printWriter.print(entry); } /** * Close the print writer connection. */ public void close() { printWriter.close(); } }
3,661
0.574803
0.572903
136
26.080883
27.324589
110
false
false
0
0
0
0
0
0
0.272059
false
false
9
192f76d2ae18383cc33bb3de19540e1a2c9ee50f
9,844,065,052,345
5d0c3b52af8c801c4cb851a0ec45ed978b5e0033
/challenge/src/main/java/orange/talents/restapi/challenge/service/IUserService.java
1380935cdc678dee4fd4f5d4e23e1170342a2ec3
[]
no_license
devrosilva/Java-Spring-Hibernate-REST-API
https://github.com/devrosilva/Java-Spring-Hibernate-REST-API
595b58007748d28834fe46fa645128d09e6303e3
a701053e3e6daa2763bbd5c21ec1e98ce5277f68
refs/heads/main
2023-05-15T09:40:19.060000
2021-06-08T23:29:37
2021-06-08T23:29:37
374,501,903
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package orange.talents.restapi.challenge.service; import orange.talents.restapi.challenge.model.User; public interface IUserService { public User registerUser(User newUser); public User getUser(Integer id); public User getUser(String cpf); public boolean checkIfUserExists(Integer id); public boolean checkIfUserExists(String cpf); public User getOwner(Integer id); public User getOwner(String cpf); }
UTF-8
Java
446
java
IUserService.java
Java
[]
null
[]
package orange.talents.restapi.challenge.service; import orange.talents.restapi.challenge.model.User; public interface IUserService { public User registerUser(User newUser); public User getUser(Integer id); public User getUser(String cpf); public boolean checkIfUserExists(Integer id); public boolean checkIfUserExists(String cpf); public User getOwner(Integer id); public User getOwner(String cpf); }
446
0.742152
0.742152
21
19.238094
20.142126
51
false
false
0
0
0
0
0
0
1.047619
false
false
9
bb0c347a305aae8ce8a9bdb68286be013973b8eb
4,612,794,893,514
27e279bbfed609ac6c86a568556d5c7adea22e92
/src/main/java/ru/ruamo/web/impl/GuestServiceImpl.java
a3dd5ce9f83a3c4ffb36ab390ba5fc7daf6811be
[]
no_license
vmstukalov/ruamo
https://github.com/vmstukalov/ruamo
f3d2f32dcb3ecb94993b204c611f1b36949ad826
c75b04f444240415eee4d0ec5f9b1f8ecf58e4a0
refs/heads/master
2016-08-26T13:59:05.533000
2016-08-26T13:10:39
2016-08-26T13:10:39
61,363,962
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.ruamo.web.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.ruamo.web.entities.Guest; import ru.ruamo.web.entities.User; import ru.ruamo.web.services.GuestRepository; import ru.ruamo.web.services.GuestService; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.*; @Repository @Transactional @Service("guestService") public class GuestServiceImpl implements GuestService { private GuestRepository guestRepository; private final Logger logger = LoggerFactory.getLogger(getClass().getName()); @PersistenceContext private EntityManager entityManager; @Override public Guest save(Guest guest) { return guestRepository.save(guest); } //гости страницы @Override public List<Guest> lastGuests(User user) { List<Guest> guests = entityManager.createQuery("select distinct g from Guest g where g.user.id = " + user.getId()).getResultList(); Collections.sort(guests); //25 - количество последних гостей. Если больше, удаляем старых if (guests.size() > 25) { for (int i = 0; i < guests.size() - 25; i++) { guestRepository.delete(guests.get(i)); } } Collections.reverse(guests); //logger.info("Guests: " + guests); return guests; } @Override public void delete(Guest guest) { guestRepository.delete(guest); } @Autowired public void setGuestRepository(GuestRepository guestRepository) { this.guestRepository = guestRepository; } }
UTF-8
Java
1,893
java
GuestServiceImpl.java
Java
[]
null
[]
package ru.ruamo.web.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.ruamo.web.entities.Guest; import ru.ruamo.web.entities.User; import ru.ruamo.web.services.GuestRepository; import ru.ruamo.web.services.GuestService; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.*; @Repository @Transactional @Service("guestService") public class GuestServiceImpl implements GuestService { private GuestRepository guestRepository; private final Logger logger = LoggerFactory.getLogger(getClass().getName()); @PersistenceContext private EntityManager entityManager; @Override public Guest save(Guest guest) { return guestRepository.save(guest); } //гости страницы @Override public List<Guest> lastGuests(User user) { List<Guest> guests = entityManager.createQuery("select distinct g from Guest g where g.user.id = " + user.getId()).getResultList(); Collections.sort(guests); //25 - количество последних гостей. Если больше, удаляем старых if (guests.size() > 25) { for (int i = 0; i < guests.size() - 25; i++) { guestRepository.delete(guests.get(i)); } } Collections.reverse(guests); //logger.info("Guests: " + guests); return guests; } @Override public void delete(Guest guest) { guestRepository.delete(guest); } @Autowired public void setGuestRepository(GuestRepository guestRepository) { this.guestRepository = guestRepository; } }
1,893
0.709061
0.704148
60
29.533333
25.708279
139
false
false
0
0
0
0
0
0
0.483333
false
false
9
d14b7e47693f2ce3cf35e04ca1c5852ecb9d4bd0
2,138,893,731,549
41ed4c9b0a09f5557ba677fe035df0d33a4e7201
/src/com/company/CountPairsWithGivenSum.java
8c8f2fa793fe2c66d5b898cfaefd5705b5953783
[]
no_license
Sanjay1149/CodingProblems
https://github.com/Sanjay1149/CodingProblems
f3d3ae46529b6db229304393f3facd2aedc02412
17b452a9a4dc2059c1ce9115650140872054874c
refs/heads/master
2023-06-12T14:42:17.096000
2021-07-05T09:28:28
2021-07-05T09:28:28
378,673,485
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.HashMap; import java.util.Map; public class CountPairsWithGivenSum { /** * https://www.geeksforgeeks.org/count-pairs-with-given-sum/ */ public static void main(String[] args) { /* int[] arr = {10, 12, 10, 15, -1, 7, 6, 5, 4, 2, 1, 1, 1}; int sum = 11;*/ int[] arr = {1,2,3,1,1,3}; int sum = 2; int count = getCountPairs(arr, sum); System.out.println(count); } private static int getCountPairs(int[] arr, int sum) { int count = 0, dupCount; Map<Integer, Integer> countMap = new HashMap<>(); for ( int pairVal : arr ) { if ( countMap.containsKey(sum - pairVal) ) { dupCount = countMap.get(sum - pairVal); count+=dupCount; for ( int i = 0; i < dupCount; i++ ) { System.out.println("Pair -> [ " + (sum - pairVal) + " , " + pairVal + " ]"); } countMap.put(pairVal, dupCount + 1); } else { dupCount = countMap.getOrDefault(pairVal, 0); countMap.put(pairVal, dupCount + 1); } } return count; } }
UTF-8
Java
1,233
java
CountPairsWithGivenSum.java
Java
[]
null
[]
package com.company; import java.util.HashMap; import java.util.Map; public class CountPairsWithGivenSum { /** * https://www.geeksforgeeks.org/count-pairs-with-given-sum/ */ public static void main(String[] args) { /* int[] arr = {10, 12, 10, 15, -1, 7, 6, 5, 4, 2, 1, 1, 1}; int sum = 11;*/ int[] arr = {1,2,3,1,1,3}; int sum = 2; int count = getCountPairs(arr, sum); System.out.println(count); } private static int getCountPairs(int[] arr, int sum) { int count = 0, dupCount; Map<Integer, Integer> countMap = new HashMap<>(); for ( int pairVal : arr ) { if ( countMap.containsKey(sum - pairVal) ) { dupCount = countMap.get(sum - pairVal); count+=dupCount; for ( int i = 0; i < dupCount; i++ ) { System.out.println("Pair -> [ " + (sum - pairVal) + " , " + pairVal + " ]"); } countMap.put(pairVal, dupCount + 1); } else { dupCount = countMap.getOrDefault(pairVal, 0); countMap.put(pairVal, dupCount + 1); } } return count; } }
1,233
0.489862
0.46472
40
29.825001
22.781448
96
false
false
0
0
0
0
0
0
1.125
false
false
9
4b877023486dc66eac92c90c1ec12be3d1169253
14,525,579,410,698
23abba37f98d3c07e9b2bb88f45891a5532c631c
/camel/jms2rest/src/test/java/net/lr/tutorial/karaf/camel/jms2rest/Jms2RestAdapterTest.java
bb56a7a1e994a435e971937fd843e284f76f6024
[ "Apache-2.0" ]
permissive
sidekava/Karaf_Tutorial
https://github.com/sidekava/Karaf_Tutorial
6619007a83cc84320ea9a774e3a77e799e74276c
9a8883721d44ad032c712d4f20be4d613ac2f1b7
refs/heads/master
2023-01-04T13:08:41.105000
2020-11-02T12:07:49
2020-11-02T12:07:49
309,357,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
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 net.lr.tutorial.karaf.camel.jms2rest; import java.io.InputStream; import javax.jms.ConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.xml.XPathBuilder; import org.apache.camel.component.jms.JmsComponent; import org.apache.camel.component.jms.JmsConfiguration; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.component.properties.PropertiesComponent; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public class Jms2RestAdapterTest extends CamelTestSupport { @EndpointInject(uri="mock:received") MockEndpoint received; /** * We send the person record to the person queue and expect it to be added to the persons the rest service manages * @throws Exception */ @Ignore public void testSendPerson() throws Exception { received.expectedMessageCount(1); InputStream is = this.getClass().getResourceAsStream("/person1.xml"); template.requestBody("jms:person", is); received.assertIsSatisfied(); Exchange ex = received.getExchanges().get(0); String id = XPathBuilder.xpath("//id").namespace("ns1", "http://person.jms2rest.camel.karaf.tutorial.lr.net").stringResult().evaluate(ex, String.class); Assert.assertEquals("1001", id); } @Override protected RouteBuilder[] createRouteBuilders() throws Exception { context.setTracing(true); PropertiesComponent properties = new PropertiesComponent("person2jms.cfg"); context.addComponent("properties", properties); addTestJmsComponent(); return new RouteBuilder[]{new Jms2RestRoute(), new RouteBuilder() { @Override public void configure() throws Exception { from("jetty:{{personServiceUri}}?matchOnUriPrefix=true").to(received); } }}; } /* * Adds a local in memory JMS component for the test */ private void addTestJmsComponent() { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://test?broker.persistent=false"); JmsConfiguration jmsConfig = new JmsConfiguration(connectionFactory); JmsComponent component = new JmsComponent(jmsConfig); context.addComponent("jms", component); } }
UTF-8
Java
3,340
java
Jms2RestAdapterTest.java
Java
[]
null
[]
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.lr.tutorial.karaf.camel.jms2rest; import java.io.InputStream; import javax.jms.ConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.xml.XPathBuilder; import org.apache.camel.component.jms.JmsComponent; import org.apache.camel.component.jms.JmsConfiguration; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.component.properties.PropertiesComponent; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public class Jms2RestAdapterTest extends CamelTestSupport { @EndpointInject(uri="mock:received") MockEndpoint received; /** * We send the person record to the person queue and expect it to be added to the persons the rest service manages * @throws Exception */ @Ignore public void testSendPerson() throws Exception { received.expectedMessageCount(1); InputStream is = this.getClass().getResourceAsStream("/person1.xml"); template.requestBody("jms:person", is); received.assertIsSatisfied(); Exchange ex = received.getExchanges().get(0); String id = XPathBuilder.xpath("//id").namespace("ns1", "http://person.jms2rest.camel.karaf.tutorial.lr.net").stringResult().evaluate(ex, String.class); Assert.assertEquals("1001", id); } @Override protected RouteBuilder[] createRouteBuilders() throws Exception { context.setTracing(true); PropertiesComponent properties = new PropertiesComponent("person2jms.cfg"); context.addComponent("properties", properties); addTestJmsComponent(); return new RouteBuilder[]{new Jms2RestRoute(), new RouteBuilder() { @Override public void configure() throws Exception { from("jetty:{{personServiceUri}}?matchOnUriPrefix=true").to(received); } }}; } /* * Adds a local in memory JMS component for the test */ private void addTestJmsComponent() { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://test?broker.persistent=false"); JmsConfiguration jmsConfig = new JmsConfiguration(connectionFactory); JmsComponent component = new JmsComponent(jmsConfig); context.addComponent("jms", component); } }
3,340
0.718862
0.713473
84
38.761906
31.691452
160
false
false
0
0
0
0
0
0
0.547619
false
false
9
746d0e445a81b96a73e80f20b701fb6c5c1e4eda
103,079,231,437
4e0bed8702f153060cd7226061e21a9240b2bfe9
/app/src/main/java/sheva/bank/dagger/component/AppComponent.java
3a3017d85019d65b9c12669cadb492cf82a0c161
[]
no_license
shevchenkona19/NikitaShevchenko
https://github.com/shevchenkona19/NikitaShevchenko
cb30bb7d1ec551b32298376fd2bcf6c11a233796
fe9511a7d819b04ff27c809c0d2f3b31cdb78353
refs/heads/master
2021-01-24T18:39:38.399000
2017-03-19T16:29:47
2017-03-19T16:29:47
84,467,702
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package sheva.bank.dagger.component; import javax.inject.Singleton; import dagger.Component; import sheva.bank.dagger.module.AppModule; import sheva.bank.dagger.module.RetrofitModule; import sheva.bank.mvp.view.MainActivity; /** * Created by shevc on 18.03.2017. */ @Component(modules = AppModule.class) @Singleton public interface AppComponent { RetrofitComponent plusRetrofitComponent(RetrofitModule rfModule); void inject(MainActivity activity); }
UTF-8
Java
465
java
AppComponent.java
Java
[ { "context": "eva.bank.mvp.view.MainActivity;\n\n/**\n * Created by shevc on 18.03.2017.\n */\n@Component(modules = AppModule", "end": 251, "score": 0.9995722770690918, "start": 246, "tag": "USERNAME", "value": "shevc" } ]
null
[]
package sheva.bank.dagger.component; import javax.inject.Singleton; import dagger.Component; import sheva.bank.dagger.module.AppModule; import sheva.bank.dagger.module.RetrofitModule; import sheva.bank.mvp.view.MainActivity; /** * Created by shevc on 18.03.2017. */ @Component(modules = AppModule.class) @Singleton public interface AppComponent { RetrofitComponent plusRetrofitComponent(RetrofitModule rfModule); void inject(MainActivity activity); }
465
0.793548
0.776344
19
23.473684
20.212994
69
false
false
0
0
0
0
0
0
0.421053
false
false
9
ed5860d710d9d9c2cf4f0cd2f9e0b1d7b69c9a58
17,892,833,773,657
6650a143c56ff5ff96cd5382a178d471ec9df349
/src/main/java/de/gerdiproject/harvest/utils/data/WebDataRetriever.java
51094495d824c59cc779cbed7203f1a0bbe3391c
[]
no_license
GeRDI-Project/HarvesterBaseLibrary_Harvester-Libraries
https://github.com/GeRDI-Project/HarvesterBaseLibrary_Harvester-Libraries
56237eabe6ee22e4c3dfb7a538f6b72386594c7b
de75a3f66464796bb477fd1415ac7a15b84e2bc2
refs/heads/master
2020-09-08T14:51:27.646000
2019-12-20T09:32:27
2019-12-20T09:32:27
221,163,371
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright © 2017 Robin Weiss (http://www.gerdi-project.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.gerdiproject.harvest.utils.data; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.zip.GZIPInputStream; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.xml.ws.http.HTTPException; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import de.gerdiproject.harvest.config.Configuration; import de.gerdiproject.harvest.config.parameters.IntegerParameter; import de.gerdiproject.harvest.rest.constants.RestConstants; import de.gerdiproject.harvest.utils.data.constants.DataOperationConstants; import de.gerdiproject.harvest.utils.data.enums.RestRequestType; import lombok.Getter; import lombok.Setter; /** * This class provides methods for reading files from the web. * * @author Robin Weiss */ public class WebDataRetriever implements IDataRetriever { private static final Logger LOGGER = LoggerFactory.getLogger(WebDataRetriever.class); private final Gson gson; private final IntegerParameter retriesParam; @Setter private int timeout; @Getter @Setter private Charset charset; /** * Constructor that sets the GSON (de-)serializer for reading and * writing JSON objects, as well as the charset and timeout. * * @param gson the GSON (de-)serializer for reading and writing JSON objects * @param charset the charset of the files to be read and written * @param timeout the web request timeout in milliseconds */ public WebDataRetriever(final Gson gson, final Charset charset, final int timeout) { this.gson = gson; this.charset = charset; this.timeout = timeout; // set up retries parameters IntegerParameter retriesTemp; try { retriesTemp = Configuration.registerParameter(DataOperationConstants.RETRIES_PARAM); } catch (final IllegalStateException e) { retriesTemp = DataOperationConstants.RETRIES_PARAM; } this.retriesParam = retriesTemp; } /** * Constructor that sets the GSON (de-)serializer for reading and * writing JSON objects, as well as the charset. * * @param gson the GSON (de-)serializer for reading and writing JSON objects * @param charset the charset of the files to be read and written */ public WebDataRetriever(final Gson gson, final Charset charset) { this(gson, charset, DataOperationConstants.NO_TIMEOUT); } /** * Constructor that copies settings from another {@linkplain WebDataRetriever}. * * @param other the {@linkplain WebDataRetriever} of which the settings are copied */ public WebDataRetriever(final WebDataRetriever other) { this(other.gson, other.charset, other.timeout); } @Override public String getString(final String url) { String responseText = null; try (BufferedReader reader = new BufferedReader(createWebReader(url))) { // read the first line of the response String line = reader.readLine(); // make sure we got a response if (line != null) { final StringBuilder responseBuilder = new StringBuilder(line); // read subsequent lines of the response line = reader.readLine(); while (line != null) { // add linebreak before appending the next line responseBuilder.append('\n').append(line); line = reader.readLine(); } responseText = responseBuilder.toString(); } } catch (final IOException e) { LOGGER.warn(String.format(DataOperationConstants.WEB_ERROR_JSON, url), e); } return responseText; } @Override public <T> T getObject(final String url, final Class<T> targetClass) { T object = null; try (InputStreamReader reader = createWebReader(url)) { object = gson.fromJson(reader, targetClass); } catch (IOException | IllegalStateException | JsonIOException | JsonSyntaxException e) { LOGGER.warn(String.format(DataOperationConstants.WEB_ERROR_JSON, url), e); } return object; } @Override public <T> T getObject(final String url, final Type targetType) { T object = null; try (InputStreamReader reader = createWebReader(url)) { object = gson.fromJson(reader, targetType); } catch (IOException | IllegalStateException | JsonIOException | JsonSyntaxException e) { LOGGER.warn(String.format(DataOperationConstants.WEB_ERROR_JSON, url), e); } return object; } @Override public Document getHtml(final String url) { try { final HttpURLConnection connection = sendWebRequest( RestRequestType.GET, url, null, null, MediaType.TEXT_PLAIN, retriesParam.getValue()); return Jsoup.parse(this.getInputStream(connection), charset.displayName(), url); } catch (final IOException | HTTPException e) { LOGGER.warn(String.format(DataOperationConstants.WEB_ERROR_JSON, url), e); return null; } } /** * Sends an authorized REST request with a specified body and returns the * response as a string. * * @param method the request method that is being sent * @param url the URL to which the request is being sent * @param body the body of the request, or null if no body is to be sent * @param authorization the base-64-encoded username and password, or null if no * authorization is required * @param contentType the contentType of the body * * @throws HTTPException thrown if the response code is not 2xx * @throws IOException thrown if the response output stream could not be created * * @return the HTTP response as plain text */ public String getRestResponse(final RestRequestType method, final String url, final String body, final String authorization, final String contentType) throws HTTPException, IOException { final HttpURLConnection connection = sendWebRequest(method, url, body, authorization, contentType, retriesParam.getValue()); String responseText = null; // create a reader for the HTTP response try (InputStream response = this.getInputStream(connection); BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { final char[] readBuffer = new char[1024]; final StringBuilder responseBuilder = new StringBuilder(); int readBytes; while (true) { readBytes = reader.read(readBuffer, 0, 1024); if (readBytes == -1) break; responseBuilder.append(readBuffer, 0, readBytes); } responseText = responseBuilder.toString(); } // combine the read lines to a single string return responseText; } /** * Sends an authorized REST request with a specified body and returns the * header fields. * * @param method the request method that is being sent * @param url the URL to which the request is being sent * @param body the body of the request, or null if no body is to be sent * @param authorization the base-64-encoded username and password, or null if no * authorization is required * @param contentType the contentType of the body * * @throws HTTPException thrown if the response code is not 2xx * @throws IOException thrown if the response output stream could not be created * * @return the response header fields, or null if the response could not be parsed */ public Map<String, List<String>> getRestHeader(final RestRequestType method, final String url, final String body, final String authorization, final String contentType) throws HTTPException, IOException { Map<String, List<String>> headerFields = null; final HttpURLConnection connection = sendWebRequest(method, url, body, authorization, contentType, retriesParam.getValue()); headerFields = connection.getHeaderFields(); return headerFields; } /** * Sends a REST request with a specified body and returns the connection. * * @param method the request method that is being sent * @param urlString the URL to which the request is being sent * @param body the body of the request, or null if no body is to be sent * @param authorization the base-64-encoded username and password, or null if no * authorization is required * @param contentType the contentType of the body * @param retries the number of retries if the request fails with a response code 5xx * * @throws HTTPException thrown if the response code is not 2xx * @throws IOException thrown if the response output stream could not be created * * @return the connection to the host */ public HttpURLConnection sendWebRequest(final RestRequestType method, final String urlString, final String body, final String authorization, final String contentType, final int retries) throws IOException, HTTPException { // generate a URL and open a connection final URL url = new URL(urlString); final HttpURLConnection connection = createConnection(method, url, body, authorization, contentType); boolean mustRetry = false; // open the connection try { final int responseCode = connection.getResponseCode(); if (responseCode >= 300) connection.disconnect(); if (responseCode >= 500) { mustRetry = retries != 0; // throw an error if the request is not to be reattempted if (!mustRetry) { final String errorMessage = String.format( DataOperationConstants.WEB_ERROR_REST_HTTP, method.toString(), urlString, body, responseCode); throw new HttpStatusException(errorMessage, responseCode, urlString); } } else if (responseCode < 400) { final String redirectedUrl = connection.getHeaderField(HttpHeaders.LOCATION); final boolean canRedirect; // check if there is a redirection URL if (redirectedUrl == null) canRedirect = false; else { // disallow redirects from HTTPS to HTTP canRedirect = !urlString.startsWith(DataOperationConstants.HTTPS) || redirectedUrl.startsWith(DataOperationConstants.HTTPS); } // redirect only if all above conditions are met if (canRedirect) return sendWebRequest(method, redirectedUrl, body, authorization, contentType, retries); } } catch (final SocketTimeoutException e) { // if we time out, try again if (retries == 0) throw e; else mustRetry = true; } // if the request failed due to server issues, attempt to retry if (mustRetry) { // if the response header contains a retry-after field, wait for that period before retrying final int delayInSeconds = connection.getHeaderFieldInt(RestConstants.RETRY_AFTER_HEADER, 1); LOGGER.debug(String.format(DataOperationConstants.RETRY, urlString, delayInSeconds)); try { Thread.sleep(delayInSeconds * 1000); } catch (final InterruptedException e) { throw new IOException(e); } return sendWebRequest(method, urlString, body, authorization, contentType, Math.max(retries - 1, -1)); } else return connection; } /** * Sets up a {@linkplain HttpURLConnection} connection with specified properties. * * @param method the request method that is being sent * @param url the URL to which the connection is to be established * @param body the body of the request, or null if no body is to be sent * @param authorization the base-64-encoded username and password, or null if no * authorization is required * @param contentType the contentType of the body * * @throws IOException thrown if the response output stream could not be created * * @return the connection to the host */ private HttpURLConnection createConnection(final RestRequestType method, final URL url, final String body, final String authorization, final String contentType) throws IOException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // set request properties connection.setDoOutput(true); connection.setInstanceFollowRedirects(true); connection.setUseCaches(false); connection.setRequestMethod(method.toString()); connection.setRequestProperty(HttpHeaders.ACCEPT_CHARSET, charset.displayName().toLowerCase(Locale.ENGLISH)); connection.setRequestProperty(HttpHeaders.ACCEPT_ENCODING, DataOperationConstants.GZIP_ENCODING); connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType); // set timeout if (timeout != DataOperationConstants.NO_TIMEOUT) { connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); } // set authentication if (authorization != null) connection.setRequestProperty(HttpHeaders.AUTHORIZATION, authorization); // only send data if it is specified if (body != null) { // convert body string to bytes final byte[] bodyBytes = body.getBytes(charset); connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, Integer.toString(bodyBytes.length)); // try to send body final DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(bodyBytes); wr.close(); } return connection; } /** * Returns the correct InputStream based on the Content-Encoding header of * a connection. Necessary to support compression. * * @param connection the connection to be checked * * @throws IOException thrown if InputStream is corrupted * * @return an InputStream subclass */ public InputStream getInputStream(final HttpURLConnection connection) throws IOException { // if encoding is gzip and is not a HEAD request (SAI-1607), use the GZIP stream if (DataOperationConstants.GZIP_ENCODING.equals(connection.getContentEncoding()) && !DataOperationConstants.HEAD_REQUEST.equals(connection.getRequestMethod())) return new GZIPInputStream(connection.getInputStream()); return connection.getInputStream(); } /** * Creates an input stream reader of a specified URL. * * @param url the URL of which the response is to be read * * @return a reader of the URL response * * @throws MalformedURLException thrown when the URL is malformed * @throws IOException thrown for various reasons when the reader is created */ private InputStreamReader createWebReader(final String url) throws MalformedURLException, IOException { final HttpURLConnection connection = sendWebRequest( RestRequestType.GET, url, null, null, MediaType.TEXT_PLAIN, retriesParam.getValue()); return new InputStreamReader(this.getInputStream(connection), charset); } }
UTF-8
Java
17,491
java
WebDataRetriever.java
Java
[ { "context": "/**\n * Copyright © 2017 Robin Weiss (http://www.gerdi-project.de)\n *\n * Licensed unde", "end": 35, "score": 0.9997097849845886, "start": 24, "tag": "NAME", "value": "Robin Weiss" }, { "context": "hods for reading files from the web.\n *\n * @author Robin Weiss\n */\npublic class WebDataRetriever implements IDat", "end": 1974, "score": 0.9995325803756714, "start": 1963, "tag": "NAME", "value": "Robin Weiss" } ]
null
[]
/** * Copyright © 2017 <NAME> (http://www.gerdi-project.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.gerdiproject.harvest.utils.data; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.zip.GZIPInputStream; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.xml.ws.http.HTTPException; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import de.gerdiproject.harvest.config.Configuration; import de.gerdiproject.harvest.config.parameters.IntegerParameter; import de.gerdiproject.harvest.rest.constants.RestConstants; import de.gerdiproject.harvest.utils.data.constants.DataOperationConstants; import de.gerdiproject.harvest.utils.data.enums.RestRequestType; import lombok.Getter; import lombok.Setter; /** * This class provides methods for reading files from the web. * * @author <NAME> */ public class WebDataRetriever implements IDataRetriever { private static final Logger LOGGER = LoggerFactory.getLogger(WebDataRetriever.class); private final Gson gson; private final IntegerParameter retriesParam; @Setter private int timeout; @Getter @Setter private Charset charset; /** * Constructor that sets the GSON (de-)serializer for reading and * writing JSON objects, as well as the charset and timeout. * * @param gson the GSON (de-)serializer for reading and writing JSON objects * @param charset the charset of the files to be read and written * @param timeout the web request timeout in milliseconds */ public WebDataRetriever(final Gson gson, final Charset charset, final int timeout) { this.gson = gson; this.charset = charset; this.timeout = timeout; // set up retries parameters IntegerParameter retriesTemp; try { retriesTemp = Configuration.registerParameter(DataOperationConstants.RETRIES_PARAM); } catch (final IllegalStateException e) { retriesTemp = DataOperationConstants.RETRIES_PARAM; } this.retriesParam = retriesTemp; } /** * Constructor that sets the GSON (de-)serializer for reading and * writing JSON objects, as well as the charset. * * @param gson the GSON (de-)serializer for reading and writing JSON objects * @param charset the charset of the files to be read and written */ public WebDataRetriever(final Gson gson, final Charset charset) { this(gson, charset, DataOperationConstants.NO_TIMEOUT); } /** * Constructor that copies settings from another {@linkplain WebDataRetriever}. * * @param other the {@linkplain WebDataRetriever} of which the settings are copied */ public WebDataRetriever(final WebDataRetriever other) { this(other.gson, other.charset, other.timeout); } @Override public String getString(final String url) { String responseText = null; try (BufferedReader reader = new BufferedReader(createWebReader(url))) { // read the first line of the response String line = reader.readLine(); // make sure we got a response if (line != null) { final StringBuilder responseBuilder = new StringBuilder(line); // read subsequent lines of the response line = reader.readLine(); while (line != null) { // add linebreak before appending the next line responseBuilder.append('\n').append(line); line = reader.readLine(); } responseText = responseBuilder.toString(); } } catch (final IOException e) { LOGGER.warn(String.format(DataOperationConstants.WEB_ERROR_JSON, url), e); } return responseText; } @Override public <T> T getObject(final String url, final Class<T> targetClass) { T object = null; try (InputStreamReader reader = createWebReader(url)) { object = gson.fromJson(reader, targetClass); } catch (IOException | IllegalStateException | JsonIOException | JsonSyntaxException e) { LOGGER.warn(String.format(DataOperationConstants.WEB_ERROR_JSON, url), e); } return object; } @Override public <T> T getObject(final String url, final Type targetType) { T object = null; try (InputStreamReader reader = createWebReader(url)) { object = gson.fromJson(reader, targetType); } catch (IOException | IllegalStateException | JsonIOException | JsonSyntaxException e) { LOGGER.warn(String.format(DataOperationConstants.WEB_ERROR_JSON, url), e); } return object; } @Override public Document getHtml(final String url) { try { final HttpURLConnection connection = sendWebRequest( RestRequestType.GET, url, null, null, MediaType.TEXT_PLAIN, retriesParam.getValue()); return Jsoup.parse(this.getInputStream(connection), charset.displayName(), url); } catch (final IOException | HTTPException e) { LOGGER.warn(String.format(DataOperationConstants.WEB_ERROR_JSON, url), e); return null; } } /** * Sends an authorized REST request with a specified body and returns the * response as a string. * * @param method the request method that is being sent * @param url the URL to which the request is being sent * @param body the body of the request, or null if no body is to be sent * @param authorization the base-64-encoded username and password, or null if no * authorization is required * @param contentType the contentType of the body * * @throws HTTPException thrown if the response code is not 2xx * @throws IOException thrown if the response output stream could not be created * * @return the HTTP response as plain text */ public String getRestResponse(final RestRequestType method, final String url, final String body, final String authorization, final String contentType) throws HTTPException, IOException { final HttpURLConnection connection = sendWebRequest(method, url, body, authorization, contentType, retriesParam.getValue()); String responseText = null; // create a reader for the HTTP response try (InputStream response = this.getInputStream(connection); BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { final char[] readBuffer = new char[1024]; final StringBuilder responseBuilder = new StringBuilder(); int readBytes; while (true) { readBytes = reader.read(readBuffer, 0, 1024); if (readBytes == -1) break; responseBuilder.append(readBuffer, 0, readBytes); } responseText = responseBuilder.toString(); } // combine the read lines to a single string return responseText; } /** * Sends an authorized REST request with a specified body and returns the * header fields. * * @param method the request method that is being sent * @param url the URL to which the request is being sent * @param body the body of the request, or null if no body is to be sent * @param authorization the base-64-encoded username and password, or null if no * authorization is required * @param contentType the contentType of the body * * @throws HTTPException thrown if the response code is not 2xx * @throws IOException thrown if the response output stream could not be created * * @return the response header fields, or null if the response could not be parsed */ public Map<String, List<String>> getRestHeader(final RestRequestType method, final String url, final String body, final String authorization, final String contentType) throws HTTPException, IOException { Map<String, List<String>> headerFields = null; final HttpURLConnection connection = sendWebRequest(method, url, body, authorization, contentType, retriesParam.getValue()); headerFields = connection.getHeaderFields(); return headerFields; } /** * Sends a REST request with a specified body and returns the connection. * * @param method the request method that is being sent * @param urlString the URL to which the request is being sent * @param body the body of the request, or null if no body is to be sent * @param authorization the base-64-encoded username and password, or null if no * authorization is required * @param contentType the contentType of the body * @param retries the number of retries if the request fails with a response code 5xx * * @throws HTTPException thrown if the response code is not 2xx * @throws IOException thrown if the response output stream could not be created * * @return the connection to the host */ public HttpURLConnection sendWebRequest(final RestRequestType method, final String urlString, final String body, final String authorization, final String contentType, final int retries) throws IOException, HTTPException { // generate a URL and open a connection final URL url = new URL(urlString); final HttpURLConnection connection = createConnection(method, url, body, authorization, contentType); boolean mustRetry = false; // open the connection try { final int responseCode = connection.getResponseCode(); if (responseCode >= 300) connection.disconnect(); if (responseCode >= 500) { mustRetry = retries != 0; // throw an error if the request is not to be reattempted if (!mustRetry) { final String errorMessage = String.format( DataOperationConstants.WEB_ERROR_REST_HTTP, method.toString(), urlString, body, responseCode); throw new HttpStatusException(errorMessage, responseCode, urlString); } } else if (responseCode < 400) { final String redirectedUrl = connection.getHeaderField(HttpHeaders.LOCATION); final boolean canRedirect; // check if there is a redirection URL if (redirectedUrl == null) canRedirect = false; else { // disallow redirects from HTTPS to HTTP canRedirect = !urlString.startsWith(DataOperationConstants.HTTPS) || redirectedUrl.startsWith(DataOperationConstants.HTTPS); } // redirect only if all above conditions are met if (canRedirect) return sendWebRequest(method, redirectedUrl, body, authorization, contentType, retries); } } catch (final SocketTimeoutException e) { // if we time out, try again if (retries == 0) throw e; else mustRetry = true; } // if the request failed due to server issues, attempt to retry if (mustRetry) { // if the response header contains a retry-after field, wait for that period before retrying final int delayInSeconds = connection.getHeaderFieldInt(RestConstants.RETRY_AFTER_HEADER, 1); LOGGER.debug(String.format(DataOperationConstants.RETRY, urlString, delayInSeconds)); try { Thread.sleep(delayInSeconds * 1000); } catch (final InterruptedException e) { throw new IOException(e); } return sendWebRequest(method, urlString, body, authorization, contentType, Math.max(retries - 1, -1)); } else return connection; } /** * Sets up a {@linkplain HttpURLConnection} connection with specified properties. * * @param method the request method that is being sent * @param url the URL to which the connection is to be established * @param body the body of the request, or null if no body is to be sent * @param authorization the base-64-encoded username and password, or null if no * authorization is required * @param contentType the contentType of the body * * @throws IOException thrown if the response output stream could not be created * * @return the connection to the host */ private HttpURLConnection createConnection(final RestRequestType method, final URL url, final String body, final String authorization, final String contentType) throws IOException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // set request properties connection.setDoOutput(true); connection.setInstanceFollowRedirects(true); connection.setUseCaches(false); connection.setRequestMethod(method.toString()); connection.setRequestProperty(HttpHeaders.ACCEPT_CHARSET, charset.displayName().toLowerCase(Locale.ENGLISH)); connection.setRequestProperty(HttpHeaders.ACCEPT_ENCODING, DataOperationConstants.GZIP_ENCODING); connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType); // set timeout if (timeout != DataOperationConstants.NO_TIMEOUT) { connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); } // set authentication if (authorization != null) connection.setRequestProperty(HttpHeaders.AUTHORIZATION, authorization); // only send data if it is specified if (body != null) { // convert body string to bytes final byte[] bodyBytes = body.getBytes(charset); connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, Integer.toString(bodyBytes.length)); // try to send body final DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(bodyBytes); wr.close(); } return connection; } /** * Returns the correct InputStream based on the Content-Encoding header of * a connection. Necessary to support compression. * * @param connection the connection to be checked * * @throws IOException thrown if InputStream is corrupted * * @return an InputStream subclass */ public InputStream getInputStream(final HttpURLConnection connection) throws IOException { // if encoding is gzip and is not a HEAD request (SAI-1607), use the GZIP stream if (DataOperationConstants.GZIP_ENCODING.equals(connection.getContentEncoding()) && !DataOperationConstants.HEAD_REQUEST.equals(connection.getRequestMethod())) return new GZIPInputStream(connection.getInputStream()); return connection.getInputStream(); } /** * Creates an input stream reader of a specified URL. * * @param url the URL of which the response is to be read * * @return a reader of the URL response * * @throws MalformedURLException thrown when the URL is malformed * @throws IOException thrown for various reasons when the reader is created */ private InputStreamReader createWebReader(final String url) throws MalformedURLException, IOException { final HttpURLConnection connection = sendWebRequest( RestRequestType.GET, url, null, null, MediaType.TEXT_PLAIN, retriesParam.getValue()); return new InputStreamReader(this.getInputStream(connection), charset); } }
17,481
0.647341
0.644197
464
36.693966
34.456448
189
false
false
0
0
0
0
0
0
0.547414
false
false
9
f726350abbb12ed157d42418ef16a5bbabbf6ad7
18,708,877,560,224
bf13edfb670568a7e33bf0c5cb2dabaf98f03e75
/app/src/main/java-gen/nautictracker/TrackPointDao.java
e5b46df021f1dfffb2f249554e98d4605537d453
[ "MIT" ]
permissive
thymikee/NauticTracker
https://github.com/thymikee/NauticTracker
f96ad8a9a46ddb736c2cfcbbad5189cb24bb28fa
af3ff319631c57dc56cf0acdbd06b91a3c674dd5
refs/heads/master
2021-05-03T14:58:19.664000
2014-12-23T13:10:27
2014-12-23T13:10:27
27,333,629
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nautictracker; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.Property; import de.greenrobot.dao.internal.DaoConfig; import nautictracker.TrackPoint; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table TRACK_POINT. */ public class TrackPointDao extends AbstractDao<TrackPoint, Long> { public static final String TABLENAME = "TRACK_POINT"; /** * Properties of entity TrackPoint.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Trip_id = new Property(0, Long.class, "trip_id", true, "TRIP_ID"); public final static Property Latitude = new Property(1, String.class, "latitude", false, "LATITUDE"); public final static Property Longitude = new Property(2, String.class, "longitude", false, "LONGITUDE"); public final static Property Timestamp = new Property(3, java.util.Date.class, "timestamp", false, "TIMESTAMP"); public final static Property Sequence = new Property(4, Long.class, "sequence", false, "SEQUENCE"); }; public TrackPointDao(DaoConfig config) { super(config); } public TrackPointDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(SQLiteDatabase db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "'TRACK_POINT' (" + // "'TRIP_ID' INTEGER PRIMARY KEY ," + // 0: trip_id "'LATITUDE' TEXT," + // 1: latitude "'LONGITUDE' TEXT," + // 2: longitude "'TIMESTAMP' INTEGER," + // 3: timestamp "'SEQUENCE' INTEGER);"); // 4: sequence } /** Drops the underlying database table. */ public static void dropTable(SQLiteDatabase db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'TRACK_POINT'"; db.execSQL(sql); } /** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, TrackPoint entity) { stmt.clearBindings(); Long trip_id = entity.getTrip_id(); if (trip_id != null) { stmt.bindLong(1, trip_id); } String latitude = entity.getLatitude(); if (latitude != null) { stmt.bindString(2, latitude); } String longitude = entity.getLongitude(); if (longitude != null) { stmt.bindString(3, longitude); } java.util.Date timestamp = entity.getTimestamp(); if (timestamp != null) { stmt.bindLong(4, timestamp.getTime()); } Long sequence = entity.getSequence(); if (sequence != null) { stmt.bindLong(5, sequence); } } /** @inheritdoc */ @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } /** @inheritdoc */ @Override public TrackPoint readEntity(Cursor cursor, int offset) { TrackPoint entity = new TrackPoint( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // trip_id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // latitude cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // longitude cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)), // timestamp cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4) // sequence ); return entity; } /** @inheritdoc */ @Override public void readEntity(Cursor cursor, TrackPoint entity, int offset) { entity.setTrip_id(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setLatitude(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setLongitude(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); entity.setTimestamp(cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3))); entity.setSequence(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4)); } /** @inheritdoc */ @Override protected Long updateKeyAfterInsert(TrackPoint entity, long rowId) { entity.setTrip_id(rowId); return rowId; } /** @inheritdoc */ @Override public Long getKey(TrackPoint entity) { if(entity != null) { return entity.getTrip_id(); } else { return null; } } /** @inheritdoc */ @Override protected boolean isEntityUpdateable() { return true; } }
UTF-8
Java
5,148
java
TrackPointDao.java
Java
[]
null
[]
package nautictracker; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.Property; import de.greenrobot.dao.internal.DaoConfig; import nautictracker.TrackPoint; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table TRACK_POINT. */ public class TrackPointDao extends AbstractDao<TrackPoint, Long> { public static final String TABLENAME = "TRACK_POINT"; /** * Properties of entity TrackPoint.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Trip_id = new Property(0, Long.class, "trip_id", true, "TRIP_ID"); public final static Property Latitude = new Property(1, String.class, "latitude", false, "LATITUDE"); public final static Property Longitude = new Property(2, String.class, "longitude", false, "LONGITUDE"); public final static Property Timestamp = new Property(3, java.util.Date.class, "timestamp", false, "TIMESTAMP"); public final static Property Sequence = new Property(4, Long.class, "sequence", false, "SEQUENCE"); }; public TrackPointDao(DaoConfig config) { super(config); } public TrackPointDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(SQLiteDatabase db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "'TRACK_POINT' (" + // "'TRIP_ID' INTEGER PRIMARY KEY ," + // 0: trip_id "'LATITUDE' TEXT," + // 1: latitude "'LONGITUDE' TEXT," + // 2: longitude "'TIMESTAMP' INTEGER," + // 3: timestamp "'SEQUENCE' INTEGER);"); // 4: sequence } /** Drops the underlying database table. */ public static void dropTable(SQLiteDatabase db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'TRACK_POINT'"; db.execSQL(sql); } /** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, TrackPoint entity) { stmt.clearBindings(); Long trip_id = entity.getTrip_id(); if (trip_id != null) { stmt.bindLong(1, trip_id); } String latitude = entity.getLatitude(); if (latitude != null) { stmt.bindString(2, latitude); } String longitude = entity.getLongitude(); if (longitude != null) { stmt.bindString(3, longitude); } java.util.Date timestamp = entity.getTimestamp(); if (timestamp != null) { stmt.bindLong(4, timestamp.getTime()); } Long sequence = entity.getSequence(); if (sequence != null) { stmt.bindLong(5, sequence); } } /** @inheritdoc */ @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } /** @inheritdoc */ @Override public TrackPoint readEntity(Cursor cursor, int offset) { TrackPoint entity = new TrackPoint( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // trip_id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // latitude cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // longitude cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)), // timestamp cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4) // sequence ); return entity; } /** @inheritdoc */ @Override public void readEntity(Cursor cursor, TrackPoint entity, int offset) { entity.setTrip_id(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setLatitude(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setLongitude(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); entity.setTimestamp(cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3))); entity.setSequence(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4)); } /** @inheritdoc */ @Override protected Long updateKeyAfterInsert(TrackPoint entity, long rowId) { entity.setTrip_id(rowId); return rowId; } /** @inheritdoc */ @Override public Long getKey(TrackPoint entity) { if(entity != null) { return entity.getTrip_id(); } else { return null; } } /** @inheritdoc */ @Override protected boolean isEntityUpdateable() { return true; } }
5,148
0.592463
0.585276
142
34.253521
31.369545
120
false
false
0
0
0
0
0
0
0.640845
false
false
9
8876114755d7008ce0b7d65cfd90f1dea9d11d4b
22,857,815,970,681
b8b3f03b332672064e55a51a678a0cf95fc993db
/tiantian-service/service-item/item-service/src/main/java/com/tiantian/item/main/Main.java
4c6208d0df1610bea307fbcdc37d7051cebd03d4
[]
no_license
liuzw220/tiantian-dubbo
https://github.com/liuzw220/tiantian-dubbo
4dff22db0f97bbcb80ad013db4f3f2bb430280e9
904e0c4f7b4d1acde5383c5c902b5bb1d3647ba6
refs/heads/master
2021-01-12T05:51:48.866000
2018-11-01T08:06:28
2018-11-01T08:06:28
77,214,786
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tiantian.item.main; public class Main { public static void main(String[] args) throws Exception { com.alibaba.dubbo.container.Main.main(args); /*ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/*.xml"); context.start(); Thread.sleep(2000); //UserServiceImp user=context.getBean(UserServiceImp.class); System.out.println("dubbo-server服务正在监听,按任意键退出"); System.in.read();*/ } }
UTF-8
Java
477
java
Main.java
Java
[]
null
[]
package com.tiantian.item.main; public class Main { public static void main(String[] args) throws Exception { com.alibaba.dubbo.container.Main.main(args); /*ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/*.xml"); context.start(); Thread.sleep(2000); //UserServiceImp user=context.getBean(UserServiceImp.class); System.out.println("dubbo-server服务正在监听,按任意键退出"); System.in.read();*/ } }
477
0.751663
0.742794
14
31.142857
29.301041
106
false
false
0
0
0
0
0
0
1.785714
false
false
9
ec4fff4e28c094a32e91a19b4f327a67f46408c0
2,439,541,447,105
97f9ce24c8d289ad182beb91862309ac406b5aff
/src/main/java/vn/com/vndirect/assignment/backend/IStockInfoService.java
e10cd07d7af4e654574485cc673a8ff4dc0e441d
[]
no_license
tungtrandinh/nettycxfservices
https://github.com/tungtrandinh/nettycxfservices
eff4d5acf4c94c370b6335ad723add09dcc41006
5d170bf07e4f21d64e8571962bc603247e247f6f
refs/heads/master
2020-05-29T18:45:15.333000
2014-08-05T06:35:48
2014-08-05T06:35:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vn.com.vndirect.assignment.backend; import vn.com.vndirect.assignment.model.StockInfo; public interface IStockInfoService { public StockInfo getPrice(String stockCode); }
UTF-8
Java
182
java
IStockInfoService.java
Java
[]
null
[]
package vn.com.vndirect.assignment.backend; import vn.com.vndirect.assignment.model.StockInfo; public interface IStockInfoService { public StockInfo getPrice(String stockCode); }
182
0.824176
0.824176
7
25
21.699244
50
false
false
0
0
0
0
0
0
0.571429
false
false
9
83cd68d41522cec070bbc9d6665b54b70a7bd873
9,208,409,908,829
c39540998048f494e9f0006d3cc7711d5756af25
/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/extensions/dynamodb/mappingclient/operations/CreateTable.java
d6f1e7af62c5b0b1d789d42402dc156161ce94ec
[ "Apache-2.0" ]
permissive
tomarskt/aws-sdk-java-v2
https://github.com/tomarskt/aws-sdk-java-v2
c845f9813274c8b3e673eb6c464ad3f9f5329bcf
138def267fc8814418e5b7c8ab80f038b9d40641
refs/heads/master
2020-12-23T09:22:55.770000
2020-01-28T22:16:46
2020-01-29T16:26:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.extensions.dynamodb.mappingclient.operations; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.extensions.dynamodb.mappingclient.MapperExtension; import software.amazon.awssdk.extensions.dynamodb.mappingclient.OperationContext; import software.amazon.awssdk.extensions.dynamodb.mappingclient.TableMetadata; import software.amazon.awssdk.extensions.dynamodb.mappingclient.TableOperation; import software.amazon.awssdk.extensions.dynamodb.mappingclient.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.BillingMode; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; @SdkPublicApi public class CreateTable<T> implements TableOperation<T, CreateTableRequest, CreateTableResponse, Void> { private final ProvisionedThroughput provisionedThroughput; private final Collection<LocalSecondaryIndex> localSecondaryIndices; private final Collection<GlobalSecondaryIndex> globalSecondaryIndices; private CreateTable(ProvisionedThroughput provisionedThroughput, Collection<LocalSecondaryIndex> localSecondaryIndices, Collection<GlobalSecondaryIndex> globalSecondaryIndices) { this.provisionedThroughput = provisionedThroughput; this.localSecondaryIndices = localSecondaryIndices; this.globalSecondaryIndices = globalSecondaryIndices; } public static <T> CreateTable<T> create(ProvisionedThroughput provisionedThroughput) { return new CreateTable<>(provisionedThroughput, null, null); } public static <T> CreateTable<T> create() { return new CreateTable<>(null, null, null); } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return new Builder().provisionedThroughput(provisionedThroughput) .localSecondaryIndices(localSecondaryIndices) .globalSecondaryIndices(globalSecondaryIndices); } @Override public CreateTableRequest generateRequest(TableSchema<T> tableSchema, OperationContext operationContext, MapperExtension mapperExtension) { if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) { throw new IllegalArgumentException("PutItem cannot be executed against a secondary index."); } String primaryPartitionKey = tableSchema.tableMetadata().primaryPartitionKey(); Optional<String> primarySortKey = tableSchema.tableMetadata().primarySortKey(); Set<String> dedupedIndexKeys = new HashSet<>(); dedupedIndexKeys.add(primaryPartitionKey); primarySortKey.ifPresent(dedupedIndexKeys::add); List<software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex> sdkGlobalSecondaryIndices = null; List<software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex> sdkLocalSecondaryIndices = null; if (globalSecondaryIndices != null) { sdkGlobalSecondaryIndices = this.globalSecondaryIndices.stream().map(gsi -> { String indexPartitionKey = tableSchema.tableMetadata().indexPartitionKey(gsi.indexName()); Optional<String> indexSortKey = tableSchema.tableMetadata().indexSortKey(gsi.indexName()); dedupedIndexKeys.add(indexPartitionKey); indexSortKey.ifPresent(dedupedIndexKeys::add); return software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex .builder() .indexName(gsi.indexName()) .keySchema(generateKeySchema(indexPartitionKey, indexSortKey.orElse(null))) .projection(gsi.projection()) .provisionedThroughput(gsi.provisionedThroughput()) .build(); }).collect(Collectors.toList()); } if (localSecondaryIndices != null) { sdkLocalSecondaryIndices = this.localSecondaryIndices.stream().map(lsi -> { Optional<String> indexSortKey = tableSchema.tableMetadata().indexSortKey(lsi.indexName()); indexSortKey.ifPresent(dedupedIndexKeys::add); if (!primaryPartitionKey.equals( tableSchema.tableMetadata().indexPartitionKey(lsi.indexName()))) { throw new IllegalArgumentException("Attempt to create a local secondary index with a partition " + "key that is not the primary partition key. Index name: " + lsi.indexName()); } return software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex .builder() .indexName(lsi.indexName()) .keySchema(generateKeySchema(primaryPartitionKey, indexSortKey.orElse(null))) .projection(lsi.projection()) .build(); }).collect(Collectors.toList()); } List<AttributeDefinition> attributeDefinitions = dedupedIndexKeys.stream() .map(attribute -> AttributeDefinition.builder() .attributeName(attribute) .attributeType(tableSchema.tableMetadata() .scalarAttributeType(attribute) .orElseThrow(() -> new IllegalArgumentException("Could not map the key attribute '" + attribute + "' to a valid scalar type."))) .build()) .collect(Collectors.toList()); BillingMode billingMode = provisionedThroughput == null ? BillingMode.PAY_PER_REQUEST : BillingMode.PROVISIONED; return CreateTableRequest.builder() .tableName(operationContext.tableName()) .keySchema(generateKeySchema(primaryPartitionKey, primarySortKey.orElse(null))) .globalSecondaryIndexes(sdkGlobalSecondaryIndices) .localSecondaryIndexes(sdkLocalSecondaryIndices) .attributeDefinitions(attributeDefinitions) .billingMode(billingMode) .provisionedThroughput(provisionedThroughput) .build(); } @Override public Function<CreateTableRequest, CreateTableResponse> serviceCall(DynamoDbClient dynamoDbClient) { return dynamoDbClient::createTable; } @Override public Function<CreateTableRequest, CompletableFuture<CreateTableResponse>> asyncServiceCall( DynamoDbAsyncClient dynamoDbAsyncClient) { return dynamoDbAsyncClient::createTable; } @Override public Void transformResponse(CreateTableResponse response, TableSchema<T> tableSchema, OperationContext operationContext, MapperExtension mapperExtension) { // This operation does not return results return null; } public ProvisionedThroughput provisionedThroughput() { return provisionedThroughput; } public Collection<LocalSecondaryIndex> localSecondaryIndices() { return localSecondaryIndices; } public Collection<GlobalSecondaryIndex> globalSecondaryIndices() { return globalSecondaryIndices; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateTable<?> that = (CreateTable<?>) o; if (provisionedThroughput != null ? ! provisionedThroughput.equals(that.provisionedThroughput) : that.provisionedThroughput != null) { return false; } if (localSecondaryIndices != null ? ! localSecondaryIndices.equals(that.localSecondaryIndices) : that.localSecondaryIndices != null) { return false; } return globalSecondaryIndices != null ? globalSecondaryIndices.equals(that.globalSecondaryIndices) : that.globalSecondaryIndices == null; } @Override public int hashCode() { int result = provisionedThroughput != null ? provisionedThroughput.hashCode() : 0; result = 31 * result + (localSecondaryIndices != null ? localSecondaryIndices.hashCode() : 0); result = 31 * result + (globalSecondaryIndices != null ? globalSecondaryIndices.hashCode() : 0); return result; } public static final class Builder { private ProvisionedThroughput provisionedThroughput; private Collection<LocalSecondaryIndex> localSecondaryIndices; private Collection<GlobalSecondaryIndex> globalSecondaryIndices; private Builder() { } public Builder provisionedThroughput(ProvisionedThroughput provisionedThroughput) { this.provisionedThroughput = provisionedThroughput; return this; } public Builder localSecondaryIndices(Collection<LocalSecondaryIndex> localSecondaryIndices) { this.localSecondaryIndices = localSecondaryIndices; return this; } public Builder localSecondaryIndices(LocalSecondaryIndex... localSecondaryIndices) { this.localSecondaryIndices = Arrays.asList(localSecondaryIndices); return this; } public Builder globalSecondaryIndices(Collection<GlobalSecondaryIndex> globalSecondaryIndices) { this.globalSecondaryIndices = globalSecondaryIndices; return this; } public Builder globalSecondaryIndices(GlobalSecondaryIndex... globalSecondaryIndices) { this.globalSecondaryIndices = Arrays.asList(globalSecondaryIndices); return this; } public <T> CreateTable<T> build() { return new CreateTable<>(provisionedThroughput, localSecondaryIndices, globalSecondaryIndices); } } private static Collection<KeySchemaElement> generateKeySchema(String partitionKey, String sortKey) { if (sortKey == null) { return generateKeySchema(partitionKey); } return Collections.unmodifiableList(Arrays.asList(KeySchemaElement.builder() .attributeName(partitionKey) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(sortKey) .keyType(KeyType.RANGE) .build())); } private static Collection<KeySchemaElement> generateKeySchema(String partitionKey) { return Collections.singletonList(KeySchemaElement.builder() .attributeName(partitionKey) .keyType(KeyType.HASH) .build()); } }
UTF-8
Java
13,506
java
CreateTable.java
Java
[]
null
[]
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.extensions.dynamodb.mappingclient.operations; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.extensions.dynamodb.mappingclient.MapperExtension; import software.amazon.awssdk.extensions.dynamodb.mappingclient.OperationContext; import software.amazon.awssdk.extensions.dynamodb.mappingclient.TableMetadata; import software.amazon.awssdk.extensions.dynamodb.mappingclient.TableOperation; import software.amazon.awssdk.extensions.dynamodb.mappingclient.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.BillingMode; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; @SdkPublicApi public class CreateTable<T> implements TableOperation<T, CreateTableRequest, CreateTableResponse, Void> { private final ProvisionedThroughput provisionedThroughput; private final Collection<LocalSecondaryIndex> localSecondaryIndices; private final Collection<GlobalSecondaryIndex> globalSecondaryIndices; private CreateTable(ProvisionedThroughput provisionedThroughput, Collection<LocalSecondaryIndex> localSecondaryIndices, Collection<GlobalSecondaryIndex> globalSecondaryIndices) { this.provisionedThroughput = provisionedThroughput; this.localSecondaryIndices = localSecondaryIndices; this.globalSecondaryIndices = globalSecondaryIndices; } public static <T> CreateTable<T> create(ProvisionedThroughput provisionedThroughput) { return new CreateTable<>(provisionedThroughput, null, null); } public static <T> CreateTable<T> create() { return new CreateTable<>(null, null, null); } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return new Builder().provisionedThroughput(provisionedThroughput) .localSecondaryIndices(localSecondaryIndices) .globalSecondaryIndices(globalSecondaryIndices); } @Override public CreateTableRequest generateRequest(TableSchema<T> tableSchema, OperationContext operationContext, MapperExtension mapperExtension) { if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) { throw new IllegalArgumentException("PutItem cannot be executed against a secondary index."); } String primaryPartitionKey = tableSchema.tableMetadata().primaryPartitionKey(); Optional<String> primarySortKey = tableSchema.tableMetadata().primarySortKey(); Set<String> dedupedIndexKeys = new HashSet<>(); dedupedIndexKeys.add(primaryPartitionKey); primarySortKey.ifPresent(dedupedIndexKeys::add); List<software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex> sdkGlobalSecondaryIndices = null; List<software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex> sdkLocalSecondaryIndices = null; if (globalSecondaryIndices != null) { sdkGlobalSecondaryIndices = this.globalSecondaryIndices.stream().map(gsi -> { String indexPartitionKey = tableSchema.tableMetadata().indexPartitionKey(gsi.indexName()); Optional<String> indexSortKey = tableSchema.tableMetadata().indexSortKey(gsi.indexName()); dedupedIndexKeys.add(indexPartitionKey); indexSortKey.ifPresent(dedupedIndexKeys::add); return software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex .builder() .indexName(gsi.indexName()) .keySchema(generateKeySchema(indexPartitionKey, indexSortKey.orElse(null))) .projection(gsi.projection()) .provisionedThroughput(gsi.provisionedThroughput()) .build(); }).collect(Collectors.toList()); } if (localSecondaryIndices != null) { sdkLocalSecondaryIndices = this.localSecondaryIndices.stream().map(lsi -> { Optional<String> indexSortKey = tableSchema.tableMetadata().indexSortKey(lsi.indexName()); indexSortKey.ifPresent(dedupedIndexKeys::add); if (!primaryPartitionKey.equals( tableSchema.tableMetadata().indexPartitionKey(lsi.indexName()))) { throw new IllegalArgumentException("Attempt to create a local secondary index with a partition " + "key that is not the primary partition key. Index name: " + lsi.indexName()); } return software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex .builder() .indexName(lsi.indexName()) .keySchema(generateKeySchema(primaryPartitionKey, indexSortKey.orElse(null))) .projection(lsi.projection()) .build(); }).collect(Collectors.toList()); } List<AttributeDefinition> attributeDefinitions = dedupedIndexKeys.stream() .map(attribute -> AttributeDefinition.builder() .attributeName(attribute) .attributeType(tableSchema.tableMetadata() .scalarAttributeType(attribute) .orElseThrow(() -> new IllegalArgumentException("Could not map the key attribute '" + attribute + "' to a valid scalar type."))) .build()) .collect(Collectors.toList()); BillingMode billingMode = provisionedThroughput == null ? BillingMode.PAY_PER_REQUEST : BillingMode.PROVISIONED; return CreateTableRequest.builder() .tableName(operationContext.tableName()) .keySchema(generateKeySchema(primaryPartitionKey, primarySortKey.orElse(null))) .globalSecondaryIndexes(sdkGlobalSecondaryIndices) .localSecondaryIndexes(sdkLocalSecondaryIndices) .attributeDefinitions(attributeDefinitions) .billingMode(billingMode) .provisionedThroughput(provisionedThroughput) .build(); } @Override public Function<CreateTableRequest, CreateTableResponse> serviceCall(DynamoDbClient dynamoDbClient) { return dynamoDbClient::createTable; } @Override public Function<CreateTableRequest, CompletableFuture<CreateTableResponse>> asyncServiceCall( DynamoDbAsyncClient dynamoDbAsyncClient) { return dynamoDbAsyncClient::createTable; } @Override public Void transformResponse(CreateTableResponse response, TableSchema<T> tableSchema, OperationContext operationContext, MapperExtension mapperExtension) { // This operation does not return results return null; } public ProvisionedThroughput provisionedThroughput() { return provisionedThroughput; } public Collection<LocalSecondaryIndex> localSecondaryIndices() { return localSecondaryIndices; } public Collection<GlobalSecondaryIndex> globalSecondaryIndices() { return globalSecondaryIndices; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateTable<?> that = (CreateTable<?>) o; if (provisionedThroughput != null ? ! provisionedThroughput.equals(that.provisionedThroughput) : that.provisionedThroughput != null) { return false; } if (localSecondaryIndices != null ? ! localSecondaryIndices.equals(that.localSecondaryIndices) : that.localSecondaryIndices != null) { return false; } return globalSecondaryIndices != null ? globalSecondaryIndices.equals(that.globalSecondaryIndices) : that.globalSecondaryIndices == null; } @Override public int hashCode() { int result = provisionedThroughput != null ? provisionedThroughput.hashCode() : 0; result = 31 * result + (localSecondaryIndices != null ? localSecondaryIndices.hashCode() : 0); result = 31 * result + (globalSecondaryIndices != null ? globalSecondaryIndices.hashCode() : 0); return result; } public static final class Builder { private ProvisionedThroughput provisionedThroughput; private Collection<LocalSecondaryIndex> localSecondaryIndices; private Collection<GlobalSecondaryIndex> globalSecondaryIndices; private Builder() { } public Builder provisionedThroughput(ProvisionedThroughput provisionedThroughput) { this.provisionedThroughput = provisionedThroughput; return this; } public Builder localSecondaryIndices(Collection<LocalSecondaryIndex> localSecondaryIndices) { this.localSecondaryIndices = localSecondaryIndices; return this; } public Builder localSecondaryIndices(LocalSecondaryIndex... localSecondaryIndices) { this.localSecondaryIndices = Arrays.asList(localSecondaryIndices); return this; } public Builder globalSecondaryIndices(Collection<GlobalSecondaryIndex> globalSecondaryIndices) { this.globalSecondaryIndices = globalSecondaryIndices; return this; } public Builder globalSecondaryIndices(GlobalSecondaryIndex... globalSecondaryIndices) { this.globalSecondaryIndices = Arrays.asList(globalSecondaryIndices); return this; } public <T> CreateTable<T> build() { return new CreateTable<>(provisionedThroughput, localSecondaryIndices, globalSecondaryIndices); } } private static Collection<KeySchemaElement> generateKeySchema(String partitionKey, String sortKey) { if (sortKey == null) { return generateKeySchema(partitionKey); } return Collections.unmodifiableList(Arrays.asList(KeySchemaElement.builder() .attributeName(partitionKey) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(sortKey) .keyType(KeyType.RANGE) .build())); } private static Collection<KeySchemaElement> generateKeySchema(String partitionKey) { return Collections.singletonList(KeySchemaElement.builder() .attributeName(partitionKey) .keyType(KeyType.HASH) .build()); } }
13,506
0.612987
0.61158
282
46.893616
36.073349
120
false
false
0
0
0
0
0
0
0.425532
false
false
9
15b50f7dbf3752e4fd69da928266aae106f0da30
21,887,153,359,665
19b949f7fb4345fbc438d5c005e6fbf64b72cc57
/src/main/java/com/luv2code/jackson/json/demo/Driver.java
8d59218f5a28bc72a409ad12aeb46614c6f5ecc1
[]
no_license
tonymnshk/jackson-data-binding
https://github.com/tonymnshk/jackson-data-binding
130452ec5aa620fdbdbfef550262039709aa9898
d43bde696d781400123dd7d7d76b9ea7b65f0547
refs/heads/master
2020-03-16T06:24:38.227000
2018-05-08T04:25:21
2018-05-08T04:25:21
132,553,721
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.luv2code.jackson.json.demo; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; /** * Created by Tony Cai on 5/7/2018 */ public class Driver { public static void main(String[] args) { System.out.println(System.getProperty("user.dir")); try { // create the object mapper ObjectMapper mapper = new ObjectMapper(); // read JSON file and map/convert to Java POJO: // data/sample-lite.json Student theStudent = mapper.readValue(new File("data/sample-full.json"), Student.class); /*ClassLoader loader = ClassLoader.getSystemClassLoader(); Student theStudent = mapper.readValue( new File(loader.getResource("data/sample-lite.json").getFile()), Student.class);*/ // print first name and last name System.out.println(theStudent); } catch (Exception exc) { exc.printStackTrace(); } } }
UTF-8
Java
996
java
Driver.java
Java
[ { "context": "ctMapper;\n\nimport java.io.File;\n\n/**\n * Created by Tony Cai on 5/7/2018\n */\npublic class Driver {\n public ", "end": 142, "score": 0.999859094619751, "start": 134, "tag": "NAME", "value": "Tony Cai" } ]
null
[]
package com.luv2code.jackson.json.demo; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; /** * Created by <NAME> on 5/7/2018 */ public class Driver { public static void main(String[] args) { System.out.println(System.getProperty("user.dir")); try { // create the object mapper ObjectMapper mapper = new ObjectMapper(); // read JSON file and map/convert to Java POJO: // data/sample-lite.json Student theStudent = mapper.readValue(new File("data/sample-full.json"), Student.class); /*ClassLoader loader = ClassLoader.getSystemClassLoader(); Student theStudent = mapper.readValue( new File(loader.getResource("data/sample-lite.json").getFile()), Student.class);*/ // print first name and last name System.out.println(theStudent); } catch (Exception exc) { exc.printStackTrace(); } } }
994
0.613454
0.606426
31
31.161291
28.260422
102
false
false
0
0
0
0
0
0
0.387097
false
false
9
996dffca8d424e3fac55e5476fd65d2ddacfda50
21,887,153,362,184
a137796d0bfaf93506d829fa5ad6a9e9ebabfc51
/ActiTime_Project_3_3_2016/src/Browser_Commands_3/WebElementsCommands.java
c6abbdbaa41bcb05f0dbf39e8d5cd732b5eea319
[]
no_license
Nallappa/Actitimeproject
https://github.com/Nallappa/Actitimeproject
243411235d39824b9f5cf205f50b1da3444f15bb
e020e0f897cb79a91d02b6b40b4e27f7b2192c56
refs/heads/master
2020-03-30T16:56:43.532000
2018-10-03T15:25:23
2018-10-03T15:25:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Browser_Commands_3; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class WebElementsCommands { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub /* * Clear() command * SendKeys() * click() * IsDisplay() * IsEnable() * IsSelected() * Submit() * GetText() * getTagName() * getCssValue() * getAttribute() * getSize() * getLocation() * * */ WebDriver d = new FirefoxDriver(); d.get("https://www.facebook.com"); // clear() d.findElement(By.id("u_0_1")).sendKeys("Selenium automation"); Thread.sleep(5000); d.findElement(By.id("u_0_1")).clear(); //SendKeys() //other way to use webelement WebElement txtLogin = d.findElement(By.id("u_0_1")); txtLogin.sendKeys("Selenium Automation"); // isDisplayed() boolean tfound = txtLogin.isDisplayed(); System.out.println("isDisplayed : " + tfound); // isEnabled() boolean xloginFound = txtLogin.isEnabled(); System.out.println("isEnabled : " + tfound); if(xloginFound){ txtLogin.sendKeys("selenium testing"); } // IsSelected() //Checkboxes, Select Options and Radio Buttons. WebElement chkKeepMe = d.findElement(By.id("persist_box")); boolean status = chkKeepMe.isSelected(); if(status == false) { System.out.println("isSelected: " + status); chkKeepMe.click(); } // getText() WebElement lnkCreate = d.findElement(By.xpath(".//*[@id='reg_pages_msg']/a")); String s = lnkCreate.getText(); System.out.println("getText - Link text : " + s); //getTagName() System.out.println("Tag name : "+ lnkCreate.getTagName()); // getCssValue() WebElement eleCreateAccount = d.findElement(By.xpath(".//*[@id='u_0_i']")); String cssvalue = eleCreateAccount.getCssValue("font-family"); System.out.println("Css value:" + cssvalue); // getAttribute() System.out.println("Attribute id : " + eleCreateAccount.getAttribute("id")); // getSize() WebElement eleCreateAccountSize = d.findElement(By.id("u_0_i")); Dimension dimensions = eleCreateAccountSize.getSize(); System.out.println("Height :" + dimensions.height + "Width : "+ dimensions.width); //getLocation() WebElement eleCreateAccountLocation = d.findElement(By.id("u_0_i")); Point point = eleCreateAccountLocation.getLocation(); System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y); //Submit() WebElement btnSignUp = d.findElement(By.id("u_0_v")); btnSignUp.submit(); } }
UTF-8
Java
2,754
java
WebElementsCommands.java
Java
[ { "context": "clear()\n\t\td.findElement(By.id(\"u_0_1\")).sendKeys(\"Selenium automation\");\n\t\tThread.sleep(5000);\n\t\td.findElement(By.id(\"u", "end": 802, "score": 0.9930400252342224, "start": 783, "tag": "PASSWORD", "value": "Selenium automation" }, { "context": "findElement(By.id(\"u_0_1\"));\n\t\ttxtLogin.sendKeys(\"Selenium Automation\");\n\t\t\n\t\t// isDisplayed()\n\t\tboolean tfound = txtLo", "end": 1017, "score": 0.9953901171684265, "start": 998, "tag": "PASSWORD", "value": "Selenium Automation" }, { "context": "tfound);\n\t\tif(xloginFound){\n\t\t\ttxtLogin.sendKeys(\"selenium testing\");\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\t// IsSelected()\n\t\t//Checkboxes,", "end": 1308, "score": 0.9956961274147034, "start": 1292, "tag": "PASSWORD", "value": "selenium testing" } ]
null
[]
package Browser_Commands_3; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class WebElementsCommands { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub /* * Clear() command * SendKeys() * click() * IsDisplay() * IsEnable() * IsSelected() * Submit() * GetText() * getTagName() * getCssValue() * getAttribute() * getSize() * getLocation() * * */ WebDriver d = new FirefoxDriver(); d.get("https://www.facebook.com"); // clear() d.findElement(By.id("u_0_1")).sendKeys("<PASSWORD>"); Thread.sleep(5000); d.findElement(By.id("u_0_1")).clear(); //SendKeys() //other way to use webelement WebElement txtLogin = d.findElement(By.id("u_0_1")); txtLogin.sendKeys("<PASSWORD>"); // isDisplayed() boolean tfound = txtLogin.isDisplayed(); System.out.println("isDisplayed : " + tfound); // isEnabled() boolean xloginFound = txtLogin.isEnabled(); System.out.println("isEnabled : " + tfound); if(xloginFound){ txtLogin.sendKeys("<PASSWORD>"); } // IsSelected() //Checkboxes, Select Options and Radio Buttons. WebElement chkKeepMe = d.findElement(By.id("persist_box")); boolean status = chkKeepMe.isSelected(); if(status == false) { System.out.println("isSelected: " + status); chkKeepMe.click(); } // getText() WebElement lnkCreate = d.findElement(By.xpath(".//*[@id='reg_pages_msg']/a")); String s = lnkCreate.getText(); System.out.println("getText - Link text : " + s); //getTagName() System.out.println("Tag name : "+ lnkCreate.getTagName()); // getCssValue() WebElement eleCreateAccount = d.findElement(By.xpath(".//*[@id='u_0_i']")); String cssvalue = eleCreateAccount.getCssValue("font-family"); System.out.println("Css value:" + cssvalue); // getAttribute() System.out.println("Attribute id : " + eleCreateAccount.getAttribute("id")); // getSize() WebElement eleCreateAccountSize = d.findElement(By.id("u_0_i")); Dimension dimensions = eleCreateAccountSize.getSize(); System.out.println("Height :" + dimensions.height + "Width : "+ dimensions.width); //getLocation() WebElement eleCreateAccountLocation = d.findElement(By.id("u_0_i")); Point point = eleCreateAccountLocation.getLocation(); System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y); //Submit() WebElement btnSignUp = d.findElement(By.id("u_0_v")); btnSignUp.submit(); } }
2,730
0.660494
0.655047
110
24.036364
23.195581
84
false
false
0
0
0
0
0
0
2.090909
false
false
9
552b8043226b8b8c3751813ed8bb34b75e6fde43
10,376,641,012,145
564b8211f516315d1e5c0b61d06ce915eb9e6966
/src/com/smoov/smoovpass/alltransaction/AllTransaction.java
7f55cbd547b56608d94f93979e98d9137f3e7b1b
[]
no_license
lfloresca10/SmoovPay
https://github.com/lfloresca10/SmoovPay
14d9faadf75403315c9c16c948cf0073b9fae66a
5a783bba2e1e9a7480d16a99b37864bb6b33fe57
refs/heads/master
2018-01-09T22:01:09.501000
2015-05-25T09:27:18
2015-05-25T09:27:18
36,221,941
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smoov.smoovpass.alltransaction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ExpandableListView.OnGroupClickListener; import android.widget.ExpandableListView.OnGroupCollapseListener; import android.widget.ExpandableListView.OnGroupExpandListener; import com.smoov.smoovpass.FragmentLocation; import com.smoov.smoovpass.MainApplication; import com.smoov.smoovpass.MainFragment; import com.smoov.smoovpass.R; import com.smoov.smoovpass.data.FetchAllTransactionData; import com.smoov.smoovpass.data.TransactionData_; import com.smoov.smoovpass.data.TransactionTitleHeader; import com.smoov.smoovpass.service.OnServiceListener; import com.smoov.smoovpass.service.Service; import com.smoov.smoovpass.service.ServiceAction; import com.smoov.smoovpass.service.ServiceResponse; public class AllTransaction extends Fragment implements OnServiceListener{ private MainApplication mMain; private MainFragment mMainFragment; private View v; private ExpandableListAdapter listAdapter; private ExpandableListView expListView; private List<TransactionTitleHeader> listDataHeader; private HashMap<TransactionTitleHeader, List<TransactionData_>> listDataChild; public static boolean isModified = false; private Service mServiceTransaction = null; public static AllTransaction mainInstance = null; public AllTransaction() { } @Override public void onHiddenChanged(boolean hidden) { mMain.sCurrentFragment = FragmentLocation.AllTransaction; mMainFragment.getSlidingMenu().setSlidingEnabled(true); super.onHiddenChanged(hidden); if(!hidden && isModified) { isModified = false; if(mMain.checkConnection(getActivity())) getAllTransaction(); else { if(mMainFragment.allTransactionsData != null) actionBillSplitFetchAllTransaction(mMainFragment.allTransactionsData); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mMain = MainApplication.getInstance(); mMainFragment = MainFragment.getInstance(); mMain.sCurrentFragment = FragmentLocation.AllTransaction; v = inflater.inflate(R.layout.all_transactions, container, false); getActivity().setTheme(R.style.AppTheme); mainInstance = this; return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); expListView = (ExpandableListView) v.findViewById(R.id.all_transactions_expnd_listview); expListView.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { final TransactionData_ child = (TransactionData_) listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition); mMainFragment.switchContentDetails(new AllTransactionDetails(child)); return false; } }); if(mMain.checkConnection(getActivity())) getAllTransaction(); else { if(mMainFragment.allTransactionsData != null) actionBillSplitFetchAllTransaction(mMainFragment.allTransactionsData); } } public void getAllTransaction() { mServiceTransaction = new Service(this); mMain.showProgressDialog(getActivity(), "", true); mServiceTransaction.postAPIFetchAllTransaction(mMain.mSharedPref.getString("access_token", "")); } public void onClicked(View v) { switch (v.getId()) { case R.id.app_header_icon: case R.id.button_all_transactions_header_back: mMainFragment.getSlidingMenu().toggle(); break; default: break; } } @Override public void onPause() { super.onPause(); if (mMain.sCurrentFragment == FragmentLocation.AllTransaction){ MainFragment.sMain.isMainFragmentPause = true; } } public void onBackPressed(){ mMainFragment.getSlidingMenu().toggle(); } private void actionBillSplitFetchAllTransaction(FetchAllTransactionData data) { if(data.status == 1) { listDataChild = new HashMap<TransactionTitleHeader, List<TransactionData_>>(); listDataHeader = new ArrayList<TransactionTitleHeader>(); int sSize = data.month.size(); for (int i = 0; i < sSize; i++) { ArrayList<TransactionData_> listTransaction = new ArrayList<TransactionData_>(); if(i == 0) { // Expand if group has more than 1 item if(data.mapTransaction.get(i).size() > 0) listDataHeader.add(new TransactionTitleHeader(true,"This Month","")); else listDataHeader.add(new TransactionTitleHeader(false,"This Month","")); } else { listDataHeader.add(new TransactionTitleHeader(false,data.month.get(i),"")); } for (TransactionData_ transactionData_ : data.mapTransaction.get(i)) { listTransaction.add(transactionData_); } listDataChild.put(listDataHeader.get(i), listTransaction); } listAdapter = new ExpandableListAdapter(getActivity(), getActivity(), listDataHeader, listDataChild); expListView.setAdapter(listAdapter); // expListView.expandGroup(0); if(listAdapter.getChildrenCount(0) > 0) expandListView(0); else if(listAdapter.getChildrenCount(1) > 0) expandListView(1); else if(listAdapter.getChildrenCount(2) > 0) expandListView(2); else if(listAdapter.getChildrenCount(3) > 0) expandListView(3); expListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { if(listAdapter.getChildrenCount(groupPosition) == 0) { mMain.showDialog(getActivity(), "No item found.", "No Transaction", false); } return false; } }); expListView.setOnGroupExpandListener(new OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { if(listAdapter.getChildrenCount(groupPosition) > 0) { TransactionTitleHeader element = (TransactionTitleHeader) listAdapter.getGroup(groupPosition); element.isActive = true; listAdapter.notifyDataSetChanged(); } } }); expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() { @Override public void onGroupCollapse(int groupPosition) { TransactionTitleHeader element = (TransactionTitleHeader) listAdapter.getGroup(groupPosition); element.isActive = false; listAdapter.notifyDataSetChanged(); } }); } else if(data.status == -1050) { mMain.showDialogSessionExpired(getActivity()); } else { mMain.showDialog(getActivity(), data.message, getString(R.string.failed),false); } } @Override public void onCompleted(Service service, ServiceResponse result) { try { mMain.progressDialog.dismiss(); if(result.getAction() != ServiceAction.ActionNone) { if(result.getData() == null) { mMain.showDialogError(getActivity(), result.getCode()); } if(result.getAction() == ServiceAction.ActionBillSplitFetchAllTransaction) { FetchAllTransactionData data = (FetchAllTransactionData) result.getData(); mMainFragment.allTransactionsData = data; actionBillSplitFetchAllTransaction(data); } } } catch (Exception e) { e.printStackTrace(); mMain.showDialog(getActivity(), "Error has occured. Please try again.", getString(R.string.error),false); } } private void expandListView(int position) { TransactionTitleHeader element = (TransactionTitleHeader) listAdapter.getGroup(position); element.isActive = true; expListView.expandGroup(position); } }
UTF-8
Java
8,222
java
AllTransaction.java
Java
[]
null
[]
package com.smoov.smoovpass.alltransaction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ExpandableListView.OnGroupClickListener; import android.widget.ExpandableListView.OnGroupCollapseListener; import android.widget.ExpandableListView.OnGroupExpandListener; import com.smoov.smoovpass.FragmentLocation; import com.smoov.smoovpass.MainApplication; import com.smoov.smoovpass.MainFragment; import com.smoov.smoovpass.R; import com.smoov.smoovpass.data.FetchAllTransactionData; import com.smoov.smoovpass.data.TransactionData_; import com.smoov.smoovpass.data.TransactionTitleHeader; import com.smoov.smoovpass.service.OnServiceListener; import com.smoov.smoovpass.service.Service; import com.smoov.smoovpass.service.ServiceAction; import com.smoov.smoovpass.service.ServiceResponse; public class AllTransaction extends Fragment implements OnServiceListener{ private MainApplication mMain; private MainFragment mMainFragment; private View v; private ExpandableListAdapter listAdapter; private ExpandableListView expListView; private List<TransactionTitleHeader> listDataHeader; private HashMap<TransactionTitleHeader, List<TransactionData_>> listDataChild; public static boolean isModified = false; private Service mServiceTransaction = null; public static AllTransaction mainInstance = null; public AllTransaction() { } @Override public void onHiddenChanged(boolean hidden) { mMain.sCurrentFragment = FragmentLocation.AllTransaction; mMainFragment.getSlidingMenu().setSlidingEnabled(true); super.onHiddenChanged(hidden); if(!hidden && isModified) { isModified = false; if(mMain.checkConnection(getActivity())) getAllTransaction(); else { if(mMainFragment.allTransactionsData != null) actionBillSplitFetchAllTransaction(mMainFragment.allTransactionsData); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mMain = MainApplication.getInstance(); mMainFragment = MainFragment.getInstance(); mMain.sCurrentFragment = FragmentLocation.AllTransaction; v = inflater.inflate(R.layout.all_transactions, container, false); getActivity().setTheme(R.style.AppTheme); mainInstance = this; return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); expListView = (ExpandableListView) v.findViewById(R.id.all_transactions_expnd_listview); expListView.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { final TransactionData_ child = (TransactionData_) listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition); mMainFragment.switchContentDetails(new AllTransactionDetails(child)); return false; } }); if(mMain.checkConnection(getActivity())) getAllTransaction(); else { if(mMainFragment.allTransactionsData != null) actionBillSplitFetchAllTransaction(mMainFragment.allTransactionsData); } } public void getAllTransaction() { mServiceTransaction = new Service(this); mMain.showProgressDialog(getActivity(), "", true); mServiceTransaction.postAPIFetchAllTransaction(mMain.mSharedPref.getString("access_token", "")); } public void onClicked(View v) { switch (v.getId()) { case R.id.app_header_icon: case R.id.button_all_transactions_header_back: mMainFragment.getSlidingMenu().toggle(); break; default: break; } } @Override public void onPause() { super.onPause(); if (mMain.sCurrentFragment == FragmentLocation.AllTransaction){ MainFragment.sMain.isMainFragmentPause = true; } } public void onBackPressed(){ mMainFragment.getSlidingMenu().toggle(); } private void actionBillSplitFetchAllTransaction(FetchAllTransactionData data) { if(data.status == 1) { listDataChild = new HashMap<TransactionTitleHeader, List<TransactionData_>>(); listDataHeader = new ArrayList<TransactionTitleHeader>(); int sSize = data.month.size(); for (int i = 0; i < sSize; i++) { ArrayList<TransactionData_> listTransaction = new ArrayList<TransactionData_>(); if(i == 0) { // Expand if group has more than 1 item if(data.mapTransaction.get(i).size() > 0) listDataHeader.add(new TransactionTitleHeader(true,"This Month","")); else listDataHeader.add(new TransactionTitleHeader(false,"This Month","")); } else { listDataHeader.add(new TransactionTitleHeader(false,data.month.get(i),"")); } for (TransactionData_ transactionData_ : data.mapTransaction.get(i)) { listTransaction.add(transactionData_); } listDataChild.put(listDataHeader.get(i), listTransaction); } listAdapter = new ExpandableListAdapter(getActivity(), getActivity(), listDataHeader, listDataChild); expListView.setAdapter(listAdapter); // expListView.expandGroup(0); if(listAdapter.getChildrenCount(0) > 0) expandListView(0); else if(listAdapter.getChildrenCount(1) > 0) expandListView(1); else if(listAdapter.getChildrenCount(2) > 0) expandListView(2); else if(listAdapter.getChildrenCount(3) > 0) expandListView(3); expListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { if(listAdapter.getChildrenCount(groupPosition) == 0) { mMain.showDialog(getActivity(), "No item found.", "No Transaction", false); } return false; } }); expListView.setOnGroupExpandListener(new OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { if(listAdapter.getChildrenCount(groupPosition) > 0) { TransactionTitleHeader element = (TransactionTitleHeader) listAdapter.getGroup(groupPosition); element.isActive = true; listAdapter.notifyDataSetChanged(); } } }); expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() { @Override public void onGroupCollapse(int groupPosition) { TransactionTitleHeader element = (TransactionTitleHeader) listAdapter.getGroup(groupPosition); element.isActive = false; listAdapter.notifyDataSetChanged(); } }); } else if(data.status == -1050) { mMain.showDialogSessionExpired(getActivity()); } else { mMain.showDialog(getActivity(), data.message, getString(R.string.failed),false); } } @Override public void onCompleted(Service service, ServiceResponse result) { try { mMain.progressDialog.dismiss(); if(result.getAction() != ServiceAction.ActionNone) { if(result.getData() == null) { mMain.showDialogError(getActivity(), result.getCode()); } if(result.getAction() == ServiceAction.ActionBillSplitFetchAllTransaction) { FetchAllTransactionData data = (FetchAllTransactionData) result.getData(); mMainFragment.allTransactionsData = data; actionBillSplitFetchAllTransaction(data); } } } catch (Exception e) { e.printStackTrace(); mMain.showDialog(getActivity(), "Error has occured. Please try again.", getString(R.string.error),false); } } private void expandListView(int position) { TransactionTitleHeader element = (TransactionTitleHeader) listAdapter.getGroup(position); element.isActive = true; expListView.expandGroup(position); } }
8,222
0.711992
0.708952
267
29.794008
28.159636
138
false
false
0
0
0
0
0
0
2.543071
false
false
9
f0562deb76ff2f007e78785daeb70fd1e2ca1afd
14,070,312,885,147
253546ec06e1bf95ca07c61527b748c7967326d4
/project/app/src/main/java/uta/advse6324/ubs/ui/login/ChangepwActivity.java
8f000cfd6bc355a7f7325c3468fa5fe1cea1aea7
[]
no_license
astroleander/ubs-for-uta-6324
https://github.com/astroleander/ubs-for-uta-6324
bcaece49e6e776381dc521ec0890512d6fd3da8f
14d0288603eb179c3117ac6ded402bbece1835b5
refs/heads/main
2023-04-08T23:53:05.687000
2021-04-29T16:10:27
2021-04-29T16:10:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uta.advse6324.ubs.ui.login; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import uta.advse6324.ubs.R; import uta.advse6324.ubs.pojo.User; import uta.advse6324.ubs.utils.DBHelper; public class ChangepwActivity extends AppCompatActivity { private EditText password1; private EditText password2; private DBHelper dbHelper; private Button confirmButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_changepw); initView(); } private void initView() { password1= findViewById(R.id.pw_1); password2 = findViewById(R.id.pw_2); confirmButton = findViewById(R.id.confirm_button); confirmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ChangepwActivity.this.confirm(); } }); } private void confirm() { dbHelper = new DBHelper(this); String idnumber = getIntent().getStringExtra("idNumber"); String pw1 = getStringFromEditText(this.password1); String pw2 = getStringFromEditText(this.password2); User user = dbHelper.queryUser(idnumber); if(pw1.equals(pw2)&&(pw1.length()>=6)&&(pw1.length()<=12)){ Intent intent = new Intent(this, LoginActivity.class); user.setPassword(pw1); dbHelper.changePW(user); startActivity(intent); Toast.makeText(ChangepwActivity.this,"succesfull",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(ChangepwActivity.this, "The passwords did not match or they are not proper", Toast.LENGTH_LONG).show(); } } static String getStringFromEditText(EditText editText) { return editText.getText().toString().trim(); } }
UTF-8
Java
2,072
java
ChangepwActivity.java
Java
[]
null
[]
package uta.advse6324.ubs.ui.login; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import uta.advse6324.ubs.R; import uta.advse6324.ubs.pojo.User; import uta.advse6324.ubs.utils.DBHelper; public class ChangepwActivity extends AppCompatActivity { private EditText password1; private EditText password2; private DBHelper dbHelper; private Button confirmButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_changepw); initView(); } private void initView() { password1= findViewById(R.id.pw_1); password2 = findViewById(R.id.pw_2); confirmButton = findViewById(R.id.confirm_button); confirmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ChangepwActivity.this.confirm(); } }); } private void confirm() { dbHelper = new DBHelper(this); String idnumber = getIntent().getStringExtra("idNumber"); String pw1 = getStringFromEditText(this.password1); String pw2 = getStringFromEditText(this.password2); User user = dbHelper.queryUser(idnumber); if(pw1.equals(pw2)&&(pw1.length()>=6)&&(pw1.length()<=12)){ Intent intent = new Intent(this, LoginActivity.class); user.setPassword(pw1); dbHelper.changePW(user); startActivity(intent); Toast.makeText(ChangepwActivity.this,"succesfull",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(ChangepwActivity.this, "The passwords did not match or they are not proper", Toast.LENGTH_LONG).show(); } } static String getStringFromEditText(EditText editText) { return editText.getText().toString().trim(); } }
2,072
0.667471
0.651062
70
28.614286
25.868509
130
false
false
0
0
0
0
0
0
0.571429
false
false
9
f5ebe5946073fc1e12afd973b41ad707fc4afe3b
15,427,522,555,533
26e0644c6b2d10d21214c14e243a1b5391213bfa
/Android/android/app/src/main/java/com/comm/android/utils/FileUtils.java
cb51a261198c37160a018d95cfd191ee81b037df
[]
no_license
YYhorse/ChineseSupermarket
https://github.com/YYhorse/ChineseSupermarket
2662007bb88b676dff3bdbf52e912327eec3ccfe
368b0b2650ed62c03cf74be26e049d1814e11938
refs/heads/master
2018-10-22T07:58:57.261000
2018-08-17T06:16:56
2018-08-17T06:16:56
137,055,608
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.comm.android.utils; import android.content.Context; import android.os.Environment; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * 文件工具类 * * @author Homk-M <Awentljs@gmail.com> */ public class FileUtils { private static FileUtils _fileUtil = new FileUtils(); public static final int DOWNLOAD_EMOJI = 100; public static final int DOWNLOAD_BG = 101; public static FileUtils getInstance() { return _fileUtil; } /** * @param filePath * @return */ public boolean isFileExist(String filePath) { try { File f = new File(filePath); return f.exists() && f.isFile(); } catch (Exception e) { return false; } } /** * @param path */ public void isFolderExists(String path) { File file = new File(path); if (!file.exists()) { file.mkdirs(); } } /** * @param filePath * @throws IOException */ public void deleteFile(String filePath) { try { File file = new File(filePath); if (!isExist(filePath)) { return; } if (!file.isDirectory()) { file.delete(); } } catch (Exception e) { // TODO: handle exception } } /** * @param filepath * @return */ public boolean isExist(String filepath) throws IOException { File file = new File(filepath); return file.isFile(); } /** * @param oldPath String * @param newPath String * @return boolean */ public void moveFile(String oldPath, String newPath) throws IOException { File oldFile = new File(oldPath); if (!oldFile.isFile()) { return; } File newFile = new File(newPath); if (!newFile.isFile()) { String path = newPath.substring(0, newPath.lastIndexOf("/")); File dirFile = new File(path); dirFile.mkdirs(); newFile = new File(newPath); } oldFile.renameTo(newFile); } /** * 读取写入文件 * * @param oldPath * @param newPath */ public void copyFileToWrite(String oldPath, String newPath) throws IOException { FileInputStream fins = null; FileOutputStream fous = null; try { if (isExist(oldPath)) { File oldfile = new File(oldPath); fins = new FileInputStream(oldfile); File newfile = new File(newPath); if (!newfile.isFile()) { DLog.e("newfile is file", "false:"+newPath ); String path = newPath.substring(0, newPath.lastIndexOf("/")); File dirFile = new File(path); dirFile.mkdirs(); newfile.createNewFile(); } fous = new FileOutputStream(newfile); byte[] buffer = new byte[4096]; int length = 0; while ((length = fins.read(buffer)) != -1) { fous.write(buffer, 0, length); } fins.close(); fous.close(); } } finally { if (fins != null) { try { fins.close(); } catch (IOException e) { } } if (fous != null) { try { fous.close(); } catch (IOException e) { } } } } /** * 读取表情配置文件 * * @param context * @return */ public static List<String> getEmojiFile(Context context) { try { List<String> list = new ArrayList<String>(); InputStream in = context.getResources().getAssets().open("emoji"); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String str = null; while ((str = br.readLine()) != null) { list.add(str); } return list; } catch (IOException e) { e.printStackTrace(); } return null; } public static boolean exitInCache(Context context, String url, int type) { String Dir = type == DOWNLOAD_BG ? "BackGround" + File.separator : ""; String mApkDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator + Dir; boolean exist = false; String fileName = (url.substring(url.lastIndexOf("/") + 1)); File dir = new File(mApkDir); if (!dir.exists()) { dir.mkdirs(); } File mDir = new File(dir, fileName); boolean isTrue = type == DOWNLOAD_BG ? mDir.isFile() : mDir.isDirectory(); if (mDir.exists() && isTrue) { exist = true; } else { return false; } return exist; } public static String getExitInCacheFileName(Context context, String url, int type) { String Dir = type == DOWNLOAD_BG ? "BackGround" + File.separator : ""; String mApkDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator + Dir; String fileName = (url.substring(url.lastIndexOf("/") + 1)); File dir = new File(mApkDir); if (!dir.exists()) { dir.mkdirs(); } File mDir = new File(dir, fileName); boolean isTrue = type == DOWNLOAD_BG ? mDir.isFile() : mDir.isDirectory(); if (mDir.exists() && isTrue) { return mDir.getAbsolutePath(); } else { return null; } } /** * 根据byte数组生成文件 * * @param bytes 生成文件用到的byte数组 */ public static File createFileWithByte(byte[] bytes, String filePath) { if(bytes == null || bytes.length == 0){//字节为null return null; } /** * 创建File对象,其中包含文件所在的目录以及文件的命名 */ File file = new File(filePath); // 创建FileOutputStream对象 FileOutputStream outputStream = null; // 创建BufferedOutputStream对象 BufferedOutputStream bufferedOutputStream = null; try { // 如果文件存在则删除 if (file.exists()) { file.delete(); } // 在文件系统中根据路径创建一个新的空文件 file.createNewFile(); // 获取FileOutputStream对象 outputStream = new FileOutputStream(file); // 获取BufferedOutputStream对象 bufferedOutputStream = new BufferedOutputStream(outputStream); // 往文件所在的缓冲输出流中写byte数据 bufferedOutputStream.write(bytes); // 刷出缓冲输出流,该步很关键,要是不执行flush()方法,那么文件的内容是空的。 bufferedOutputStream.flush(); } catch (Exception e) { // 打印异常信息 e.printStackTrace(); } finally { // 关闭创建的流对象 if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (bufferedOutputStream != null) { try { bufferedOutputStream.close(); } catch (Exception e2) { e2.printStackTrace(); } } } return file; } }
UTF-8
Java
8,032
java
FileUtils.java
Java
[ { "context": "import java.util.List;\n\n/**\n * 文件工具类\n *\n * @author Homk-M <Awentljs@gmail.com>\n */\npublic class FileUtils {", "end": 426, "score": 0.9863250851631165, "start": 420, "tag": "USERNAME", "value": "Homk-M" }, { "context": "va.util.List;\n\n/**\n * 文件工具类\n *\n * @author Homk-M <Awentljs@gmail.com>\n */\npublic class FileUtils {\n\n private static", "end": 446, "score": 0.9999296069145203, "start": 428, "tag": "EMAIL", "value": "Awentljs@gmail.com" } ]
null
[]
package com.comm.android.utils; import android.content.Context; import android.os.Environment; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * 文件工具类 * * @author Homk-M <<EMAIL>> */ public class FileUtils { private static FileUtils _fileUtil = new FileUtils(); public static final int DOWNLOAD_EMOJI = 100; public static final int DOWNLOAD_BG = 101; public static FileUtils getInstance() { return _fileUtil; } /** * @param filePath * @return */ public boolean isFileExist(String filePath) { try { File f = new File(filePath); return f.exists() && f.isFile(); } catch (Exception e) { return false; } } /** * @param path */ public void isFolderExists(String path) { File file = new File(path); if (!file.exists()) { file.mkdirs(); } } /** * @param filePath * @throws IOException */ public void deleteFile(String filePath) { try { File file = new File(filePath); if (!isExist(filePath)) { return; } if (!file.isDirectory()) { file.delete(); } } catch (Exception e) { // TODO: handle exception } } /** * @param filepath * @return */ public boolean isExist(String filepath) throws IOException { File file = new File(filepath); return file.isFile(); } /** * @param oldPath String * @param newPath String * @return boolean */ public void moveFile(String oldPath, String newPath) throws IOException { File oldFile = new File(oldPath); if (!oldFile.isFile()) { return; } File newFile = new File(newPath); if (!newFile.isFile()) { String path = newPath.substring(0, newPath.lastIndexOf("/")); File dirFile = new File(path); dirFile.mkdirs(); newFile = new File(newPath); } oldFile.renameTo(newFile); } /** * 读取写入文件 * * @param oldPath * @param newPath */ public void copyFileToWrite(String oldPath, String newPath) throws IOException { FileInputStream fins = null; FileOutputStream fous = null; try { if (isExist(oldPath)) { File oldfile = new File(oldPath); fins = new FileInputStream(oldfile); File newfile = new File(newPath); if (!newfile.isFile()) { DLog.e("newfile is file", "false:"+newPath ); String path = newPath.substring(0, newPath.lastIndexOf("/")); File dirFile = new File(path); dirFile.mkdirs(); newfile.createNewFile(); } fous = new FileOutputStream(newfile); byte[] buffer = new byte[4096]; int length = 0; while ((length = fins.read(buffer)) != -1) { fous.write(buffer, 0, length); } fins.close(); fous.close(); } } finally { if (fins != null) { try { fins.close(); } catch (IOException e) { } } if (fous != null) { try { fous.close(); } catch (IOException e) { } } } } /** * 读取表情配置文件 * * @param context * @return */ public static List<String> getEmojiFile(Context context) { try { List<String> list = new ArrayList<String>(); InputStream in = context.getResources().getAssets().open("emoji"); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String str = null; while ((str = br.readLine()) != null) { list.add(str); } return list; } catch (IOException e) { e.printStackTrace(); } return null; } public static boolean exitInCache(Context context, String url, int type) { String Dir = type == DOWNLOAD_BG ? "BackGround" + File.separator : ""; String mApkDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator + Dir; boolean exist = false; String fileName = (url.substring(url.lastIndexOf("/") + 1)); File dir = new File(mApkDir); if (!dir.exists()) { dir.mkdirs(); } File mDir = new File(dir, fileName); boolean isTrue = type == DOWNLOAD_BG ? mDir.isFile() : mDir.isDirectory(); if (mDir.exists() && isTrue) { exist = true; } else { return false; } return exist; } public static String getExitInCacheFileName(Context context, String url, int type) { String Dir = type == DOWNLOAD_BG ? "BackGround" + File.separator : ""; String mApkDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator + Dir; String fileName = (url.substring(url.lastIndexOf("/") + 1)); File dir = new File(mApkDir); if (!dir.exists()) { dir.mkdirs(); } File mDir = new File(dir, fileName); boolean isTrue = type == DOWNLOAD_BG ? mDir.isFile() : mDir.isDirectory(); if (mDir.exists() && isTrue) { return mDir.getAbsolutePath(); } else { return null; } } /** * 根据byte数组生成文件 * * @param bytes 生成文件用到的byte数组 */ public static File createFileWithByte(byte[] bytes, String filePath) { if(bytes == null || bytes.length == 0){//字节为null return null; } /** * 创建File对象,其中包含文件所在的目录以及文件的命名 */ File file = new File(filePath); // 创建FileOutputStream对象 FileOutputStream outputStream = null; // 创建BufferedOutputStream对象 BufferedOutputStream bufferedOutputStream = null; try { // 如果文件存在则删除 if (file.exists()) { file.delete(); } // 在文件系统中根据路径创建一个新的空文件 file.createNewFile(); // 获取FileOutputStream对象 outputStream = new FileOutputStream(file); // 获取BufferedOutputStream对象 bufferedOutputStream = new BufferedOutputStream(outputStream); // 往文件所在的缓冲输出流中写byte数据 bufferedOutputStream.write(bytes); // 刷出缓冲输出流,该步很关键,要是不执行flush()方法,那么文件的内容是空的。 bufferedOutputStream.flush(); } catch (Exception e) { // 打印异常信息 e.printStackTrace(); } finally { // 关闭创建的流对象 if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (bufferedOutputStream != null) { try { bufferedOutputStream.close(); } catch (Exception e2) { e2.printStackTrace(); } } } return file; } }
8,021
0.510785
0.508056
268
27.716417
21.503942
109
false
false
0
0
0
0
0
0
0.425373
false
false
9
70b997c8161c308fd8bc66321bb89cd970d3d10b
29,815,662,994,449
dd4718f70f88a9e69a73573e9b6553fccff39abd
/TicTacToe/TicTacToe.Domain/src/main/java/Domain/IODeviceFactory.java
3cc99c6c9620e1f0002b68b1dfff0afcae8af444
[]
no_license
janisZisenis/BoardGames.TDD-London-School
https://github.com/janisZisenis/BoardGames.TDD-London-School
4173dfdb63017b4726ad3c178bace6c1d306a186
2c35e82b5cc4c3be83d89cf8758ef7b3cedbc131
refs/heads/master
2020-04-22T17:58:23.671000
2019-06-21T08:17:19
2019-06-21T08:17:19
170,560,575
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Domain; import Domain.Board.Board; import Domain.Data.Mark; import Input2D.InputGenerator; import Input2D.ValidInputGenerator.InputAlerter; public interface IODeviceFactory { InputGenerator makeHumanInputGenerator(); InputGenerator makeInvincibleInputGenerator(Board board, Mark m); InputGenerator makeHumbleInputGenerator(); InputAlerter makeFieldExistsAlerter(); InputAlerter makeFieldIsEmptyAlerter(); }
UTF-8
Java
438
java
IODeviceFactory.java
Java
[]
null
[]
package Domain; import Domain.Board.Board; import Domain.Data.Mark; import Input2D.InputGenerator; import Input2D.ValidInputGenerator.InputAlerter; public interface IODeviceFactory { InputGenerator makeHumanInputGenerator(); InputGenerator makeInvincibleInputGenerator(Board board, Mark m); InputGenerator makeHumbleInputGenerator(); InputAlerter makeFieldExistsAlerter(); InputAlerter makeFieldIsEmptyAlerter(); }
438
0.815068
0.810502
15
28.200001
20.69525
69
false
false
0
0
0
0
0
0
0.733333
false
false
9
ce73dbf94cfc9c1db1f620ba06dd3c293c9ac555
27,350,351,763,565
eef77c9808ba30ac5658266ca122e7e4c1b8069d
/javaee workspace/160204xml/src/com/test/XMLServlet.java
74b9958b1d18f23a69ecffff9c6d9def29102022
[]
no_license
geniusle/backup
https://github.com/geniusle/backup
5db620139d599c82c6571dc76c0b19ef8a5ac9f0
914b3b7d963f3637197cd3c100ba76b07cc929b4
refs/heads/master
2017-10-31T19:40:52.138000
2016-07-18T04:25:51
2016-07-18T04:25:51
63,569,944
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.*; import org.dom4j.io.XMLWriter; /** * Servlet implementation class XMLServlet */ @WebServlet("/XMLServlet") public class XMLServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public XMLServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // doGet(request, response); response.setContentType("text/xml"); Document document=DocumentHelper.createDocument(); Element root=DocumentHelper.createElement("Book-Info"); document.setRootElement(root); Element book1=root.addElement("book"); book1.addAttribute("name", "Java develop modal"); Element book1_price=book1.addElement("price"); book1_price.setText("79"); Element book1_author=book1.addElement("author"); book1_author.setText("Mr. Le"); Element book2=root.addElement("book"); book2.addAttribute("name", "Beginning of Java"); Element book2_price=book2.addElement("price"); book2_price.setText("66"); Element book2_author=book2.addElement("author"); book2_author.setText("Geniusle"); OutputStream output=response.getOutputStream(); XMLWriter writer=new XMLWriter(output); writer.write(document); writer.flush(); writer.close(); } }
UTF-8
Java
2,161
java
XMLServlet.java
Java
[ { "context": "ok2.addElement(\"author\");\n\t\tbook2_author.setText(\"Geniusle\");\n\t\tOutputStream output=response.getOutputStream", "end": 1997, "score": 0.7082780003547668, "start": 1989, "tag": "NAME", "value": "Geniusle" } ]
null
[]
package com.test; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.*; import org.dom4j.io.XMLWriter; /** * Servlet implementation class XMLServlet */ @WebServlet("/XMLServlet") public class XMLServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public XMLServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // doGet(request, response); response.setContentType("text/xml"); Document document=DocumentHelper.createDocument(); Element root=DocumentHelper.createElement("Book-Info"); document.setRootElement(root); Element book1=root.addElement("book"); book1.addAttribute("name", "Java develop modal"); Element book1_price=book1.addElement("price"); book1_price.setText("79"); Element book1_author=book1.addElement("author"); book1_author.setText("Mr. Le"); Element book2=root.addElement("book"); book2.addAttribute("name", "Beginning of Java"); Element book2_price=book2.addElement("price"); book2_price.setText("66"); Element book2_author=book2.addElement("author"); book2_author.setText("Geniusle"); OutputStream output=response.getOutputStream(); XMLWriter writer=new XMLWriter(output); writer.write(document); writer.flush(); writer.close(); } }
2,161
0.745951
0.735308
70
29.871429
26.311281
119
false
false
0
0
0
0
0
0
1.585714
false
false
9