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
8d8870fbbdd64e39041e4d1df8803a20c3c54ab6
3,238,405,377,240
b17281b182ed89fbeafb682c396f1b6ba4402c22
/src/TwitterMessageTest.java
9f40403e69931912e39f2a983db48144d30ecd12
[]
no_license
larpfairy/twittermessage
https://github.com/larpfairy/twittermessage
3bfbe0a5d175cb2a34ba700ecd6da7171db848bd
f8cad670e9d76262dbc50745cf047d226a360bb4
refs/heads/master
2021-01-10T08:07:39.751000
2016-02-18T20:50:56
2016-02-18T20:50:56
50,630,056
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TwitterMessageTest { TwitterMessage myMessage; TwitterMessage myMessage1; TwitterMessage myMessage2; TwitterMessage myMessage3; Utilities myUtility; @Before public void setUp() throws Exception { myMessage = new TwitterMessage("@franky goes to #hollywood See http://cnn.com"); myMessage1 = new TwitterMessage("#@test this tweet is a @#test"); myMessage2 = new TwitterMessage("@mentionmentionmentionmentionmentionmentionmention #topic**((&#(@#&"); myMessage3 = new TwitterMessage("@michael @tommy @#@myname)--0 hello %4@@@ @michael. http://github.com github.com http:facebook.com"); myUtility = new Utilities(); } @After public void tearDown() throws Exception { } @Test public void TwitterMessageTest(){ assertTrue(myMessage.getTweetText() == "@franky goes to #hollywood See http://cnn.com"); assertEquals(myMessage.getWords().get(3), "#hollywood"); assertEquals(myMessage1.getWords().get(3), "is"); assertEquals(myMessage2.getWords().get(1), "#topic**((&#(@#&"); assertTrue(myMessage.getDate() != null); } @Test public void WordsTest(){ assertTrue(myMessage.getWords().size() == 6); assertTrue(myMessage3.getWords().size() == 9); assertTrue(myMessage2.getWords().size() == 2); assertTrue(myMessage1.getWords().size() == 6); assertEquals(myMessage.getWords().get(2), "to"); } @Test public void MentionsTest() { assertEquals("@franky", myMessage.getMentions().get(0)); assertTrue(1 == myMessage.getMentions().size()); assertTrue(myMessage1.getMentions().size() == 0); assertTrue(myMessage2.getMentions().size() == 1); assertTrue(myMessage3.getMentions().size() == 2); } @Test public void LinksTest(){ assertEquals("http://cnn.com", myMessage.getLinks().get(0)); assertTrue(myUtility.pingUrl(myMessage.getLinks().get(0))); assertFalse(myUtility.pingUrl("htp://google.com")); myMessage.addLink("http://facebook.com"); assertTrue(myUtility.pingUrl("http://facebook.com")); assertTrue(myMessage.getLinks().get(1) == "http://facebook.com"); } @Test public void HashtagsTest(){ assertEquals(myMessage.getHashTags().get(0), "#hollywood"); assertTrue(myMessage.getHashTags().size() == 1); assertTrue(myMessage1.getHashTags().size() == 0); assertTrue(myMessage2.getHashTags().size() == 0); assertTrue(myMessage3.getHashTags().size() == 0); } }
UTF-8
Java
2,505
java
TwitterMessageTest.java
Java
[ { "context": "hrows Exception {\n\t\tmyMessage = new TwitterMessage(\"@franky goes to #hollywood See http://cnn.com\");\n\t\tmyMess", "end": 417, "score": 0.9977972507476807, "start": 410, "tag": "USERNAME", "value": "@franky" }, { "context": "pic**((&#(@#&\");\n\t\tmyMessage3 = new TwitterMessage(\"@michael @tommy @#@myname)--0 hello %4@@@ @michael. http:/", "end": 676, "score": 0.9988835453987122, "start": 668, "tag": "USERNAME", "value": "@michael" }, { "context": "@#&\");\n\t\tmyMessage3 = new TwitterMessage(\"@michael @tommy @#@myname)--0 hello %4@@@ @michael. http://github", "end": 683, "score": 0.9977142214775085, "start": 677, "tag": "USERNAME", "value": "@tommy" }, { "context": "yMessage3 = new TwitterMessage(\"@michael @tommy @#@myname)--0 hello %4@@@ @michael. http://github.com githu", "end": 693, "score": 0.9642640948295593, "start": 686, "tag": "USERNAME", "value": "@myname" }, { "context": "Message(\"@michael @tommy @#@myname)--0 hello %4@@@ @michael. http://github.com github.com http:facebook.com\")", "end": 718, "score": 0.9983392357826233, "start": 710, "tag": "USERNAME", "value": "@michael" }, { "context": "est(){\n\t\tassertTrue(myMessage.getTweetText() == \"@franky goes to #hollywood See http://cnn.com\");\n\t\tasser", "end": 953, "score": 0.8916962146759033, "start": 948, "tag": "USERNAME", "value": "frank" }, { "context": "@Test\n\tpublic void MentionsTest() {\n\t\tassertEquals(\"@franky\", myMessage.getMentions().get(0));\n\t\tassertTrue(1", "end": 1565, "score": 0.9969781041145325, "start": 1558, "tag": "USERNAME", "value": "@franky" } ]
null
[]
import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TwitterMessageTest { TwitterMessage myMessage; TwitterMessage myMessage1; TwitterMessage myMessage2; TwitterMessage myMessage3; Utilities myUtility; @Before public void setUp() throws Exception { myMessage = new TwitterMessage("@franky goes to #hollywood See http://cnn.com"); myMessage1 = new TwitterMessage("#@test this tweet is a @#test"); myMessage2 = new TwitterMessage("@mentionmentionmentionmentionmentionmentionmention #topic**((&#(@#&"); myMessage3 = new TwitterMessage("@michael @tommy @#@myname)--0 hello %4@@@ @michael. http://github.com github.com http:facebook.com"); myUtility = new Utilities(); } @After public void tearDown() throws Exception { } @Test public void TwitterMessageTest(){ assertTrue(myMessage.getTweetText() == "@franky goes to #hollywood See http://cnn.com"); assertEquals(myMessage.getWords().get(3), "#hollywood"); assertEquals(myMessage1.getWords().get(3), "is"); assertEquals(myMessage2.getWords().get(1), "#topic**((&#(@#&"); assertTrue(myMessage.getDate() != null); } @Test public void WordsTest(){ assertTrue(myMessage.getWords().size() == 6); assertTrue(myMessage3.getWords().size() == 9); assertTrue(myMessage2.getWords().size() == 2); assertTrue(myMessage1.getWords().size() == 6); assertEquals(myMessage.getWords().get(2), "to"); } @Test public void MentionsTest() { assertEquals("@franky", myMessage.getMentions().get(0)); assertTrue(1 == myMessage.getMentions().size()); assertTrue(myMessage1.getMentions().size() == 0); assertTrue(myMessage2.getMentions().size() == 1); assertTrue(myMessage3.getMentions().size() == 2); } @Test public void LinksTest(){ assertEquals("http://cnn.com", myMessage.getLinks().get(0)); assertTrue(myUtility.pingUrl(myMessage.getLinks().get(0))); assertFalse(myUtility.pingUrl("htp://google.com")); myMessage.addLink("http://facebook.com"); assertTrue(myUtility.pingUrl("http://facebook.com")); assertTrue(myMessage.getLinks().get(1) == "http://facebook.com"); } @Test public void HashtagsTest(){ assertEquals(myMessage.getHashTags().get(0), "#hollywood"); assertTrue(myMessage.getHashTags().size() == 1); assertTrue(myMessage1.getHashTags().size() == 0); assertTrue(myMessage2.getHashTags().size() == 0); assertTrue(myMessage3.getHashTags().size() == 0); } }
2,505
0.707784
0.691816
74
32.851353
27.70583
136
false
false
0
0
0
0
0
0
1.905405
false
false
2
6dab2cf0c13018295a915ed65ab6e7413bb25bcf
8,658,654,093,734
c0dad7477a15ea56592526f2589e112a2168fdaf
/zzrbiweb/src/main/java/com/zzrbi/entity/RoleDirectoryRel.java
a4d24bf8329104cb7c452dea42c39221a343c5d3
[]
no_license
hantop/BIM
https://github.com/hantop/BIM
183523809e4839c0faed14bb760aae62b8db1028
451d7aa2aa125f36a0b56a9ab4bcb42edb8f6116
refs/heads/master
2020-03-28T07:19:55.751000
2018-06-10T10:03:22
2018-06-10T10:03:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zzrbi.entity; import java.io.Serializable; /** * RoleDirectoryRel的实体 * @author yinlonglong * @date 2017年3月21日 下午2:54:16 */ public class RoleDirectoryRel implements Serializable { private static final long serialVersionUID = 7984628723379269935L; /** * 角色目录id */ private int id; /** * 目录id */ private int directoryId; /** * 角色id */ private int roleId; /** * 角色目录id */ public int getId() { return id; } /** * 角色目录id */ public void setId(int id) { this.id = id; } /** * 目录id */ public int getDirectoryId() { return directoryId; } /** * 目录id */ public void setDirectoryId(int directoryId) { this.directoryId = directoryId; } /** * 角色id */ public int getRoleId() { return roleId; } /** * 角色id */ public void setRoleId(int roleId) { this.roleId = roleId; } }
UTF-8
Java
925
java
RoleDirectoryRel.java
Java
[ { "context": "rializable;\n\n/**\n * RoleDirectoryRel的实体\n * @author yinlonglong\n * @date 2017年3月21日 下午2:54:16\n */\npublic class Ro", "end": 106, "score": 0.9986110925674438, "start": 95, "tag": "USERNAME", "value": "yinlonglong" } ]
null
[]
package com.zzrbi.entity; import java.io.Serializable; /** * RoleDirectoryRel的实体 * @author yinlonglong * @date 2017年3月21日 下午2:54:16 */ public class RoleDirectoryRel implements Serializable { private static final long serialVersionUID = 7984628723379269935L; /** * 角色目录id */ private int id; /** * 目录id */ private int directoryId; /** * 角色id */ private int roleId; /** * 角色目录id */ public int getId() { return id; } /** * 角色目录id */ public void setId(int id) { this.id = id; } /** * 目录id */ public int getDirectoryId() { return directoryId; } /** * 目录id */ public void setDirectoryId(int directoryId) { this.directoryId = directoryId; } /** * 角色id */ public int getRoleId() { return roleId; } /** * 角色id */ public void setRoleId(int roleId) { this.roleId = roleId; } }
925
0.61324
0.577236
70
11.3
13.597636
67
false
false
0
0
0
0
0
0
1.057143
false
false
2
7b8b7fc6a46823c4567ae7bfaed2617a68bf9d0a
6,485,400,629,167
f42bf68ba72743f7571d3984bafb560a69974f15
/problem-set/Tree/623.-Add-One-Row-to-Tree/AddOneRowtoTree.java
d007622f2520c6fea2b3d2594830de1cf263eb29
[]
no_license
FFYzz/LeetCode-Journey
https://github.com/FFYzz/LeetCode-Journey
a3c0fb6efdd266266849a5443cef2d50f23aaf78
76a1b6ebee7c4c21e6360ae8711ee737d9aa7022
refs/heads/master
2022-04-28T00:14:12.667000
2022-04-13T00:54:21
2022-04-13T00:54:21
245,954,107
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @Title: * @Author: FFYzz * @Mail: cryptochen95 at gmail dot com * @Date: 2020/12/6 */ public class AddOneRowtoTree { public TreeNode addOneRow(TreeNode root, int v, int d) { Queue<TreeNode> queue = new LinkedList<>(); int currentLevel = 1; List<TreeNode> preNodes = new ArrayList<>(); queue.offer(root); while (!queue.isEmpty()) { if (currentLevel == d) { if (preNodes.size() == 0) { TreeNode newRoot = new TreeNode(v); newRoot.left = root; return newRoot; } for (int i = 0; i < preNodes.size(); ++i) { TreeNode currentNode = preNodes.get(i); TreeNode left = new TreeNode(v); TreeNode right = new TreeNode(v); left.left = currentNode.left; right.right = currentNode.right; currentNode.left = left; currentNode.right = right; } ++currentLevel; break; } preNodes.clear(); int size = queue.size(); for (int i = 0; i < size; ++i) { TreeNode currentNode = queue.poll(); preNodes.add(currentNode); if (currentNode.left != null) { queue.offer(currentNode.left); } if (currentNode.right != null) { queue.offer(currentNode.right); } } ++currentLevel; } if (currentLevel == d) { for (int i = 0; i < preNodes.size(); ++i) { preNodes.get(i).left = new TreeNode(v); preNodes.get(i).right = new TreeNode(v); } } return root; } public static void main(String[] args) { TreeNode t1 = new TreeNode(1); TreeNode t2 = new TreeNode(2); TreeNode t3 = new TreeNode(3); TreeNode t4 = new TreeNode(4); // TreeNode t5 = new TreeNode(1); // TreeNode t6 = new TreeNode(5); t1.left = t2; t1.right = t3; t2.left = t4; // t2.right = t5; // t3.left = t6; new AddOneRowtoTree().addOneRow(t1, 5, 4); } }
UTF-8
Java
2,442
java
AddOneRowtoTree.java
Java
[ { "context": "mport java.util.Queue;\n\n/**\n * @Title:\n * @Author: FFYzz\n * @Mail: cryptochen95 at gmail dot com\n * @Date:", "end": 137, "score": 0.999671459197998, "start": 132, "tag": "USERNAME", "value": "FFYzz" }, { "context": "Queue;\n\n/**\n * @Title:\n * @Author: FFYzz\n * @Mail: cryptochen95 at gmail dot com\n * @Date: 2020/12/6\n */\npublic c", "end": 160, "score": 0.8439220786094666, "start": 148, "tag": "EMAIL", "value": "cryptochen95" } ]
null
[]
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @Title: * @Author: FFYzz * @Mail: <EMAIL> at gmail dot com * @Date: 2020/12/6 */ public class AddOneRowtoTree { public TreeNode addOneRow(TreeNode root, int v, int d) { Queue<TreeNode> queue = new LinkedList<>(); int currentLevel = 1; List<TreeNode> preNodes = new ArrayList<>(); queue.offer(root); while (!queue.isEmpty()) { if (currentLevel == d) { if (preNodes.size() == 0) { TreeNode newRoot = new TreeNode(v); newRoot.left = root; return newRoot; } for (int i = 0; i < preNodes.size(); ++i) { TreeNode currentNode = preNodes.get(i); TreeNode left = new TreeNode(v); TreeNode right = new TreeNode(v); left.left = currentNode.left; right.right = currentNode.right; currentNode.left = left; currentNode.right = right; } ++currentLevel; break; } preNodes.clear(); int size = queue.size(); for (int i = 0; i < size; ++i) { TreeNode currentNode = queue.poll(); preNodes.add(currentNode); if (currentNode.left != null) { queue.offer(currentNode.left); } if (currentNode.right != null) { queue.offer(currentNode.right); } } ++currentLevel; } if (currentLevel == d) { for (int i = 0; i < preNodes.size(); ++i) { preNodes.get(i).left = new TreeNode(v); preNodes.get(i).right = new TreeNode(v); } } return root; } public static void main(String[] args) { TreeNode t1 = new TreeNode(1); TreeNode t2 = new TreeNode(2); TreeNode t3 = new TreeNode(3); TreeNode t4 = new TreeNode(4); // TreeNode t5 = new TreeNode(1); // TreeNode t6 = new TreeNode(5); t1.left = t2; t1.right = t3; t2.left = t4; // t2.right = t5; // t3.left = t6; new AddOneRowtoTree().addOneRow(t1, 5, 4); } }
2,437
0.470925
0.454955
76
31.131578
17.381435
60
false
false
0
0
0
0
0
0
0.684211
false
false
2
46a8347c871c1aed561084c6207ab525135022f8
24,292,335,053,485
46c606ea9e714f6b8981d3681c4165770f72dca7
/spring-boot/spring-boot-oauth/security-basic/src/main/java/com/xlaser4j/demo/service/TestService.java
dc66cc85a8346d72eec92d8065b98a4d7861f7e7
[ "MIT" ]
permissive
poppycoding/2020-lab-01
https://github.com/poppycoding/2020-lab-01
b0774c7dafe6eb5329c8716acc89f0cf727da062
49dac5154bc02410320dccde041dd6ab16372179
refs/heads/master
2023-06-29T18:17:04.713000
2020-04-20T13:19:21
2020-04-20T13:19:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xlaser4j.demo.service; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; /** * @package: com.xlaser4j.demo.service * @author: Elijah.D * @time: 2020/2/2 15:57 * @description: * @modified: Elijah.D */ @Service public class TestService { /** * @return */ @PreAuthorize("hasRole('user')") public String preU() { return "PreAuthorize: 首先配置config类开启方法权限控制,然后方法上添加PreAuthorize注解控制权限(user)."; } /** * @return */ @PreAuthorize("hasAnyRole('user','admin')") public String preAu() { return "PreAuthorize: 首先配置config类开启方法权限控制,然后方法上添加PreAuthorize注解控制权限(user&admin)."; } /** * 查看登陆成功的认证信息即可直到前缀信息: authority: "ROLE_user" * { * password: null, * username: "elijah", * authorities: [{ * authority: "ROLE_user" * }], * accountNonExpired: true, * accountNonLocked: true, * credentialsNonExpired: true, * enabled: true * } * * @return */ @Secured("ROLE_admin") public String secureA() { return "Secured: 首先配置config类开启方法权限控制,然后(默认角色前缀ROLE_)方法上添加Secured注解控制权限(admin)."; } /** * @return */ @Secured({"ROLE_admin", "ROLE_user"}) public String secureAu() { return "Secured: 首先配置config类开启方法权限控制,然后默认角色前缀ROLE_方法上添加Secured注解控制权限(admin&user)."; } }
UTF-8
Java
1,741
java
TestService.java
Java
[ { "context": " * @package: com.xlaser4j.demo.service\n * @author: Elijah.D\n * @time: 2020/2/2 15:57\n * @description:\n * @mod", "end": 275, "score": 0.9886975288391113, "start": 267, "tag": "NAME", "value": "Elijah.D" }, { "context": "ime: 2020/2/2 15:57\n * @description:\n * @modified: Elijah.D\n */\n@Service\npublic class TestService {\n /**\n ", "end": 340, "score": 0.9893203973770142, "start": 332, "tag": "NAME", "value": "Elijah.D" }, { "context": ": authority: \"ROLE_user\"\n * {\n * password: null,\n * username: \"elijah\",\n * authorities: [", "end": 862, "score": 0.9984496831893921, "start": 858, "tag": "PASSWORD", "value": "null" }, { "context": " * {\n * password: null,\n * username: \"elijah\",\n * authorities: [{\n * authority: \"ROLE_", "end": 888, "score": 0.9996058344841003, "start": 882, "tag": "USERNAME", "value": "elijah" } ]
null
[]
package com.xlaser4j.demo.service; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; /** * @package: com.xlaser4j.demo.service * @author: Elijah.D * @time: 2020/2/2 15:57 * @description: * @modified: Elijah.D */ @Service public class TestService { /** * @return */ @PreAuthorize("hasRole('user')") public String preU() { return "PreAuthorize: 首先配置config类开启方法权限控制,然后方法上添加PreAuthorize注解控制权限(user)."; } /** * @return */ @PreAuthorize("hasAnyRole('user','admin')") public String preAu() { return "PreAuthorize: 首先配置config类开启方法权限控制,然后方法上添加PreAuthorize注解控制权限(user&admin)."; } /** * 查看登陆成功的认证信息即可直到前缀信息: authority: "ROLE_user" * { * password: <PASSWORD>, * username: "elijah", * authorities: [{ * authority: "ROLE_user" * }], * accountNonExpired: true, * accountNonLocked: true, * credentialsNonExpired: true, * enabled: true * } * * @return */ @Secured("ROLE_admin") public String secureA() { return "Secured: 首先配置config类开启方法权限控制,然后(默认角色前缀ROLE_)方法上添加Secured注解控制权限(admin)."; } /** * @return */ @Secured({"ROLE_admin", "ROLE_user"}) public String secureAu() { return "Secured: 首先配置config类开启方法权限控制,然后默认角色前缀ROLE_方法上添加Secured注解控制权限(admin&user)."; } }
1,747
0.628824
0.620666
60
23.516666
23.147709
91
false
false
0
0
0
0
0
0
0.333333
false
false
2
7d09e5eb4218eca813722471303f4b7e1d48e57b
5,025,111,743,964
72a6974bcd5e543228b13405aad0d83e73c89dff
/test/sudoku/test/SolverTest.java
c431c5455f99c9f9379c48d6b478510212c1aa0d
[ "MIT" ]
permissive
mkhadaro/sudoku-toolbox
https://github.com/mkhadaro/sudoku-toolbox
a8c5721af93a91069bac4f740235723d98375c32
4f8b57ec6263d836214180e02a8d9c26ea8db78b
refs/heads/master
2021-01-16T17:42:45.055000
2013-09-26T12:38:00
2013-09-26T12:38:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sudoku.test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import sudoku.StaticGrid; import sudoku.exception.InvalidGridException; import sudoku.generator.Difficulty; import sudoku.solver.Solver; import sudoku.solver.SolverMode; import sudoku.solver.SolverResult; public class SolverTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void setUp() throws Exception { } @Test public void testSolveEasyGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.EASY.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertTrue(s.getResult() == SolverResult.ONE_SOLUTION); } @Test public void testSolveMediumGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.MEDIUM.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertEquals("356719824248563197791284653635972481827146935419835276962457318583621749174398562", s.getSolutions().get(0).toString()); } @Test public void testSolveHardGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.HARD.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertTrue(s.getSolvingTime() < 30); } @Test public void testSolveEvilGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.EVIL.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertTrue(s.getSolvingTime() < 50); } @Test public void testSolveMultipleSolutionsGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.MULTIPLE_SOLUTIONS.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertEquals(5, s.getSolutionsCount()); } @Test public void testSolveLotsOfSolutionsGrid1() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.LOTS_OF_SOLUTIONS.getGridString())); s.solve(SolverMode.STOP_FIRST_SOLUTION); assertEquals(SolverResult.AT_LEAST_ONE_SOLUTION, s.getResult()); } @Test public void testSolveLotsOfSolutionsGrid2() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.LOTS_OF_SOLUTIONS.getGridString())); s.solve(SolverMode.STOP_SECOND_SOLUTION); assertEquals(SolverResult.MULTIPLE_SOLUTIONS, s.getResult()); } @Test public void testSolveNoSolutionGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.NO_SOLUTION.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertEquals(SolverResult.NO_SOLUTION, s.getResult()); } @Test public void testDetermineHumanDifficultyPieceOfCakeGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.PIECE_OF_CAKE.getGridString())); assertEquals(Difficulty.PIECE_OF_CAKE, s.determineHumanDifficulty()); } @Test public void testDetermineHumanDifficultyEasyGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.EASY.getGridString())); assertEquals(Difficulty.EASY, s.determineHumanDifficulty()); } }
UTF-8
Java
3,139
java
SolverTest.java
Java
[]
null
[]
package sudoku.test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import sudoku.StaticGrid; import sudoku.exception.InvalidGridException; import sudoku.generator.Difficulty; import sudoku.solver.Solver; import sudoku.solver.SolverMode; import sudoku.solver.SolverResult; public class SolverTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void setUp() throws Exception { } @Test public void testSolveEasyGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.EASY.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertTrue(s.getResult() == SolverResult.ONE_SOLUTION); } @Test public void testSolveMediumGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.MEDIUM.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertEquals("356719824248563197791284653635972481827146935419835276962457318583621749174398562", s.getSolutions().get(0).toString()); } @Test public void testSolveHardGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.HARD.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertTrue(s.getSolvingTime() < 30); } @Test public void testSolveEvilGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.EVIL.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertTrue(s.getSolvingTime() < 50); } @Test public void testSolveMultipleSolutionsGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.MULTIPLE_SOLUTIONS.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertEquals(5, s.getSolutionsCount()); } @Test public void testSolveLotsOfSolutionsGrid1() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.LOTS_OF_SOLUTIONS.getGridString())); s.solve(SolverMode.STOP_FIRST_SOLUTION); assertEquals(SolverResult.AT_LEAST_ONE_SOLUTION, s.getResult()); } @Test public void testSolveLotsOfSolutionsGrid2() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.LOTS_OF_SOLUTIONS.getGridString())); s.solve(SolverMode.STOP_SECOND_SOLUTION); assertEquals(SolverResult.MULTIPLE_SOLUTIONS, s.getResult()); } @Test public void testSolveNoSolutionGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.NO_SOLUTION.getGridString())); s.solve(SolverMode.DO_NOT_STOP); assertEquals(SolverResult.NO_SOLUTION, s.getResult()); } @Test public void testDetermineHumanDifficultyPieceOfCakeGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.PIECE_OF_CAKE.getGridString())); assertEquals(Difficulty.PIECE_OF_CAKE, s.determineHumanDifficulty()); } @Test public void testDetermineHumanDifficultyEasyGrid() throws InvalidGridException { Solver s = new Solver(new StaticGrid(TestGrid.EASY.getGridString())); assertEquals(Difficulty.EASY, s.determineHumanDifficulty()); } }
3,139
0.753743
0.72539
94
31.393618
31.162313
136
false
false
0
0
0
0
81
0.025804
1.489362
false
false
2
7dd63bc1edc283857459cb417451f93135f41023
11,476,152,622,501
a1f7ac771d66bca439132f7346663f65e640bf11
/BankAccountDetails.java
300122ad7832b09f90b98087c23bacfd0e8aa3b8
[]
no_license
muditgarg188/DBSHacktrix_Team1_March30_2019
https://github.com/muditgarg188/DBSHacktrix_Team1_March30_2019
bc3a0af68e39bf2033d909ebf63952556cdc290f
864560e9b7ea6e3b2642f5c48e850f6e4de00bf1
refs/heads/master
2020-05-03T08:20:12.590000
2019-03-30T09:17:44
2019-03-30T09:17:44
178,523,255
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package testPackage; public class BankAccountDetails { private int creditCards; private int personalLoans; private int homeLoans; private boolean isDefaulter; public BankAccountDetails( ) { creditCards = 0; personalLoans = 0; homeLoans = 0; isDefaulter = false; } public int getCreditCards() { return creditCards; } public void setCreditCards(int creditCards) { this.creditCards = creditCards; } public int getPersonalLoans() { return personalLoans; } public void setPersonalLoans(int personalLoans) { this.personalLoans = personalLoans; } public int getHomeLoans() { return homeLoans; } public void setHomeLoans(int homeLoans) { this.homeLoans = homeLoans; } public boolean isDefaulter() { return isDefaulter; } public void setDefaulter(boolean isDefaulter) { this.isDefaulter = isDefaulter; } }
UTF-8
Java
894
java
BankAccountDetails.java
Java
[]
null
[]
package testPackage; public class BankAccountDetails { private int creditCards; private int personalLoans; private int homeLoans; private boolean isDefaulter; public BankAccountDetails( ) { creditCards = 0; personalLoans = 0; homeLoans = 0; isDefaulter = false; } public int getCreditCards() { return creditCards; } public void setCreditCards(int creditCards) { this.creditCards = creditCards; } public int getPersonalLoans() { return personalLoans; } public void setPersonalLoans(int personalLoans) { this.personalLoans = personalLoans; } public int getHomeLoans() { return homeLoans; } public void setHomeLoans(int homeLoans) { this.homeLoans = homeLoans; } public boolean isDefaulter() { return isDefaulter; } public void setDefaulter(boolean isDefaulter) { this.isDefaulter = isDefaulter; } }
894
0.704698
0.701342
42
19.285715
15.095388
50
false
false
0
0
0
0
0
0
1.595238
false
false
2
1cf2e9bde7e5af0e9ed7d53dbf28ddb423eceff3
21,311,627,773,003
d17b841bc2dcde2ed0fb790b6e42df8a339d1788
/src/main/java/com/jio/iot/smartreplenishment/application/resources/ReplenishmentResource.java
46f94c9b9b90fc2eb294f7546392dd2b9c755920
[]
no_license
chaitanya-plylabs/smartstore
https://github.com/chaitanya-plylabs/smartstore
6bf36fdf5129a1cf825a959c0c219f11ab78e69c
d323895d2ee5c0e527f1e170a26911623a63a4e6
refs/heads/master
2020-05-20T13:47:28.870000
2019-05-15T03:44:48
2019-05-15T03:44:48
185,607,460
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jio.iot.smartreplenishment.application.resources; import com.jio.iot.smartreplenishment.application.representation.ConstraintRepresentation; import com.jio.iot.smartreplenishment.application.representation.ReplenishRepresentation; import com.jio.iot.smartreplenishment.application.service.ReplenishmentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import javax.validation.Valid; import javax.validation.constraints.NotNull; @RestController @RequestMapping("store/{storeId}/replenish") public class ReplenishmentResource { @Autowired private ReplenishmentService replenishmentService; @PostMapping @ResponseStatus(HttpStatus.OK) public Mono<ReplenishRepresentation> replenish(@NotNull @PathVariable("storeId") final String storeId , @RequestBody @NotNull @Valid final ConstraintRepresentation representation) { return Mono.just(this.replenishmentService.replenish(storeId, representation)); } }
UTF-8
Java
1,110
java
ReplenishmentResource.java
Java
[]
null
[]
package com.jio.iot.smartreplenishment.application.resources; import com.jio.iot.smartreplenishment.application.representation.ConstraintRepresentation; import com.jio.iot.smartreplenishment.application.representation.ReplenishRepresentation; import com.jio.iot.smartreplenishment.application.service.ReplenishmentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import javax.validation.Valid; import javax.validation.constraints.NotNull; @RestController @RequestMapping("store/{storeId}/replenish") public class ReplenishmentResource { @Autowired private ReplenishmentService replenishmentService; @PostMapping @ResponseStatus(HttpStatus.OK) public Mono<ReplenishRepresentation> replenish(@NotNull @PathVariable("storeId") final String storeId , @RequestBody @NotNull @Valid final ConstraintRepresentation representation) { return Mono.just(this.replenishmentService.replenish(storeId, representation)); } }
1,110
0.820721
0.820721
26
41.692307
32.714111
105
false
false
0
0
0
0
0
0
0.538462
false
false
2
86c730525468246afe9cce308112705b44d1fecd
42,949,714,121
757eec054082e6582155acd734294d6eb09d181c
/java_tutorials/src/LessonB5_EventListener/implementClass_Mouse_main.java
5afa3a2ef1400dee19c5b531c03f183071ca5914
[]
no_license
estellechoi/java-tutorials
https://github.com/estellechoi/java-tutorials
3ed2d1ccf3270eda62880ea187b2143e2b0bb38b
0f92bd4e8e051b732405be9d2414bf137561f0cc
refs/heads/master
2020-05-22T14:04:29.407000
2019-10-18T05:53:03
2019-10-18T05:53:03
186,374,622
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package LessonB5_EventListener; public class implementClass_Mouse_main { public static void main(String[] args) { implementClass_Mouse f = new implementClass_Mouse(); } }
UTF-8
Java
191
java
implementClass_Mouse_main.java
Java
[]
null
[]
package LessonB5_EventListener; public class implementClass_Mouse_main { public static void main(String[] args) { implementClass_Mouse f = new implementClass_Mouse(); } }
191
0.701571
0.696335
11
15.363636
20.374996
54
false
false
0
0
0
0
0
0
0.545455
false
false
2
8d7630ec13e0afb7c49155f0bc113e108fc75dc9
13,700,945,696,045
e959ad9dd61368bdaa0a4954c34ac259c36b9165
/src/main/java/com/nisum/macyd/nisumJersyDemo/NisumJersyDemoApplication.java
ca0ef261d14cf5909df1b174638ad5b6a3d30878
[]
no_license
Harish6372/demo-git
https://github.com/Harish6372/demo-git
e86a5bafe10af188e7f109eec98b5b1b940cf8ff
f010aeab8473310d38a75e36309f66b6abf86801
refs/heads/master
2021-05-06T18:48:22.180000
2017-11-26T16:14:58
2017-11-26T16:14:58
112,053,720
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nisum.macyd.nisumJersyDemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class NisumJersyDemoApplication { public static void main(String[] args) { System.out.println("sating lskbs"); SpringApplication.run(NisumJersyDemoApplication.class, args); System.out.println("starting lskbs"); System.out.println("starsmsmsmnsmsmting lskbs"); System.out.println("starsmsmsmnsmsmting lskbs local"); System.out.println("starsmsmsmnsmsmting lskbs local1"); System.out.println("starsmsmsmnsmsmting lskbs local1s"); System.out.println("starsmsmsmnsmsmting lskbs ljsajsajksajkocal1s"); } }
UTF-8
Java
712
java
NisumJersyDemoApplication.java
Java
[]
null
[]
package com.nisum.macyd.nisumJersyDemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class NisumJersyDemoApplication { public static void main(String[] args) { System.out.println("sating lskbs"); SpringApplication.run(NisumJersyDemoApplication.class, args); System.out.println("starting lskbs"); System.out.println("starsmsmsmnsmsmting lskbs"); System.out.println("starsmsmsmnsmsmting lskbs local"); System.out.println("starsmsmsmnsmsmting lskbs local1"); System.out.println("starsmsmsmnsmsmting lskbs local1s"); System.out.println("starsmsmsmnsmsmting lskbs ljsajsajksajkocal1s"); } }
712
0.807584
0.803371
19
36.473682
24.221279
70
false
false
0
0
0
0
0
0
1.578947
false
false
2
e2e58caabea327a5b8357a7e9c67c9c84e3e5fb1
7,052,336,305,597
feb5186c8d67ca79b3e9cdbdbc0a261eb9d9a8cf
/src/main/java/com/asl/pms/model/Demand.java
f69939eac538fcaef10583048464ff99018784c4
[]
no_license
TofazzalTopu/Pharmacy-App-Spring-Boot-Hibernate-Jpa-MariaDB
https://github.com/TofazzalTopu/Pharmacy-App-Spring-Boot-Hibernate-Jpa-MariaDB
6e14de7ddae4a53aa8f82be8045315f5d006e080
c16cd71e9418ac859dbd83b6da9c62297eadfa1e
refs/heads/master
2022-08-27T22:12:29.746000
2020-05-30T12:42:47
2020-05-30T12:42:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.asl.pms.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "demand") public @Data class Demand { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.LAZY) @JsonIgnore private Drug drug; private String priority; private String remarks; @Setter @Getter private Date createDate; public Demand() { } /*public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Drug getDrug() { return drug; } public void setDrug(Drug drug) { this.drug = drug; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; }*/ }
UTF-8
Java
1,350
java
Demand.java
Java
[]
null
[]
package com.asl.pms.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "demand") public @Data class Demand { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.LAZY) @JsonIgnore private Drug drug; private String priority; private String remarks; @Setter @Getter private Date createDate; public Demand() { } /*public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Drug getDrug() { return drug; } public void setDrug(Drug drug) { this.drug = drug; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; }*/ }
1,350
0.585926
0.585926
75
16
15.039503
54
false
false
0
0
0
0
0
0
0.293333
false
false
2
aafdf1ac6f9fd1f1103511cad8df394195fb384b
16,063,177,755,843
79952a618a14e598374a7a9c7f247b8e4aa8104c
/klinsurance-service/src/main/java/com/ht/klinsurance/sys/model/WordTemplateVo.java
266c1e226e973b82b38173a2626ffcc85a2848ea
[]
no_license
Lindp/klinsurance
https://github.com/Lindp/klinsurance
68d3b26fb9f9683bdca8d8c772c77adaa7c422f9
09e53d4aa48ae5448e21d7282471d38a3c592ea9
refs/heads/master
2016-09-22T16:58:21.882000
2016-09-21T03:21:41
2016-09-21T03:21:41
65,885,899
0
1
null
false
2016-08-30T13:20:55
2016-08-17T07:28:42
2016-08-18T08:14:52
2016-08-30T13:20:55
3,148
0
1
1
FreeMarker
null
null
package com.ht.klinsurance.sys.model; import lombok.Data; @Data public class WordTemplateVo { private byte[] byteArray; private String fileType; }
UTF-8
Java
153
java
WordTemplateVo.java
Java
[]
null
[]
package com.ht.klinsurance.sys.model; import lombok.Data; @Data public class WordTemplateVo { private byte[] byteArray; private String fileType; }
153
0.764706
0.764706
10
14.3
13.616534
37
false
false
0
0
0
0
0
0
0.7
false
false
2
f43aad6dcdba321ef925e8fa77a6a8809ee27a90
20,375,324,890,677
3ffeb817f463610351d390b68488c2d505091227
/src/main/java/com/vikasKrSherawat/payroll/controller/EmployeeController.java
9477c78a6870b0e0cc0e2a247fb0e40ea6ded1ed
[]
no_license
VikasSherawat/SpringRestfulApi
https://github.com/VikasSherawat/SpringRestfulApi
6e78e715ff1ae4a43fc5a600570708d5dcaf27f4
db43c8fe74a77598f0ddb53baca6779379a863b9
refs/heads/master
2023-02-24T06:57:29.073000
2021-01-30T05:31:40
2021-01-30T05:31:40
334,337,022
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vikasKrSherawat.payroll.controller; import com.vikasKrSherawat.payroll.exception.EmployeeNotFoundException; import com.vikasKrSherawat.payroll.model.employee.Employee; import com.vikasKrSherawat.payroll.model.employee.EmployeeModelAssembler; import com.vikasKrSherawat.payroll.repository.EmployeeRepository; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.IanaLinkRelations; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; 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.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.stream.Collectors; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @RestController public class EmployeeController { private final EmployeeRepository employeeRepository; private final EmployeeModelAssembler employeeAssembler; public EmployeeController(EmployeeRepository employeeRepository,EmployeeModelAssembler employeeAssembler) { this.employeeRepository = employeeRepository; this.employeeAssembler = employeeAssembler; } @GetMapping("/employees") public CollectionModel<EntityModel<Employee>> getAllEmployees(){ List<EntityModel<Employee>> employees = employeeRepository.findAll() .stream() .map(employeeAssembler::toModel).collect(Collectors.toList()); return CollectionModel.of(employees, linkTo(methodOn(EmployeeController.class).getAllEmployees()).withSelfRel()); } @GetMapping("/employee/{id}") public EntityModel<Employee> findEmployeeById(@PathVariable Long id) { Employee employee = employeeRepository.findById(id) .orElseThrow(()->new EmployeeNotFoundException(id)); return employeeAssembler.toModel(employee); } @PostMapping("/employees") public ResponseEntity<?> addEmployee(@RequestBody Employee employee){ EntityModel<Employee> entityModel = employeeAssembler.toModel(employeeRepository.save(employee)); return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()) .body(entityModel); } @PutMapping("/employees/{id}") ResponseEntity<?> updateEmployee(@RequestBody Employee newEmployee, @PathVariable Long id) { Employee updatedEmployee = employeeRepository.findById(id) .map(employee -> { employee.setName(newEmployee.getName()); employee.setRole(newEmployee.getRole()); return employeeRepository.save(employee); }) .orElseThrow(()->new EmployeeNotFoundException(id)); EntityModel<Employee> entityModel = employeeAssembler.toModel(updatedEmployee); return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()) .body(entityModel); } @DeleteMapping("/employees/{id}") ResponseEntity<?> deleteEmployee(@PathVariable Long id) { employeeRepository.deleteById(id); return ResponseEntity.noContent().build(); } }
UTF-8
Java
3,614
java
EmployeeController.java
Java
[]
null
[]
package com.vikasKrSherawat.payroll.controller; import com.vikasKrSherawat.payroll.exception.EmployeeNotFoundException; import com.vikasKrSherawat.payroll.model.employee.Employee; import com.vikasKrSherawat.payroll.model.employee.EmployeeModelAssembler; import com.vikasKrSherawat.payroll.repository.EmployeeRepository; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.IanaLinkRelations; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; 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.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.stream.Collectors; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @RestController public class EmployeeController { private final EmployeeRepository employeeRepository; private final EmployeeModelAssembler employeeAssembler; public EmployeeController(EmployeeRepository employeeRepository,EmployeeModelAssembler employeeAssembler) { this.employeeRepository = employeeRepository; this.employeeAssembler = employeeAssembler; } @GetMapping("/employees") public CollectionModel<EntityModel<Employee>> getAllEmployees(){ List<EntityModel<Employee>> employees = employeeRepository.findAll() .stream() .map(employeeAssembler::toModel).collect(Collectors.toList()); return CollectionModel.of(employees, linkTo(methodOn(EmployeeController.class).getAllEmployees()).withSelfRel()); } @GetMapping("/employee/{id}") public EntityModel<Employee> findEmployeeById(@PathVariable Long id) { Employee employee = employeeRepository.findById(id) .orElseThrow(()->new EmployeeNotFoundException(id)); return employeeAssembler.toModel(employee); } @PostMapping("/employees") public ResponseEntity<?> addEmployee(@RequestBody Employee employee){ EntityModel<Employee> entityModel = employeeAssembler.toModel(employeeRepository.save(employee)); return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()) .body(entityModel); } @PutMapping("/employees/{id}") ResponseEntity<?> updateEmployee(@RequestBody Employee newEmployee, @PathVariable Long id) { Employee updatedEmployee = employeeRepository.findById(id) .map(employee -> { employee.setName(newEmployee.getName()); employee.setRole(newEmployee.getRole()); return employeeRepository.save(employee); }) .orElseThrow(()->new EmployeeNotFoundException(id)); EntityModel<Employee> entityModel = employeeAssembler.toModel(updatedEmployee); return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()) .body(entityModel); } @DeleteMapping("/employees/{id}") ResponseEntity<?> deleteEmployee(@PathVariable Long id) { employeeRepository.deleteById(id); return ResponseEntity.noContent().build(); } }
3,614
0.740454
0.740454
80
44.174999
29.119055
111
false
false
0
0
0
0
0
0
0.5125
false
false
2
6f27b5eeaa0b18df06a6c53406534d6d654211aa
6,356,551,601,807
6cbc56eeb231ff481d5e836bc07180420f138807
/Java Web/POO/src/Unidad1/ParameterManager.java
6222c8cd6434694c64fe4094a2d1cbdacfcbee14
[]
no_license
flynn1411/POO_IPAC2020
https://github.com/flynn1411/POO_IPAC2020
ee4d0eab87875b2b2dea61fc8bfe5372f3f20a75
58f3a49b4e8dcf245e02227f23ca713c64345b5f
refs/heads/master
2020-12-22T10:14:56.904000
2020-03-12T06:00:33
2020-03-12T06:00:33
236,748,169
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Unidad1; import java.util.ArrayList; import java.util.List; import java.util.Map; /* Visibilidad: Caracteristica de los objetos Public:Cuando el atributo o método se puede ver desde dentro o fuera de la clase. Private:No se puede heredar ni son visibles fuera de la clase. Protected: No son visibles fuera de la clase pero son heredables. */ /** * Gestiona la cantidad de parámetros recibidos. * Cuantifica y categoriza los parámetros recibidos por el programa. * @author @POO * @version 0.1.0 */ public class ParameterManager { public ResponseParameterManager analyze (Map<String, String[]> parameters){ int count = 0; ResponseParameterManager rpm = new ResponseParameterManager(); List<ParameterAnalysis> results = new ArrayList<>(); for (String[] parameter: parameters.values()) { /** * hobbie=1 * age=20 * name=POO * hobbie=1 * hobbie=1 * hobbie=0 * hobbie=7 */ //Ejemplo primitivo de la generación de la matriz //StringBuilder p = new StringBuilder(""); for(String element: parameter) { count++; int length; String parameterType; //Tamaño en caracteres del valor del parámetro length = element.length(); //element contiene el valor del parametro que se procesa if(element.matches("-?\\d+(\\.\\d+)?")) { parameterType = "numeric"; }else { parameterType = "alphanumeric"; } results.add( new ParameterAnalysis(element, length, parameterType) ); } rpm.setCount(count); //System.out.println(p); rpm.setResult(results); } //rpm.setCount(count); return rpm; } public String convertResponseToHTML(ResponseParameterManager rpm) { int count = rpm.getCount(); List<ParameterAnalysis> results = rpm.getResults(); StringBuilder html = new StringBuilder("<table border ='1'>"); html.append( String.format("<tr><td>Parámetros encontrados:</td><td>%s</td></tr>", count) ); html.append( String.format("<tr><td colspan='2'>%s</td></tr>", this.convertResultsToHTMLTable(results) ) ); html.append("</table>"); return html.toString(); } private String convertResultsToHTMLTable( List<ParameterAnalysis> results ) { int count = 1; StringBuilder html = new StringBuilder("<table border='1'>"); html.append("<thead>"); html.append("<tr>"); html.append( "<th>No.</th>" ); html.append( "<th>Valor</th>" ); html.append( "<th>Tamaño en Carácteres</th>" ); html.append( "<th>Tipo de Dato</th>" ); html.append("</tr>"); html.append("<thead>"); html.append("<tbody>"); try { for( ParameterAnalysis element: results ) { html.append("<tr>"); html.append( String.format( "<td>%s</td>" , count ) ); html.append( String.format( "<td>%s</td>" , element.getValue() ) ); html.append( String.format( "<td>%s</td>" , element.getLength() ) ); html.append( String.format( "<td>%s</td>" , element.getType() ) ); html.append("</tr>"); count++; } }catch(Exception e) { System.out.println("Error: " + e); } html.append("</tbody>"); html.append("</table>"); return html.toString(); } }
ISO-8859-1
Java
3,725
java
ParameterManager.java
Java
[ { "context": " parámetros recibidos por el programa.\r\n * @author @POO\r\n * @version 0.1.0\r\n */\r\npublic class ParameterMa", "end": 519, "score": 0.9996476173400879, "start": 515, "tag": "USERNAME", "value": "@POO" }, { "context": " * hobbie=1\r\n \t * age=20\r\n \t * name=POO\r\n \t * hobbie=1\r\n \t * hobbie=1\r\n ", "end": 974, "score": 0.9959543943405151, "start": 971, "tag": "NAME", "value": "POO" } ]
null
[]
package Unidad1; import java.util.ArrayList; import java.util.List; import java.util.Map; /* Visibilidad: Caracteristica de los objetos Public:Cuando el atributo o método se puede ver desde dentro o fuera de la clase. Private:No se puede heredar ni son visibles fuera de la clase. Protected: No son visibles fuera de la clase pero son heredables. */ /** * Gestiona la cantidad de parámetros recibidos. * Cuantifica y categoriza los parámetros recibidos por el programa. * @author @POO * @version 0.1.0 */ public class ParameterManager { public ResponseParameterManager analyze (Map<String, String[]> parameters){ int count = 0; ResponseParameterManager rpm = new ResponseParameterManager(); List<ParameterAnalysis> results = new ArrayList<>(); for (String[] parameter: parameters.values()) { /** * hobbie=1 * age=20 * name=POO * hobbie=1 * hobbie=1 * hobbie=0 * hobbie=7 */ //Ejemplo primitivo de la generación de la matriz //StringBuilder p = new StringBuilder(""); for(String element: parameter) { count++; int length; String parameterType; //Tamaño en caracteres del valor del parámetro length = element.length(); //element contiene el valor del parametro que se procesa if(element.matches("-?\\d+(\\.\\d+)?")) { parameterType = "numeric"; }else { parameterType = "alphanumeric"; } results.add( new ParameterAnalysis(element, length, parameterType) ); } rpm.setCount(count); //System.out.println(p); rpm.setResult(results); } //rpm.setCount(count); return rpm; } public String convertResponseToHTML(ResponseParameterManager rpm) { int count = rpm.getCount(); List<ParameterAnalysis> results = rpm.getResults(); StringBuilder html = new StringBuilder("<table border ='1'>"); html.append( String.format("<tr><td>Parámetros encontrados:</td><td>%s</td></tr>", count) ); html.append( String.format("<tr><td colspan='2'>%s</td></tr>", this.convertResultsToHTMLTable(results) ) ); html.append("</table>"); return html.toString(); } private String convertResultsToHTMLTable( List<ParameterAnalysis> results ) { int count = 1; StringBuilder html = new StringBuilder("<table border='1'>"); html.append("<thead>"); html.append("<tr>"); html.append( "<th>No.</th>" ); html.append( "<th>Valor</th>" ); html.append( "<th>Tamaño en Carácteres</th>" ); html.append( "<th>Tipo de Dato</th>" ); html.append("</tr>"); html.append("<thead>"); html.append("<tbody>"); try { for( ParameterAnalysis element: results ) { html.append("<tr>"); html.append( String.format( "<td>%s</td>" , count ) ); html.append( String.format( "<td>%s</td>" , element.getValue() ) ); html.append( String.format( "<td>%s</td>" , element.getLength() ) ); html.append( String.format( "<td>%s</td>" , element.getType() ) ); html.append("</tr>"); count++; } }catch(Exception e) { System.out.println("Error: " + e); } html.append("</tbody>"); html.append("</table>"); return html.toString(); } }
3,725
0.543057
0.538751
126
27.492064
24.379847
112
false
false
0
0
0
0
0
0
1.730159
false
false
2
5a31c825cd9005f94024026cfaeec816d7cc3a23
23,888,608,130,487
67b5beab604c3dec6cd72f041d7f0333774de541
/app/src/main/java/com/example/projektmanagment/ProfessorDialog.java
a9a9a2b92aef06dc9e5501a52c336c87e5c584a7
[]
no_license
nils-imhoff/projektmanagement
https://github.com/nils-imhoff/projektmanagement
0d09387fd9d331512b5d7301b11c9134b06238d1
b68a8c6e73977736734fe71d32e6dee7372689b6
refs/heads/master
2020-06-01T13:23:06.898000
2019-06-23T18:51:59
2019-06-23T18:51:59
190,793,326
0
0
null
false
2019-06-19T20:55:25
2019-06-07T18:46:26
2019-06-16T08:16:36
2019-06-19T20:55:24
188
1
0
12
Java
false
false
package com.example.projektmanagment; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.appcompat.app.AppCompatDialogFragment; public class ProfessorDialog extends AppCompatDialogFragment { private Professor prof; public ProfessorDialog(Professor prof){ super(); this.prof = prof; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(prof.getName()).setMessage("Raum " + prof.getRaumnummer()+ "\nTel. "+prof.getTelefonnummer()+"\nFax. "+prof.getFaxnummer()+"\nMail "+prof.getEmail()+"\nLink "+prof.getLink()).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); return builder.create(); } }
UTF-8
Java
990
java
ProfessorDialog.java
Java
[ { "context": " builder.setTitle(prof.getName()).setMessage(\"Raum \" + prof.getRaumnummer()+ \"\\nTel. \"+prof.getTele", "end": 618, "score": 0.9912166595458984, "start": 614, "tag": "NAME", "value": "Raum" } ]
null
[]
package com.example.projektmanagment; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.appcompat.app.AppCompatDialogFragment; public class ProfessorDialog extends AppCompatDialogFragment { private Professor prof; public ProfessorDialog(Professor prof){ super(); this.prof = prof; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(prof.getName()).setMessage("Raum " + prof.getRaumnummer()+ "\nTel. "+prof.getTelefonnummer()+"\nFax. "+prof.getFaxnummer()+"\nMail "+prof.getEmail()+"\nLink "+prof.getLink()).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); return builder.create(); } }
990
0.7
0.7
29
33.137932
49.191898
264
false
false
0
0
0
0
0
0
0.482759
false
false
2
a1ed504c227bc745437e1ac03ff10837281fbe17
29,712,583,803,786
f8471cde07593556927eaee5dac765c63c0826fb
/java-1/Lesson 3/Lesson 3 Assingments/Assignment 4/src/coin/toss/Coin2.java
e115fe86525af8d643199230cba2e86b2118d6a7
[]
no_license
johnkirch123/java
https://github.com/johnkirch123/java
6ccadcf4f3a27e6a392b349c4ad0d28f4cf76957
2f0928b3f76a2f8f7c22eccaae97b018fb332110
refs/heads/master
2020-02-26T14:48:02.199000
2017-08-28T01:31:06
2017-08-28T01:31:06
95,608,407
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coin.toss; /** *Student: John Kirch *ID: S01581562 *Date: 02-07-2017 *CSC-240 Assignment 4 */ import java.security.SecureRandom; public enum Coin { HEADS, TAILS; private static final SecureRandom randomFlips = new SecureRandom(); private static int headsCounter; private static int tailsCounter; private static String coinReturnStatement; private final static int HEADS_STATE = 0; private final static int TAILS_STATE = 1; public static void flip (int numberOfTosses){ Coin coinState = Coin.HEADS; for (int i = 0; i < numberOfTosses; i++) { int flip = randomFlips.nextInt(2); if (flip == HEADS_STATE) { coinState = Coin.HEADS; } if (flip == TAILS_STATE) { coinState = Coin.TAILS; } switch (coinState) { case HEADS: headsCounter++; break; case TAILS: tailsCounter++; break; } } coinReturnStatement = "The total number of heads flipped is: " + headsCounter + "\nThe total number of tails flipped is: " + tailsCounter; } static String getStatement () { return coinReturnStatement; } }
UTF-8
Java
1,598
java
Coin2.java
Java
[ { "context": "\npackage coin.toss;\n\n/**\n *Student: John Kirch\n *ID: S01581562\n *Date: 02-07-2017\n *CSC-240 Assi", "end": 46, "score": 0.9998591542243958, "start": 36, "tag": "NAME", "value": "John Kirch" } ]
null
[]
package coin.toss; /** *Student: <NAME> *ID: S01581562 *Date: 02-07-2017 *CSC-240 Assignment 4 */ import java.security.SecureRandom; public enum Coin { HEADS, TAILS; private static final SecureRandom randomFlips = new SecureRandom(); private static int headsCounter; private static int tailsCounter; private static String coinReturnStatement; private final static int HEADS_STATE = 0; private final static int TAILS_STATE = 1; public static void flip (int numberOfTosses){ Coin coinState = Coin.HEADS; for (int i = 0; i < numberOfTosses; i++) { int flip = randomFlips.nextInt(2); if (flip == HEADS_STATE) { coinState = Coin.HEADS; } if (flip == TAILS_STATE) { coinState = Coin.TAILS; } switch (coinState) { case HEADS: headsCounter++; break; case TAILS: tailsCounter++; break; } } coinReturnStatement = "The total number of heads flipped is: " + headsCounter + "\nThe total number of tails flipped is: " + tailsCounter; } static String getStatement () { return coinReturnStatement; } }
1,594
0.460576
0.445557
67
22.835821
18.497759
85
false
false
0
0
0
0
0
0
0.328358
false
false
2
67b79244488eb11fb8613e3baa46ea7a6c0989b9
12,352,325,992,555
dd50b1b6d94e089d5561974e0f40da3a4ecdc0cb
/PushBullet/src/main/java/com/pushbullet/service/AccountsService.java
6fa5ae24af415c3fe0fcc031a36c455e164c38e5
[]
no_license
YusufAzam/NotificationApi
https://github.com/YusufAzam/NotificationApi
b507bf82147027b6e62d570564808e2480c716bf
7af672ed37e4074d69ded5070ec8bf2aaf4bf4b6
refs/heads/main
2023-04-14T13:58:13.700000
2021-04-28T08:34:23
2021-04-28T08:34:23
362,088,378
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pushbullet.service; import java.time.Instant; import java.util.ArrayList; import java.util.List; import com.pushbullet.exceptions.DuplicateUserException; import com.pushbullet.models.RegisterUserModel; import com.pushbullet.models.UserModel; import org.springframework.stereotype.Service; @Service public class AccountsService { private List<UserModel> listOfUsers = new ArrayList<UserModel>(); public Boolean createUser(RegisterUserModel registerUserModel) { UserModel user = new UserModel( registerUserModel.getUserName(), registerUserModel.getAccessToken(), Instant.now().toString().substring(0,19), 0); if(!this.listOfUsers.stream().anyMatch(userItem -> userItem.getUsername().equals(registerUserModel.getUserName()))) { this.listOfUsers.add(user); return true; } throw new DuplicateUserException("User " + registerUserModel.getUserName() + " already exists"); } public List<UserModel> getAllUsers() { return listOfUsers; } public UserModel getUser(String userName) { for(UserModel userModel: this.listOfUsers) { if(userModel.getUsername().equals(userName)) { return userModel; } } return null; } public void increment(String userName) { this.listOfUsers.forEach(user -> { if(user.getUsername().equals(userName)) { user.incrementNumOfNotificationsPushed(); } }); } }
UTF-8
Java
1,378
java
AccountsService.java
Java
[]
null
[]
package com.pushbullet.service; import java.time.Instant; import java.util.ArrayList; import java.util.List; import com.pushbullet.exceptions.DuplicateUserException; import com.pushbullet.models.RegisterUserModel; import com.pushbullet.models.UserModel; import org.springframework.stereotype.Service; @Service public class AccountsService { private List<UserModel> listOfUsers = new ArrayList<UserModel>(); public Boolean createUser(RegisterUserModel registerUserModel) { UserModel user = new UserModel( registerUserModel.getUserName(), registerUserModel.getAccessToken(), Instant.now().toString().substring(0,19), 0); if(!this.listOfUsers.stream().anyMatch(userItem -> userItem.getUsername().equals(registerUserModel.getUserName()))) { this.listOfUsers.add(user); return true; } throw new DuplicateUserException("User " + registerUserModel.getUserName() + " already exists"); } public List<UserModel> getAllUsers() { return listOfUsers; } public UserModel getUser(String userName) { for(UserModel userModel: this.listOfUsers) { if(userModel.getUsername().equals(userName)) { return userModel; } } return null; } public void increment(String userName) { this.listOfUsers.forEach(user -> { if(user.getUsername().equals(userName)) { user.incrementNumOfNotificationsPushed(); } }); } }
1,378
0.740203
0.7373
52
25.5
25.810329
119
false
false
0
0
0
0
0
0
1.961538
false
false
2
8d5de1533c011dc6ac85ea57c4fe07bfcd9ff301
23,081,154,303,002
80babfb1a1c9076e33c6bff9fd86f826ed2a9537
/src/test/java/autoTests/pages/service/test/TestFieldsBankidPage.java
2137e1cfc8f924432cb40aa4ebb1013f77850ee3
[]
no_license
bent533/iTest
https://github.com/bent533/iTest
0a1872e08d5e1061b46924f5a1e3f6b546cb0d7a
a836311812db907c9b9a3ec51fcb42497e6e0889
refs/heads/master
2021-01-13T12:06:29.628000
2016-06-14T13:15:23
2016-06-14T13:15:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package autoTests.pages.service.test; import autoTests.ConfigurationVariables; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import autoTests.pages.service.BaseServicePage; import java.awt.*; import java.awt.datatransfer.StringSelection; public class TestFieldsBankidPage extends BaseServicePage { WebDriver driver; ConfigurationVariables configVariables = ConfigurationVariables.getInstance(); public static String referenceNumber; //---------------- Элементы страницы------------------// @FindBy(name = "bankIdsID_Country") private WebElement countryField; // поле ввода гражданства @FindBy(name = "bankIdAddressFactual") private WebElement addressField; // поле ввода адреса прописки @FindBy(xpath = "(//input[@type='file'])[1]") public WebElement attachDocumentButton; // поле аттача @FindBy(name = "email") public WebElement emailField; @FindBy(xpath = "//div[@class='text-center ng-binding ng-scope']") private WebElement successText; //текст удачной создании заявки public TestFieldsBankidPage(WebDriver driver) { PageFactory.initElements(driver, this); this.driver = driver; } private static void setClipboardData(String document) { StringSelection stringSelection = new StringSelection(document); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(stringSelection, null); } //---------------- Методы ввода данных в поля------------------// public TestFieldsBankidPage typeInCountryField(String country) { countryField.clear(); countryField.sendKeys(country); // ввод гражданства return this; } public TestFieldsBankidPage typeInAddressField(String address) { addressField.clear(); addressField.sendKeys(address); // ввод адреса прописки return this; } public TestFieldsBankidPage typeInEmailField(String email){ emailField.clear(); emailField.sendKeys(email); return this; } @Override public TestFieldsBankidPage clickConfirmButton() { super.clickConfirmButton(); return this; } public TestFieldsBankidPage verifyServiceSuccessCreated(String email) { Assert.assertEquals(successText.getText(), "Результати будуть спрямовані на Ваш e-mail " + email);// проверка успешного создания заявки return this; } //=================методы по работе с номером заявки=======================// @Override public String saveReferenceNumber() { referenceNumber = super.saveReferenceNumber(); return referenceNumber; } }
UTF-8
Java
3,028
java
TestFieldsBankidPage.java
Java
[]
null
[]
package autoTests.pages.service.test; import autoTests.ConfigurationVariables; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import autoTests.pages.service.BaseServicePage; import java.awt.*; import java.awt.datatransfer.StringSelection; public class TestFieldsBankidPage extends BaseServicePage { WebDriver driver; ConfigurationVariables configVariables = ConfigurationVariables.getInstance(); public static String referenceNumber; //---------------- Элементы страницы------------------// @FindBy(name = "bankIdsID_Country") private WebElement countryField; // поле ввода гражданства @FindBy(name = "bankIdAddressFactual") private WebElement addressField; // поле ввода адреса прописки @FindBy(xpath = "(//input[@type='file'])[1]") public WebElement attachDocumentButton; // поле аттача @FindBy(name = "email") public WebElement emailField; @FindBy(xpath = "//div[@class='text-center ng-binding ng-scope']") private WebElement successText; //текст удачной создании заявки public TestFieldsBankidPage(WebDriver driver) { PageFactory.initElements(driver, this); this.driver = driver; } private static void setClipboardData(String document) { StringSelection stringSelection = new StringSelection(document); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(stringSelection, null); } //---------------- Методы ввода данных в поля------------------// public TestFieldsBankidPage typeInCountryField(String country) { countryField.clear(); countryField.sendKeys(country); // ввод гражданства return this; } public TestFieldsBankidPage typeInAddressField(String address) { addressField.clear(); addressField.sendKeys(address); // ввод адреса прописки return this; } public TestFieldsBankidPage typeInEmailField(String email){ emailField.clear(); emailField.sendKeys(email); return this; } @Override public TestFieldsBankidPage clickConfirmButton() { super.clickConfirmButton(); return this; } public TestFieldsBankidPage verifyServiceSuccessCreated(String email) { Assert.assertEquals(successText.getText(), "Результати будуть спрямовані на Ваш e-mail " + email);// проверка успешного создания заявки return this; } //=================методы по работе с номером заявки=======================// @Override public String saveReferenceNumber() { referenceNumber = super.saveReferenceNumber(); return referenceNumber; } }
3,028
0.688307
0.687948
82
33
27.851086
143
false
false
0
0
0
0
0
0
0.487805
false
false
2
e9c336b0a11cf16d93d89f113dd6aef243dc6a7b
33,139,967,707,410
72d2389ac84d9d21b4af890de627f256128b1702
/src/com/logistics/service/UserService.java
1af84ad525cbfa67a7048c9233cfe14da4e408e6
[]
no_license
geniepapa/JLogistics
https://github.com/geniepapa/JLogistics
55237ce1d5d8896ed6b6cb888a7988283911c57b
b8b74259fc3c7dc0a66953ced413fe0d47f7ee0e
refs/heads/master
2015-08-04T00:51:53.426000
2012-10-25T05:23:33
2012-10-25T05:23:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.logistics.service; import com.logistics.domain.User; public interface UserService { boolean hasMatchUser(String userName,String password); void loginSuccess(User user); }
UTF-8
Java
192
java
UserService.java
Java
[ { "context": "rface UserService {\n\t\n\tboolean hasMatchUser(String userName,String password);\n void loginSuccess(User user", "end": 137, "score": 0.9979009628295898, "start": 129, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.logistics.service; import com.logistics.domain.User; public interface UserService { boolean hasMatchUser(String userName,String password); void loginSuccess(User user); }
192
0.786458
0.786458
9
20.333334
19.102064
55
false
false
0
0
0
0
0
0
0.777778
false
false
2
d7e23670e62b05e903da779cd253c77bb547a58d
22,325,240,060,571
af81e9c5cd1b808ff02c78025300eae8c3d03cd3
/src/GuestsList.java
284f69460884b7e7769c90e2af8f4f0a45b58b87
[]
no_license
IrinaAlexandraDobre/Module2Project1
https://github.com/IrinaAlexandraDobre/Module2Project1
db0bddd3da277d967586e54891697ecab8b57478
58e6cf23f5c6207cb15ea5da489c1f0868832846
refs/heads/master
2023-04-18T14:35:14.242000
2021-05-06T08:38:58
2021-05-06T08:38:58
364,840,920
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Scanner; public class GuestsList { private int availableSeats; private int maxAvailableSeats; private ArrayList<Guest> participantsList; private ArrayList<Guest> waitingListInvites; public GuestsList() { this.maxAvailableSeats = 3; this.participantsList = new ArrayList<>(this.maxAvailableSeats); for (int i = 0; i < this.participantsList.size(); i++) { this.participantsList.add(0, this.participantsList.get(i)); } this.waitingListInvites = new ArrayList<>(this.maxAvailableSeats); for (int i = 0; i < this.waitingListInvites.size(); i++) { this.waitingListInvites.add(0, this.waitingListInvites.get(i)); } } Scanner sc = new Scanner(System.in); public Guest newGuest() { System.out.println("Enter last name: "); String lastName = sc.nextLine(); System.out.println("Enter first name: "); String firstName = sc.nextLine(); System.out.println("Enter email: "); String email = sc.nextLine(); System.out.println("Enter phone number: "); String phoneNumber = sc.nextLine(); Guest newGuest1 = new Guest(lastName, firstName, email, phoneNumber); return newGuest1; } public int add(String search) { this.availableSeats = this.maxAvailableSeats - participantsList.size(); int result = 0; if (check(search)) { result = -1; System.out.println("This person is already on the list."); } else if (!check(search)) { Guest addGuest = newGuest(); if (this.availableSeats > 0) { this.participantsList.add(addGuest); System.out.println("[" + addGuest + "]" + "Congratulations! Your place at the event is confirmed. We are waiting for you!"); result = 0; } else if (this.availableSeats == 0) { this.waitingListInvites.add(addGuest); System.out.println("[" + addGuest + "]" + "You have successfully signed up for the waiting list and received the order number: " + getWaitingPersonsNo() + ". We will notify you if a seat becomes available."); result = getWaitingPersonsNo(); } } return result; } private Guest searchGuest(String search) { Guest foundGuest = new Guest(); for (Guest guest : this.participantsList) { if (search.equalsIgnoreCase(guest.getFullName()) || search.equalsIgnoreCase(guest.getEmail()) || search.equalsIgnoreCase(guest.getPhoneNumber())) { foundGuest = guest; break; } } for (Guest guest : this.waitingListInvites) { if (search.equalsIgnoreCase(guest.getFullName()) || search.equalsIgnoreCase(guest.getEmail()) || search.equalsIgnoreCase(guest.getPhoneNumber())) { foundGuest = guest; break; } } return foundGuest; } public boolean check(String search) { if (searchGuest(search).getFullName() == null || searchGuest(search).getEmail() == null || searchGuest(search).getPhoneNumber() == null) { return false; } else { return true; } } public void update(String search, int number, String input) { if (check(search)) { switch (number) { case 1: searchGuest(search).setFirstName(input); System.out.println("First name changed."); break; case 2: searchGuest(search).setLastName(input); System.out.println("Last name changed."); break; case 3: searchGuest(search).setEmail(input); System.out.println("Email changed."); break; case 4: searchGuest(search).setPhoneNumber(input); System.out.println("Phone number changed."); break; default: System.out.println("Wrong choice."); break; } } else if (!check(search)) { System.out.println("Error."); } } public boolean remove(String search) { boolean result = false; if (check(search)) { for (Guest guest : this.participantsList) { if (search.equalsIgnoreCase(guest.getFullName()) || search.equalsIgnoreCase(guest.getEmail()) || search.equalsIgnoreCase(guest.getPhoneNumber())) { this.participantsList.remove(guest); System.out.print("The person was deleted."); if (this.waitingListInvites.size() > 0) { this.participantsList.add(this.waitingListInvites.get(0)); this.waitingListInvites.remove(this.waitingListInvites.get(0)); } this.availableSeats = this.maxAvailableSeats - participantsList.size(); result = true; break; } } if (!result) { this.waitingListInvites.remove(searchGuest(search)); System.out.print("The person was deleted."); result = true; } } else { System.out.print("Error"); result = false; } return result; } private int searchFields(String value, ArrayList<Guest> searchList) { int counter = 0; for (int i = 0; i < searchList.size(); i++) { if (searchList.get(i).getFullName().toLowerCase().contains(value)) { System.out.println("\tName: " + searchList.get(i).getFullName() + ", e-mail: " + searchList.get(i).getEmail() + ", phone number: " + searchList.get(i).getPhoneNumber()); counter++; } else if (searchList.get(i).getEmail().toLowerCase().contains(value)) { System.out.println("\tName: " + searchList.get(i).getFullName() + ", e-mail: " + searchList.get(i).getEmail() + ", phone number: " + searchList.get(i).getPhoneNumber()); counter++; } else if (searchList.get(i).getPhoneNumber().contains(value)) { System.out.println("\tName: " + searchList.get(i).getFullName() + ", e-mail: " + searchList.get(i).getEmail() + ", phone number: " + searchList.get(i).getPhoneNumber()); counter++; } } return counter; } public void search(String value) { value = value.toLowerCase(); int counterParticipantsList = 0; int counterWaitingListInvites = 0; System.out.println("Results:"); counterParticipantsList = searchFields(value, this.participantsList); counterWaitingListInvites = searchFields(value, this.waitingListInvites); if (counterWaitingListInvites == 0 && counterParticipantsList == 0) { System.out.println("\tThis person doesn't exist on the lists. Please try again"); } } public int getWaitingPersonsNo() { return this.waitingListInvites.size(); } public int getParticipantsListNo() { return this.participantsList.size(); } public int availableSeatsNo() { this.availableSeats = this.maxAvailableSeats - participantsList.size(); return this.availableSeats; } public int getAllParticipantsNo() { return this.participantsList.size() + getWaitingPersonsNo(); } public void allParticipatingGuests() { System.out.println("Participants:"); for (int i = 0; i < this.participantsList.size(); i++) { System.out.println(this.participantsList.get(i).toString()); } } public void allWaitingGuests() { System.out.println("Waiting persons:"); for (int i = 0; i < this.waitingListInvites.size(); i++) { System.out.println(this.waitingListInvites.get(i).toString()); } } public void help() { System.out.println("help - Displays command list\n" + "add - Add a new person (registration)\n" + "check - Check if a person is registered for the event\n" + "remove - Delete an existing person from the list\n" + "update - Updates a person's details\n" + "guests - List of people participating at the event\n" + "waitlist - People on the waiting list\n" + "available - Numarul de locuri libere\n" + "guests_no - Number of people participating in the event\n" + "waitlist_no - Number of people on the waiting list\n" + "subscribe_no - Total number of people registered\n" + "search - Search all invitations according to the string entered\n" + "quit - Close app"); } @Override public String toString() { return "The list has " + this.availableSeats + " available seats\n" + "There are " + getParticipantsListNo() + " participants and " + getWaitingPersonsNo() + " waiting persons."; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } GuestsList other = (GuestsList) obj; if ((this.availableSeats == other.availableSeats) && (this.maxAvailableSeats == other.maxAvailableSeats) && (this.participantsList.equals(other.participantsList)) && (this.waitingListInvites.equals(other.waitingListInvites))) { return true; } return false; } @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + availableSeats; result = prime * result + maxAvailableSeats; result = prime * result + participantsList.hashCode(); result = prime * result + waitingListInvites.hashCode(); return result; } }
UTF-8
Java
8,915
java
GuestsList.java
Java
[ { "context": "xtLine();\r\n\t\tGuest newGuest1 = new Guest(lastName, firstName, email, phoneNumber);\r\n\t\treturn newGuest1;\r\n\t}\r\n\r", "end": 1146, "score": 0.9401090145111084, "start": 1137, "tag": "NAME", "value": "firstName" } ]
null
[]
import java.util.ArrayList; import java.util.Scanner; public class GuestsList { private int availableSeats; private int maxAvailableSeats; private ArrayList<Guest> participantsList; private ArrayList<Guest> waitingListInvites; public GuestsList() { this.maxAvailableSeats = 3; this.participantsList = new ArrayList<>(this.maxAvailableSeats); for (int i = 0; i < this.participantsList.size(); i++) { this.participantsList.add(0, this.participantsList.get(i)); } this.waitingListInvites = new ArrayList<>(this.maxAvailableSeats); for (int i = 0; i < this.waitingListInvites.size(); i++) { this.waitingListInvites.add(0, this.waitingListInvites.get(i)); } } Scanner sc = new Scanner(System.in); public Guest newGuest() { System.out.println("Enter last name: "); String lastName = sc.nextLine(); System.out.println("Enter first name: "); String firstName = sc.nextLine(); System.out.println("Enter email: "); String email = sc.nextLine(); System.out.println("Enter phone number: "); String phoneNumber = sc.nextLine(); Guest newGuest1 = new Guest(lastName, firstName, email, phoneNumber); return newGuest1; } public int add(String search) { this.availableSeats = this.maxAvailableSeats - participantsList.size(); int result = 0; if (check(search)) { result = -1; System.out.println("This person is already on the list."); } else if (!check(search)) { Guest addGuest = newGuest(); if (this.availableSeats > 0) { this.participantsList.add(addGuest); System.out.println("[" + addGuest + "]" + "Congratulations! Your place at the event is confirmed. We are waiting for you!"); result = 0; } else if (this.availableSeats == 0) { this.waitingListInvites.add(addGuest); System.out.println("[" + addGuest + "]" + "You have successfully signed up for the waiting list and received the order number: " + getWaitingPersonsNo() + ". We will notify you if a seat becomes available."); result = getWaitingPersonsNo(); } } return result; } private Guest searchGuest(String search) { Guest foundGuest = new Guest(); for (Guest guest : this.participantsList) { if (search.equalsIgnoreCase(guest.getFullName()) || search.equalsIgnoreCase(guest.getEmail()) || search.equalsIgnoreCase(guest.getPhoneNumber())) { foundGuest = guest; break; } } for (Guest guest : this.waitingListInvites) { if (search.equalsIgnoreCase(guest.getFullName()) || search.equalsIgnoreCase(guest.getEmail()) || search.equalsIgnoreCase(guest.getPhoneNumber())) { foundGuest = guest; break; } } return foundGuest; } public boolean check(String search) { if (searchGuest(search).getFullName() == null || searchGuest(search).getEmail() == null || searchGuest(search).getPhoneNumber() == null) { return false; } else { return true; } } public void update(String search, int number, String input) { if (check(search)) { switch (number) { case 1: searchGuest(search).setFirstName(input); System.out.println("First name changed."); break; case 2: searchGuest(search).setLastName(input); System.out.println("Last name changed."); break; case 3: searchGuest(search).setEmail(input); System.out.println("Email changed."); break; case 4: searchGuest(search).setPhoneNumber(input); System.out.println("Phone number changed."); break; default: System.out.println("Wrong choice."); break; } } else if (!check(search)) { System.out.println("Error."); } } public boolean remove(String search) { boolean result = false; if (check(search)) { for (Guest guest : this.participantsList) { if (search.equalsIgnoreCase(guest.getFullName()) || search.equalsIgnoreCase(guest.getEmail()) || search.equalsIgnoreCase(guest.getPhoneNumber())) { this.participantsList.remove(guest); System.out.print("The person was deleted."); if (this.waitingListInvites.size() > 0) { this.participantsList.add(this.waitingListInvites.get(0)); this.waitingListInvites.remove(this.waitingListInvites.get(0)); } this.availableSeats = this.maxAvailableSeats - participantsList.size(); result = true; break; } } if (!result) { this.waitingListInvites.remove(searchGuest(search)); System.out.print("The person was deleted."); result = true; } } else { System.out.print("Error"); result = false; } return result; } private int searchFields(String value, ArrayList<Guest> searchList) { int counter = 0; for (int i = 0; i < searchList.size(); i++) { if (searchList.get(i).getFullName().toLowerCase().contains(value)) { System.out.println("\tName: " + searchList.get(i).getFullName() + ", e-mail: " + searchList.get(i).getEmail() + ", phone number: " + searchList.get(i).getPhoneNumber()); counter++; } else if (searchList.get(i).getEmail().toLowerCase().contains(value)) { System.out.println("\tName: " + searchList.get(i).getFullName() + ", e-mail: " + searchList.get(i).getEmail() + ", phone number: " + searchList.get(i).getPhoneNumber()); counter++; } else if (searchList.get(i).getPhoneNumber().contains(value)) { System.out.println("\tName: " + searchList.get(i).getFullName() + ", e-mail: " + searchList.get(i).getEmail() + ", phone number: " + searchList.get(i).getPhoneNumber()); counter++; } } return counter; } public void search(String value) { value = value.toLowerCase(); int counterParticipantsList = 0; int counterWaitingListInvites = 0; System.out.println("Results:"); counterParticipantsList = searchFields(value, this.participantsList); counterWaitingListInvites = searchFields(value, this.waitingListInvites); if (counterWaitingListInvites == 0 && counterParticipantsList == 0) { System.out.println("\tThis person doesn't exist on the lists. Please try again"); } } public int getWaitingPersonsNo() { return this.waitingListInvites.size(); } public int getParticipantsListNo() { return this.participantsList.size(); } public int availableSeatsNo() { this.availableSeats = this.maxAvailableSeats - participantsList.size(); return this.availableSeats; } public int getAllParticipantsNo() { return this.participantsList.size() + getWaitingPersonsNo(); } public void allParticipatingGuests() { System.out.println("Participants:"); for (int i = 0; i < this.participantsList.size(); i++) { System.out.println(this.participantsList.get(i).toString()); } } public void allWaitingGuests() { System.out.println("Waiting persons:"); for (int i = 0; i < this.waitingListInvites.size(); i++) { System.out.println(this.waitingListInvites.get(i).toString()); } } public void help() { System.out.println("help - Displays command list\n" + "add - Add a new person (registration)\n" + "check - Check if a person is registered for the event\n" + "remove - Delete an existing person from the list\n" + "update - Updates a person's details\n" + "guests - List of people participating at the event\n" + "waitlist - People on the waiting list\n" + "available - Numarul de locuri libere\n" + "guests_no - Number of people participating in the event\n" + "waitlist_no - Number of people on the waiting list\n" + "subscribe_no - Total number of people registered\n" + "search - Search all invitations according to the string entered\n" + "quit - Close app"); } @Override public String toString() { return "The list has " + this.availableSeats + " available seats\n" + "There are " + getParticipantsListNo() + " participants and " + getWaitingPersonsNo() + " waiting persons."; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } GuestsList other = (GuestsList) obj; if ((this.availableSeats == other.availableSeats) && (this.maxAvailableSeats == other.maxAvailableSeats) && (this.participantsList.equals(other.participantsList)) && (this.waitingListInvites.equals(other.waitingListInvites))) { return true; } return false; } @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + availableSeats; result = prime * result + maxAvailableSeats; result = prime * result + participantsList.hashCode(); result = prime * result + waitingListInvites.hashCode(); return result; } }
8,915
0.653057
0.649692
271
30.896679
28.087837
114
false
false
0
0
0
0
0
0
2.856089
false
false
2
b7d3bb5589ab21a29fd38a3df0a6585710a49626
12,128,987,708,698
a0f73b9761757cac7472b6f029efe51ac0f9ce5b
/src_common/com/someweb/common/helper/ValidateHelper.java
3f2b039b8ac06b40f9ac556ca147e50346f148fd
[]
no_license
xmc283714251/someweb
https://github.com/xmc283714251/someweb
9f1667c96dafce05423cdd09f8598b2da7bddb0f
d0f534a5b65b275aff7a93712ceab72e408d4e7e
refs/heads/master
2021-01-20T23:17:01.981000
2015-12-13T15:18:14
2015-12-13T15:18:14
36,173,781
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.someweb.common.helper; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Map; /** * 判断对象是否是null,及 字符串是否为空字符串 * 集合是否为空集合 * @author mingchun.xiong * */ public final class ValidateHelper { @SuppressWarnings("unused") private static <T> boolean isEmptyArray(T[] array) { if (array == null || array.length == 0) { return true; } else { return false; } } public static <T> boolean isNotEmptyArray(T[] array) { if (array != null && array.length > 0) { return true; } else { return false; } } public static boolean isEmptyString(String string) { if (string == null || string.length() == 0) { return true; } else { return false; } } public static boolean isNotEmptyString(String string) { if (string != null && string.length() > 0) { return true; } else { return false; } } public static boolean isEmptyCollection(Collection<?> collection) { if (collection == null || collection.isEmpty()) { return true; } else { return false; } } public static boolean isNotEmptyCollection(Collection<?> collection) { if (collection != null && !collection.isEmpty()) { return true; } else { return false; } } @SuppressWarnings("rawtypes") public static boolean isNotEmptyMap(Map map) { if (map != null && !map.isEmpty()) { return true; } else { return false; } } @SuppressWarnings("rawtypes") public static boolean isEmptyMap(Map map) { if (map == null || map.isEmpty()) { return true; } else { return false; } } /** * 验证时间字符串是否满足指定格式 * @param datestr 时间字符串 * @param format 验证的时间格式串 如:yyyy-MM-dd * @return boolean * @author 熊明春 * @date 2015-12-10下午9:18:56 */ public static boolean isValidDateFormat(String datestr, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); try { Date date = formatter.parse(datestr); return datestr.equals(formatter.format(date)); } catch(Exception e) { } return false; } }
UTF-8
Java
2,369
java
ValidateHelper.java
Java
[ { "context": " 判断对象是否是null,及 字符串是否为空字符串\r\n * 集合是否为空集合\r\n * @author mingchun.xiong\r\n *\r\n */\r\npublic final class ValidateHelper {\r\n\t\r", "end": 225, "score": 0.6913577318191528, "start": 211, "tag": "NAME", "value": "mingchun.xiong" }, { "context": "式串 如:yyyy-MM-dd\r\n\t * @return boolean\r\n\t * @author 熊明春\r\n\t * @date 2015-12-10下午9:18:56\r\n\t */\r\n\tpublic sta", "end": 1898, "score": 0.9998553991317749, "start": 1895, "tag": "NAME", "value": "熊明春" } ]
null
[]
package com.someweb.common.helper; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Map; /** * 判断对象是否是null,及 字符串是否为空字符串 * 集合是否为空集合 * @author mingchun.xiong * */ public final class ValidateHelper { @SuppressWarnings("unused") private static <T> boolean isEmptyArray(T[] array) { if (array == null || array.length == 0) { return true; } else { return false; } } public static <T> boolean isNotEmptyArray(T[] array) { if (array != null && array.length > 0) { return true; } else { return false; } } public static boolean isEmptyString(String string) { if (string == null || string.length() == 0) { return true; } else { return false; } } public static boolean isNotEmptyString(String string) { if (string != null && string.length() > 0) { return true; } else { return false; } } public static boolean isEmptyCollection(Collection<?> collection) { if (collection == null || collection.isEmpty()) { return true; } else { return false; } } public static boolean isNotEmptyCollection(Collection<?> collection) { if (collection != null && !collection.isEmpty()) { return true; } else { return false; } } @SuppressWarnings("rawtypes") public static boolean isNotEmptyMap(Map map) { if (map != null && !map.isEmpty()) { return true; } else { return false; } } @SuppressWarnings("rawtypes") public static boolean isEmptyMap(Map map) { if (map == null || map.isEmpty()) { return true; } else { return false; } } /** * 验证时间字符串是否满足指定格式 * @param datestr 时间字符串 * @param format 验证的时间格式串 如:yyyy-MM-dd * @return boolean * @author 熊明春 * @date 2015-12-10下午9:18:56 */ public static boolean isValidDateFormat(String datestr, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); try { Date date = formatter.parse(datestr); return datestr.equals(formatter.format(date)); } catch(Exception e) { } return false; } }
2,369
0.594209
0.586637
138
14.268116
17.337879
71
false
false
0
0
0
0
0
0
1.797101
false
false
2
3d94efb42206b96f9d95863414989b76d49b1dfe
33,320,356,284,025
41b2a421baa1c769ee3aa1be54e40ea0c5a5eb62
/base/src/main/java/com/smapley/base/adapter/BaseAdapter.java
ba78477fdcf8e9a62f96d08d55781b32c02ddf90
[]
no_license
smapley/vehicle-merchat
https://github.com/smapley/vehicle-merchat
39d0b280a50d97850aa1310b47d525ec72ff4543
b0aa8667108569593b7890804104e7bc7c9b0e07
refs/heads/master
2020-05-28T10:36:18.509000
2017-06-11T13:34:41
2017-06-11T13:34:41
94,006,482
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smapley.base.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; import java.util.Map; /** * Created by wuzhixiong on 2017/6/10. */ public abstract class BaseAdapter extends android.widget.BaseAdapter { protected Context context; protected LayoutInflater inflater; private List<Map> list; public BaseAdapter(Context context, List<Map> list) { this.context = context; this.list = list; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public abstract int getLayout(); public abstract BaseHolder getHolder(View view); @Override public int getCount() { if (list == null) return 0; else return list.size(); } @Override public Map getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return 0; } }
UTF-8
Java
1,064
java
BaseAdapter.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by wuzhixiong on 2017/6/10.\n */\n\npublic abstract class BaseAdap", "end": 236, "score": 0.9997033476829529, "start": 226, "tag": "USERNAME", "value": "wuzhixiong" } ]
null
[]
package com.smapley.base.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; import java.util.Map; /** * Created by wuzhixiong on 2017/6/10. */ public abstract class BaseAdapter extends android.widget.BaseAdapter { protected Context context; protected LayoutInflater inflater; private List<Map> list; public BaseAdapter(Context context, List<Map> list) { this.context = context; this.list = list; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public abstract int getLayout(); public abstract BaseHolder getHolder(View view); @Override public int getCount() { if (list == null) return 0; else return list.size(); } @Override public Map getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return 0; } }
1,064
0.663534
0.655075
52
19.461538
20.652306
99
false
false
0
0
0
0
0
0
0.384615
false
false
2
763dfb5aa7717eb700b59da782a4a4a861dadcae
15,564,961,544,436
7d3ebc343c9826e47c28ffbe55759255cc53267a
/src/main/java/org/example/repository/OrderRepository.java
3212d03a3e348445bf97c371c8b89a19e33a1330
[]
no_license
Mozzherin/Store
https://github.com/Mozzherin/Store
d1dad8a0c1393adedc0a33ad3b5cf070c10afd79
cd2272adbdf52f92e3b9305959873c5741ba8a3c
refs/heads/master
2023-08-07T22:24:17.189000
2021-09-01T05:44:02
2021-09-01T05:44:02
401,211,622
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.example.repository; import org.example.entityes.Order; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface OrderRepository extends CrudRepository<Order, Long> { List<Order> findAll(); Order findById(long id); }
UTF-8
Java
281
java
OrderRepository.java
Java
[]
null
[]
package org.example.repository; import org.example.entityes.Order; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface OrderRepository extends CrudRepository<Order, Long> { List<Order> findAll(); Order findById(long id); }
281
0.786477
0.786477
11
24.545454
22.761066
70
false
false
0
0
0
0
0
0
0.636364
false
false
2
9439a77df1f23130f777ff635f8d96b5b0e8f5a4
16,939,351,079,635
535ecb9ec1fc78055a3c7b873b73abedd8171f2e
/src/main/java/com/socialmap/server/config/MvcConfig.java
d2f41b43642e0d52eeeddab293999561855cd2a8
[]
no_license
social-map-team/tbs-core
https://github.com/social-map-team/tbs-core
2db20f31367ea2e70fc3be85182082d7a727fa1b
6aa94121b4445010ba266597a19aeccd51376561
refs/heads/master
2021-03-12T19:37:36.662000
2015-03-27T16:14:34
2015-03-27T16:14:34
32,049,012
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.socialmap.server.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import java.util.List; /** * Created by yy on 3/4/15. */ @Configuration @EnableWebMvc @ComponentScan("com.socialmap.server.controller") public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); // 将HTTP响应的Java类自动转换成JSON converters.add(new MappingJackson2HttpMessageConverter()); // 自动转换字节数组,用于图片传输 converters.add(new ByteArrayHttpMessageConverter()); } @Override public void addViewControllers(ViewControllerRegistry registry) { //registry.addViewController("/error/401").setViewName("error/401"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/favicon.ico").addResourceLocations("/favicon.ico"); registry.addResourceHandler("/css/**").addResourceLocations("/static/css/**"); registry.addResourceHandler("/font/**").addResourceLocations("/static/font/**"); registry.addResourceHandler("/img/**").addResourceLocations("/static/img/**"); registry.addResourceHandler("/js/**").addResourceLocations("/static/js/**"); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } }
UTF-8
Java
2,387
java
MvcConfig.java
Java
[ { "context": "solver;\n\nimport java.util.List;\n\n/**\n * Created by yy on 3/4/15.\n */\n@Configuration\n@EnableWebMvc\n@Comp", "end": 868, "score": 0.990543782711029, "start": 866, "tag": "USERNAME", "value": "yy" } ]
null
[]
package com.socialmap.server.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import java.util.List; /** * Created by yy on 3/4/15. */ @Configuration @EnableWebMvc @ComponentScan("com.socialmap.server.controller") public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); // 将HTTP响应的Java类自动转换成JSON converters.add(new MappingJackson2HttpMessageConverter()); // 自动转换字节数组,用于图片传输 converters.add(new ByteArrayHttpMessageConverter()); } @Override public void addViewControllers(ViewControllerRegistry registry) { //registry.addViewController("/error/401").setViewName("error/401"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/favicon.ico").addResourceLocations("/favicon.ico"); registry.addResourceHandler("/css/**").addResourceLocations("/static/css/**"); registry.addResourceHandler("/font/**").addResourceLocations("/static/font/**"); registry.addResourceHandler("/img/**").addResourceLocations("/static/img/**"); registry.addResourceHandler("/js/**").addResourceLocations("/static/js/**"); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } }
2,387
0.767651
0.762516
54
42.277779
31.957968
89
false
false
0
0
0
0
0
0
0.481481
false
false
2
0d3b29fa6903e17cd4d5e5cbfe4be3a0b663f157
9,259,949,495,383
02995a8c7060119203f27c26f3a48a3c8e275751
/h2/src/main/org/h2/api/Interval.java
72423eb7cd17e9e0cd6a99d5f02397f699a4119b
[]
no_license
zhuzhiqing/h2database
https://github.com/zhuzhiqing/h2database
76eba109dd195049b30de0ec78377b23f28cef00
a7e9c1aad1fcf1a8b6c76762c56c0a5668b2c53c
refs/heads/master
2020-03-26T13:38:57.896000
2018-08-16T06:12:12
2018-08-16T06:12:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import org.h2.util.DateTimeUtils; /** * {@code INTERVAL} representation for result sets. */ public final class Interval { private final IntervalQualifier qualifier; private final boolean negative; private final long leading; private final long remaining; /** * Creates a new interval. * * @param years * years * @return interval */ public static Interval ofYears(long years) { return new Interval(IntervalQualifier.YEAR, years < 0, Math.abs(years), 0); } /** * Creates a new interval. * * @param months * months * @return interval */ public static Interval ofMonths(long months) { return new Interval(IntervalQualifier.MONTH, months < 0, Math.abs(months), 0); } /** * Creates a new interval. * * @param days * days * @return interval */ public static Interval ofDays(long days) { return new Interval(IntervalQualifier.DAY, days < 0, Math.abs(days), 0); } /** * Creates a new interval. * * @param hours * hours * @return interval */ public static Interval ofHours(long hours) { return new Interval(IntervalQualifier.HOUR, hours < 0, Math.abs(hours), 0); } /** * Creates a new interval. * * @param minutes * minutes * @return interval */ public static Interval ofMinutes(long minutes) { return new Interval(IntervalQualifier.MINUTE, minutes < 0, Math.abs(minutes), 0); } /** * Creates a new interval. * * @param nanos * nanoseconds (including seconds) * @return interval */ public static Interval ofNanos(long nanos) { boolean negative = nanos < 0; if (negative) { nanos = -nanos; if (nanos < 0) { throw new IllegalArgumentException(); } } return new Interval(IntervalQualifier.SECOND, negative, nanos / 1_000_000_000, nanos % 1_000_000_000); } /** * Creates a new interval. * * @param qualifier * qualifier * @param negative * whether interval is negative * @param leading * value of leading field * @param remaining * values of all remaining fields */ public Interval(IntervalQualifier qualifier, boolean negative, long leading, long remaining) { this.qualifier = qualifier; this.negative = DateTimeUtils.validateInterval(qualifier, negative, leading, remaining); this.leading = leading; this.remaining = remaining; } /** * Returns qualifier of this interval. * * @return qualifier */ public IntervalQualifier getQualifier() { return qualifier; } /** * Returns where the interval is negative. * * @return where the interval is negative */ public boolean isNegative() { return negative; } /** * Returns value of leading field of this interval. For {@code SECOND} * intervals returns integer part of seconds. * * @return value of leading field */ public long getLeading() { return leading; } /** * Returns combined value of remaining fields of this interval. For * {@code SECOND} intervals returns nanoseconds. * * @return combined value of remaining fields */ public long getRemaining() { return remaining; } /** * @return years, or 0 */ public long getYears() { return DateTimeUtils.yearsFromInterval(qualifier, negative, leading, remaining); } /** * @return months, or 0 */ public long getMonths() { return DateTimeUtils.monthsFromInterval(qualifier, negative, leading, remaining); } /** * @return days, or 0 */ public long getDays() { return DateTimeUtils.daysFromInterval(qualifier, negative, leading, remaining); } /** * @return hours, or 0 */ public long getHours() { return DateTimeUtils.hoursFromInterval(qualifier, negative, leading, remaining); } /** * @return minutes, or 0 */ public long getMinutes() { return DateTimeUtils.minutesFromInterval(qualifier, negative, leading, remaining); } /** * @return nanoseconds (including seconds), or 0 */ public long getNanos() { return DateTimeUtils.nanosFromInterval(qualifier, negative, leading, remaining); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + qualifier.hashCode(); result = prime * result + (negative ? 1231 : 1237); result = prime * result + (int) (leading ^ leading >>> 32); result = prime * result + (int) (remaining ^ remaining >>> 32); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Interval)) { return false; } Interval other = (Interval) obj; return qualifier == other.qualifier && negative == other.negative && leading == other.leading && remaining == other.remaining; } @Override public String toString() { return DateTimeUtils.intervalToString(qualifier, negative, leading, remaining); } }
UTF-8
Java
5,746
java
Interval.java
Java
[]
null
[]
/* * Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.api; import org.h2.util.DateTimeUtils; /** * {@code INTERVAL} representation for result sets. */ public final class Interval { private final IntervalQualifier qualifier; private final boolean negative; private final long leading; private final long remaining; /** * Creates a new interval. * * @param years * years * @return interval */ public static Interval ofYears(long years) { return new Interval(IntervalQualifier.YEAR, years < 0, Math.abs(years), 0); } /** * Creates a new interval. * * @param months * months * @return interval */ public static Interval ofMonths(long months) { return new Interval(IntervalQualifier.MONTH, months < 0, Math.abs(months), 0); } /** * Creates a new interval. * * @param days * days * @return interval */ public static Interval ofDays(long days) { return new Interval(IntervalQualifier.DAY, days < 0, Math.abs(days), 0); } /** * Creates a new interval. * * @param hours * hours * @return interval */ public static Interval ofHours(long hours) { return new Interval(IntervalQualifier.HOUR, hours < 0, Math.abs(hours), 0); } /** * Creates a new interval. * * @param minutes * minutes * @return interval */ public static Interval ofMinutes(long minutes) { return new Interval(IntervalQualifier.MINUTE, minutes < 0, Math.abs(minutes), 0); } /** * Creates a new interval. * * @param nanos * nanoseconds (including seconds) * @return interval */ public static Interval ofNanos(long nanos) { boolean negative = nanos < 0; if (negative) { nanos = -nanos; if (nanos < 0) { throw new IllegalArgumentException(); } } return new Interval(IntervalQualifier.SECOND, negative, nanos / 1_000_000_000, nanos % 1_000_000_000); } /** * Creates a new interval. * * @param qualifier * qualifier * @param negative * whether interval is negative * @param leading * value of leading field * @param remaining * values of all remaining fields */ public Interval(IntervalQualifier qualifier, boolean negative, long leading, long remaining) { this.qualifier = qualifier; this.negative = DateTimeUtils.validateInterval(qualifier, negative, leading, remaining); this.leading = leading; this.remaining = remaining; } /** * Returns qualifier of this interval. * * @return qualifier */ public IntervalQualifier getQualifier() { return qualifier; } /** * Returns where the interval is negative. * * @return where the interval is negative */ public boolean isNegative() { return negative; } /** * Returns value of leading field of this interval. For {@code SECOND} * intervals returns integer part of seconds. * * @return value of leading field */ public long getLeading() { return leading; } /** * Returns combined value of remaining fields of this interval. For * {@code SECOND} intervals returns nanoseconds. * * @return combined value of remaining fields */ public long getRemaining() { return remaining; } /** * @return years, or 0 */ public long getYears() { return DateTimeUtils.yearsFromInterval(qualifier, negative, leading, remaining); } /** * @return months, or 0 */ public long getMonths() { return DateTimeUtils.monthsFromInterval(qualifier, negative, leading, remaining); } /** * @return days, or 0 */ public long getDays() { return DateTimeUtils.daysFromInterval(qualifier, negative, leading, remaining); } /** * @return hours, or 0 */ public long getHours() { return DateTimeUtils.hoursFromInterval(qualifier, negative, leading, remaining); } /** * @return minutes, or 0 */ public long getMinutes() { return DateTimeUtils.minutesFromInterval(qualifier, negative, leading, remaining); } /** * @return nanoseconds (including seconds), or 0 */ public long getNanos() { return DateTimeUtils.nanosFromInterval(qualifier, negative, leading, remaining); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + qualifier.hashCode(); result = prime * result + (negative ? 1231 : 1237); result = prime * result + (int) (leading ^ leading >>> 32); result = prime * result + (int) (remaining ^ remaining >>> 32); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Interval)) { return false; } Interval other = (Interval) obj; return qualifier == other.qualifier && negative == other.negative && leading == other.leading && remaining == other.remaining; } @Override public String toString() { return DateTimeUtils.intervalToString(qualifier, negative, leading, remaining); } }
5,746
0.580578
0.568395
224
24.651785
25.027025
110
false
false
0
0
0
0
0
0
0.415179
false
false
2
4462ce233e6fe3f7daca11d76305eb0223ac8ebb
5,162,550,690,769
bfbec97c78aee200603f6db54546c633e54a925d
/src/test/java/uk/co/realisticsolutions/crawler/cli/CrawlerCLITest.java
2b52d2f9e462494371f65b90a159cab50c5a6816
[]
no_license
davidhilton68/crawler
https://github.com/davidhilton68/crawler
78871e72526ff1cff40487f74a4e6fbe5d102a74
13edc6ba0200ac517403933536614da0844d04cc
refs/heads/master
2020-03-03T00:53:26.579000
2016-09-22T09:19:00
2016-09-22T09:19:00
62,347,022
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.co.realisticsolutions.crawler.cli; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.junit.Assert.*; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import uk.co.realisticsolutions.crawler.AbstractCrawler; import uk.co.realisticsolutions.crawler.CrawlerException; import uk.co.realisticsolutions.crawler.CrawlerFactory; import uk.co.realisticsolutions.crawler.cli.CrawlerApplicationException; import uk.co.realisticsolutions.crawler.cli.CrawlerCLI; @RunWith(MockitoJUnitRunner.class) public class CrawlerCLITest { private CrawlerCLI testCrawlerCLI; private static final String TEST_WEBSITE = "xx.yy.com"; private static final String DUMMY_REPORT = "dummy report"; @Mock private CrawlerFactory crawlerFactoryMock; @Mock private AbstractCrawler crawlerMock; @Before public void setUp() { testCrawlerCLI = new CrawlerCLI(crawlerFactoryMock) ; } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testCLIWithoutParametersThrowsCrawlerApplicationException() throws CrawlerException { thrown.expect(CrawlerApplicationException.class); thrown.expectMessage(startsWith(CrawlerCLI.INCORRECT_NUMBER_OF_ARGUMENTS)); testCrawlerCLI.launch(null); } @Test public void testCLIWithOneParametersThrowsCrawlerApplicationException() throws CrawlerException { thrown.expect(CrawlerApplicationException.class); thrown.expectMessage(startsWith(CrawlerCLI.INCORRECT_NUMBER_OF_ARGUMENTS)); testCrawlerCLI.launch(new String [] { "A"} ); } @Test public void testCLIWithOneInputs() throws CrawlerException { when(crawlerFactoryMock.create( CrawlerFactory.CrawlerType.WIPRO_WORDPRESS, TEST_WEBSITE)).thenReturn(crawlerMock); when(crawlerMock.crawl()).thenReturn(DUMMY_REPORT); String actualReport = testCrawlerCLI.launch(new String [] { CrawlerFactory.CrawlerType.WIPRO_WORDPRESS.toString(), TEST_WEBSITE }); assertEquals("The expected report was not produced", DUMMY_REPORT, actualReport); } }
UTF-8
Java
2,296
java
CrawlerCLITest.java
Java
[]
null
[]
package uk.co.realisticsolutions.crawler.cli; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.junit.Assert.*; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import uk.co.realisticsolutions.crawler.AbstractCrawler; import uk.co.realisticsolutions.crawler.CrawlerException; import uk.co.realisticsolutions.crawler.CrawlerFactory; import uk.co.realisticsolutions.crawler.cli.CrawlerApplicationException; import uk.co.realisticsolutions.crawler.cli.CrawlerCLI; @RunWith(MockitoJUnitRunner.class) public class CrawlerCLITest { private CrawlerCLI testCrawlerCLI; private static final String TEST_WEBSITE = "xx.yy.com"; private static final String DUMMY_REPORT = "dummy report"; @Mock private CrawlerFactory crawlerFactoryMock; @Mock private AbstractCrawler crawlerMock; @Before public void setUp() { testCrawlerCLI = new CrawlerCLI(crawlerFactoryMock) ; } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testCLIWithoutParametersThrowsCrawlerApplicationException() throws CrawlerException { thrown.expect(CrawlerApplicationException.class); thrown.expectMessage(startsWith(CrawlerCLI.INCORRECT_NUMBER_OF_ARGUMENTS)); testCrawlerCLI.launch(null); } @Test public void testCLIWithOneParametersThrowsCrawlerApplicationException() throws CrawlerException { thrown.expect(CrawlerApplicationException.class); thrown.expectMessage(startsWith(CrawlerCLI.INCORRECT_NUMBER_OF_ARGUMENTS)); testCrawlerCLI.launch(new String [] { "A"} ); } @Test public void testCLIWithOneInputs() throws CrawlerException { when(crawlerFactoryMock.create( CrawlerFactory.CrawlerType.WIPRO_WORDPRESS, TEST_WEBSITE)).thenReturn(crawlerMock); when(crawlerMock.crawl()).thenReturn(DUMMY_REPORT); String actualReport = testCrawlerCLI.launch(new String [] { CrawlerFactory.CrawlerType.WIPRO_WORDPRESS.toString(), TEST_WEBSITE }); assertEquals("The expected report was not produced", DUMMY_REPORT, actualReport); } }
2,296
0.780923
0.780923
62
36.032257
31.005707
136
false
false
0
0
0
0
0
0
0.983871
false
false
2
12c94de615479c1389ccb9ac8319a766724b562f
6,133,213,355,393
183744d6f703314a0a3b5cf414912fc7de5fca92
/src/hdfs/SerializeHelper.java
8afac8d660666be8f166db2a334bb687cac22d2b
[]
no_license
thomachan/Hadoop-Hbase
https://github.com/thomachan/Hadoop-Hbase
682ed2a7327c3aaefeb5153c57d6ba6736543d47
cee9de1bf080dbbda223352a17b5c595893ad2af
refs/heads/master
2020-11-26T15:28:36.219000
2014-06-23T10:26:27
2014-06-23T10:26:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hdfs; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.hadoop.fs.FSDataInputStream; public class SerializeHelper { public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(b); o.writeObject(obj); return b.toByteArray(); } public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream b = new ByteArrayInputStream(bytes); ObjectInputStream o = new ObjectInputStream(b); return o.readObject(); } public static void serialize(String outFile, Object serializableObject) throws IOException { FileOutputStream fos = new FileOutputStream(outFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(serializableObject); } public static Object deserialize(String serilizedObject) throws FileNotFoundException, IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream(serilizedObject); ObjectInputStream ois = new ObjectInputStream(fis); return ois.readObject(); } public static Object deserialize(FSDataInputStream in) throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(in); return ois.readObject(); } }
UTF-8
Java
1,652
java
SerializeHelper.java
Java
[]
null
[]
package hdfs; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.hadoop.fs.FSDataInputStream; public class SerializeHelper { public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(b); o.writeObject(obj); return b.toByteArray(); } public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream b = new ByteArrayInputStream(bytes); ObjectInputStream o = new ObjectInputStream(b); return o.readObject(); } public static void serialize(String outFile, Object serializableObject) throws IOException { FileOutputStream fos = new FileOutputStream(outFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(serializableObject); } public static Object deserialize(String serilizedObject) throws FileNotFoundException, IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream(serilizedObject); ObjectInputStream ois = new ObjectInputStream(fis); return ois.readObject(); } public static Object deserialize(FSDataInputStream in) throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(in); return ois.readObject(); } }
1,652
0.761501
0.761501
45
35.711113
25.058706
95
false
false
0
0
0
0
0
0
1.111111
false
false
2
0f8ea68e91b20d7389b6654cd4bdaee8dad9a67d
30,769,145,765,515
fb3e8646012065afc3645d66e5e57a8746c99f56
/big-data-architecture/src/main/java/ua/edu/ucu/bda/validation/PlayerToValidator.java
d8b2dc11d6e6711b79deafec627dfc231e4b87c4
[]
no_license
atykhonov/ucucsds
https://github.com/atykhonov/ucucsds
f9e30d8ad43507cdfe441fcbd17349e659c77528
fde538b99fda2d27d533bb7ce1ceb0e3a2c0a939
refs/heads/master
2021-01-12T12:34:56.163000
2017-06-06T00:28:58
2017-06-06T00:28:58
72,590,899
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.edu.ucu.bda.validation; import org.springframework.stereotype.Component; @Component public class PlayerToValidator extends PlayerValidator { public static final String ERROR_COLUMN_NAME = "errorPlayerToDoesntExist"; public static final String PLAYER_COLUMN_NAME = "to"; @Override public String getErrorColumnName() { return ERROR_COLUMN_NAME; } @Override public String getPlayerColumnName() { return PLAYER_COLUMN_NAME; } }
UTF-8
Java
489
java
PlayerToValidator.java
Java
[]
null
[]
package ua.edu.ucu.bda.validation; import org.springframework.stereotype.Component; @Component public class PlayerToValidator extends PlayerValidator { public static final String ERROR_COLUMN_NAME = "errorPlayerToDoesntExist"; public static final String PLAYER_COLUMN_NAME = "to"; @Override public String getErrorColumnName() { return ERROR_COLUMN_NAME; } @Override public String getPlayerColumnName() { return PLAYER_COLUMN_NAME; } }
489
0.721881
0.721881
21
22.285715
23.415792
78
false
false
0
0
0
0
0
0
0.285714
false
false
2
393a832fb1b145a1096a4aa337d2561633109d0c
26,405,459,002,647
ae53f74bc62014dd20464ced031234ea8333b36e
/app/src/main/java/xar/com/qqapp/adapter/MessagePageListAdapter.java
b01e5ba01a3236cb7c0180a338bdf7547e752d84
[]
no_license
xarcarry/lets-chat-android
https://github.com/xarcarry/lets-chat-android
4b1d660036d13d5979bdaf67041a45690e7c7aae
8010c7d4b6dc98e85986916ebbe32c2df47dcd80
refs/heads/master
2020-11-24T11:58:55.245000
2019-12-15T05:38:30
2019-12-15T05:38:30
228,134,284
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xar.com.qqapp.adapter; import android.app.Activity; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import xar.com.qqapp.R; public class MessagePageListAdapter extends RecyclerView.Adapter<MessagePageListAdapter.MyViewHolder> { //用于获取 private Activity activity; //创建一个带参数的构造方法,通过参数可以把Activity传过来 public MessagePageListAdapter(Activity activity){ this.activity = activity; } @NonNull @Override public MessagePageListAdapter.MyViewHolder onCreateViewHolder( @NonNull ViewGroup viewGroup, int viewType) { //从layout资源加载行view LayoutInflater inflater = activity.getLayoutInflater(); View view = null; if (viewType == R.layout.message_list_item_search){ view = inflater.inflate(R.layout.message_list_item_search, viewGroup, false); }else{ view = inflater.inflate(R.layout.message_list_item_chat, viewGroup, false); } MyViewHolder viewHolder = new MyViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull MessagePageListAdapter.MyViewHolder myViewHolder, int i) { } @Override public int getItemCount() { return 15; } @Override public int getItemViewType(int position) { if (0 == position){ //只有最顶端这行是搜索 return R.layout.message_list_item_search; } //其余各行都一样的控件 return R.layout.message_list_item_chat; } //将ViewHolder声明为Adapter的内部类 class MyViewHolder extends RecyclerView.ViewHolder{ public MyViewHolder(View itemView){ super(itemView); } } }
UTF-8
Java
1,973
java
MessagePageListAdapter.java
Java
[]
null
[]
package xar.com.qqapp.adapter; import android.app.Activity; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import xar.com.qqapp.R; public class MessagePageListAdapter extends RecyclerView.Adapter<MessagePageListAdapter.MyViewHolder> { //用于获取 private Activity activity; //创建一个带参数的构造方法,通过参数可以把Activity传过来 public MessagePageListAdapter(Activity activity){ this.activity = activity; } @NonNull @Override public MessagePageListAdapter.MyViewHolder onCreateViewHolder( @NonNull ViewGroup viewGroup, int viewType) { //从layout资源加载行view LayoutInflater inflater = activity.getLayoutInflater(); View view = null; if (viewType == R.layout.message_list_item_search){ view = inflater.inflate(R.layout.message_list_item_search, viewGroup, false); }else{ view = inflater.inflate(R.layout.message_list_item_chat, viewGroup, false); } MyViewHolder viewHolder = new MyViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull MessagePageListAdapter.MyViewHolder myViewHolder, int i) { } @Override public int getItemCount() { return 15; } @Override public int getItemViewType(int position) { if (0 == position){ //只有最顶端这行是搜索 return R.layout.message_list_item_search; } //其余各行都一样的控件 return R.layout.message_list_item_chat; } //将ViewHolder声明为Adapter的内部类 class MyViewHolder extends RecyclerView.ViewHolder{ public MyViewHolder(View itemView){ super(itemView); } } }
1,973
0.659643
0.657482
67
26.626865
22.787687
100
false
false
0
0
0
0
0
0
0.38806
false
false
2
1d8a3d1e3d4a957a36a42149f781cda9a5111d3f
30,734,786,032,424
5e79782dfc62f8aa5a285dd69f5242559a20a922
/src/main/java/com/example/TelegramConstants.java
2dd2dfba0c519478acbe935af4bc725cf3488502
[]
no_license
ADM-Sasha-Sasha/Telegram-bot
https://github.com/ADM-Sasha-Sasha/Telegram-bot
caae0335b1d9848ecf7784426ff1d96186045357
e4d82a9c164c6aa8ff552b08bb38d1938a563454
refs/heads/master
2023-05-09T23:17:13.779000
2021-05-31T14:17:18
2021-05-31T14:17:18
372,530,572
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example; public class TelegramConstants { public static final String BOT_NAME = "MyTelTestBot"; public static final String BOT_TOKEN = "1871776950:AAGCvy3CEMlKGgFNo4HcFTjY1vjYDhIauNQ"; }
UTF-8
Java
208
java
TelegramConstants.java
Java
[ { "context": "ants {\n public static final String BOT_NAME = \"MyTelTestBot\";\n public static final String BOT_TOKEN = \"187", "end": 110, "score": 0.9221463203430176, "start": 98, "tag": "USERNAME", "value": "MyTelTestBot" }, { "context": "Bot\";\n public static final String BOT_TOKEN = \"1871776950:AAGCvy3CEMlKGgFNo4HcFTjY1vjYDhIauNQ\";\n}\n", "end": 203, "score": 0.9955786466598511, "start": 157, "tag": "KEY", "value": "1871776950:AAGCvy3CEMlKGgFNo4HcFTjY1vjYDhIauNQ" } ]
null
[]
package com.example; public class TelegramConstants { public static final String BOT_NAME = "MyTelTestBot"; public static final String BOT_TOKEN = "<KEY>"; }
167
0.783654
0.721154
6
33.666668
32.499573
92
false
false
0
0
0
0
0
0
0.5
false
false
2
f193bd331b551e2bf544bc6e062522208ecc6497
27,436,251,087,916
003e0552e521a1c5cb64305977836cb20c093b7e
/src/test/java/inheritanceLearning/Animal.java
ea16f9f85b6fb94d7e8d12673878c3c55c51f03d
[]
no_license
Jeetworld/JavaLearning
https://github.com/Jeetworld/JavaLearning
000171986a5e842d800f054f77447beff5959598
4ee9dc6304748ca63013433cf6d2216c32a29fd8
refs/heads/master
2023-04-19T20:43:21.487000
2021-04-19T13:33:49
2021-04-19T13:33:49
353,751,576
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package inheritanceLearning; public class Animal { public void sound() { System.out.println("Sound generated from superclass"); } }
UTF-8
Java
150
java
Animal.java
Java
[]
null
[]
package inheritanceLearning; public class Animal { public void sound() { System.out.println("Sound generated from superclass"); } }
150
0.68
0.68
13
10.538462
16.026974
56
false
false
0
0
0
0
0
0
1.076923
false
false
2
14a0528576746ccd284c0975d729ad4e8d1f4692
27,427,661,218,696
3a6f73010b05fe19bcb70d675816777699085125
/ssz/src/main/java/org/ethereum/beacon/ssz/access/basic/UIntPrimitive.java
117fb5e2453b949f7fb806a346c2cff1d997305a
[ "Apache-2.0" ]
permissive
harmony-dev/beacon-chain-java
https://github.com/harmony-dev/beacon-chain-java
9b5a586963f29d42d50541a149120a197b54e865
1fe38d266d657b33be4be6fb0004a17fcf1d9c76
refs/heads/develop
2020-04-13T08:18:58.072000
2019-12-11T11:42:43
2019-12-11T11:42:43
163,078,506
32
9
Apache-2.0
false
2019-12-03T09:48:33
2018-12-25T11:54:24
2019-11-30T11:51:06
2019-12-03T09:48:32
5,218
17
6
50
Java
false
false
package org.ethereum.beacon.ssz.access.basic; import net.consensys.cava.bytes.Bytes; import org.ethereum.beacon.ssz.visitor.SSZReader; import org.ethereum.beacon.ssz.visitor.SSZWriter; import net.consensys.cava.ssz.SSZException; import org.ethereum.beacon.ssz.access.SSZBasicAccessor; import org.ethereum.beacon.ssz.access.SSZField; import org.ethereum.beacon.ssz.SSZSchemeException; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.function.Function.identity; /** * {@link SSZBasicAccessor} for all primitive Java integers and their default wrappers * * <p>All numerics are considered unsigned, bit size could be clarified by {@link * SSZField#getExtraSize()} */ public class UIntPrimitive implements SSZBasicAccessor { private static final int DEFAULT_BYTE_SIZE = 8; private static final int DEFAULT_SHORT_SIZE = 16; private static final int DEFAULT_INT_SIZE = 32; private static final int DEFAULT_LONG_SIZE = 64; private static final int DEFAULT_BIGINT_SIZE = 512; private static Map<Class, NumericType> classToNumericType = new HashMap<>(); private static Set<String> supportedTypes = new HashSet<>(); private static Set<Class> supportedClassTypes = new HashSet<>(); static { classToNumericType.put(byte.class, NumericType.of(Type.INT, DEFAULT_BYTE_SIZE)); classToNumericType.put(Byte.class, NumericType.of(Type.INT, DEFAULT_BYTE_SIZE)); classToNumericType.put(int.class, NumericType.of(Type.INT, DEFAULT_INT_SIZE)); classToNumericType.put(Integer.class, NumericType.of(Type.INT, DEFAULT_INT_SIZE)); classToNumericType.put(short.class, NumericType.of(Type.INT, DEFAULT_SHORT_SIZE)); classToNumericType.put(Short.class, NumericType.of(Type.INT, DEFAULT_SHORT_SIZE)); classToNumericType.put(long.class, NumericType.of(Type.LONG, DEFAULT_LONG_SIZE)); classToNumericType.put(Long.class, NumericType.of(Type.LONG, DEFAULT_LONG_SIZE)); classToNumericType.put(BigInteger.class, NumericType.of(Type.BIGINT, DEFAULT_BIGINT_SIZE)); } static { supportedTypes.add("uint"); } static { supportedClassTypes.add(byte.class); supportedClassTypes.add(Byte.class); supportedClassTypes.add(int.class); supportedClassTypes.add(Integer.class); supportedClassTypes.add(short.class); supportedClassTypes.add(Short.class); supportedClassTypes.add(long.class); supportedClassTypes.add(Long.class); supportedClassTypes.add(BigInteger.class); } private static void encodeInt(Object value, NumericType type, OutputStream result) { encodeLong(((Number) value).intValue() & type.mask, type.size, result); } private static void encodeLong(Object value, NumericType type, OutputStream result) { encodeLong((long) value, type.size, result); } private static void encodeLong(long value, int bitLength, OutputStream result) { Bytes res = SSZWriter.encodeULong(value, bitLength); try { result.write(res.toArrayUnsafe()); } catch (IOException e) { throw new SSZException(String.format("Failed to write value \"%s\" to stream", value), e); } } private static void encodeBigInt(Object value, NumericType type, OutputStream result) { BigInteger valueBI = (BigInteger) value; Bytes res = SSZWriter.encodeBigInteger(valueBI, type.size); try { result.write(res.toArrayUnsafe()); } catch (IOException e) { throw new SSZException(String.format("Failed to write value \"%s\" to stream", value), e); } } @Override public Set<String> getSupportedSSZTypes() { return supportedTypes; } @Override public Set<Class> getSupportedClasses() { return supportedClassTypes; } @Override public int getSize(SSZField field) { return parseFieldType(field).size / 8; } @Override public void encode(Object value, SSZField field, OutputStream result) { NumericType numericType = parseFieldType(field); switch (numericType.type) { case INT: { encodeInt(value, numericType, result); break; } case LONG: { encodeLong(value, numericType, result); break; } case BIGINT: { encodeBigInt(value, numericType, result); break; } default: { throwUnsupportedType(field); } } } @Override public Object decode(SSZField field, SSZReader reader) { NumericType numericType = parseFieldType(field); switch (numericType.type) { case INT: { return decodeInt(numericType, reader); } case LONG: { return decodeLong(numericType, reader); } case BIGINT: { return decodeBigInt(numericType, reader); } } return throwUnsupportedType(field); } private Object decodeInt(NumericType type, SSZReader reader) { return reader.readUInt(type.size); } private Object decodeLong(NumericType type, SSZReader reader) { return reader.readULong(type.size); } private Object decodeBigInt(NumericType type, SSZReader reader) { return reader.readUnsignedBigInteger(type.size); } private NumericType parseFieldType(SSZField field) { if (field.getExtraSize() != null && field.getExtraSize() % Byte.SIZE != 0) { String error = String.format( "Size of numeric field in bits should match whole bytes, found %s", field.getExtraSize()); throw new SSZSchemeException(error); } NumericType res = classToNumericType.get(field.getRawClass()); if (field.getExtraSize() != null) { res = NumericType.of(res.type, field.getExtraSize()); } return res; } enum Type { INT("int"), LONG("long"), BIGINT("bigint"); private static final Map<String, Type> ENUM_MAP; static { ENUM_MAP = Stream.of(Type.values()).collect(Collectors.toMap(e -> e.type, identity())); } private String type; Type(String type) { this.type = type; } static Type fromValue(String type) { return ENUM_MAP.get(type); } @Override public String toString() { return type; } } static class NumericType { final Type type; final int size; final int mask; NumericType(Type type, int size) { this.type = type; this.size = size; int mask = 0; for (int i = 0; i < size; i++) { mask = 1 | mask << 1; } this.mask = mask; } static NumericType of(Type type, int size) { return new NumericType(type, size); } } }
UTF-8
Java
6,792
java
UIntPrimitive.java
Java
[]
null
[]
package org.ethereum.beacon.ssz.access.basic; import net.consensys.cava.bytes.Bytes; import org.ethereum.beacon.ssz.visitor.SSZReader; import org.ethereum.beacon.ssz.visitor.SSZWriter; import net.consensys.cava.ssz.SSZException; import org.ethereum.beacon.ssz.access.SSZBasicAccessor; import org.ethereum.beacon.ssz.access.SSZField; import org.ethereum.beacon.ssz.SSZSchemeException; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.function.Function.identity; /** * {@link SSZBasicAccessor} for all primitive Java integers and their default wrappers * * <p>All numerics are considered unsigned, bit size could be clarified by {@link * SSZField#getExtraSize()} */ public class UIntPrimitive implements SSZBasicAccessor { private static final int DEFAULT_BYTE_SIZE = 8; private static final int DEFAULT_SHORT_SIZE = 16; private static final int DEFAULT_INT_SIZE = 32; private static final int DEFAULT_LONG_SIZE = 64; private static final int DEFAULT_BIGINT_SIZE = 512; private static Map<Class, NumericType> classToNumericType = new HashMap<>(); private static Set<String> supportedTypes = new HashSet<>(); private static Set<Class> supportedClassTypes = new HashSet<>(); static { classToNumericType.put(byte.class, NumericType.of(Type.INT, DEFAULT_BYTE_SIZE)); classToNumericType.put(Byte.class, NumericType.of(Type.INT, DEFAULT_BYTE_SIZE)); classToNumericType.put(int.class, NumericType.of(Type.INT, DEFAULT_INT_SIZE)); classToNumericType.put(Integer.class, NumericType.of(Type.INT, DEFAULT_INT_SIZE)); classToNumericType.put(short.class, NumericType.of(Type.INT, DEFAULT_SHORT_SIZE)); classToNumericType.put(Short.class, NumericType.of(Type.INT, DEFAULT_SHORT_SIZE)); classToNumericType.put(long.class, NumericType.of(Type.LONG, DEFAULT_LONG_SIZE)); classToNumericType.put(Long.class, NumericType.of(Type.LONG, DEFAULT_LONG_SIZE)); classToNumericType.put(BigInteger.class, NumericType.of(Type.BIGINT, DEFAULT_BIGINT_SIZE)); } static { supportedTypes.add("uint"); } static { supportedClassTypes.add(byte.class); supportedClassTypes.add(Byte.class); supportedClassTypes.add(int.class); supportedClassTypes.add(Integer.class); supportedClassTypes.add(short.class); supportedClassTypes.add(Short.class); supportedClassTypes.add(long.class); supportedClassTypes.add(Long.class); supportedClassTypes.add(BigInteger.class); } private static void encodeInt(Object value, NumericType type, OutputStream result) { encodeLong(((Number) value).intValue() & type.mask, type.size, result); } private static void encodeLong(Object value, NumericType type, OutputStream result) { encodeLong((long) value, type.size, result); } private static void encodeLong(long value, int bitLength, OutputStream result) { Bytes res = SSZWriter.encodeULong(value, bitLength); try { result.write(res.toArrayUnsafe()); } catch (IOException e) { throw new SSZException(String.format("Failed to write value \"%s\" to stream", value), e); } } private static void encodeBigInt(Object value, NumericType type, OutputStream result) { BigInteger valueBI = (BigInteger) value; Bytes res = SSZWriter.encodeBigInteger(valueBI, type.size); try { result.write(res.toArrayUnsafe()); } catch (IOException e) { throw new SSZException(String.format("Failed to write value \"%s\" to stream", value), e); } } @Override public Set<String> getSupportedSSZTypes() { return supportedTypes; } @Override public Set<Class> getSupportedClasses() { return supportedClassTypes; } @Override public int getSize(SSZField field) { return parseFieldType(field).size / 8; } @Override public void encode(Object value, SSZField field, OutputStream result) { NumericType numericType = parseFieldType(field); switch (numericType.type) { case INT: { encodeInt(value, numericType, result); break; } case LONG: { encodeLong(value, numericType, result); break; } case BIGINT: { encodeBigInt(value, numericType, result); break; } default: { throwUnsupportedType(field); } } } @Override public Object decode(SSZField field, SSZReader reader) { NumericType numericType = parseFieldType(field); switch (numericType.type) { case INT: { return decodeInt(numericType, reader); } case LONG: { return decodeLong(numericType, reader); } case BIGINT: { return decodeBigInt(numericType, reader); } } return throwUnsupportedType(field); } private Object decodeInt(NumericType type, SSZReader reader) { return reader.readUInt(type.size); } private Object decodeLong(NumericType type, SSZReader reader) { return reader.readULong(type.size); } private Object decodeBigInt(NumericType type, SSZReader reader) { return reader.readUnsignedBigInteger(type.size); } private NumericType parseFieldType(SSZField field) { if (field.getExtraSize() != null && field.getExtraSize() % Byte.SIZE != 0) { String error = String.format( "Size of numeric field in bits should match whole bytes, found %s", field.getExtraSize()); throw new SSZSchemeException(error); } NumericType res = classToNumericType.get(field.getRawClass()); if (field.getExtraSize() != null) { res = NumericType.of(res.type, field.getExtraSize()); } return res; } enum Type { INT("int"), LONG("long"), BIGINT("bigint"); private static final Map<String, Type> ENUM_MAP; static { ENUM_MAP = Stream.of(Type.values()).collect(Collectors.toMap(e -> e.type, identity())); } private String type; Type(String type) { this.type = type; } static Type fromValue(String type) { return ENUM_MAP.get(type); } @Override public String toString() { return type; } } static class NumericType { final Type type; final int size; final int mask; NumericType(Type type, int size) { this.type = type; this.size = size; int mask = 0; for (int i = 0; i < size; i++) { mask = 1 | mask << 1; } this.mask = mask; } static NumericType of(Type type, int size) { return new NumericType(type, size); } } }
6,792
0.678298
0.675942
233
28.150215
26.63501
96
false
false
0
0
0
0
0
0
0.686695
false
false
2
ec4bef075a8b364155e2f019435688c834f36090
33,775,622,882,609
588113d5e312a899e6e9ccb54b17d62a04f28f2a
/src/main/java/io/bonitoo/influxdemo/ui/TagStructure.java
589a78eeb1b98b562b6452dc92fd85dd498e87d9
[]
no_license
bonitoo-io/influxdata-iot-petstore
https://github.com/bonitoo-io/influxdata-iot-petstore
4c356b543e0125168a5dce3e537edc7c79ecc054
0f04364bf11cf69744c8762f35112bcbb31e8631
refs/heads/master
2021-09-16T19:46:30.960000
2019-07-30T11:44:34
2019-07-30T11:44:34
169,589,156
2
2
null
false
2021-08-30T16:25:44
2019-02-07T14:58:26
2019-11-08T11:43:55
2021-08-30T16:25:38
4,966
1
2
3
Java
false
false
package io.bonitoo.influxdemo.ui; public class TagStructure { String tag; String[] values; public TagStructure(final String tag, final String... values) { this.tag = tag; this.values = values; } }
UTF-8
Java
229
java
TagStructure.java
Java
[]
null
[]
package io.bonitoo.influxdemo.ui; public class TagStructure { String tag; String[] values; public TagStructure(final String tag, final String... values) { this.tag = tag; this.values = values; } }
229
0.641921
0.641921
10
22
18.676188
67
false
false
0
0
0
0
0
0
0.6
false
false
2
c4a7ffc40bee830838dc5d3550d38ea5b7dc87c7
38,534,446,607,561
c71d30086ee41b0e99e99972bc16573e8cb4c6fc
/java/day10/StringBuilderStringBufferTest.java
338e140fafec08a10e3ca9c6b1c0f69b03b58d6e
[]
no_license
hy1116/MyJava
https://github.com/hy1116/MyJava
ac6d1e0acba05ab03e96abee8c1d83f9e02031ad
a780f69c00c14b788683aabb738b4273f10f3d74
refs/heads/master
2022-01-22T10:48:56.588000
2018-12-11T02:03:24
2018-12-11T02:03:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package my.day10; public class StringBuilderStringBufferTest { public static void main(String[] args) { /* 문자열을 변경할때 마다 새로운 객체를 생성하는 String 클래스와는 다르게 문자열 변경시 새로운 객체를 생성하지 않고 버퍼에 담겨있는 문자열을 바로 수정한다. StringBuilder 클래스와 StringBuffer 클래스의 객체는 객체생성시 크기를 지정하지 않으면 기본적으로 16개의 문자열을 담을 수 있는 버퍼의 크기를 가지게 된다. 16개의 문자열을 담을 수 있는 크기를 초과한 문자열을 받으면 16*2 = 32 로 버퍼의 크기가 자동으로 증가되고, 32개의 문자열을 담을 수 있는 크기를 초과한 문자열을 받으면 32*2 = 64 로 버퍼의 크기가 자동으로 증가.... 이런식으로 매번 2배씩 자동으로 증가된다. StringBuilder 클래스와 StringBuffer 클래스의 차이점은 StringBuffer 클래스만 멀티스레드 하에서 동기화 기능을 지원해주는 것이다. 그 외에는 StringBuilder 클래스와 StringBuffer 클래스는 동일하게 동작한다. */ String str = ""; System.out.println(str.hashCode()); // 0 // 객체명.hashCode() ==> 객체가 할당받은 메모리의 주소값(정수) str += "안녕"; System.out.println(str.hashCode()); // 1611021 str += "하세요"; System.out.println(str.hashCode()); // 803356551 str += "행복하세요"; System.out.println(str.hashCode()); // -280857471 System.out.println(str); // 안녕하세요행복하세요 System.out.println("str 크기 : " + str.length()); // 10 System.out.println("\r\n====================================\r\n"); StringBuilder sbuilder = new StringBuilder(); sbuilder.append("안녕"); System.out.println(sbuilder.hashCode()); // 1028566121 sbuilder.append("하세요"); System.out.println(sbuilder.hashCode()); // 1028566121 sbuilder.append("행복하세요"); System.out.println(sbuilder.hashCode()); // 1028566121 System.out.println(sbuilder.toString()); // 안녕하세요행복하세요 System.out.println("sbuilder 크기 : " + sbuilder.length()); // 10 System.out.println("\r\n====================================\r\n"); StringBuffer sbuffer = new StringBuffer(); sbuffer.append("안녕"); System.out.println(sbuffer.hashCode()); // 1118140819 sbuffer.append("하세요"); System.out.println(sbuffer.hashCode()); // 1118140819 sbuffer.append("행복하세요"); System.out.println(sbuffer.hashCode()); // 1118140819 System.out.println(sbuffer.toString()); // 안녕하세요행복하세요 System.out.println("sbuffer 크기 : " + sbuffer.length()); // 10 } }
UTF-8
Java
2,782
java
StringBuilderStringBufferTest.java
Java
[]
null
[]
package my.day10; public class StringBuilderStringBufferTest { public static void main(String[] args) { /* 문자열을 변경할때 마다 새로운 객체를 생성하는 String 클래스와는 다르게 문자열 변경시 새로운 객체를 생성하지 않고 버퍼에 담겨있는 문자열을 바로 수정한다. StringBuilder 클래스와 StringBuffer 클래스의 객체는 객체생성시 크기를 지정하지 않으면 기본적으로 16개의 문자열을 담을 수 있는 버퍼의 크기를 가지게 된다. 16개의 문자열을 담을 수 있는 크기를 초과한 문자열을 받으면 16*2 = 32 로 버퍼의 크기가 자동으로 증가되고, 32개의 문자열을 담을 수 있는 크기를 초과한 문자열을 받으면 32*2 = 64 로 버퍼의 크기가 자동으로 증가.... 이런식으로 매번 2배씩 자동으로 증가된다. StringBuilder 클래스와 StringBuffer 클래스의 차이점은 StringBuffer 클래스만 멀티스레드 하에서 동기화 기능을 지원해주는 것이다. 그 외에는 StringBuilder 클래스와 StringBuffer 클래스는 동일하게 동작한다. */ String str = ""; System.out.println(str.hashCode()); // 0 // 객체명.hashCode() ==> 객체가 할당받은 메모리의 주소값(정수) str += "안녕"; System.out.println(str.hashCode()); // 1611021 str += "하세요"; System.out.println(str.hashCode()); // 803356551 str += "행복하세요"; System.out.println(str.hashCode()); // -280857471 System.out.println(str); // 안녕하세요행복하세요 System.out.println("str 크기 : " + str.length()); // 10 System.out.println("\r\n====================================\r\n"); StringBuilder sbuilder = new StringBuilder(); sbuilder.append("안녕"); System.out.println(sbuilder.hashCode()); // 1028566121 sbuilder.append("하세요"); System.out.println(sbuilder.hashCode()); // 1028566121 sbuilder.append("행복하세요"); System.out.println(sbuilder.hashCode()); // 1028566121 System.out.println(sbuilder.toString()); // 안녕하세요행복하세요 System.out.println("sbuilder 크기 : " + sbuilder.length()); // 10 System.out.println("\r\n====================================\r\n"); StringBuffer sbuffer = new StringBuffer(); sbuffer.append("안녕"); System.out.println(sbuffer.hashCode()); // 1118140819 sbuffer.append("하세요"); System.out.println(sbuffer.hashCode()); // 1118140819 sbuffer.append("행복하세요"); System.out.println(sbuffer.hashCode()); // 1118140819 System.out.println(sbuffer.toString()); // 안녕하세요행복하세요 System.out.println("sbuffer 크기 : " + sbuffer.length()); // 10 } }
2,782
0.643407
0.58999
68
29.558823
25.051348
74
false
false
0
0
0
0
0
0
2.235294
false
false
2
3d02c2bada043fb7220716370a534d8ab3017a55
39,462,159,547,823
35d3127d5cf1a30c23aa42dd2984b257fe2eb510
/cloud-account/src/main/java/com/dukoia/cloud/account/fallback/AccountFallback.java
f85eeac76e096b563fa96b19a7bccea10fafd255
[]
no_license
Dukoia/cloud-study
https://github.com/Dukoia/cloud-study
262c9065fc0c9751b10c75a4a5b5c9a2d52a4660
6c5220b8accd980d9ab3292fef09ca182c16eee8
refs/heads/main
2023-06-30T06:31:33.961000
2021-07-30T08:43:00
2021-07-30T08:43:00
380,160,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dukoia.cloud.account.fallback; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.dukoia.cloud.Result; import org.springframework.stereotype.Component; /** * @Description: AccountFallback * @Author: jiangze.He * @Date: 2021-07-29 * @Version: v1.0 */ @Component public class AccountFallback { public static Result handler(Long id, BlockException exception){ return Result.success("请求失败"); } }
UTF-8
Java
456
java
AccountFallback.java
Java
[ { "context": "\n\n/**\n * @Description: AccountFallback\n * @Author: jiangze.He\n * @Date: 2021-07-29\n * @Version: v1.0\n */\n@Compo", "end": 245, "score": 0.9996131658554077, "start": 235, "tag": "NAME", "value": "jiangze.He" } ]
null
[]
package com.dukoia.cloud.account.fallback; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.dukoia.cloud.Result; import org.springframework.stereotype.Component; /** * @Description: AccountFallback * @Author: jiangze.He * @Date: 2021-07-29 * @Version: v1.0 */ @Component public class AccountFallback { public static Result handler(Long id, BlockException exception){ return Result.success("请求失败"); } }
456
0.738839
0.716518
19
22.578947
20.688965
68
false
false
0
0
0
0
0
0
0.315789
false
false
2
45c055d180bfebb7a72299ec0ece9f77d334a0cd
39,049,842,698,925
13005f6f9b834cc36e3e788d403ce3565488c2ad
/week-04/day-01/exercise-13/src/Blog.java
de5ad552ac8691f3dbaa19c4d572b4f7b264b9ab
[]
no_license
greenfox-academy/tamasbrandstadter
https://github.com/greenfox-academy/tamasbrandstadter
007cd787ef996d0428e46616558ea96b019abec2
be601e684728ddcb1d3407e752c72b63a09fdb5e
refs/heads/master
2021-01-22T22:39:29.550000
2017-07-10T08:09:09
2017-07-10T08:09:09
85,564,297
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; public class Blog { List<BlogPost> list; public Blog() { this.list = new ArrayList<>(); } public void delete(int index) { list.remove(index); } public void update(int index, BlogPost blogPost) { list.set(index, blogPost); } }
UTF-8
Java
306
java
Blog.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.List; public class Blog { List<BlogPost> list; public Blog() { this.list = new ArrayList<>(); } public void delete(int index) { list.remove(index); } public void update(int index, BlogPost blogPost) { list.set(index, blogPost); } }
306
0.656863
0.656863
18
16.055555
15.116115
52
false
false
0
0
0
0
0
0
0.444444
false
false
2
81177c260ef9dd8f5e6a378118c04f52567b728c
7,267,084,728,720
47950c9bf7b77a14d7e243e259db793641590021
/src/main/java/com/omb/msx/elektronika/ComboServo.java
3964773386e20adc3b20524092a1043df023b4cd
[]
no_license
v-bodnar/RpiSpeedster
https://github.com/v-bodnar/RpiSpeedster
b330ae6a12ad500cc02ebcc5eb58fcb4e1b77e59
8a260b65eee3c9013faf3d2286e4cbe24f198f70
refs/heads/master
2023-05-11T14:29:09.397000
2020-09-05T23:39:49
2020-09-05T23:39:49
169,216,947
0
0
null
false
2023-04-30T09:36:08
2019-02-05T09:34:26
2020-09-05T23:42:43
2023-04-30T09:36:07
557
0
0
8
Java
false
false
package com.omb.msx.elektronika; import com.pi4j.component.servo.ServoDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class ComboServo implements com.pi4j.component.servo.Servo { private static final Logger LOGGER = LoggerFactory.getLogger(ComboServo.class); //PCA9685 to stop the servo private final byte[] PWM_STOP = new byte[]{0X00, 0X00, 0X00, 0X00}; //Adafruit Servo Hat used to command servo functions private final AdafruitHat servoHat; //Motor name "S01" through "S16" private final ServoName servoName; private final float period; //period or duty-cycle in milliseconds //I'm going to drain power from DC motor Output private final DcMotor dcMotor; /* * operating limits of servo are based on pulse width (milliseconds). * These initial values are fairly conservative and should work for * many servos. The operating limits can be updated by the application * with the setOperatingLimits() method. Consult the servo's data sheet * to obtain the manufacture's recommended values. */ private float minimumPulseWidth = 0; private float neutralPulseWidth = 0; private float maximumPulseWidth = 0; /* * The relative minimum and maximum values to command the servo * through the setPosition() method. The minimum value corresponds to * minimumPulseWidth position of the servo. The maximum value corresponds * to the maximum pulse width position. */ private float minimumX = 0.0f; private float maximumX = 1.0f; //PCA9685 Register addresses for PWM that control motor speed private final int[] pwmAddr; //Corresponding speed values private byte[] pwmValues; //current servo position private float servoPosition; public ComboServo(AdafruitHat servoHat, DcMotor dcMotor, int[] pwmAddr, ServoName servoName) { this.servoHat = servoHat; this.servoName = servoName; this.pwmAddr = pwmAddr; this.dcMotor = dcMotor; this.period = (1.0f / (float) servoHat.getFrequency()) * 1000.0f; } /** * Set the pulse width (milliseconds) to drive servo position. * * @param pulseWidth in milliseconds */ public void setPulseWidth(float pulseWidth) { if (pulseWidth < minimumPulseWidth || pulseWidth > maximumPulseWidth || pulseWidth > period) { LOGGER.debug("*** Error *** pulseWidth value invalid"); LOGGER.debug("Must be in range: {} to {}", minimumPulseWidth, maximumPulseWidth); LOGGER.debug("and must be less than period: {}", period); servoHat.stopAll(); throw new IllegalArgumentException(Float.toString(pulseWidth)); } //raw servo value for setting the pulseWidth int rawServo = (int) (Math.round((pulseWidth / period) * 4095.0)); if (rawServo < 0) rawServo = 0; pwmValues = new byte[]{(byte) 0, (byte) 0, (byte) (rawServo & 0XFF), (byte) (rawServo >> 8)}; sendCommands(); } /** * Set the operating pulse width range for the servo. Consult the servo's data sheet * for the manufacturer's recommended pulse width designation. * * @param minimumPulseWidth minimum-position pulse width in milliseconds * @param neutralPulseWidth neutral-position pulse width in milliseconds * @param maximumPulseWidth maximum-position pulse width in milliseconds */ public void setOperatingLimits(float minimumPulseWidth, float neutralPulseWidth, float maximumPulseWidth) { boolean hit = false; if (minimumPulseWidth <= 0.0 || neutralPulseWidth <= 0.0 || maximumPulseWidth <= 0.0) { hit = true; LOGGER.debug("*** Error *** pulse width values can not be 0.0"); } if (minimumPulseWidth > period || neutralPulseWidth > period || maximumPulseWidth > period) { } if (minimumPulseWidth >= neutralPulseWidth) { hit = true; LOGGER.debug("*** Error *** minimumPulseWidth > neutralPulseWidth"); } if (minimumPulseWidth >= maximumPulseWidth) { hit = true; LOGGER.debug("*** Error *** minimumPulseWidth >= maximumPulseWidth"); } if (neutralPulseWidth >= maximumPulseWidth) { hit = true; LOGGER.debug("*** Error *** neutralPulseWidth >= maximumPulseWidth"); } if (hit) { servoHat.stopAll(); throw new IllegalArgumentException(); } this.minimumPulseWidth = minimumPulseWidth; this.neutralPulseWidth = neutralPulseWidth; this.maximumPulseWidth = maximumPulseWidth; //we will need full power, which corresponds to 5V dcMotor.setPowerRange(100.0f); dcMotor.forward(); dcMotor.speed(100f); setPulseWidth(neutralPulseWidth); } /** * Specify the relative minimum and maximum value range of the servo motor. * The value passed to the setPostion() method must be in this range. * The minimumX value corresponds to the servo position of minimum pulse width and * maximumX to the servo position of the maximum pulse width. * * @param minimumX Defaults to 0.0 * @param maximumX Defaults to 1.0 */ public void setPositionRange(float minimumX, float maximumX) { if (minimumX >= maximumX) { LOGGER.debug("*** Error *** xMax must be greater than xMin"); servoHat.stopAll(); throw new IllegalArgumentException(); } this.minimumX = minimumX; this.maximumX = maximumX; } /** * Move servo to relative position. * * @param servoPosition The range of the servoPosition corresponds to the minimum * and maximum values set in the setPositionRange() method. The default range * is 0.0 to 1.0 if the setPositionRange() method is not called. */ @Override public void setPosition(float servoPosition) { if (servoPosition < minimumX || servoPosition > maximumX) { LOGGER.debug("*** Error *** servo value must be in range 0.0 to 1.0"); servoHat.stopAll(); throw new IllegalArgumentException(Float.toString(servoPosition)); } float slope = (maximumPulseWidth - minimumPulseWidth) / (maximumX - minimumX); float b = maximumPulseWidth - slope * maximumX; float pulseWidth = slope * servoPosition + b; if (pulseWidth > maximumPulseWidth) pulseWidth = maximumPulseWidth; if (pulseWidth < minimumPulseWidth) pulseWidth = minimumPulseWidth; setPulseWidth(pulseWidth); this.servoPosition = servoPosition; } /** * Return the current servo position */ @Override public float getPosition() { return (float) servoPosition; } public float getMinimumPosition() { return minimumX; } public float getMaximumPosition() { return maximumX; } @Override public void off() { servoHat.stopAll(); } /** * Return the operating PWM frequency in cycles per second. * The operating frequency can be changed with the * AdafruitServoHat.setPwmFreq() method. * * @return PWM frequency in cycles/second */ public float getPwmFreq() { return (float) servoHat.getFrequency(); } /** * Return minimum operating pulse width of servo. * * @return minimumPulseWidth in milliseconds */ public float getMinimumPulseWidth() { return minimumPulseWidth; } /** * Return neutral operating pulse width of servo. * * @return neutralPulseWidth in milliseconds */ public float getNeutralPulseWidth() { return neutralPulseWidth; } /** * Return maximum operating pulse width of servo. * * @return maximumPulseWidth in milliseconds */ public float getMaximumPulseWidth() { return maximumPulseWidth; } /** * Stop servo */ public void stop() { pwmValues = PWM_STOP; sendCommands(); } /** * Send commands to the I2C device. */ private void sendCommands() { for (int i = 0; i < 4; i++) servoHat.write(pwmAddr[i], pwmValues[i]); } /** * Does nothing. */ @Override public void setName(String name) { } /** * return name of servo, name constructed in method() */ @Override public String getName() { //Here's our generated device return servoName.name(); } /* * Not applicable methods to this implementation of the servo class */ @Override public void setTag(Object tag) { throw new UnsupportedOperationException(); } @Override public Object getTag() { throw new UnsupportedOperationException(); } @Override public void setProperty(String key, String value) { throw new UnsupportedOperationException(); } @Override public boolean hasProperty(String key) { throw new UnsupportedOperationException(); } @Override public String getProperty(String key, String defaultValue) { throw new UnsupportedOperationException(); } @Override public String getProperty(String key) { throw new UnsupportedOperationException(); } @Override public Map<String, String> getProperties() { throw new UnsupportedOperationException(); } @Override public void removeProperty(String key) { throw new UnsupportedOperationException(); } @Override public void clearProperties() { throw new UnsupportedOperationException(); } @Override public ServoDriver getServoDriver() { throw new UnsupportedOperationException(); } public enum ServoName { S_1, S_2, S_14, S_15; } }
UTF-8
Java
10,013
java
ComboServo.java
Java
[]
null
[]
package com.omb.msx.elektronika; import com.pi4j.component.servo.ServoDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class ComboServo implements com.pi4j.component.servo.Servo { private static final Logger LOGGER = LoggerFactory.getLogger(ComboServo.class); //PCA9685 to stop the servo private final byte[] PWM_STOP = new byte[]{0X00, 0X00, 0X00, 0X00}; //Adafruit Servo Hat used to command servo functions private final AdafruitHat servoHat; //Motor name "S01" through "S16" private final ServoName servoName; private final float period; //period or duty-cycle in milliseconds //I'm going to drain power from DC motor Output private final DcMotor dcMotor; /* * operating limits of servo are based on pulse width (milliseconds). * These initial values are fairly conservative and should work for * many servos. The operating limits can be updated by the application * with the setOperatingLimits() method. Consult the servo's data sheet * to obtain the manufacture's recommended values. */ private float minimumPulseWidth = 0; private float neutralPulseWidth = 0; private float maximumPulseWidth = 0; /* * The relative minimum and maximum values to command the servo * through the setPosition() method. The minimum value corresponds to * minimumPulseWidth position of the servo. The maximum value corresponds * to the maximum pulse width position. */ private float minimumX = 0.0f; private float maximumX = 1.0f; //PCA9685 Register addresses for PWM that control motor speed private final int[] pwmAddr; //Corresponding speed values private byte[] pwmValues; //current servo position private float servoPosition; public ComboServo(AdafruitHat servoHat, DcMotor dcMotor, int[] pwmAddr, ServoName servoName) { this.servoHat = servoHat; this.servoName = servoName; this.pwmAddr = pwmAddr; this.dcMotor = dcMotor; this.period = (1.0f / (float) servoHat.getFrequency()) * 1000.0f; } /** * Set the pulse width (milliseconds) to drive servo position. * * @param pulseWidth in milliseconds */ public void setPulseWidth(float pulseWidth) { if (pulseWidth < minimumPulseWidth || pulseWidth > maximumPulseWidth || pulseWidth > period) { LOGGER.debug("*** Error *** pulseWidth value invalid"); LOGGER.debug("Must be in range: {} to {}", minimumPulseWidth, maximumPulseWidth); LOGGER.debug("and must be less than period: {}", period); servoHat.stopAll(); throw new IllegalArgumentException(Float.toString(pulseWidth)); } //raw servo value for setting the pulseWidth int rawServo = (int) (Math.round((pulseWidth / period) * 4095.0)); if (rawServo < 0) rawServo = 0; pwmValues = new byte[]{(byte) 0, (byte) 0, (byte) (rawServo & 0XFF), (byte) (rawServo >> 8)}; sendCommands(); } /** * Set the operating pulse width range for the servo. Consult the servo's data sheet * for the manufacturer's recommended pulse width designation. * * @param minimumPulseWidth minimum-position pulse width in milliseconds * @param neutralPulseWidth neutral-position pulse width in milliseconds * @param maximumPulseWidth maximum-position pulse width in milliseconds */ public void setOperatingLimits(float minimumPulseWidth, float neutralPulseWidth, float maximumPulseWidth) { boolean hit = false; if (minimumPulseWidth <= 0.0 || neutralPulseWidth <= 0.0 || maximumPulseWidth <= 0.0) { hit = true; LOGGER.debug("*** Error *** pulse width values can not be 0.0"); } if (minimumPulseWidth > period || neutralPulseWidth > period || maximumPulseWidth > period) { } if (minimumPulseWidth >= neutralPulseWidth) { hit = true; LOGGER.debug("*** Error *** minimumPulseWidth > neutralPulseWidth"); } if (minimumPulseWidth >= maximumPulseWidth) { hit = true; LOGGER.debug("*** Error *** minimumPulseWidth >= maximumPulseWidth"); } if (neutralPulseWidth >= maximumPulseWidth) { hit = true; LOGGER.debug("*** Error *** neutralPulseWidth >= maximumPulseWidth"); } if (hit) { servoHat.stopAll(); throw new IllegalArgumentException(); } this.minimumPulseWidth = minimumPulseWidth; this.neutralPulseWidth = neutralPulseWidth; this.maximumPulseWidth = maximumPulseWidth; //we will need full power, which corresponds to 5V dcMotor.setPowerRange(100.0f); dcMotor.forward(); dcMotor.speed(100f); setPulseWidth(neutralPulseWidth); } /** * Specify the relative minimum and maximum value range of the servo motor. * The value passed to the setPostion() method must be in this range. * The minimumX value corresponds to the servo position of minimum pulse width and * maximumX to the servo position of the maximum pulse width. * * @param minimumX Defaults to 0.0 * @param maximumX Defaults to 1.0 */ public void setPositionRange(float minimumX, float maximumX) { if (minimumX >= maximumX) { LOGGER.debug("*** Error *** xMax must be greater than xMin"); servoHat.stopAll(); throw new IllegalArgumentException(); } this.minimumX = minimumX; this.maximumX = maximumX; } /** * Move servo to relative position. * * @param servoPosition The range of the servoPosition corresponds to the minimum * and maximum values set in the setPositionRange() method. The default range * is 0.0 to 1.0 if the setPositionRange() method is not called. */ @Override public void setPosition(float servoPosition) { if (servoPosition < minimumX || servoPosition > maximumX) { LOGGER.debug("*** Error *** servo value must be in range 0.0 to 1.0"); servoHat.stopAll(); throw new IllegalArgumentException(Float.toString(servoPosition)); } float slope = (maximumPulseWidth - minimumPulseWidth) / (maximumX - minimumX); float b = maximumPulseWidth - slope * maximumX; float pulseWidth = slope * servoPosition + b; if (pulseWidth > maximumPulseWidth) pulseWidth = maximumPulseWidth; if (pulseWidth < minimumPulseWidth) pulseWidth = minimumPulseWidth; setPulseWidth(pulseWidth); this.servoPosition = servoPosition; } /** * Return the current servo position */ @Override public float getPosition() { return (float) servoPosition; } public float getMinimumPosition() { return minimumX; } public float getMaximumPosition() { return maximumX; } @Override public void off() { servoHat.stopAll(); } /** * Return the operating PWM frequency in cycles per second. * The operating frequency can be changed with the * AdafruitServoHat.setPwmFreq() method. * * @return PWM frequency in cycles/second */ public float getPwmFreq() { return (float) servoHat.getFrequency(); } /** * Return minimum operating pulse width of servo. * * @return minimumPulseWidth in milliseconds */ public float getMinimumPulseWidth() { return minimumPulseWidth; } /** * Return neutral operating pulse width of servo. * * @return neutralPulseWidth in milliseconds */ public float getNeutralPulseWidth() { return neutralPulseWidth; } /** * Return maximum operating pulse width of servo. * * @return maximumPulseWidth in milliseconds */ public float getMaximumPulseWidth() { return maximumPulseWidth; } /** * Stop servo */ public void stop() { pwmValues = PWM_STOP; sendCommands(); } /** * Send commands to the I2C device. */ private void sendCommands() { for (int i = 0; i < 4; i++) servoHat.write(pwmAddr[i], pwmValues[i]); } /** * Does nothing. */ @Override public void setName(String name) { } /** * return name of servo, name constructed in method() */ @Override public String getName() { //Here's our generated device return servoName.name(); } /* * Not applicable methods to this implementation of the servo class */ @Override public void setTag(Object tag) { throw new UnsupportedOperationException(); } @Override public Object getTag() { throw new UnsupportedOperationException(); } @Override public void setProperty(String key, String value) { throw new UnsupportedOperationException(); } @Override public boolean hasProperty(String key) { throw new UnsupportedOperationException(); } @Override public String getProperty(String key, String defaultValue) { throw new UnsupportedOperationException(); } @Override public String getProperty(String key) { throw new UnsupportedOperationException(); } @Override public Map<String, String> getProperties() { throw new UnsupportedOperationException(); } @Override public void removeProperty(String key) { throw new UnsupportedOperationException(); } @Override public void clearProperties() { throw new UnsupportedOperationException(); } @Override public ServoDriver getServoDriver() { throw new UnsupportedOperationException(); } public enum ServoName { S_1, S_2, S_14, S_15; } }
10,013
0.635873
0.626885
319
30.388714
27.614895
111
false
false
0
0
0
0
0
0
0.404389
false
false
2
bbb585d21f57cd855abeb5b2d0c6c05716fc1cfe
20,907,900,861,682
9ad01474e06aedb3897e6abe5cb3e609ea88a2c0
/compiler/src/gallifreyc/extension/GallifreyFormalExt.java
a06edba565a12512646cedd9937c3c372389f66e
[]
no_license
apl-cornell/gallifreyc
https://github.com/apl-cornell/gallifreyc
6ae9621c0867bf1adb04990c6e76151a2b9b3426
d5c40217d31285fe128aafd5388c83a69c213a2f
refs/heads/master
2023-03-30T09:28:11.541000
2021-03-30T04:16:36
2021-03-30T04:16:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gallifreyc.extension; import polyglot.types.SemanticException; import polyglot.util.Position; import polyglot.util.SerialVersionUID; import polyglot.visit.TypeBuilder; import gallifreyc.ast.GallifreyNodeFactory; import gallifreyc.ast.LocalRef; import gallifreyc.ast.RefQualification; import gallifreyc.ast.RefQualifiedTypeNode; import gallifreyc.ast.RestrictionId; import gallifreyc.ast.SharedRef; import gallifreyc.ast.UnknownRef; import gallifreyc.translate.GallifreyCodegenRewriter; import gallifreyc.types.GallifreyLocalInstance; import polyglot.ast.ArrayTypeNode; import polyglot.ast.Formal; import polyglot.ast.Node; import polyglot.ast.TypeNode; public class GallifreyFormalExt extends GallifreyExt { private static final long serialVersionUID = SerialVersionUID.generate(); public RefQualification qualification; { qualification = new UnknownRef(Position.COMPILER_GENERATED); } @Override public Formal node() { return (Formal) super.node(); } @Override public Node buildTypes(TypeBuilder tb) throws SemanticException { Formal n = (Formal) superLang().buildTypes(this.node, tb); TypeNode t = n.type(); GallifreyLocalInstance li; if (t instanceof RefQualifiedTypeNode) { RefQualifiedTypeNode rt = (RefQualifiedTypeNode) t; li = (GallifreyLocalInstance) n.localInstance(); li.gallifreyType().qualification = rt.qualification(); } else if (t instanceof ArrayTypeNode && ((ArrayTypeNode) t).base() instanceof RefQualifiedTypeNode) { RefQualifiedTypeNode rt = (RefQualifiedTypeNode) ((ArrayTypeNode) t).base(); li = (GallifreyLocalInstance) n.localInstance(); li.gallifreyType().qualification = rt.qualification(); } else { // default to local for unqualified + primitives li = (GallifreyLocalInstance) n.localInstance(); li.gallifreyType().qualification = new LocalRef(Position.COMPILER_GENERATED); } qualification = li.gallifreyType().qualification; return n; } @Override public Node gallifreyRewrite(GallifreyCodegenRewriter rw) throws SemanticException { Formal f = node(); GallifreyNodeFactory nf = rw.nodeFactory(); RefQualification q = qualification; if (q.isShared()) { SharedRef s = (SharedRef) q; RestrictionId rid = s.restriction(); return f.type(rw.getFormalTypeNode(rid)); } return f; } }
UTF-8
Java
2,540
java
GallifreyFormalExt.java
Java
[]
null
[]
package gallifreyc.extension; import polyglot.types.SemanticException; import polyglot.util.Position; import polyglot.util.SerialVersionUID; import polyglot.visit.TypeBuilder; import gallifreyc.ast.GallifreyNodeFactory; import gallifreyc.ast.LocalRef; import gallifreyc.ast.RefQualification; import gallifreyc.ast.RefQualifiedTypeNode; import gallifreyc.ast.RestrictionId; import gallifreyc.ast.SharedRef; import gallifreyc.ast.UnknownRef; import gallifreyc.translate.GallifreyCodegenRewriter; import gallifreyc.types.GallifreyLocalInstance; import polyglot.ast.ArrayTypeNode; import polyglot.ast.Formal; import polyglot.ast.Node; import polyglot.ast.TypeNode; public class GallifreyFormalExt extends GallifreyExt { private static final long serialVersionUID = SerialVersionUID.generate(); public RefQualification qualification; { qualification = new UnknownRef(Position.COMPILER_GENERATED); } @Override public Formal node() { return (Formal) super.node(); } @Override public Node buildTypes(TypeBuilder tb) throws SemanticException { Formal n = (Formal) superLang().buildTypes(this.node, tb); TypeNode t = n.type(); GallifreyLocalInstance li; if (t instanceof RefQualifiedTypeNode) { RefQualifiedTypeNode rt = (RefQualifiedTypeNode) t; li = (GallifreyLocalInstance) n.localInstance(); li.gallifreyType().qualification = rt.qualification(); } else if (t instanceof ArrayTypeNode && ((ArrayTypeNode) t).base() instanceof RefQualifiedTypeNode) { RefQualifiedTypeNode rt = (RefQualifiedTypeNode) ((ArrayTypeNode) t).base(); li = (GallifreyLocalInstance) n.localInstance(); li.gallifreyType().qualification = rt.qualification(); } else { // default to local for unqualified + primitives li = (GallifreyLocalInstance) n.localInstance(); li.gallifreyType().qualification = new LocalRef(Position.COMPILER_GENERATED); } qualification = li.gallifreyType().qualification; return n; } @Override public Node gallifreyRewrite(GallifreyCodegenRewriter rw) throws SemanticException { Formal f = node(); GallifreyNodeFactory nf = rw.nodeFactory(); RefQualification q = qualification; if (q.isShared()) { SharedRef s = (SharedRef) q; RestrictionId rid = s.restriction(); return f.type(rw.getFormalTypeNode(rid)); } return f; } }
2,540
0.701968
0.701968
69
35.811596
25.978964
110
false
false
0
0
0
0
0
0
0.623188
false
false
2
a48cc3c45a0cff462c20a2bd44baa5571a369876
16,389,595,271,040
611b8136a599411c0b09b27708a0b9a60a70589d
/FirebaseTest/src/main/java/Users.java
3a300a690f8710453e9f2ddc66096e3547c1ef07
[]
no_license
panduwicaksono91/firebasetest
https://github.com/panduwicaksono91/firebasetest
a81d8c40d19c82f5ed405d2076679bd3703a39c3
17430a30d8ebefdb7ae442251e85b67c9e2fc683
refs/heads/master
2020-07-25T22:40:57.513000
2016-12-10T16:03:07
2016-12-10T16:03:07
73,647,999
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Users { public String email; public String name; public String phone; public String username; public Users(){ this.email = ""; this.name = ""; this.phone = ""; this.username = ""; } public Users(String email, String name, String phone, String username) { this.email = email; this.name = name; this.phone = phone; this.username = username; } @Override public String toString(){ return "Email: " + email + ", Name : " + name + ", Phone: " + phone + ", Username: " + username; } }
UTF-8
Java
532
java
Users.java
Java
[ { "context": "me = name;\n\t\tthis.phone = phone;\n\t\tthis.username = username;\n\t}\n\t\n\t@Override\n\tpublic String toString(){\n\t\tret", "end": 378, "score": 0.9903783798217773, "start": 370, "tag": "USERNAME", "value": "username" }, { "context": " name + \", Phone: \" + phone +\n\t\t\t\t\", Username: \" + username;\n\t}\n\n}\n", "end": 524, "score": 0.9700514078140259, "start": 516, "tag": "USERNAME", "value": "username" } ]
null
[]
public class Users { public String email; public String name; public String phone; public String username; public Users(){ this.email = ""; this.name = ""; this.phone = ""; this.username = ""; } public Users(String email, String name, String phone, String username) { this.email = email; this.name = name; this.phone = phone; this.username = username; } @Override public String toString(){ return "Email: " + email + ", Name : " + name + ", Phone: " + phone + ", Username: " + username; } }
532
0.620301
0.620301
27
18.666666
17.761799
73
false
false
0
0
0
0
0
0
2.037037
false
false
2
18881007066dd3af171321b19d601c1757a980b7
7,438,883,366,306
122b32971c47fad19f10b08f71690d29a250e6de
/exception/FuncionarioException.java
fa9847156f1bcda8b0e4d4da233f7c177b101037
[]
no_license
ewertonluna-inc/ProjetoPOO
https://github.com/ewertonluna-inc/ProjetoPOO
eef007a990cab113589066fd4439d341147367ff
8ec65efc88fcde5c0d8e671d861e662865b3da10
refs/heads/master
2023-01-12T10:48:28.576000
2020-11-12T16:48:03
2020-11-12T16:48:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exception; public class FuncionarioException extends Exception { public FuncionarioException(String mensagem) { super(mensagem); } }
UTF-8
Java
157
java
FuncionarioException.java
Java
[]
null
[]
package exception; public class FuncionarioException extends Exception { public FuncionarioException(String mensagem) { super(mensagem); } }
157
0.738854
0.738854
7
21.571428
20.624931
53
false
false
0
0
0
0
0
0
0.285714
false
false
2
0639c78903e400f61f832e08d6e2a5f154604773
23,914,377,965,230
8e8cca20d23863e13eb7f8a3235888c4e00f8b2c
/PadroesDeProjeto/Factory/src/Pizzaria2.java
72c6f01ed07254931c8ed09ba53a00b7f9c0d545
[]
no_license
andrefcordeiro/Aprendendo-Java
https://github.com/andrefcordeiro/Aprendendo-Java
d55b3a0b8fe0bd3e9376dbfe563ef65951c0618f
75dcd5aa563fac81f5cc4edbcf40988f453833c2
refs/heads/master
2023-02-04T12:15:03.431000
2020-12-22T02:13:05
2020-12-22T02:13:05
264,568,323
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Pizzaria2 extends Pizzaria { /* faz pizza de mussarela */ @Override public Pizza fazerPizza() { Pizza p = new PizzaMussarela(); return p; } }
UTF-8
Java
171
java
Pizzaria2.java
Java
[]
null
[]
public class Pizzaria2 extends Pizzaria { /* faz pizza de mussarela */ @Override public Pizza fazerPizza() { Pizza p = new PizzaMussarela(); return p; } }
171
0.660819
0.654971
12
13.166667
14.564988
41
false
false
0
0
0
0
0
0
1.083333
false
false
2
f5bc466ed02ccc4595c7e58eadfcb2743cd56100
31,275,951,882,185
d30268d2d07df5f6fab98b7bbf0248bf423c4ec4
/god.com370-table/src/main/java/god/com/table/web/GodTableController.java
c078b6f96266de401a9af0147e01928d14e6c21e
[]
no_license
god18/egovframe
https://github.com/god18/egovframe
26496da1ba03a21ae3c6b65205491d99ade0541c
e952d22646ab4f81984c9635c8b9554a126d2eb5
refs/heads/master
2020-04-07T01:31:29.920000
2019-04-01T05:34:24
2019-04-01T05:34:24
157,943,841
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package god.com.table.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import egovframework.rte.psl.dataaccess.util.EgovMap; import god.com.table.service.GodTableService; import god.com.table.service.GodTableVO; @Controller public class GodTableController { @Autowired private GodTableService service; @RequestMapping("/table/selectList.do") public String selectList(GodTableVO vo, Model model) { vo.setUseAt("Y"); List<EgovMap> results = service.selectList(vo); model.addAttribute("results", results); return "god/com/table/selectList"; } @RequestMapping("/table/insertForm.do") public String insertForm(GodTableVO vo, Model model) { service.insertForm(vo, model); return "god/com/table/insertForm"; } @RequestMapping("/table/insert.do") public String insert(GodTableVO vo, Model model) { service.insert(vo, model); return "god/com/table/insert"; } @RequestMapping("/table/updateForm.do") public String updateForm(GodTableVO vo, Model model) { service.updateForm(vo, model); return "god/com/table/insertForm"; } @RequestMapping("/table/update.do") public String update(GodTableVO vo, Model model) { service.update(vo, model); return "god/com/table/insert"; } @RequestMapping("/table/delete.do") public String delete(GodTableVO vo, Model model) { service.delete(vo, model); return "god/com/table/delete"; } }
UTF-8
Java
1,619
java
GodTableController.java
Java
[]
null
[]
package god.com.table.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import egovframework.rte.psl.dataaccess.util.EgovMap; import god.com.table.service.GodTableService; import god.com.table.service.GodTableVO; @Controller public class GodTableController { @Autowired private GodTableService service; @RequestMapping("/table/selectList.do") public String selectList(GodTableVO vo, Model model) { vo.setUseAt("Y"); List<EgovMap> results = service.selectList(vo); model.addAttribute("results", results); return "god/com/table/selectList"; } @RequestMapping("/table/insertForm.do") public String insertForm(GodTableVO vo, Model model) { service.insertForm(vo, model); return "god/com/table/insertForm"; } @RequestMapping("/table/insert.do") public String insert(GodTableVO vo, Model model) { service.insert(vo, model); return "god/com/table/insert"; } @RequestMapping("/table/updateForm.do") public String updateForm(GodTableVO vo, Model model) { service.updateForm(vo, model); return "god/com/table/insertForm"; } @RequestMapping("/table/update.do") public String update(GodTableVO vo, Model model) { service.update(vo, model); return "god/com/table/insert"; } @RequestMapping("/table/delete.do") public String delete(GodTableVO vo, Model model) { service.delete(vo, model); return "god/com/table/delete"; } }
1,619
0.730698
0.730698
58
25.913794
20.275928
62
false
false
0
0
0
0
0
0
1.448276
false
false
2
80b15b5ad87d6d746c24551960710faf35753954
12,970,801,269,339
e26c4432dc79a204a46b3210f318459fbf14ce52
/Android-App/app/src/main/java/ch/dss/gadgeothek/SingleViewFragment.java
3f2f734302ade07d4f4bd8ca6249f3cdf0eab3c0
[]
no_license
marshalluous/AndroidBibliothekApp
https://github.com/marshalluous/AndroidBibliothekApp
1e81f0650b7014a4de14576b7dc1e83528f4b6bf
7c25e49a859b201ab98a96a18b0c8a2ec7428bc7
refs/heads/master
2021-01-11T20:36:27.649000
2017-01-16T19:57:52
2017-01-16T19:57:52
79,152,399
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.dss.gadgeothek; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import ch.dss.gadgeothek.domain.Gadget; import ch.dss.gadgeothek.domain.Loan; import ch.dss.gadgeothek.domain.Reservation; import ch.dss.gadgeothek.service.Callback; import ch.dss.gadgeothek.service.LibraryService; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link SingleViewFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link SingleViewFragment#newInstance} factory method to * create an instance of this fragment. */ public class SingleViewFragment extends Fragment { // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER public static final String ARG_ITEM = "note_to_show"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; private Activity activity; public enum Availability { LOAN, RESERVED, AVAILABLE } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SingleViewFragment. */ public static SingleViewFragment newInstance(String param1, String param2) { SingleViewFragment fragment = new SingleViewFragment(); Bundle args = new Bundle(); args.putString(ARG_ITEM, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_ITEM); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { activity = getActivity(); // Inflate the layout for this fragment final View parent = inflater.inflate(R.layout.fragment_single_view, container, false); GadgetApplication app = (GadgetApplication) getActivity().getApplication(); Gadget gadget = app.getAllGadgets().get(getArguments().getInt(ARG_ITEM)); setFragmentTitle(parent, gadget.getManufacturer() + " " + gadget.getName()); setGadgetConditionDescription(parent, gadget.getCondition().toString()); setGadgetPrice(parent, gadget.getPrice()); setImage(parent, gadget.getName()); setContextActions(parent, gadget); return parent; } private void setContextActions(final View parent, final Gadget gadget) { final List<Reservation> reservations = new ArrayList<>(); LibraryService.getReservationsForCustomer(new Callback<List<Reservation>>() { @Override public void onCompletion(List<Reservation> input) { reservations.clear(); reservations.addAll(input); Reservation myReservation = null; for (Reservation reservation : reservations) { if(reservation.getGadget().equals(gadget)){ myReservation = reservation; break; } } if(myReservation != null){ // gadget is reserved from current user --> delete action applyContextToView(Availability.RESERVED, parent, gadget, myReservation, null); } else { final List<Loan> loans = new ArrayList<>(); LibraryService.getLoansForCustomer(new Callback<List<Loan>>() { @Override public void onCompletion(List<Loan> input) { loans.clear(); loans.addAll(input); Loan myLoan = null; for (Loan loan : loans) { if(loan.getGadget().equals(gadget)){ myLoan = loan; break; } } if(myLoan != null){ // gadget is loan from current user --> no action applyContextToView(Availability.LOAN, parent, gadget, null, myLoan); } else { // gadget is not reserved nor loan from current user --> reservation action applyContextToView(Availability.AVAILABLE, parent, gadget, null, null); } } @Override public void onError(String message) { Toast toast = Toast.makeText(activity, "Fehler beim Laden der Ausleihen", Toast.LENGTH_SHORT); toast.show(); } }); } } @Override public void onError(String message) { Toast toast = Toast.makeText(activity, "Fehler beim Laden der Reservationen", Toast.LENGTH_SHORT); toast.show(); } }); } public void applyContextToView(Availability context, final View parent, final Gadget gadget, final Reservation myReservation, final Loan myLoan){ final TextView availability = (TextView) parent.findViewById(R.id.availability); final Button actionButton = (Button) parent.findViewById(R.id.buttonAction1); switch (context) { case RESERVED: availability.setText("reserviert"); actionButton.setText("Reservation löschen"); actionButton.setVisibility(View.VISIBLE); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { LibraryService.deleteReservation(myReservation, new Callback<Boolean>() { @Override public void onCompletion(Boolean input) { Toast toast = Toast.makeText(activity, "Reservation gelöscht!", Toast.LENGTH_SHORT); toast.show(); setContextActions(parent, gadget); } @Override public void onError(String message) { Toast toast = Toast.makeText(activity, "Fehler: Reservation konnte nicht gelöscht werden", Toast.LENGTH_SHORT); toast.show(); } }); } }); break; case LOAN: DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); String dateToReturn = dateFormat.format(myLoan.overDueDate()); availability.setText("Ausgeliehen - zurückgeben am: " + dateToReturn); actionButton.setVisibility(View.INVISIBLE); break; case AVAILABLE: availability.setText("verfügbar"); actionButton.setText("Reservieren"); actionButton.setVisibility(View.VISIBLE); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { LibraryService.reserveGadget(gadget, new Callback<Boolean>() { @Override public void onCompletion(Boolean input) { Toast toast = Toast.makeText(activity, "Reservation bestätigt!", Toast.LENGTH_SHORT); toast.show(); setContextActions(parent, gadget); } @Override public void onError(String message) { Toast toast = Toast.makeText(activity, "Reservierung fehlgeschlagen!", Toast.LENGTH_SHORT); toast.show(); } }); } }); break; default: availability.setText("unbekannt"); actionButton.setVisibility(View.INVISIBLE); break; } } private void setFragmentTitle(View parent, String title) { TextView fragmentTitle = (TextView) parent.findViewById(R.id.textGadgetTitle); fragmentTitle.setText(title); fragmentTitle.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); } private void setGadgetConditionDescription(View parent, String state) { TextView gadgetState = (TextView) parent.findViewById(R.id.textGadgetCondition); gadgetState.setText(state); } private void setGadgetPrice(View parent, double price) { TextView gadgetState = (TextView) parent.findViewById(R.id.textPrice); gadgetState.setText(Double.toString(price)); } private void setImage(View parent, String gadgetName) { ImageView gadgetImage = (ImageView) parent.findViewById(R.id.gadgetimage); switch (gadgetName) { case "IPhone": gadgetImage.setImageResource(R.drawable.iphone7); break; case "IPhone1": gadgetImage.setImageResource(R.drawable.iphone1); break; case "IPhone2": gadgetImage.setImageResource(R.drawable.iphone2); break; case "IPhone3": gadgetImage.setImageResource(R.drawable.iphone3); break; case "IPhone4": gadgetImage.setImageResource(R.drawable.iphone4); break; case "Android1": gadgetImage.setImageResource(R.drawable.android1); break; case "Android2": gadgetImage.setImageResource(R.drawable.android2); break; default: gadgetImage.setImageResource(R.drawable.placeholderimage); break; } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } }
UTF-8
Java
12,533
java
SingleViewFragment.java
Java
[]
null
[]
package ch.dss.gadgeothek; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import ch.dss.gadgeothek.domain.Gadget; import ch.dss.gadgeothek.domain.Loan; import ch.dss.gadgeothek.domain.Reservation; import ch.dss.gadgeothek.service.Callback; import ch.dss.gadgeothek.service.LibraryService; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link SingleViewFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link SingleViewFragment#newInstance} factory method to * create an instance of this fragment. */ public class SingleViewFragment extends Fragment { // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER public static final String ARG_ITEM = "note_to_show"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; private Activity activity; public enum Availability { LOAN, RESERVED, AVAILABLE } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SingleViewFragment. */ public static SingleViewFragment newInstance(String param1, String param2) { SingleViewFragment fragment = new SingleViewFragment(); Bundle args = new Bundle(); args.putString(ARG_ITEM, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_ITEM); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { activity = getActivity(); // Inflate the layout for this fragment final View parent = inflater.inflate(R.layout.fragment_single_view, container, false); GadgetApplication app = (GadgetApplication) getActivity().getApplication(); Gadget gadget = app.getAllGadgets().get(getArguments().getInt(ARG_ITEM)); setFragmentTitle(parent, gadget.getManufacturer() + " " + gadget.getName()); setGadgetConditionDescription(parent, gadget.getCondition().toString()); setGadgetPrice(parent, gadget.getPrice()); setImage(parent, gadget.getName()); setContextActions(parent, gadget); return parent; } private void setContextActions(final View parent, final Gadget gadget) { final List<Reservation> reservations = new ArrayList<>(); LibraryService.getReservationsForCustomer(new Callback<List<Reservation>>() { @Override public void onCompletion(List<Reservation> input) { reservations.clear(); reservations.addAll(input); Reservation myReservation = null; for (Reservation reservation : reservations) { if(reservation.getGadget().equals(gadget)){ myReservation = reservation; break; } } if(myReservation != null){ // gadget is reserved from current user --> delete action applyContextToView(Availability.RESERVED, parent, gadget, myReservation, null); } else { final List<Loan> loans = new ArrayList<>(); LibraryService.getLoansForCustomer(new Callback<List<Loan>>() { @Override public void onCompletion(List<Loan> input) { loans.clear(); loans.addAll(input); Loan myLoan = null; for (Loan loan : loans) { if(loan.getGadget().equals(gadget)){ myLoan = loan; break; } } if(myLoan != null){ // gadget is loan from current user --> no action applyContextToView(Availability.LOAN, parent, gadget, null, myLoan); } else { // gadget is not reserved nor loan from current user --> reservation action applyContextToView(Availability.AVAILABLE, parent, gadget, null, null); } } @Override public void onError(String message) { Toast toast = Toast.makeText(activity, "Fehler beim Laden der Ausleihen", Toast.LENGTH_SHORT); toast.show(); } }); } } @Override public void onError(String message) { Toast toast = Toast.makeText(activity, "Fehler beim Laden der Reservationen", Toast.LENGTH_SHORT); toast.show(); } }); } public void applyContextToView(Availability context, final View parent, final Gadget gadget, final Reservation myReservation, final Loan myLoan){ final TextView availability = (TextView) parent.findViewById(R.id.availability); final Button actionButton = (Button) parent.findViewById(R.id.buttonAction1); switch (context) { case RESERVED: availability.setText("reserviert"); actionButton.setText("Reservation löschen"); actionButton.setVisibility(View.VISIBLE); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { LibraryService.deleteReservation(myReservation, new Callback<Boolean>() { @Override public void onCompletion(Boolean input) { Toast toast = Toast.makeText(activity, "Reservation gelöscht!", Toast.LENGTH_SHORT); toast.show(); setContextActions(parent, gadget); } @Override public void onError(String message) { Toast toast = Toast.makeText(activity, "Fehler: Reservation konnte nicht gelöscht werden", Toast.LENGTH_SHORT); toast.show(); } }); } }); break; case LOAN: DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); String dateToReturn = dateFormat.format(myLoan.overDueDate()); availability.setText("Ausgeliehen - zurückgeben am: " + dateToReturn); actionButton.setVisibility(View.INVISIBLE); break; case AVAILABLE: availability.setText("verfügbar"); actionButton.setText("Reservieren"); actionButton.setVisibility(View.VISIBLE); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { LibraryService.reserveGadget(gadget, new Callback<Boolean>() { @Override public void onCompletion(Boolean input) { Toast toast = Toast.makeText(activity, "Reservation bestätigt!", Toast.LENGTH_SHORT); toast.show(); setContextActions(parent, gadget); } @Override public void onError(String message) { Toast toast = Toast.makeText(activity, "Reservierung fehlgeschlagen!", Toast.LENGTH_SHORT); toast.show(); } }); } }); break; default: availability.setText("unbekannt"); actionButton.setVisibility(View.INVISIBLE); break; } } private void setFragmentTitle(View parent, String title) { TextView fragmentTitle = (TextView) parent.findViewById(R.id.textGadgetTitle); fragmentTitle.setText(title); fragmentTitle.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); } private void setGadgetConditionDescription(View parent, String state) { TextView gadgetState = (TextView) parent.findViewById(R.id.textGadgetCondition); gadgetState.setText(state); } private void setGadgetPrice(View parent, double price) { TextView gadgetState = (TextView) parent.findViewById(R.id.textPrice); gadgetState.setText(Double.toString(price)); } private void setImage(View parent, String gadgetName) { ImageView gadgetImage = (ImageView) parent.findViewById(R.id.gadgetimage); switch (gadgetName) { case "IPhone": gadgetImage.setImageResource(R.drawable.iphone7); break; case "IPhone1": gadgetImage.setImageResource(R.drawable.iphone1); break; case "IPhone2": gadgetImage.setImageResource(R.drawable.iphone2); break; case "IPhone3": gadgetImage.setImageResource(R.drawable.iphone3); break; case "IPhone4": gadgetImage.setImageResource(R.drawable.iphone4); break; case "Android1": gadgetImage.setImageResource(R.drawable.android1); break; case "Android2": gadgetImage.setImageResource(R.drawable.android2); break; default: gadgetImage.setImageResource(R.drawable.placeholderimage); break; } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } }
12,533
0.566217
0.563742
312
39.150642
28.964386
143
false
false
0
0
0
0
0
0
0.608974
false
false
2
42e61ffcb44f6ae6dc5a49008577ff5c84cbb18f
22,926,535,460,169
9a3cfdecd0424059e6e6ef78fcce9c58c08db059
/src/main/java/br/com/exemplo/roteador/RouterBeanConfig.java
1c8d3d03aaa196771f477c91de4c27d1233be6e1
[]
no_license
brunoboassi/roteador-assync
https://github.com/brunoboassi/roteador-assync
e4616c72ccd48783745aa1d50fd09767b6fe583c
d8345bd9c866ec794f76c48ce509a4c1fe352a20
refs/heads/master
2022-11-27T19:03:09.972000
2020-07-30T04:16:31
2020-07-30T04:16:31
281,017,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.exemplo.roteador; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.integration.config.EnableIntegration; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import java.io.IOException; import java.util.UUID; @Configuration @EnableBinding({GatewayChannels.class}) @EnableIntegration @IntegrationComponentScan @RequiredArgsConstructor public class RouterBeanConfig { private final ObjectMapper objectMapper; @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("path_route_cloud", r -> r.path("/get") .uri("forward:/magica")) .build(); } @Bean public RouterFunction<ServerResponse> testWhenMetricPathIsNotMeet(ObjectMapper mapper, QueueGateway gateway, @Value("${spring.cloud.stream.instanceIndex}") String partition) { RouterFunction<ServerResponse> route = RouterFunctions.route( RequestPredicates.path("/magica"), request -> { try { return ServerResponse.ok().body(BodyInserters .fromValue(mapper.readValue(gateway.handle(Request.builder().id(UUID.randomUUID().toString()).origin(1).messageIndex(1).build(),partition), Response.class))); } catch (IOException e) { e.printStackTrace(); return ServerResponse.badRequest().build(); } }); return route; } }
UTF-8
Java
2,373
java
RouterBeanConfig.java
Java
[]
null
[]
package br.com.exemplo.roteador; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.integration.config.EnableIntegration; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import java.io.IOException; import java.util.UUID; @Configuration @EnableBinding({GatewayChannels.class}) @EnableIntegration @IntegrationComponentScan @RequiredArgsConstructor public class RouterBeanConfig { private final ObjectMapper objectMapper; @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("path_route_cloud", r -> r.path("/get") .uri("forward:/magica")) .build(); } @Bean public RouterFunction<ServerResponse> testWhenMetricPathIsNotMeet(ObjectMapper mapper, QueueGateway gateway, @Value("${spring.cloud.stream.instanceIndex}") String partition) { RouterFunction<ServerResponse> route = RouterFunctions.route( RequestPredicates.path("/magica"), request -> { try { return ServerResponse.ok().body(BodyInserters .fromValue(mapper.readValue(gateway.handle(Request.builder().id(UUID.randomUUID().toString()).origin(1).messageIndex(1).build(),partition), Response.class))); } catch (IOException e) { e.printStackTrace(); return ServerResponse.badRequest().build(); } }); return route; } }
2,373
0.718078
0.717236
54
42.944443
37.223259
190
false
false
0
0
0
0
0
0
0.574074
false
false
2
eb49e65bb54bb65b93e1f5f8282a67685a598160
16,200,616,682,647
a640afb80eddf90eb49e3bf8d1b4ca5d9ad39648
/TurnAroundNode.java
244359d430e4542d5a1a8f561fb68ff066e0b123
[]
no_license
Caitlin-Goodger/261-ass4
https://github.com/Caitlin-Goodger/261-ass4
c99e0d75e316638369eebb620582fe93b8ba32a1
d91411f00af4dc494e40f5e521884c569b86b81e
refs/heads/master
2020-06-16T14:52:07.571000
2019-07-07T05:39:39
2019-07-07T05:39:39
195,614,566
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Node to turn node around */ public class TurnAroundNode extends Node { public TurnAroundNode() { } @Override public String toString() { return "turnAround \n"; } @Override public void execute(Robot r) { r.turnAround(); } }
UTF-8
Java
300
java
TurnAroundNode.java
Java
[]
null
[]
/** * Node to turn node around */ public class TurnAroundNode extends Node { public TurnAroundNode() { } @Override public String toString() { return "turnAround \n"; } @Override public void execute(Robot r) { r.turnAround(); } }
300
0.543333
0.543333
18
14.666667
13.824294
42
false
false
0
0
0
0
0
0
0.111111
false
false
2
6d68aef8e0b4d9d06605b216bfadfa424e33df13
13,726,715,522,738
3ef9ec53b87c19246925c0778b8ffed7e2e887cc
/src/ServerInfo.java
0c555634f31272a65b5734f69dc0b98512a1f87d
[]
no_license
tetherless-world/dco-doi-bulk-upload
https://github.com/tetherless-world/dco-doi-bulk-upload
d62a1e5b14719156e77f5ca5f173d3619973d85c
250b9be05456f92cd11a5417f661af595c1e7d2f
refs/heads/master
2021-01-21T23:44:49.734000
2015-05-21T14:52:57
2015-05-21T14:52:57
35,386,503
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class ServerInfo { private static ServerInfo instance = null; private String machineURL = "http://info.deepcarbon.net/vivo"; private String absoluteMachineURL = "http://info.deepcarbon.net/vivo"; private String handleURL = "http://128.213.3.13:8080/dcohandleservice/services/handles/"; private String ckanURL = "http://data.deepcarbon.net/ckan"; private String dcoOntoNameSpace = "http://info.deepcarbon.net/schema#"; private String dcoNamespace = "http://info.deepcarbon.net"; private String rootName = "XXXXX"; private String rootPassword = "XXXXXX"; private void ServerInfo(){ machineURL = "http://udco.tw.rpi.edu/vivo"; absoluteMachineURL = "http://udco.tw.rpi.edu/vivo"; handleURL = "http://128.213.3.13:8080/dcohandleservice/services/handles/"; ckanURL = "http://data.deepcarbon.net/ckan"; dcoOntoNameSpace = "http://info.deepcarbon.net/schema#"; dcoNamespace = "http://info.deepcarbon.net"; rootName = "XXXXX"; rootPassword = "XXXX"; } public static ServerInfo getInstance(){ if(instance==null){ return new ServerInfo(); }else{ return instance; } } public String getRootName(){ return this.rootName; } public String getRootPassword(){ return this.rootPassword; } public String getMachineURL(){ return this.machineURL; } public String getHandleURL(){ return this.handleURL; } public String getCkanURL(){ return this.ckanURL; } public String getDcoOntoNamespace(){ return this.dcoOntoNameSpace; } public String getDcoNamespace(){ return this.dcoNamespace; } public String getAbsoluteMachineURL(){ return this.absoluteMachineURL; } }
UTF-8
Java
1,639
java
ServerInfo.java
Java
[ { "context": "on.net/vivo\";\n\tprivate String handleURL = \"http://128.213.3.13:8080/dcohandleservice/services/handles/\";\n\tprivat", "end": 256, "score": 0.9997621178627014, "start": 244, "tag": "IP_ADDRESS", "value": "128.213.3.13" }, { "context": "otName = \"XXXXX\";\n\tprivate String rootPassword = \"XXXXXX\";\n\t\n\tprivate void ServerInfo(){\n\t\tmachineURL = \"h", "end": 568, "score": 0.9991978406906128, "start": 562, "tag": "PASSWORD", "value": "XXXXXX" }, { "context": "tp://udco.tw.rpi.edu/vivo\";\n\t\thandleURL = \"http://128.213.3.13:8080/dcohandleservice/services/handles/\";\n\t\tckanU", "end": 735, "score": 0.9997655749320984, "start": 723, "tag": "IP_ADDRESS", "value": "128.213.3.13" }, { "context": "bon.net\";\n\t\trootName = \"XXXXX\";\n\t\trootPassword = \"XXXX\";\n\t\t\n\t}\n\t\n\tpublic static ServerInfo getInstance()", "end": 975, "score": 0.9975163340568542, "start": 971, "tag": "PASSWORD", "value": "XXXX" } ]
null
[]
public class ServerInfo { private static ServerInfo instance = null; private String machineURL = "http://info.deepcarbon.net/vivo"; private String absoluteMachineURL = "http://info.deepcarbon.net/vivo"; private String handleURL = "http://172.16.17.32:8080/dcohandleservice/services/handles/"; private String ckanURL = "http://data.deepcarbon.net/ckan"; private String dcoOntoNameSpace = "http://info.deepcarbon.net/schema#"; private String dcoNamespace = "http://info.deepcarbon.net"; private String rootName = "XXXXX"; private String rootPassword = "<PASSWORD>"; private void ServerInfo(){ machineURL = "http://udco.tw.rpi.edu/vivo"; absoluteMachineURL = "http://udco.tw.rpi.edu/vivo"; handleURL = "http://172.16.17.32:8080/dcohandleservice/services/handles/"; ckanURL = "http://data.deepcarbon.net/ckan"; dcoOntoNameSpace = "http://info.deepcarbon.net/schema#"; dcoNamespace = "http://info.deepcarbon.net"; rootName = "XXXXX"; rootPassword = "<PASSWORD>"; } public static ServerInfo getInstance(){ if(instance==null){ return new ServerInfo(); }else{ return instance; } } public String getRootName(){ return this.rootName; } public String getRootPassword(){ return this.rootPassword; } public String getMachineURL(){ return this.machineURL; } public String getHandleURL(){ return this.handleURL; } public String getCkanURL(){ return this.ckanURL; } public String getDcoOntoNamespace(){ return this.dcoOntoNameSpace; } public String getDcoNamespace(){ return this.dcoNamespace; } public String getAbsoluteMachineURL(){ return this.absoluteMachineURL; } }
1,649
0.723002
0.707138
62
25.435484
22.82233
90
false
false
0
0
0
0
0
0
1.774194
false
false
2
49da5647503a234562f151793ac12aa755687499
18,494,129,211,149
363095f50c3420bcaedb4a22d4c5dd0ef0286e95
/src/main/java/com/istorozhev/trading/stock/stockAbstract.java
c698496ef82dd23b5ae57f57d8319c0c42d490ab
[]
no_license
aaa3d/webQueue
https://github.com/aaa3d/webQueue
6508710efeb050bde55f3e128ca7436a42c1b9fc
7a04c433e5d696e5c493ef151217048daca34358
refs/heads/master
2021-01-22T06:01:48.484000
2017-06-19T14:24:07
2017-06-19T14:24:07
92,513,903
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.istorozhev.trading.stock; import com.istorozhev.trading.model.orderbook_details; import com.istorozhev.trading.model.orderbook; import com.istorozhev.trading.model.ticker; import com.istorozhev.trading.model.trade; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import lombok.Getter; /** * * @author istorozhev */ public abstract class stockAbstract implements stockInterface{ protected List<orderbook_details> orders = new java.util.ArrayList<orderbook_details>(); protected List<trade> trades = new java.util.ArrayList<trade>(); protected ticker ticker = new ticker(); protected List<orderbook> orderbooks = new ArrayList<orderbook>(); protected List<String> stockPairs = new ArrayList<String>(); protected Calendar serverTime = Calendar.getInstance();; protected String stock_name; public List<orderbook> getOrderbooks(){ return orderbooks; } /* public List<order> getOrders(){ return orders; } */ public List<trade> getTrades(){ return trades; } }
UTF-8
Java
1,304
java
stockAbstract.java
Java
[ { "context": "til.List;\nimport lombok.Getter;\n\n/**\n *\n * @author istorozhev\n */\npublic abstract class stockAbstract implement", "end": 542, "score": 0.9990016222000122, "start": 532, "tag": "USERNAME", "value": "istorozhev" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.istorozhev.trading.stock; import com.istorozhev.trading.model.orderbook_details; import com.istorozhev.trading.model.orderbook; import com.istorozhev.trading.model.ticker; import com.istorozhev.trading.model.trade; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import lombok.Getter; /** * * @author istorozhev */ public abstract class stockAbstract implements stockInterface{ protected List<orderbook_details> orders = new java.util.ArrayList<orderbook_details>(); protected List<trade> trades = new java.util.ArrayList<trade>(); protected ticker ticker = new ticker(); protected List<orderbook> orderbooks = new ArrayList<orderbook>(); protected List<String> stockPairs = new ArrayList<String>(); protected Calendar serverTime = Calendar.getInstance();; protected String stock_name; public List<orderbook> getOrderbooks(){ return orderbooks; } /* public List<order> getOrders(){ return orders; } */ public List<trade> getTrades(){ return trades; } }
1,304
0.707055
0.707055
47
26.74468
24.761387
92
false
false
0
0
0
0
0
0
0.489362
false
false
2
9da9fb88febe268acb2c19443d22bd057cfc435f
32,126,355,414,775
6203307579be1d80cd64e218782d811a40f9dfcd
/src/main/java/com/ts/server/safe/company/service/CompProductKey.java
705f28f1598e7a420ff8ab6718293e18e621563d
[]
no_license
hp-wsp/ts-safe
https://github.com/hp-wsp/ts-safe
833eb198ad82de9a99e528bad51c517337a0d035
f03bdf9d3b05c39c20384951d952f2e57ead05ea
refs/heads/master
2021-09-19T15:49:20.998000
2020-03-11T15:03:10
2020-03-11T15:03:10
229,449,034
1
0
null
false
2021-08-02T17:20:05
2019-12-21T15:48:09
2020-03-11T15:03:21
2021-08-02T17:20:05
34,891
1
0
2
Java
false
false
package com.ts.server.safe.company.service; /** * 企业信息key * * @author <a href="mailto:hhywangwei@gmail.com">WangWei</a> */ public enum CompProductKey { KRBFCCS("krbfccs", 0, "涉及可燃爆粉作业场所"), PTCS("ptcs", 0, "喷涂作业场所"), YXCS("yxcs", 0, "有限作业场所"), SAZNQY("saznqy", 0, "涉氨制冷企业"), CPWXQY("cpwxqy", 0, "船舶维修企业"), YJQY("zjqy", 0, "冶金企业"), WHXP("whxp", 0, "危化学品"), YHBZQY("yhbzqy", 0, "烟花爆竹企业"), KSQY("ksqy", 0, "矿山企业"), SJZDAQSCYH("sjzdaqscyh", 0, "是否涉及重大安全生产隐患"); private final String key; private final int defValue; private final String remark; CompProductKey(String key, int defValue, String remark) { this.key = key; this.defValue = defValue; this.remark = remark; } public String getKey() { return key; } public int getDefValue() { return defValue; } public String getRemark() { return remark; } }
UTF-8
Java
1,074
java
CompProductKey.java
Java
[ { "context": "ce;\n\n/**\n * 企业信息key\n *\n * @author <a href=\"mailto:hhywangwei@gmail.com\">WangWei</a>\n */\npublic enum CompProductKey {\n ", "end": 110, "score": 0.9999220967292786, "start": 90, "tag": "EMAIL", "value": "hhywangwei@gmail.com" }, { "context": "\n * @author <a href=\"mailto:hhywangwei@gmail.com\">WangWei</a>\n */\npublic enum CompProductKey {\n KRBFCCS", "end": 119, "score": 0.999791145324707, "start": 112, "tag": "NAME", "value": "WangWei" } ]
null
[]
package com.ts.server.safe.company.service; /** * 企业信息key * * @author <a href="mailto:<EMAIL>">WangWei</a> */ public enum CompProductKey { KRBFCCS("krbfccs", 0, "涉及可燃爆粉作业场所"), PTCS("ptcs", 0, "喷涂作业场所"), YXCS("yxcs", 0, "有限作业场所"), SAZNQY("saznqy", 0, "涉氨制冷企业"), CPWXQY("cpwxqy", 0, "船舶维修企业"), YJQY("zjqy", 0, "冶金企业"), WHXP("whxp", 0, "危化学品"), YHBZQY("yhbzqy", 0, "烟花爆竹企业"), KSQY("ksqy", 0, "矿山企业"), SJZDAQSCYH("sjzdaqscyh", 0, "是否涉及重大安全生产隐患"); private final String key; private final int defValue; private final String remark; CompProductKey(String key, int defValue, String remark) { this.key = key; this.defValue = defValue; this.remark = remark; } public String getKey() { return key; } public int getDefValue() { return defValue; } public String getRemark() { return remark; } }
1,061
0.584222
0.573561
41
21.878048
16.736401
61
false
false
0
0
0
0
0
0
1.02439
false
false
2
db1303df7cc39eef1c4ff9dbb39bffd392448fdf
32,126,355,415,904
2546bd63ac8992b89ef42205f9db88b086506fd6
/che_heng_shi/src/main/java/com/dingguan/cheHengShi/product/entity/Sku.java
de78639b49c1c79c26501b9f60d0bd16b6f4bc5b
[]
no_license
shunWCS/chehengshi-back
https://github.com/shunWCS/chehengshi-back
f881578860a76f8144e92a7159a1d75eb2cb7427
6f46b1c173a5900508ec5cc620f9cd130b15ce73
refs/heads/master
2022-06-22T07:04:27.102000
2019-12-12T12:35:26
2019-12-12T12:35:26
219,137,588
0
0
null
false
2022-06-21T02:09:46
2019-11-02T10:24:37
2019-12-12T12:35:38
2022-06-21T02:09:42
192
0
0
6
Java
false
false
package com.dingguan.cheHengShi.product.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.NotBlank; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.math.BigDecimal; import java.util.List; /** * Created by zyc on 2018/12/21. */ @Data @Entity @NoArgsConstructor @AllArgsConstructor @Builder @Table(name = "sku") @ApiModel(description = "sku") public class Sku { @Id @Column(columnDefinition = "varchar(30) comment '产品详情表'") private String id; @NotBlank @ApiModelProperty(value = "* 所属产品id") @Column(columnDefinition = "varchar(30) comment 'spuId'",name = "[product_id]") private String productId; @NotBlank @ApiModelProperty(value = "* 产品详情名") @Column(columnDefinition = "varchar(30) comment '产品详情名'",name = "[name]") private String name; @ApiModelProperty(value = " sku的小图片") @Column(columnDefinition = "varchar(300) comment 'sku的小图片'",name = "[banner]") private String banner; @ApiModelProperty(value = " 描述") @Column( name = "[introduce]",columnDefinition = "varchar(300) comment '描述'") private String introduce; @NotNull @ApiModelProperty(value = "* 价格 如果是积分商品这个价格就仅用作展示") @Column(columnDefinition = "decimal(11,2) comment 'sku的原价'" ) private BigDecimal price; @ApiModelProperty(value = "兑换所需积分 仅积分商品需要的字段") @Column( name = "[integral]",columnDefinition = "int(11) comment '兑换所需积分'") private Integer integral; @NotNull @ApiModelProperty(value = "* 库存") @Column( name = "[stock]",columnDefinition = "int(11) comment '库存'") private Integer stock; @ApiModelProperty(value = "sku的销量") @Column(columnDefinition = "integer comment '销量 本销量不展示 仅做统计用'") private Integer sales; }
UTF-8
Java
2,157
java
Sku.java
Java
[ { "context": "Decimal;\nimport java.util.List;\n\n/**\n * Created by zyc on 2018/12/21.\n */\n\n@Data\n@Entity\n@NoArgsConstruc", "end": 448, "score": 0.9995496273040771, "start": 445, "tag": "USERNAME", "value": "zyc" } ]
null
[]
package com.dingguan.cheHengShi.product.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.NotBlank; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.math.BigDecimal; import java.util.List; /** * Created by zyc on 2018/12/21. */ @Data @Entity @NoArgsConstructor @AllArgsConstructor @Builder @Table(name = "sku") @ApiModel(description = "sku") public class Sku { @Id @Column(columnDefinition = "varchar(30) comment '产品详情表'") private String id; @NotBlank @ApiModelProperty(value = "* 所属产品id") @Column(columnDefinition = "varchar(30) comment 'spuId'",name = "[product_id]") private String productId; @NotBlank @ApiModelProperty(value = "* 产品详情名") @Column(columnDefinition = "varchar(30) comment '产品详情名'",name = "[name]") private String name; @ApiModelProperty(value = " sku的小图片") @Column(columnDefinition = "varchar(300) comment 'sku的小图片'",name = "[banner]") private String banner; @ApiModelProperty(value = " 描述") @Column( name = "[introduce]",columnDefinition = "varchar(300) comment '描述'") private String introduce; @NotNull @ApiModelProperty(value = "* 价格 如果是积分商品这个价格就仅用作展示") @Column(columnDefinition = "decimal(11,2) comment 'sku的原价'" ) private BigDecimal price; @ApiModelProperty(value = "兑换所需积分 仅积分商品需要的字段") @Column( name = "[integral]",columnDefinition = "int(11) comment '兑换所需积分'") private Integer integral; @NotNull @ApiModelProperty(value = "* 库存") @Column( name = "[stock]",columnDefinition = "int(11) comment '库存'") private Integer stock; @ApiModelProperty(value = "sku的销量") @Column(columnDefinition = "integer comment '销量 本销量不展示 仅做统计用'") private Integer sales; }
2,157
0.698017
0.684291
86
21.88372
24.084839
83
false
false
0
0
0
0
0
0
0.325581
false
false
2
a5dde0621fa9cfc9750ee12530fb3c86964e2084
18,236,431,183,900
0a84ecbb8f93209c58b1699f3701b9457147475f
/src/main/java/com/hnu/fk/controller/MaintenanceScheduleController.java
07f2dc8335d06ced82f3343c5d2988211d8fdb7c
[]
no_license
zhouweixin/fksrc
https://github.com/zhouweixin/fksrc
d3835809eba7ec8aeaadcf082c7100a337530ebf
9210fdcfb543428c03fca99d5b238de4fd5f826e
refs/heads/master
2020-03-24T22:54:37.613000
2018-08-23T10:20:47
2018-08-23T10:20:47
143,107,916
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hnu.fk.controller; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import com.hnu.fk.domain.MaintenanceSchedule; import com.hnu.fk.domain.Result; import com.hnu.fk.service.MaintenanceScheduleService; import com.hnu.fk.utils.ActionLogUtil; import com.hnu.fk.utils.ResultUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Sort; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; import java.util.Objects; import static cn.afterturn.easypoi.excel.entity.enmus.ExcelType.XSSF; /** * 说明: * * @author WaveLee * 日期: 2018/8/21 */ @RestController @RequestMapping(value = "/maintenanceSchedule") @Api(tags = "检修计划") public class MaintenanceScheduleController { @Autowired private MaintenanceScheduleService maintenanceScheduleService; @PostMapping(value = "/add") @ApiOperation(value = "新增", notes = "id自增长不需要传参") public Result<MaintenanceSchedule> add(@Valid MaintenanceSchedule maintenanceSchedule, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return ResultUtil.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage()); } return ResultUtil.success(maintenanceScheduleService.save(maintenanceSchedule)); } @PostMapping(value = "/update") @ApiOperation(value = "更新") public Result<MaintenanceSchedule> update(@Valid MaintenanceSchedule maintenanceSchedule, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return ResultUtil.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage()); } return ResultUtil.success(maintenanceScheduleService.update(maintenanceSchedule)); } @DeleteMapping(value = "/deleteByIds") @ApiOperation(value = "通过主键数组ids批量删除") public Result delete(@ApiParam(value = "主键数组ids") @RequestParam Integer[] ids){ maintenanceScheduleService.deleteInBatch(ids); return ResultUtil.success(); } @GetMapping(value = "/getById") @ApiOperation(value = "通过id查询") public Result<MaintenanceSchedule> getById(@ApiParam(value = "主键id") @RequestParam(value = "id") Integer id){ return ResultUtil.success(maintenanceScheduleService.findById(id)); } @GetMapping(value = "/getAllByPage") @ApiOperation(value = "查询所有计划-分页") public Result<Page<MaintenanceSchedule>> getAllByPage( @ApiParam(value = "页码(默认为0)") @RequestParam(value = "page", defaultValue = "0") Integer page, @ApiParam(value = "每页记录数(默认为10)") @RequestParam(value = "size", defaultValue = "10") Integer size, @ApiParam(value = "排序字段名(默认为id)") @RequestParam(value = "sortFieldName", defaultValue = "enteringTime") String sortFieldName, @ApiParam(value = "排序方向(0:降序;1升序;这里默认为0)") @RequestParam(value = "asc", defaultValue = "0") Integer asc) { return ResultUtil.success(maintenanceScheduleService.findAllByPage(page, size, sortFieldName, asc)); } @GetMapping(value = "/getAllNotCompleteByPage") @ApiOperation(value = "查询所有未完成计划-分页") public Result<Page<MaintenanceSchedule>> getAllNotCompleteByPage( @ApiParam(value = "页码(默认为0)") @RequestParam(value = "page", defaultValue = "0") Integer page, @ApiParam(value = "每页记录数(默认为10)") @RequestParam(value = "size", defaultValue = "10") Integer size, @ApiParam(value = "排序字段名(默认为enteringTime)") @RequestParam(value = "sortFieldName", defaultValue = "enteringTime") String sortFieldName, @ApiParam(value = "排序方向(0:降序;1升序;这里默认为0)") @RequestParam(value = "asc", defaultValue = "0") Integer asc) { return ResultUtil.success(maintenanceScheduleService.findAllNotCompleteByPage(page, size, sortFieldName, asc)); } @GetMapping(value = "getAllByNameAndDescriptionLikeByPage") @ApiOperation(value = "通过设备名称和故障描述模糊查询-分页") public Result<Page<MaintenanceSchedule>> getAllByNameAndDescriptionLikeByPage( @ApiParam(value = "设备名称") @RequestParam(value = "name") String name, @ApiParam(value = "故障描述") @RequestParam(value = "description",required = false) String description, @ApiParam(value = "页码(默认为0)") @RequestParam(value = "page", defaultValue = "0") Integer page, @ApiParam(value = "每页记录数(默认为10)") @RequestParam(value = "size", defaultValue = "10") Integer size, @ApiParam(value = "排序字段名(默认为enteringTime)") @RequestParam(value = "sortFieldName", defaultValue = "enteringTime") String sortFieldName, @ApiParam(value = "排序方向(0:降序;1升序;这里默认为0)") @RequestParam(value = "asc", defaultValue = "0") Integer asc) { return ResultUtil.success(maintenanceScheduleService.findAllByNameAndDescriptionLike(name,description,page, size, sortFieldName, asc)); } @GetMapping(value = "/download") @ApiOperation(value = "导出excel",notes = "导出所有检修计划") public Result downloadThisYear(HttpServletResponse response) throws IOException { ActionLogUtil.log("检修计划"); Sort sort = new Sort(Sort.Direction.DESC, "enteringTime"); List<MaintenanceSchedule> maintenance = maintenanceScheduleService.findAll(sort); Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("检修计划表","sheet1",XSSF), MaintenanceSchedule.class,maintenance); Date time = new Date(); String fileName = "检修计划表" + time.getTime() + ".xlsx"; response.addHeader("Content-Disposition","attachment;fileName=" +new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)); response.flushBuffer(); workbook.write(response.getOutputStream()); return ResultUtil.success(); } }
UTF-8
Java
6,662
java
MaintenanceScheduleController.java
Java
[ { "context": "ty.enmus.ExcelType.XSSF;\n\n/**\n * 说明:\n *\n * @author WaveLee\n * 日期: 2018/8/21\n */\n@RestController\n@RequestMapp", "end": 1091, "score": 0.9986630082130432, "start": 1084, "tag": "USERNAME", "value": "WaveLee" } ]
null
[]
package com.hnu.fk.controller; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import com.hnu.fk.domain.MaintenanceSchedule; import com.hnu.fk.domain.Result; import com.hnu.fk.service.MaintenanceScheduleService; import com.hnu.fk.utils.ActionLogUtil; import com.hnu.fk.utils.ResultUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Sort; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; import java.util.Objects; import static cn.afterturn.easypoi.excel.entity.enmus.ExcelType.XSSF; /** * 说明: * * @author WaveLee * 日期: 2018/8/21 */ @RestController @RequestMapping(value = "/maintenanceSchedule") @Api(tags = "检修计划") public class MaintenanceScheduleController { @Autowired private MaintenanceScheduleService maintenanceScheduleService; @PostMapping(value = "/add") @ApiOperation(value = "新增", notes = "id自增长不需要传参") public Result<MaintenanceSchedule> add(@Valid MaintenanceSchedule maintenanceSchedule, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return ResultUtil.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage()); } return ResultUtil.success(maintenanceScheduleService.save(maintenanceSchedule)); } @PostMapping(value = "/update") @ApiOperation(value = "更新") public Result<MaintenanceSchedule> update(@Valid MaintenanceSchedule maintenanceSchedule, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return ResultUtil.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage()); } return ResultUtil.success(maintenanceScheduleService.update(maintenanceSchedule)); } @DeleteMapping(value = "/deleteByIds") @ApiOperation(value = "通过主键数组ids批量删除") public Result delete(@ApiParam(value = "主键数组ids") @RequestParam Integer[] ids){ maintenanceScheduleService.deleteInBatch(ids); return ResultUtil.success(); } @GetMapping(value = "/getById") @ApiOperation(value = "通过id查询") public Result<MaintenanceSchedule> getById(@ApiParam(value = "主键id") @RequestParam(value = "id") Integer id){ return ResultUtil.success(maintenanceScheduleService.findById(id)); } @GetMapping(value = "/getAllByPage") @ApiOperation(value = "查询所有计划-分页") public Result<Page<MaintenanceSchedule>> getAllByPage( @ApiParam(value = "页码(默认为0)") @RequestParam(value = "page", defaultValue = "0") Integer page, @ApiParam(value = "每页记录数(默认为10)") @RequestParam(value = "size", defaultValue = "10") Integer size, @ApiParam(value = "排序字段名(默认为id)") @RequestParam(value = "sortFieldName", defaultValue = "enteringTime") String sortFieldName, @ApiParam(value = "排序方向(0:降序;1升序;这里默认为0)") @RequestParam(value = "asc", defaultValue = "0") Integer asc) { return ResultUtil.success(maintenanceScheduleService.findAllByPage(page, size, sortFieldName, asc)); } @GetMapping(value = "/getAllNotCompleteByPage") @ApiOperation(value = "查询所有未完成计划-分页") public Result<Page<MaintenanceSchedule>> getAllNotCompleteByPage( @ApiParam(value = "页码(默认为0)") @RequestParam(value = "page", defaultValue = "0") Integer page, @ApiParam(value = "每页记录数(默认为10)") @RequestParam(value = "size", defaultValue = "10") Integer size, @ApiParam(value = "排序字段名(默认为enteringTime)") @RequestParam(value = "sortFieldName", defaultValue = "enteringTime") String sortFieldName, @ApiParam(value = "排序方向(0:降序;1升序;这里默认为0)") @RequestParam(value = "asc", defaultValue = "0") Integer asc) { return ResultUtil.success(maintenanceScheduleService.findAllNotCompleteByPage(page, size, sortFieldName, asc)); } @GetMapping(value = "getAllByNameAndDescriptionLikeByPage") @ApiOperation(value = "通过设备名称和故障描述模糊查询-分页") public Result<Page<MaintenanceSchedule>> getAllByNameAndDescriptionLikeByPage( @ApiParam(value = "设备名称") @RequestParam(value = "name") String name, @ApiParam(value = "故障描述") @RequestParam(value = "description",required = false) String description, @ApiParam(value = "页码(默认为0)") @RequestParam(value = "page", defaultValue = "0") Integer page, @ApiParam(value = "每页记录数(默认为10)") @RequestParam(value = "size", defaultValue = "10") Integer size, @ApiParam(value = "排序字段名(默认为enteringTime)") @RequestParam(value = "sortFieldName", defaultValue = "enteringTime") String sortFieldName, @ApiParam(value = "排序方向(0:降序;1升序;这里默认为0)") @RequestParam(value = "asc", defaultValue = "0") Integer asc) { return ResultUtil.success(maintenanceScheduleService.findAllByNameAndDescriptionLike(name,description,page, size, sortFieldName, asc)); } @GetMapping(value = "/download") @ApiOperation(value = "导出excel",notes = "导出所有检修计划") public Result downloadThisYear(HttpServletResponse response) throws IOException { ActionLogUtil.log("检修计划"); Sort sort = new Sort(Sort.Direction.DESC, "enteringTime"); List<MaintenanceSchedule> maintenance = maintenanceScheduleService.findAll(sort); Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("检修计划表","sheet1",XSSF), MaintenanceSchedule.class,maintenance); Date time = new Date(); String fileName = "检修计划表" + time.getTime() + ".xlsx"; response.addHeader("Content-Disposition","attachment;fileName=" +new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)); response.flushBuffer(); workbook.write(response.getOutputStream()); return ResultUtil.success(); } }
6,662
0.717656
0.710594
134
45.492538
41.605244
157
false
false
0
0
0
0
0
0
0.69403
false
false
2
2695a722b49188c2fdbe2aa2725e564b386a983a
18,236,431,181,477
2e2586cb7d60886e29a9eabb65de407bd2508287
/src/main/java/cn/springmvc/service/DeptService.java
05b56dd5c9d039590fcac65334d269db43d31a9c
[]
no_license
Rainydayfmb/ssm
https://github.com/Rainydayfmb/ssm
c5a4acba8e0f08d65f7a5ca53fbcdeb29cd1e948
eb70eb5d64582810b3bdad0b16bafe0d4ef7ad75
refs/heads/master
2020-12-30T15:30:01.360000
2017-06-14T16:27:29
2017-06-14T16:27:29
91,148,995
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.springmvc.service; import cn.springmvc.model.Dept; import com.github.pagehelper.PageInfo; /** * @Description: * @Author:feipeng * @Date: 2017/5/19 23:23 */ public interface DeptService { /** * 获得所有部门,分页查询 * @return Dept对象的List集合 * */ PageInfo<Dept> findDept(Dept dept,int pageNum,int PageSize); void removeUserById(Integer id); Dept findDeptById(Integer id); void updateDept(Dept dept); void addDept(Dept dept); }
UTF-8
Java
511
java
DeptService.java
Java
[ { "context": "helper.PageInfo;\n\n/**\n * @Description:\n * @Author:feipeng\n * @Date: 2017/5/19 23:23\n */\npublic interface De", "end": 142, "score": 0.999420166015625, "start": 135, "tag": "USERNAME", "value": "feipeng" } ]
null
[]
package cn.springmvc.service; import cn.springmvc.model.Dept; import com.github.pagehelper.PageInfo; /** * @Description: * @Author:feipeng * @Date: 2017/5/19 23:23 */ public interface DeptService { /** * 获得所有部门,分页查询 * @return Dept对象的List集合 * */ PageInfo<Dept> findDept(Dept dept,int pageNum,int PageSize); void removeUserById(Integer id); Dept findDeptById(Integer id); void updateDept(Dept dept); void addDept(Dept dept); }
511
0.673684
0.650526
26
17.26923
16.579779
64
false
false
0
0
0
0
0
0
0.384615
false
false
2
80cfa28452560c9b8ae3dd95d274d9e9b7b6ea91
31,370,441,170,074
5fb3e522fe4e124821aec5f37b7fce9da819e99f
/Waze/src/Dijkstra.java
8c7e6f4cd0ae2bfdf00c9d5d1451ccd3b25e054f
[]
no_license
bogdan159tbi/POO
https://github.com/bogdan159tbi/POO
40a3b87b7757ac914a495d4f1c92963a57f3c83b
353ec24096691ec54a83adb62a86c5db1eccc45b
refs/heads/main
2023-01-24T16:13:12.318000
2020-12-10T20:18:22
2020-12-10T20:18:22
306,371,595
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; import java.util.*; public class Dijkstra { private Map<String,Integer> distances; private Set<Node> visited; private PriorityQueue<Node> pq; private ArrayList<Street> streets; private int noNodes, len; private ArrayList<String> passed; ArrayList<Node> list, nodes; public Dijkstra(GoogleMaps maps){ this.distances = new HashMap<>(); visited = new HashSet<Node>(); pq = new PriorityQueue<Node>(maps.noNodes, new Node()); this.list = new ArrayList<>(); this.nodes = new ArrayList<>(); this.noNodes = maps.noNodes; this.streets = maps.streets; this.passed = new ArrayList<>(); len = -1; } public void createGraph(Vehicle vehicle){ int gabarit = -1; if(vehicle instanceof Bike) gabarit = Bike.gabarit; else if(vehicle instanceof Motorcycle) gabarit = Motorcycle.gabarit; else if(vehicle instanceof Car) gabarit = Car.gabarit; else if(vehicle instanceof Truck) gabarit = Truck.gabarit; for(int i = 0 ;i < noNodes; i++) nodes.add(new Node("P" +i)); for(Node startNode : nodes) { for (Street street : streets) if (startNode.getName().equals(street.getStart())) { for (Node endNode : nodes) { if (endNode.getName().equals(street.getEnd()) && gabarit <= street.getMaxGabarit()) startNode.addDestination(endNode, street.cost); } } } } public void drive(String st,String end,Vehicle vehicle){ Node root = null; for(int i = 0; i < noNodes; i++){ String name = "P" + i; distances.put(name,Integer.MAX_VALUE); } for(Node findRoot: nodes) if(findRoot.getName().equals(st)) { root = findRoot; distances.put(st,0); root.setDistance(0); } pq.add(root); while(!pq.isEmpty()){ Node neighbour = pq.remove(); if(!neighbour.visited) { visitNeighbours(neighbour, vehicle); neighbour.setVisited(true); visited.add(neighbour); } } } public void visitNeighbours(Node root, Vehicle vehicle){ int newDist = -1, edgeDist = -1,rootDist = -1; rootDist = distances.get(root.getName()); for (Map.Entry<Node, Integer> edge : root.getDestinations().entrySet()){ Node neighbour = edge.getKey(); if(!visited.contains(neighbour)){ neighbour.setParent(root); int distNeigh = distances.get(neighbour.getName()); Street str = Street.findStreet(this.streets ,root.getName(), neighbour.getName()); edgeDist = str.getVehicleCost(vehicle); newDist = rootDist + edgeDist; if(newDist < distNeigh) { neighbour.setDistance(newDist); distances.put(neighbour.getName(), newDist); } pq.add(neighbour); } } } public void parents(String start,String end) { if(distances.get(end) == Integer.MAX_VALUE){ passed.add(start); passed.add(end); passed.add("null"); System.out.println(start + " "+end+ " "+"null"); } else{ if(len < 0) { len = distances.get(end); passed.add(Integer.toString(len)); } if(end.equals(start)) { passed.add(start); for(int i = passed.size() - 1; i >= 0 ; i--) System.out.printf(passed.get(i) + " "); System.out.println(); return; } for(Node findRoot: nodes) if(findRoot.getName().equals(end)) { passed.add(end); parents(start,findRoot.getParent().getName()); } } } }
UTF-8
Java
4,097
java
Dijkstra.java
Java
[]
null
[]
import java.io.*; import java.util.*; public class Dijkstra { private Map<String,Integer> distances; private Set<Node> visited; private PriorityQueue<Node> pq; private ArrayList<Street> streets; private int noNodes, len; private ArrayList<String> passed; ArrayList<Node> list, nodes; public Dijkstra(GoogleMaps maps){ this.distances = new HashMap<>(); visited = new HashSet<Node>(); pq = new PriorityQueue<Node>(maps.noNodes, new Node()); this.list = new ArrayList<>(); this.nodes = new ArrayList<>(); this.noNodes = maps.noNodes; this.streets = maps.streets; this.passed = new ArrayList<>(); len = -1; } public void createGraph(Vehicle vehicle){ int gabarit = -1; if(vehicle instanceof Bike) gabarit = Bike.gabarit; else if(vehicle instanceof Motorcycle) gabarit = Motorcycle.gabarit; else if(vehicle instanceof Car) gabarit = Car.gabarit; else if(vehicle instanceof Truck) gabarit = Truck.gabarit; for(int i = 0 ;i < noNodes; i++) nodes.add(new Node("P" +i)); for(Node startNode : nodes) { for (Street street : streets) if (startNode.getName().equals(street.getStart())) { for (Node endNode : nodes) { if (endNode.getName().equals(street.getEnd()) && gabarit <= street.getMaxGabarit()) startNode.addDestination(endNode, street.cost); } } } } public void drive(String st,String end,Vehicle vehicle){ Node root = null; for(int i = 0; i < noNodes; i++){ String name = "P" + i; distances.put(name,Integer.MAX_VALUE); } for(Node findRoot: nodes) if(findRoot.getName().equals(st)) { root = findRoot; distances.put(st,0); root.setDistance(0); } pq.add(root); while(!pq.isEmpty()){ Node neighbour = pq.remove(); if(!neighbour.visited) { visitNeighbours(neighbour, vehicle); neighbour.setVisited(true); visited.add(neighbour); } } } public void visitNeighbours(Node root, Vehicle vehicle){ int newDist = -1, edgeDist = -1,rootDist = -1; rootDist = distances.get(root.getName()); for (Map.Entry<Node, Integer> edge : root.getDestinations().entrySet()){ Node neighbour = edge.getKey(); if(!visited.contains(neighbour)){ neighbour.setParent(root); int distNeigh = distances.get(neighbour.getName()); Street str = Street.findStreet(this.streets ,root.getName(), neighbour.getName()); edgeDist = str.getVehicleCost(vehicle); newDist = rootDist + edgeDist; if(newDist < distNeigh) { neighbour.setDistance(newDist); distances.put(neighbour.getName(), newDist); } pq.add(neighbour); } } } public void parents(String start,String end) { if(distances.get(end) == Integer.MAX_VALUE){ passed.add(start); passed.add(end); passed.add("null"); System.out.println(start + " "+end+ " "+"null"); } else{ if(len < 0) { len = distances.get(end); passed.add(Integer.toString(len)); } if(end.equals(start)) { passed.add(start); for(int i = passed.size() - 1; i >= 0 ; i--) System.out.printf(passed.get(i) + " "); System.out.println(); return; } for(Node findRoot: nodes) if(findRoot.getName().equals(end)) { passed.add(end); parents(start,findRoot.getParent().getName()); } } } }
4,097
0.517696
0.514767
119
33.42017
20.48098
107
false
false
0
0
0
0
0
0
0.705882
false
false
2
046b8bfc998a31b8c4d30b2602a39498dfff39cc
4,707,284,189,750
d67087e7d573d7acc9d51bda518905076890ea8e
/src/test/java/com/Tests/automation/facebook.java
947a5fa48ed8946b6119750c3efa724986d933c3
[]
no_license
Harmeet-Walia/Automation
https://github.com/Harmeet-Walia/Automation
48719433cf8951f14262d24926be2138cff028e8
fe662ffeeec746f7cc38497cf0916559564d897d
refs/heads/master
2023-05-11T08:25:59.831000
2020-03-04T21:19:05
2020-03-04T21:19:05
203,656,046
0
0
null
false
2023-05-09T18:14:59
2019-08-21T20:02:54
2020-03-04T21:20:43
2023-05-09T18:14:56
122
0
0
1
HTML
false
false
package com.Tests.automation; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.Facebook.LoginPage; import com.practice.automation.basetest.driverConfig; public class facebook extends driverConfig { @Test public void testLogin() { LoginPage login=new LoginPage(driver); login.sendFirstName("BePositive"); login.selectBirthdayMonth("5"); } }
UTF-8
Java
564
java
facebook.java
Java
[ { "context": "gin=new LoginPage(driver);\n\t\tlogin.sendFirstName(\"BePositive\");\n\t\tlogin.selectBirthdayMonth(\"5\");\n\n\t}\n\n}\n", "end": 519, "score": 0.8284400701522827, "start": 509, "tag": "USERNAME", "value": "BePositive" } ]
null
[]
package com.Tests.automation; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.Facebook.LoginPage; import com.practice.automation.basetest.driverConfig; public class facebook extends driverConfig { @Test public void testLogin() { LoginPage login=new LoginPage(driver); login.sendFirstName("BePositive"); login.selectBirthdayMonth("5"); } }
564
0.794326
0.792553
25
21.559999
19.127111
53
false
false
0
0
0
0
0
0
0.92
false
false
2
d99b8501512b68c90e3b8fc6334a1d98aabd8d0e
33,423,435,538,845
08a16e9629fd8c264efb34e350eaf90cccd515fc
/Menu.java
b62c1e7e0bbcc6fa67b281b22efb3c9833a17a54
[]
no_license
excelgum/Tron-Legacy
https://github.com/excelgum/Tron-Legacy
6fa207371030faab5b8c060c19dba544d528410f
59822fafd95ef0f8cd3ba058201079b985c87091
refs/heads/master
2020-05-20T01:34:32.696000
2015-01-07T06:10:48
2015-01-07T06:10:48
28,739,902
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//Menu.Java /*The Menu Class is a Jframe window of the menu and displays the instruction and allows the user to launch either *single player or two player game mode * **/ import java.util.*; import java.awt.event.*; import javax.swing.*; import java.awt.*; public class Menu extends JFrame implements MouseListener,KeyListener,MouseMotionListener{ public String game="none";//game keeps track of which game the user choose either Single or Two private final int HEIGHT=625; private final int WIDTH=1000; private Image dbImage; private Graphics dbg; //below are images loaded to make the menu look attractive private Image bgImage=(new ImageIcon("bg.png")).getImage(); private Image spImage=(new ImageIcon("sp.png")).getImage(); private Image tpImage=(new ImageIcon("tp.png")).getImage(); private Image hImage=(new ImageIcon("h.png")).getImage(); private Image inImage=(new ImageIcon("instruct.png")).getImage(); private Image iImage=(new ImageIcon("instructions.png")).getImage(); private int x,y;//Position of the mouse private boolean click=false;//turns true when the mouse is clicked //Sound is a class that plays music private Sound music= new Sound("song.wav"); public Menu() { super ("Tron Legacy"); music.loop();//command used to start the soundtrack setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); setSize (WIDTH,HEIGHT); setVisible (true); addMouseListener(this); addMouseMotionListener(this); } public void paint(Graphics g){ //Double Buffer if (dbImage==null){ dbImage=createImage(WIDTH,HEIGHT); dbg=dbImage.getGraphics(); } dbg.drawImage(bgImage,0,0,this); //the if conditions below draws highlighted images if the mouse is ontop of the given text //by looking at the location //if the user clicks the text the string game is changed to indicate which game mode to run if (y>0 && y<90){ dbg.drawImage(hImage,0,30,this); if (x<300 && click){ game="Single"; } } else if (y>90 && y <145){ dbg.drawImage(hImage,0,90,this); if (x<300 && click){ game="Two"; } } else if (y>545 && y <600 && x<300){ dbg.drawImage(iImage,0,0,this); dbg.drawImage(hImage,0,550,this); } if (click){ click=false; } //draws the images in the appropriate places dbg.drawImage(spImage,0,10,this); dbg.drawImage(tpImage,-10,70,this); dbg.drawImage(inImage,13,542,this); g.drawImage(dbImage,0,0,this); } //the main class is built into the menu public static void main (String [] arguments){ Menu menu = new Menu ();//creates the menu //the while loop keeps the menu visible untill the user has choosen a game mode while(menu.game.equals("none")){ menu.repaint(); delay(20); } menu.setVisible(false); //then it creates an object of the corresponding game mode class to begin a match in that game mode if (menu.game.equals("Single")){ SinglePlayer frame=new SinglePlayer(); while(frame.running){ frame.run(); delay(20); } frame.repaint(); } else{ TwoPlayer frame=new TwoPlayer(); while(frame.running){ frame.run(); delay(20); } frame.repaint(); } } public static void delay(long len){ try{ Thread.sleep(len); } catch(InterruptedException ex){ System.out.println(ex); } } public void mousePressed(MouseEvent e){} public void mouseMoved(MouseEvent e){this.x=e.getX();this.y=e.getY();}//updates the x and y coordinate of the mouse when it moves public void mouseDragged(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseClicked(MouseEvent e){//when the mouse is clicked it sets click to be true click=true; } public void mouseReleased(MouseEvent e){} public void keyTyped(KeyEvent e){} public void keyPressed(KeyEvent e){} public void keyReleased(KeyEvent e){} }
UTF-8
Java
4,059
java
Menu.java
Java
[]
null
[]
//Menu.Java /*The Menu Class is a Jframe window of the menu and displays the instruction and allows the user to launch either *single player or two player game mode * **/ import java.util.*; import java.awt.event.*; import javax.swing.*; import java.awt.*; public class Menu extends JFrame implements MouseListener,KeyListener,MouseMotionListener{ public String game="none";//game keeps track of which game the user choose either Single or Two private final int HEIGHT=625; private final int WIDTH=1000; private Image dbImage; private Graphics dbg; //below are images loaded to make the menu look attractive private Image bgImage=(new ImageIcon("bg.png")).getImage(); private Image spImage=(new ImageIcon("sp.png")).getImage(); private Image tpImage=(new ImageIcon("tp.png")).getImage(); private Image hImage=(new ImageIcon("h.png")).getImage(); private Image inImage=(new ImageIcon("instruct.png")).getImage(); private Image iImage=(new ImageIcon("instructions.png")).getImage(); private int x,y;//Position of the mouse private boolean click=false;//turns true when the mouse is clicked //Sound is a class that plays music private Sound music= new Sound("song.wav"); public Menu() { super ("Tron Legacy"); music.loop();//command used to start the soundtrack setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); setSize (WIDTH,HEIGHT); setVisible (true); addMouseListener(this); addMouseMotionListener(this); } public void paint(Graphics g){ //Double Buffer if (dbImage==null){ dbImage=createImage(WIDTH,HEIGHT); dbg=dbImage.getGraphics(); } dbg.drawImage(bgImage,0,0,this); //the if conditions below draws highlighted images if the mouse is ontop of the given text //by looking at the location //if the user clicks the text the string game is changed to indicate which game mode to run if (y>0 && y<90){ dbg.drawImage(hImage,0,30,this); if (x<300 && click){ game="Single"; } } else if (y>90 && y <145){ dbg.drawImage(hImage,0,90,this); if (x<300 && click){ game="Two"; } } else if (y>545 && y <600 && x<300){ dbg.drawImage(iImage,0,0,this); dbg.drawImage(hImage,0,550,this); } if (click){ click=false; } //draws the images in the appropriate places dbg.drawImage(spImage,0,10,this); dbg.drawImage(tpImage,-10,70,this); dbg.drawImage(inImage,13,542,this); g.drawImage(dbImage,0,0,this); } //the main class is built into the menu public static void main (String [] arguments){ Menu menu = new Menu ();//creates the menu //the while loop keeps the menu visible untill the user has choosen a game mode while(menu.game.equals("none")){ menu.repaint(); delay(20); } menu.setVisible(false); //then it creates an object of the corresponding game mode class to begin a match in that game mode if (menu.game.equals("Single")){ SinglePlayer frame=new SinglePlayer(); while(frame.running){ frame.run(); delay(20); } frame.repaint(); } else{ TwoPlayer frame=new TwoPlayer(); while(frame.running){ frame.run(); delay(20); } frame.repaint(); } } public static void delay(long len){ try{ Thread.sleep(len); } catch(InterruptedException ex){ System.out.println(ex); } } public void mousePressed(MouseEvent e){} public void mouseMoved(MouseEvent e){this.x=e.getX();this.y=e.getY();}//updates the x and y coordinate of the mouse when it moves public void mouseDragged(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseClicked(MouseEvent e){//when the mouse is clicked it sets click to be true click=true; } public void mouseReleased(MouseEvent e){} public void keyTyped(KeyEvent e){} public void keyPressed(KeyEvent e){} public void keyReleased(KeyEvent e){} }
4,059
0.664203
0.648436
121
32.553719
25.446411
130
false
false
0
0
0
0
0
0
1.900826
false
false
2
16489559fc9bfa79bd844836a5d7380d19dfc7b7
12,498,354,878,955
96c576ab675fea05544ca0a7a54019cefd5a454e
/skyeye-promote/skyeye-common/src/main/java/com/skyeye/eve/service/SysEveModelTypeService.java
99638f1377a0e819ab0c79efbeca9381cabfe519
[]
permissive
weizhiqiang1995/erp-pro
https://github.com/weizhiqiang1995/erp-pro
1cf07409cb4caca79573cb898dd2f348e95b2163
2381ff145a73314d027be6567757b380b9503039
refs/heads/company_server
2023-06-25T11:54:01.056000
2023-06-19T06:14:11
2023-06-19T06:14:11
214,651,539
318
109
Apache-2.0
false
2022-06-18T05:49:04
2019-10-12T13:26:35
2022-06-16T02:31:51
2022-06-18T05:49:03
66,097
207
86
4
Java
false
false
/******************************************************************************* * Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye ******************************************************************************/ package com.skyeye.eve.service; import com.skyeye.common.object.InputObject; import com.skyeye.common.object.OutputObject; /** * @ClassName: SysEveModelTypeService * @Description: 系统模板分类业务层 * @author: skyeye云系列 * @date: 2021/11/13 11:13 * @Copyright: 2021 https://gitee.com/doc_wei01/skyeye Inc. All rights reserved. * 注意:本内容仅限购买后使用.禁止私自外泄以及用于其他的商业目的 */ public interface SysEveModelTypeService { /** * 获取系统模板分类列表 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void querySysEveModelTypeList(InputObject inputObject, OutputObject outputObject); /** * 新增系统模板分类 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void insertSysEveModelType(InputObject inputObject, OutputObject outputObject); /** * 根据id查询系统模板分类详情 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void querySysEveModelTypeById(InputObject inputObject, OutputObject outputObject); /** * 通过parentId查找对应的系统模板分类列表 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void querySysEveModelTypeByParentId(InputObject inputObject, OutputObject outputObject); /** * 通过id编辑对应的系统模板分类信息 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void updateSysEveModelTypeById(InputObject inputObject, OutputObject outputObject); /** * 删除系统模板分类 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void delSysEveModelTypeById(InputObject inputObject, OutputObject outputObject); }
UTF-8
Java
2,530
java
SysEveModelTypeService.java
Java
[ { "context": "************************************\n * Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地", "end": 97, "score": 0.9997260570526123, "start": 94, "tag": "NAME", "value": "卫志强" }, { "context": "*****************************\n * Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/", "end": 117, "score": 0.9987831711769104, "start": 101, "tag": "EMAIL", "value": "598748873@qq.com" }, { "context": " Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye\n *****************************************", "end": 176, "score": 0.9973059892654419, "start": 167, "tag": "USERNAME", "value": "doc_wei01" }, { "context": "11/13 11:13\n * @Copyright: 2021 https://gitee.com/doc_wei01/skyeye Inc. All rights reserved.\n * 注意:本内容仅限购买后使用", "end": 556, "score": 0.9910885691642761, "start": 547, "tag": "USERNAME", "value": "doc_wei01" } ]
null
[]
/******************************************************************************* * Copyright 卫志强 QQ:<EMAIL> Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye ******************************************************************************/ package com.skyeye.eve.service; import com.skyeye.common.object.InputObject; import com.skyeye.common.object.OutputObject; /** * @ClassName: SysEveModelTypeService * @Description: 系统模板分类业务层 * @author: skyeye云系列 * @date: 2021/11/13 11:13 * @Copyright: 2021 https://gitee.com/doc_wei01/skyeye Inc. All rights reserved. * 注意:本内容仅限购买后使用.禁止私自外泄以及用于其他的商业目的 */ public interface SysEveModelTypeService { /** * 获取系统模板分类列表 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void querySysEveModelTypeList(InputObject inputObject, OutputObject outputObject); /** * 新增系统模板分类 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void insertSysEveModelType(InputObject inputObject, OutputObject outputObject); /** * 根据id查询系统模板分类详情 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void querySysEveModelTypeById(InputObject inputObject, OutputObject outputObject); /** * 通过parentId查找对应的系统模板分类列表 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void querySysEveModelTypeByParentId(InputObject inputObject, OutputObject outputObject); /** * 通过id编辑对应的系统模板分类信息 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void updateSysEveModelTypeById(InputObject inputObject, OutputObject outputObject); /** * 删除系统模板分类 * * @param inputObject 入参以及用户信息等获取对象 * @param outputObject 出参以及提示信息的返回值对象 */ void delSysEveModelTypeById(InputObject inputObject, OutputObject outputObject); }
2,521
0.648374
0.633638
68
27.941177
28.535778
102
false
false
0
0
0
0
0
0
0.220588
false
false
2
a1699f7533e9fe2497f4eca60f1d5f7b36db9b03
26,474,178,455,469
0a13c8cb86f558e417282883a2c5388901ae710c
/Lektion_02/src/Dialogrutor.java
2b67eeba9bf1a2def151be3e8ca56b935f59e722
[]
no_license
mahmudalhakim/OOP-HT19
https://github.com/mahmudalhakim/OOP-HT19
430bda8c61acd704ce4a51a038363a95f7703b4a
b4b3b995ff92da505346f5fcf6fd3bee44bf679b
refs/heads/master
2020-08-20T03:12:26.404000
2019-12-12T10:40:56
2019-12-12T10:40:56
215,977,951
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.swing.*; /** * Created by Mahmud Al Hakim * Nackademin - Stockholm - Sweden * Project: OOP_HT19 * Date: 2019-10-23 10:15 * Copyright: MIT * * Ett program som visar olika * typer av dialogrutor i Java */ public class Dialogrutor { /** * Metoden main är huvudingången till programmet <br> * Här finns några exempel på kommentarer * och <b>dialogrutor</b> * @param args data som skickas till main */ public static void main(String[] args) { /* Deklaration av två stängar name och message */ String name; String message; // TODO: 2019-10-23 hämta vikt // Visa en input-ruta name = JOptionPane.showInputDialog("Vad heter du?"); // TODO: 2019-10-23 Lagra vikt i en variabel som heter weight message = "Välkommen " + name + "!"; // Visa en dialogruta JOptionPane.showMessageDialog(null, message); // TODO: 2019-10-23 Visa flera dialogrutor } }
UTF-8
Java
1,036
java
Dialogrutor.java
Java
[ { "context": "import javax.swing.*;\n\n/**\n * Created by Mahmud Al Hakim\n * Nackademin - Stockholm - Sweden\n * Project: OO", "end": 56, "score": 0.9998696446418762, "start": 41, "tag": "NAME", "value": "Mahmud Al Hakim" }, { "context": "vax.swing.*;\n\n/**\n * Created by Mahmud Al Hakim\n * Nackademin - Stockholm - Sweden\n * Project: OOP_HT19\n ", "end": 64, "score": 0.8465834856033325, "start": 60, "tag": "NAME", "value": "Nack" }, { "context": "g.*;\n\n/**\n * Created by Mahmud Al Hakim\n * Nackademin - Stockholm - Sweden\n * Project: OOP_HT19\n * Date", "end": 70, "score": 0.5536855459213257, "start": 67, "tag": "NAME", "value": "min" } ]
null
[]
import javax.swing.*; /** * Created by <NAME> * Nackademin - Stockholm - Sweden * Project: OOP_HT19 * Date: 2019-10-23 10:15 * Copyright: MIT * * Ett program som visar olika * typer av dialogrutor i Java */ public class Dialogrutor { /** * Metoden main är huvudingången till programmet <br> * Här finns några exempel på kommentarer * och <b>dialogrutor</b> * @param args data som skickas till main */ public static void main(String[] args) { /* Deklaration av två stängar name och message */ String name; String message; // TODO: 2019-10-23 hämta vikt // Visa en input-ruta name = JOptionPane.showInputDialog("Vad heter du?"); // TODO: 2019-10-23 Lagra vikt i en variabel som heter weight message = "Välkommen " + name + "!"; // Visa en dialogruta JOptionPane.showMessageDialog(null, message); // TODO: 2019-10-23 Visa flera dialogrutor } }
1,027
0.597858
0.560857
42
23.452381
19.416737
70
false
false
0
0
0
0
0
0
0.166667
false
false
2
14a5595ef45b071eec344ad9e22bc4681368db55
24,275,155,175,900
5cea1c4ed3b57df158705ca0c4f0f33f4a61aa97
/src/main/java/com/election/DatabaseConn/DbConnection.java
45dbaee1cc90ea828837bbadb33965d9df81a626
[]
no_license
shubham-tin/ElectionWebServer
https://github.com/shubham-tin/ElectionWebServer
0282fb64b79cbf61643fc9c00de3af9e2ab5362a
3adedb757c0e1e92840ffe4a6df8d6d7bd362ac5
refs/heads/master
2020-04-10T08:59:32.643000
2018-12-08T09:09:12
2018-12-08T09:09:12
160,922,153
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.election.DatabaseConn; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class DbConnection { private Connection conn = null; private Statement stmt = null; private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://localhost:3306/"; private static final String USER = "root"; private static final String PASSWORD = "123456789"; public DbConnection(){ try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASSWORD); stmt = conn.createStatement(); String sql; sql = "create database IF NOT EXISTS restdb;"; stmt.executeUpdate(sql); sql= "use restdb;"; stmt.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); }catch(Exception e) { System.out.println(e); } } public Connection getConn() { return conn; } }
UTF-8
Java
957
java
DbConnection.java
Java
[ { "context": " \"root\";\n\tprivate static final String PASSWORD = \"123456789\";\n\t\n\tpublic DbConnection(){\n\t\t\n\t\ttry {\n\t\t\tClass.f", "end": 478, "score": 0.9992154240608215, "start": 469, "tag": "PASSWORD", "value": "123456789" } ]
null
[]
package com.election.DatabaseConn; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class DbConnection { private Connection conn = null; private Statement stmt = null; private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://localhost:3306/"; private static final String USER = "root"; private static final String PASSWORD = "<PASSWORD>"; public DbConnection(){ try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASSWORD); stmt = conn.createStatement(); String sql; sql = "create database IF NOT EXISTS restdb;"; stmt.executeUpdate(sql); sql= "use restdb;"; stmt.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); }catch(Exception e) { System.out.println(e); } } public Connection getConn() { return conn; } }
958
0.711599
0.698015
38
24.18421
18.63903
69
false
false
0
0
0
0
0
0
2.157895
false
false
2
9e8f80557aa6d54b039410deed2469bf2c88b71c
8,332,236,576,211
e9904f0e38d36e08a35c91153705399f49af3337
/src/test/java/io/cucumber/grupo/CasoDeTeste3Steps.java
ea888323a59fcdfc40ed5c3ad74d0ffdbb5b960e
[]
no_license
victoriardspaiva/qa-projeto404
https://github.com/victoriardspaiva/qa-projeto404
bf2a656ae56c46397bbb86e6206e5ad41702806b
778870ac1e65404e7130656488aa0bf88dbe92d5
refs/heads/main
2023-04-03T02:06:46.622000
2021-03-31T23:23:32
2021-03-31T23:23:32
352,395,838
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.cucumber.grupo; import static org.junit.Assert.assertEquals; import org.openqa.selenium.By; import io.cucumber.grupo.configuracao.Configuracao; import io.cucumber.java.pt.*; public class CasoDeTeste3Steps { @Quando("clico no menu carreiras") public void clico_no_menu_carreiras() throws Exception { Thread.sleep(3000); Configuracao.seletorQueryCss("div[data-target='#primaryLink4_Carreiras']").click(); } @E("clico no item procurar por vagas") public void procurarVagas() throws InterruptedException { Thread.sleep(3000); Configuracao.seletorQueryCss("a[href='/br-pt/careers/jobsearch']").click(); } @E("digito no campo de busca Desenvolvedor") public void digito_no_campo_de_busca() { Configuracao.browser.findElement(By.id("job-search-hero-bar")).sendKeys("Desenvolvedor"); } @E("clico no botao procurar") public void clico_no_botao_procurar() { Configuracao.seletorQueryCss(".button-container.col-xs-2").click(); } @Entao("devo encontrar vagas para programadores") public void devo_encontrar_vagas_para_programadores() throws InterruptedException { Thread.sleep(3000); assertEquals(true, Configuracao.seletorQueryCssTodos(".upper-set-jobs.job-listing-block.col-xs-12").size() > 0); Configuracao.fechar(); } }
UTF-8
Java
1,265
java
CasoDeTeste3Steps.java
Java
[]
null
[]
package io.cucumber.grupo; import static org.junit.Assert.assertEquals; import org.openqa.selenium.By; import io.cucumber.grupo.configuracao.Configuracao; import io.cucumber.java.pt.*; public class CasoDeTeste3Steps { @Quando("clico no menu carreiras") public void clico_no_menu_carreiras() throws Exception { Thread.sleep(3000); Configuracao.seletorQueryCss("div[data-target='#primaryLink4_Carreiras']").click(); } @E("clico no item procurar por vagas") public void procurarVagas() throws InterruptedException { Thread.sleep(3000); Configuracao.seletorQueryCss("a[href='/br-pt/careers/jobsearch']").click(); } @E("digito no campo de busca Desenvolvedor") public void digito_no_campo_de_busca() { Configuracao.browser.findElement(By.id("job-search-hero-bar")).sendKeys("Desenvolvedor"); } @E("clico no botao procurar") public void clico_no_botao_procurar() { Configuracao.seletorQueryCss(".button-container.col-xs-2").click(); } @Entao("devo encontrar vagas para programadores") public void devo_encontrar_vagas_para_programadores() throws InterruptedException { Thread.sleep(3000); assertEquals(true, Configuracao.seletorQueryCssTodos(".upper-set-jobs.job-listing-block.col-xs-12").size() > 0); Configuracao.fechar(); } }
1,265
0.751779
0.737549
39
31.461538
30.234846
114
false
false
0
0
0
0
0
0
1.282051
false
false
2
b546b03410190f0c7e621e308aeb07e0095ec63d
26,499,948,225,352
3163b89e29a7de8c081f505fb2bc44b52a5d6bc1
/src/main/java/com/scu/freeread/service/NoteService.java
bd21a2cd48c5d1a19225811088534208e74fe74a
[]
no_license
lanyaosmy/freeRead-java
https://github.com/lanyaosmy/freeRead-java
f7146d9627eacc03ed0b9ec8423e572a2f8546f6
d20403d54eb9e5c36a3f0eea8f4d2e3dc218cfa2
refs/heads/master
2020-05-03T09:32:00.100000
2019-03-30T12:36:17
2019-03-30T12:36:17
178,556,469
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.scu.freeread.service; import com.alibaba.fastjson.JSONObject; import com.scu.freeread.entity.Note; import com.scu.freeread.mapper.CommentMapper; import com.scu.freeread.mapper.NoteMapper; import com.scu.freeread.mapper.TagMapper; import com.scu.freeread.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @Service public class NoteService { static private Integer limitSize=200; @Autowired NoteMapper noteMapper; @Autowired TagMapper tagMapper; @Autowired UserMapper userMapper; @Autowired CommentMapper commentMapper; // 获取笔记详情 public JSONObject selectNote(int noteid){ JSONObject json=new JSONObject(); try { json.put("note",noteMapper.selectNote(noteid)); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","获取笔记详情失败"); return error; } } // 增加访问量 public int addVisitNum(int noteid){ return noteMapper.addVisitNum(noteid); } /** * 添加笔记信息 * @param note * @return */ public int addNote(Note note){ return noteMapper.addNote(note); } public JSONObject getNoteid(int userid,Date publishtime){ try { return noteMapper.getNoteidByTime(userid,publishtime); }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","获取笔记详情失败"); return error; } } /** * 给笔记添加标签 * @param taglist * @param noteid * @return */ public int addNoteTag(List<Integer> taglist,int noteid){ int size=taglist.size(); if(size<=0){ return 0; } for (int i = 0; i < size; i++) { if(tagMapper.addNoteTag(taglist.get(i), noteid)!=1){ return 0; } } return 1; } /** * 获取热门笔记 * @param page * @return */ public JSONObject selectHot(int page){ try { List<JSONObject> hotlist = noteMapper.selectHot(page); return noteFormat(hotlist); }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } /** * 获取用户关注标签动态 * @param userid * @param page * @return */ public JSONObject selectNew(int userid, int page){ try { List<JSONObject> newlist = noteMapper.selectNew(userid,page); return noteFormat(newlist); }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } // 获取关注作者最新动态 public JSONObject authorLatestNote(int userid){ try { JSONObject json= new JSONObject(); List<JSONObject> list = noteMapper.authorLatestNote(userid); int size=list.size(); for (int i = 0; i < size; i++) { JSONObject item=list.get(i); item.put("publishtime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(item.get("publishtime"))); } json.put("authorlatest",list); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } /** * 格式化笔记列表 * @param list * @return */ public JSONObject noteFormat(List<JSONObject> list){ JSONObject json=new JSONObject(); int size=list.size(); if(size<10){ json.put("hasMore",false); }else{ json.put("hasMore",true); } for (int i = 0; i < size; i++) { JSONObject item=list.get(i); if(item.containsKey("content")) { String content = item.getString("content"); item.put("content", content.substring(0, content.length() > limitSize ? limitSize : content.length())); } item.put("taglist",tagMapper.selectTag(item.getInteger("noteid"))); item.put("commentCount",commentMapper.countComment(item.getInteger("noteid"))); item.put("publishtime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(item.get("publishtime"))); } json.put("notelist",list); return json; } /** * 收藏笔记 * @param userid * @param noteid * @return */ public JSONObject collectNote(int userid, int noteid){ JSONObject error=new JSONObject(); try { if(noteMapper.collectNote(userid,noteid)==1) { return error; } error.put("error","收藏笔记失败"); return error; }catch (Exception e){ error.put("error","收藏笔记失败"); return error; } } /** * 取消收藏笔记 * @param userid * @param noteid * @return */ public JSONObject deleteCollect(int userid, int noteid){ JSONObject error=new JSONObject(); try { if(noteMapper.deleteCollect(userid,noteid)==1) { return error; } error.put("error","取消收藏笔记失败"); return error; }catch (Exception e){ error.put("error","取消收藏笔记失败"); return error; } } // 个人中心 // 查看用户已发表的笔记——分页 public JSONObject publishedNote(int userid, int page){ JSONObject json=new JSONObject(); try { List<JSONObject> list = noteMapper.publishedNote(userid,page); int size=list.size(); for (int i = 0; i < size; i++) { JSONObject item=list.get(i); item.put("publishtime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(item.get("publishtime"))); } json.put("notelist",list); json.put("totalpage",noteMapper.countPublishedNote(userid)); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } // 查看用户草稿箱中的笔记 public JSONObject notPublishedNote(int userid){ JSONObject json=new JSONObject(); try { List<JSONObject> list = noteMapper.notPublishedNote(userid); json.put("notelist",list); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } // 删除笔记(已发表or草稿箱) public JSONObject deleteNote(int noteid, int userid){ JSONObject error=new JSONObject(); try { if(noteMapper.selectNote(noteid).getInteger("userid")!=userid){ error.put("error","不可以删除他人的笔记"); return error; } if(noteMapper.deleteNote(noteid)==1) { return error; } error.put("error","删除笔记失败"); return error; }catch (Exception e){ error.put("error","删除笔记失败"); return error; } } // 查看用户收藏的笔记 public JSONObject selectCollectNote(int userid, int page){ JSONObject json=new JSONObject(); try { List<JSONObject> list = noteMapper.selectCollectNote(userid,page); int size=list.size(); for (int i = 0; i < size; i++) { JSONObject item=list.get(i); item.put("publishtime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(item.get("publishtime"))); } json.put("notelist",list); json.put("totalpage",noteMapper.countCollectNote(userid)); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } // 修改草稿箱中笔记 or 发表 public int changeBoxNote(Note note){ return noteMapper.changeBoxNote(note); } }
UTF-8
Java
8,700
java
NoteService.java
Java
[]
null
[]
package com.scu.freeread.service; import com.alibaba.fastjson.JSONObject; import com.scu.freeread.entity.Note; import com.scu.freeread.mapper.CommentMapper; import com.scu.freeread.mapper.NoteMapper; import com.scu.freeread.mapper.TagMapper; import com.scu.freeread.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @Service public class NoteService { static private Integer limitSize=200; @Autowired NoteMapper noteMapper; @Autowired TagMapper tagMapper; @Autowired UserMapper userMapper; @Autowired CommentMapper commentMapper; // 获取笔记详情 public JSONObject selectNote(int noteid){ JSONObject json=new JSONObject(); try { json.put("note",noteMapper.selectNote(noteid)); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","获取笔记详情失败"); return error; } } // 增加访问量 public int addVisitNum(int noteid){ return noteMapper.addVisitNum(noteid); } /** * 添加笔记信息 * @param note * @return */ public int addNote(Note note){ return noteMapper.addNote(note); } public JSONObject getNoteid(int userid,Date publishtime){ try { return noteMapper.getNoteidByTime(userid,publishtime); }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","获取笔记详情失败"); return error; } } /** * 给笔记添加标签 * @param taglist * @param noteid * @return */ public int addNoteTag(List<Integer> taglist,int noteid){ int size=taglist.size(); if(size<=0){ return 0; } for (int i = 0; i < size; i++) { if(tagMapper.addNoteTag(taglist.get(i), noteid)!=1){ return 0; } } return 1; } /** * 获取热门笔记 * @param page * @return */ public JSONObject selectHot(int page){ try { List<JSONObject> hotlist = noteMapper.selectHot(page); return noteFormat(hotlist); }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } /** * 获取用户关注标签动态 * @param userid * @param page * @return */ public JSONObject selectNew(int userid, int page){ try { List<JSONObject> newlist = noteMapper.selectNew(userid,page); return noteFormat(newlist); }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } // 获取关注作者最新动态 public JSONObject authorLatestNote(int userid){ try { JSONObject json= new JSONObject(); List<JSONObject> list = noteMapper.authorLatestNote(userid); int size=list.size(); for (int i = 0; i < size; i++) { JSONObject item=list.get(i); item.put("publishtime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(item.get("publishtime"))); } json.put("authorlatest",list); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } /** * 格式化笔记列表 * @param list * @return */ public JSONObject noteFormat(List<JSONObject> list){ JSONObject json=new JSONObject(); int size=list.size(); if(size<10){ json.put("hasMore",false); }else{ json.put("hasMore",true); } for (int i = 0; i < size; i++) { JSONObject item=list.get(i); if(item.containsKey("content")) { String content = item.getString("content"); item.put("content", content.substring(0, content.length() > limitSize ? limitSize : content.length())); } item.put("taglist",tagMapper.selectTag(item.getInteger("noteid"))); item.put("commentCount",commentMapper.countComment(item.getInteger("noteid"))); item.put("publishtime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(item.get("publishtime"))); } json.put("notelist",list); return json; } /** * 收藏笔记 * @param userid * @param noteid * @return */ public JSONObject collectNote(int userid, int noteid){ JSONObject error=new JSONObject(); try { if(noteMapper.collectNote(userid,noteid)==1) { return error; } error.put("error","收藏笔记失败"); return error; }catch (Exception e){ error.put("error","收藏笔记失败"); return error; } } /** * 取消收藏笔记 * @param userid * @param noteid * @return */ public JSONObject deleteCollect(int userid, int noteid){ JSONObject error=new JSONObject(); try { if(noteMapper.deleteCollect(userid,noteid)==1) { return error; } error.put("error","取消收藏笔记失败"); return error; }catch (Exception e){ error.put("error","取消收藏笔记失败"); return error; } } // 个人中心 // 查看用户已发表的笔记——分页 public JSONObject publishedNote(int userid, int page){ JSONObject json=new JSONObject(); try { List<JSONObject> list = noteMapper.publishedNote(userid,page); int size=list.size(); for (int i = 0; i < size; i++) { JSONObject item=list.get(i); item.put("publishtime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(item.get("publishtime"))); } json.put("notelist",list); json.put("totalpage",noteMapper.countPublishedNote(userid)); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } // 查看用户草稿箱中的笔记 public JSONObject notPublishedNote(int userid){ JSONObject json=new JSONObject(); try { List<JSONObject> list = noteMapper.notPublishedNote(userid); json.put("notelist",list); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } // 删除笔记(已发表or草稿箱) public JSONObject deleteNote(int noteid, int userid){ JSONObject error=new JSONObject(); try { if(noteMapper.selectNote(noteid).getInteger("userid")!=userid){ error.put("error","不可以删除他人的笔记"); return error; } if(noteMapper.deleteNote(noteid)==1) { return error; } error.put("error","删除笔记失败"); return error; }catch (Exception e){ error.put("error","删除笔记失败"); return error; } } // 查看用户收藏的笔记 public JSONObject selectCollectNote(int userid, int page){ JSONObject json=new JSONObject(); try { List<JSONObject> list = noteMapper.selectCollectNote(userid,page); int size=list.size(); for (int i = 0; i < size; i++) { JSONObject item=list.get(i); item.put("publishtime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(item.get("publishtime"))); } json.put("notelist",list); json.put("totalpage",noteMapper.countCollectNote(userid)); return json; }catch (Exception e){ JSONObject error=new JSONObject(); error.put("error","数据请求出错"); return error; } } // 修改草稿箱中笔记 or 发表 public int changeBoxNote(Note note){ return noteMapper.changeBoxNote(note); } }
8,700
0.546348
0.544043
295
26.938984
22.820663
119
false
false
0
0
0
0
0
0
0.586441
false
false
2
349d46826b2d69b6dd30b8da72b617fa8fba6fb0
5,815,385,720,282
489c2afba84ba7b62b8a029fb3438b11a506840d
/user/src/main/java/com/example/user/controller/AuthController.java
a4a3240d30c0425627fc9da83d9a5eea2e6dd7f5
[]
no_license
xhb1987/spring-boot-one
https://github.com/xhb1987/spring-boot-one
3f4bb6bead2888e17527aca686ac6f044907964b
5e541756f1542960954eab669d94a3d6f6e68505
refs/heads/master
2020-06-21T04:25:48.124000
2019-07-31T13:35:58
2019-07-31T13:35:58
197,343,547
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.user.controller; import java.util.HashMap; import java.util.Map; import static org.springframework.http.ResponseEntity.ok; import com.example.user.model.User; import com.example.user.repository.UserRepository; import com.example.user.service.CustomeUserDetailService; import com.example.user.service.JwtServices; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; 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; @RequestMapping("/auth") @RestController public class AuthController { @Autowired JwtServices jwtServices; @Autowired UserRepository users; @Autowired private CustomeUserDetailService userService; @PostMapping("/login") public ResponseEntity login(@RequestBody AuthBody data) { try { String username = data.getName(); // authenticationManager.authenticate(new // UsernamePasswordAuthenticationToken(username, data.getPassword())); String token = jwtServices.createToken(username, this.users.findByName(username).getRole()); Map<Object, Object> model = new HashMap(); model.put("username", username); model.put("token", token); return ok(model); } catch (AuthenticationException e) { throw new BadCredentialsException("Invalid email password"); } } @PostMapping("/register") public String register(@RequestBody User user) { userService.saveUser(user); return "ok"; } }
UTF-8
Java
2,068
java
AuthController.java
Java
[]
null
[]
package com.example.user.controller; import java.util.HashMap; import java.util.Map; import static org.springframework.http.ResponseEntity.ok; import com.example.user.model.User; import com.example.user.repository.UserRepository; import com.example.user.service.CustomeUserDetailService; import com.example.user.service.JwtServices; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; 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; @RequestMapping("/auth") @RestController public class AuthController { @Autowired JwtServices jwtServices; @Autowired UserRepository users; @Autowired private CustomeUserDetailService userService; @PostMapping("/login") public ResponseEntity login(@RequestBody AuthBody data) { try { String username = data.getName(); // authenticationManager.authenticate(new // UsernamePasswordAuthenticationToken(username, data.getPassword())); String token = jwtServices.createToken(username, this.users.findByName(username).getRole()); Map<Object, Object> model = new HashMap(); model.put("username", username); model.put("token", token); return ok(model); } catch (AuthenticationException e) { throw new BadCredentialsException("Invalid email password"); } } @PostMapping("/register") public String register(@RequestBody User user) { userService.saveUser(user); return "ok"; } }
2,068
0.749516
0.749516
59
34.067795
26.720058
104
false
false
0
0
0
0
0
0
0.610169
false
false
2
54fe94e4be94f9c2952b4e72c2c91a9ac45b76b0
8,220,567,411,239
a7f266871e11db764611025efa4a712f0511ae59
/src/netty/authority/OtherSample1HelloHandler.java
561a1479311c0719c56aedd56ae0784979d202e4
[]
no_license
babayetu/shangxuetang
https://github.com/babayetu/shangxuetang
44cba13325c9f5acf97113721dc073123560173d
c13b2b31f383bce338b2f07050f02ca31381b142
refs/heads/master
2021-01-19T09:52:55.086000
2017-03-21T10:19:32
2017-03-21T10:19:32
58,524,613
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package netty.authority; import java.util.Date; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class OtherSample1HelloHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf b = (ByteBuf)msg; byte[] bb = new byte[b.readableBytes()]; b.readBytes(bb); System.out.println("Input command is:" + new String(bb,"UTF-8")); //释放资源 b.release(); String resp = new Date(System.currentTimeMillis()).toString(); ByteBuf outBuff = ctx.alloc().buffer(4 * resp.length()); outBuff.writeBytes(resp.getBytes()); ctx.writeAndFlush(outBuff); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
UTF-8
Java
1,147
java
OtherSample1HelloHandler.java
Java
[]
null
[]
package netty.authority; import java.util.Date; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class OtherSample1HelloHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf b = (ByteBuf)msg; byte[] bb = new byte[b.readableBytes()]; b.readBytes(bb); System.out.println("Input command is:" + new String(bb,"UTF-8")); //释放资源 b.release(); String resp = new Date(System.currentTimeMillis()).toString(); ByteBuf outBuff = ctx.alloc().buffer(4 * resp.length()); outBuff.writeBytes(resp.getBytes()); ctx.writeAndFlush(outBuff); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
1,147
0.647059
0.644425
42
26.119047
26.05233
85
false
false
0
0
0
0
0
0
0.595238
false
false
2
fb6cc405979f8dd7bdad5dc8d9a285d5bd379d77
1,022,202,283,083
13ed5e2200004acd14ee3c9548f8d1d6276fd169
/src/main/java/com/xxx/portal/web/login/LoginAction.java
95f94e032e00fa8098d936db837cc9d7214f0787
[]
no_license
pengzhoushuo/rz-portal
https://github.com/pengzhoushuo/rz-portal
64c062bf1fc0171d365f1f104e286c14f154f87f
b1ca9ff0d1d06fabc9ff1a7de04ef5af6a97410f
refs/heads/master
2021-01-17T12:39:03.227000
2016-06-28T08:16:02
2016-06-28T08:16:02
58,530,384
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xxx.portal.web.login; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.xxx.portal.util.BaseResponse; /** * 图片验证码Action * @author peng */ @Controller @RequestMapping({"/login"}) public class LoginAction{ /** * 检验用户输入的验证码是否正确 * @param model * @param req * @return */ @RequestMapping(value={"validateRndCode"}, method={RequestMethod.POST}) @ResponseBody public BaseResponse<String> check(Model model, HttpServletRequest req){ BaseResponse<String> response = new BaseResponse<String>(); response.setCode(BaseResponse.CODE_FAILURE); response.setMessage("验证码不正确"); String rndcode = req.getParameter("rndcode"); Object codeInSession = req.getSession().getAttribute("code"); if(codeInSession != null){ String codeInSessionString = codeInSession.toString(); if(codeInSessionString.equalsIgnoreCase(rndcode)){ response.setCode(BaseResponse.CODE_SUCCESS); response.setMessage(""); } } return response; } }
UTF-8
Java
1,616
java
LoginAction.java
Java
[ { "context": "util.BaseResponse;\n\n\n/**\n * 图片验证码Action\n * @author peng\n */\n@Controller\n@RequestMapping({\"/login\"})\npubli", "end": 753, "score": 0.9457491040229797, "start": 749, "tag": "USERNAME", "value": "peng" } ]
null
[]
package com.xxx.portal.web.login; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.xxx.portal.util.BaseResponse; /** * 图片验证码Action * @author peng */ @Controller @RequestMapping({"/login"}) public class LoginAction{ /** * 检验用户输入的验证码是否正确 * @param model * @param req * @return */ @RequestMapping(value={"validateRndCode"}, method={RequestMethod.POST}) @ResponseBody public BaseResponse<String> check(Model model, HttpServletRequest req){ BaseResponse<String> response = new BaseResponse<String>(); response.setCode(BaseResponse.CODE_FAILURE); response.setMessage("验证码不正确"); String rndcode = req.getParameter("rndcode"); Object codeInSession = req.getSession().getAttribute("code"); if(codeInSession != null){ String codeInSessionString = codeInSession.toString(); if(codeInSessionString.equalsIgnoreCase(rndcode)){ response.setCode(BaseResponse.CODE_SUCCESS); response.setMessage(""); } } return response; } }
1,616
0.775223
0.775223
56
26.964285
21.474207
72
false
false
0
0
0
0
0
0
1.303571
false
false
2
bce7b65e5441ce8e9b0cf4d9785afacc4deb65d3
5,634,997,154,716
610cd90b48271022714f81efa4a1ace5f5614387
/src/com/caixihua/game/Bullet.java
d6d2d5b0f3ce62af0158c330870d751a6615a22b
[]
no_license
Thuantanon/TankWar
https://github.com/Thuantanon/TankWar
480ba722d244f306564c46c89568ee1a64ee71af
e426f4197f7c75914e208334773b2edd2678db1a
refs/heads/master
2021-08-07T05:47:51.265000
2017-11-07T16:30:07
2017-11-07T16:30:07
109,852,638
2
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.caixihua.game; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.util.List; import javax.swing.ImageIcon; public class Bullet { public static final int SIZE = 6; public static final int SPEED = 10; public static Image img = new ImageIcon("images/other/bullet.gif").getImage(); private int x; private int y; private int dir; private GamePanel gamePanel; private boolean who; // 标记 public boolean isLive = true; public Bullet(int x,int y,int d,GamePanel g){ this.x = x; this.y = y; this.dir = d; this.gamePanel = g; this.who = false; } public Bullet(int x,int y,int d,GamePanel g,boolean who){ // 构造 this(x,y,d,g); this.who = true; } public void draw(Graphics g){ // 移除已经爆炸的炮弹 if(!isLive){ gamePanel.bullets.remove(this); } // 画出 if(isLive){ g.drawImage(Bullet.img, x, y, Bullet.SIZE, Bullet.SIZE, null); } move(); } private void move(){ // 移动 switch (dir) { case Tank.U: this.y -= Bullet.SPEED; break; case Tank.L: this.x -= Bullet.SPEED; break; case Tank.R: this.x += Bullet.SPEED; break; case Tank.D: this.y += Bullet.SPEED; break; default: break; } // 判断是否出界 if(x <= 0 || x >= 700 || y <= 0 || y >= 725){ this.isLive = false; } } public boolean hitTank(Tank t){ // 判断是否与坦克相撞 if(this.isLive && t.isLive && this.who != t.isWho() && !t.isGod() && this.getBulletRect().intersects(t.getTankRect())){ // 添加爆炸 // 攻击到坦克 if(!t.isWho()){ gamePanel.explodes.add(new Explode(t.getX(), t.getY(), Tank.SIZE, gamePanel)); gamePanel.TANK_NUM --; gamePanel.kill++; MediaPlayer.play(MediaPlayer.BLAST); this.isLive = false; t.isLive = false; } // 攻击到自己 if(t.isWho()){ gamePanel.die ++; t.life -= 10; this.isLive = false; if(t.life <= 0){ gamePanel.explodes.add(new Explode(t.getX(), t.getY(), Tank.SIZE, gamePanel)); t.isLive = false; } } return true; } return false; } public boolean hitTanks(List<Tank> tanks){ // 判断是否攻击到坦克群 for(int i=0;i<tanks.size();i++){ if(hitTank(tanks.get(i))){ return true; } } return false; } public boolean hitBullet(Bullet b){ // 是否撞到子弹 if(this.isLive && b.isLive && this.getBulletRect().intersects(b.getBulletRect())){ this.isLive = false; b.isLive = false; return true; } return false; } public boolean hitBullets(List<Bullet> bs){ // 子弹群 for(int i=0;i<bs.size();i++){ if(this != bs.get(i) && this.hitBullet(bs.get(i))){ return true; } } return false; } public boolean hitWall(Wall w){ // 子弹击中墙体 if(w.getWallType() != Wall.SEA && w.getWallType() != Wall.FOREST && w.getWallType() != Wall.ICE && this.isLive && this.getBulletRect().intersects(w.getWallRect())){ // 子弹可以穿过ice,forest,sea if(w.getWallType() == Wall.BRICK){ gamePanel.map.remove(w); gamePanel.explodes.add(new Explode(w.getX(), w.getY(), w.getWidth(), gamePanel)); this.isLive = false; return true; } // 不能打坏steel if(w.getWallType() == Wall.STEEL){ gamePanel.explodes.add(new Explode(x-9, y-9, SIZE*4, gamePanel)); this.isLive = false; return true; } } return false; } public boolean hitWalls(List<Wall> walls){ // 击中墙 for(int i=0;i<walls.size();i++){ if(this.hitWall(walls.get(i))){ return true; } } return false; } public Rectangle getBulletRect(){ return new Rectangle(x, y, Bullet.SIZE, Bullet.SIZE); } public int getX(){ return this.x; } public int getY(){ return this.y; } }
GB18030
Java
3,948
java
Bullet.java
Java
[]
null
[]
package com.caixihua.game; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.util.List; import javax.swing.ImageIcon; public class Bullet { public static final int SIZE = 6; public static final int SPEED = 10; public static Image img = new ImageIcon("images/other/bullet.gif").getImage(); private int x; private int y; private int dir; private GamePanel gamePanel; private boolean who; // 标记 public boolean isLive = true; public Bullet(int x,int y,int d,GamePanel g){ this.x = x; this.y = y; this.dir = d; this.gamePanel = g; this.who = false; } public Bullet(int x,int y,int d,GamePanel g,boolean who){ // 构造 this(x,y,d,g); this.who = true; } public void draw(Graphics g){ // 移除已经爆炸的炮弹 if(!isLive){ gamePanel.bullets.remove(this); } // 画出 if(isLive){ g.drawImage(Bullet.img, x, y, Bullet.SIZE, Bullet.SIZE, null); } move(); } private void move(){ // 移动 switch (dir) { case Tank.U: this.y -= Bullet.SPEED; break; case Tank.L: this.x -= Bullet.SPEED; break; case Tank.R: this.x += Bullet.SPEED; break; case Tank.D: this.y += Bullet.SPEED; break; default: break; } // 判断是否出界 if(x <= 0 || x >= 700 || y <= 0 || y >= 725){ this.isLive = false; } } public boolean hitTank(Tank t){ // 判断是否与坦克相撞 if(this.isLive && t.isLive && this.who != t.isWho() && !t.isGod() && this.getBulletRect().intersects(t.getTankRect())){ // 添加爆炸 // 攻击到坦克 if(!t.isWho()){ gamePanel.explodes.add(new Explode(t.getX(), t.getY(), Tank.SIZE, gamePanel)); gamePanel.TANK_NUM --; gamePanel.kill++; MediaPlayer.play(MediaPlayer.BLAST); this.isLive = false; t.isLive = false; } // 攻击到自己 if(t.isWho()){ gamePanel.die ++; t.life -= 10; this.isLive = false; if(t.life <= 0){ gamePanel.explodes.add(new Explode(t.getX(), t.getY(), Tank.SIZE, gamePanel)); t.isLive = false; } } return true; } return false; } public boolean hitTanks(List<Tank> tanks){ // 判断是否攻击到坦克群 for(int i=0;i<tanks.size();i++){ if(hitTank(tanks.get(i))){ return true; } } return false; } public boolean hitBullet(Bullet b){ // 是否撞到子弹 if(this.isLive && b.isLive && this.getBulletRect().intersects(b.getBulletRect())){ this.isLive = false; b.isLive = false; return true; } return false; } public boolean hitBullets(List<Bullet> bs){ // 子弹群 for(int i=0;i<bs.size();i++){ if(this != bs.get(i) && this.hitBullet(bs.get(i))){ return true; } } return false; } public boolean hitWall(Wall w){ // 子弹击中墙体 if(w.getWallType() != Wall.SEA && w.getWallType() != Wall.FOREST && w.getWallType() != Wall.ICE && this.isLive && this.getBulletRect().intersects(w.getWallRect())){ // 子弹可以穿过ice,forest,sea if(w.getWallType() == Wall.BRICK){ gamePanel.map.remove(w); gamePanel.explodes.add(new Explode(w.getX(), w.getY(), w.getWidth(), gamePanel)); this.isLive = false; return true; } // 不能打坏steel if(w.getWallType() == Wall.STEEL){ gamePanel.explodes.add(new Explode(x-9, y-9, SIZE*4, gamePanel)); this.isLive = false; return true; } } return false; } public boolean hitWalls(List<Wall> walls){ // 击中墙 for(int i=0;i<walls.size();i++){ if(this.hitWall(walls.get(i))){ return true; } } return false; } public Rectangle getBulletRect(){ return new Rectangle(x, y, Bullet.SIZE, Bullet.SIZE); } public int getX(){ return this.x; } public int getY(){ return this.y; } }
3,948
0.583069
0.577778
179
19.117319
22.113285
166
false
false
0
0
0
0
0
0
2.687151
false
false
2
911313f80641cd140f71fd167af7d8a08435db9c
33,268,816,743,248
108cccc3142d4bb8a471e03f0221de0261feec66
/sample/src/main/java/com/github/ayvazj/ephemeral/sample/main/SplashFragment.java
48e33a26e002b929110b7642adca6144a1a25c1e
[]
no_license
ayvazj/ephemeral
https://github.com/ayvazj/ephemeral
2c940a27bc3fd5948f8be208bb775e29287deee2
5b2cc4d16c02acc103fe8be338c2285b65ccfe41
refs/heads/master
2016-09-13T03:13:13.750000
2016-08-02T13:58:44
2016-08-02T13:58:44
64,761,383
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.ayvazj.ephemeral.sample.main; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.github.ayvazj.ephemeral.sample.R; import com.github.ayvazj.ephemeral.sample.app.AppFragment; import butterknife.BindView; import butterknife.ButterKnife; public class SplashFragment extends AppFragment { @BindView(R.id.login_button) LoginButton loginButton; private CallbackManager callbackManager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_splash, container, false); ButterKnife.bind(this, view); callbackManager = CallbackManager.Factory.create(); loginButton.setReadPermissions("user_friends"); loginButton.setFragment(this); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Toast.makeText(getActivity(), "Login successful", Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { Toast.makeText(getActivity(), "Login canceled", Toast.LENGTH_SHORT).show(); } @Override public void onError(FacebookException exception) { Toast.makeText(getActivity(), "Login error", Toast.LENGTH_SHORT).show(); } }); return view; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } }
UTF-8
Java
2,072
java
SplashFragment.java
Java
[ { "context": "package com.github.ayvazj.ephemeral.sample.main;\n\nimport android.content.In", "end": 25, "score": 0.9990020990371704, "start": 19, "tag": "USERNAME", "value": "ayvazj" }, { "context": "ebook.login.widget.LoginButton;\nimport com.github.ayvazj.ephemeral.sample.R;\nimport com.github.ayvazj.ephe", "end": 453, "score": 0.9985657930374146, "start": 447, "tag": "USERNAME", "value": "ayvazj" }, { "context": "thub.ayvazj.ephemeral.sample.R;\nimport com.github.ayvazj.ephemeral.sample.app.AppFragment;\n\nimport butterk", "end": 498, "score": 0.9979689717292786, "start": 492, "tag": "USERNAME", "value": "ayvazj" } ]
null
[]
package com.github.ayvazj.ephemeral.sample.main; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.github.ayvazj.ephemeral.sample.R; import com.github.ayvazj.ephemeral.sample.app.AppFragment; import butterknife.BindView; import butterknife.ButterKnife; public class SplashFragment extends AppFragment { @BindView(R.id.login_button) LoginButton loginButton; private CallbackManager callbackManager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_splash, container, false); ButterKnife.bind(this, view); callbackManager = CallbackManager.Factory.create(); loginButton.setReadPermissions("user_friends"); loginButton.setFragment(this); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Toast.makeText(getActivity(), "Login successful", Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { Toast.makeText(getActivity(), "Login canceled", Toast.LENGTH_SHORT).show(); } @Override public void onError(FacebookException exception) { Toast.makeText(getActivity(), "Login error", Toast.LENGTH_SHORT).show(); } }); return view; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } }
2,072
0.704633
0.704633
64
31.359375
28.379332
103
false
false
0
0
0
0
0
0
0.75
false
false
2
b287207de54bf61162b8773aa7f1984189374d60
22,273,700,465,050
33eb35d095cc219f2141f603176c1a205ac97bb0
/soccerForecaster/src/models/SoccerForecaster.java
b30378f04665c7b0a962056ce80c1829d7d61c8c
[]
no_license
Leon30/ayp
https://github.com/Leon30/ayp
1c349db68e77a39a8ad5d000717b80544c98d3e8
bbe7476f322f696e7a852ed9bbd9d92a26e53802
refs/heads/master
2021-01-17T10:20:29.597000
2016-07-22T04:20:11
2016-07-22T04:20:11
58,009,468
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package models; import views.IoManager; public class SoccerForecaster { public static final int MAX_MATCHS = 20; public static final int MAX_TEAMS = 20; private Match[] matchList; private Team[] teamList; public SoccerForecaster() { matchList = new Match[MAX_MATCHS]; teamList = new Team[MAX_TEAMS]; initTeams(); } public int getWinner(Match m){ return m.calculateVictory(); } public Team[] getTeamList() { return teamList; } public void initTeams(){ for (int i = 0; i < Team.INIT_TEAMS_LIST.length; i++) { teamList[i] = Team.INIT_TEAMS_LIST[i]; } } public void registerMatch(Match m){ for (int i = 0; i < matchList.length; i++) { if (matchList[i] == null) { matchList[i]= m; } } } public void registerTeam(Team t){ for (int i = 0; i < teamList.length; i++) { if (teamList[i] == null) { teamList[i]= t; return ; } } } public Match getMatch(int i){ return matchList[i]; } }
UTF-8
Java
1,231
java
SoccerForecaster.java
Java
[]
null
[]
package models; import views.IoManager; public class SoccerForecaster { public static final int MAX_MATCHS = 20; public static final int MAX_TEAMS = 20; private Match[] matchList; private Team[] teamList; public SoccerForecaster() { matchList = new Match[MAX_MATCHS]; teamList = new Team[MAX_TEAMS]; initTeams(); } public int getWinner(Match m){ return m.calculateVictory(); } public Team[] getTeamList() { return teamList; } public void initTeams(){ for (int i = 0; i < Team.INIT_TEAMS_LIST.length; i++) { teamList[i] = Team.INIT_TEAMS_LIST[i]; } } public void registerMatch(Match m){ for (int i = 0; i < matchList.length; i++) { if (matchList[i] == null) { matchList[i]= m; } } } public void registerTeam(Team t){ for (int i = 0; i < teamList.length; i++) { if (teamList[i] == null) { teamList[i]= t; return ; } } } public Match getMatch(int i){ return matchList[i]; } }
1,231
0.490658
0.484972
52
21.673077
17.100069
63
false
false
0
0
0
0
0
0
0.423077
false
false
2
393d09c6ec9d3f5ff722bea9c99efdcff1807d69
25,391,846,660,500
67ed11c728deb72bfcd4dfa01640400476d11103
/src/main/java/resources/Version1_1Resource.java
5308b2557e00a663f82574f020ba4d9e3c032d4e
[]
no_license
infinitiessoft/AttendenceSystem
https://github.com/infinitiessoft/AttendenceSystem
f753e8a2f36877d8705adc3a2cbc2924cafee2e0
d43659e627979d4dacf7a29c518aeea33dde99c1
refs/heads/master
2021-01-14T08:50:37.739000
2017-12-14T11:27:43
2017-12-14T11:27:43
48,523,986
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package resources; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import resources.version1.admin.AdminResource; import resources.version1.general.GeneralResource; import resources.version1.member.AuthResource; import resources.version1.member.MemberAttendRecordTypesResource; import resources.version1.member.MemberDepartmentsResource; import resources.version1.member.MembersResource; @Component @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("v1.0") public class Version1_1Resource { @Autowired private AdminResource adminResource; @Autowired private AuthResource authResource; @Autowired private MembersResource membersResource; @Autowired private MemberDepartmentsResource memberDepartmentsResource; @Autowired private MemberAttendRecordTypesResource memberAttendRecordTypesResource; @Autowired private GeneralResource generalResource; @Path("admin") public AdminResource getAdminResource() { return adminResource; } @Path("auth") public AuthResource getAuthResource() { return authResource; } @Path("employees") public MembersResource getEmployeesResource() { return membersResource; } @Path("departments") public MemberDepartmentsResource getDepartmentsResource() { return memberDepartmentsResource; } @Path("recordtypes") public MemberAttendRecordTypesResource getAttendRecordTypesResource() { return memberAttendRecordTypesResource; } @Path("general") public GeneralResource getGeneralResource() { return generalResource; } }
UTF-8
Java
1,706
java
Version1_1Resource.java
Java
[]
null
[]
package resources; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import resources.version1.admin.AdminResource; import resources.version1.general.GeneralResource; import resources.version1.member.AuthResource; import resources.version1.member.MemberAttendRecordTypesResource; import resources.version1.member.MemberDepartmentsResource; import resources.version1.member.MembersResource; @Component @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("v1.0") public class Version1_1Resource { @Autowired private AdminResource adminResource; @Autowired private AuthResource authResource; @Autowired private MembersResource membersResource; @Autowired private MemberDepartmentsResource memberDepartmentsResource; @Autowired private MemberAttendRecordTypesResource memberAttendRecordTypesResource; @Autowired private GeneralResource generalResource; @Path("admin") public AdminResource getAdminResource() { return adminResource; } @Path("auth") public AuthResource getAuthResource() { return authResource; } @Path("employees") public MembersResource getEmployeesResource() { return membersResource; } @Path("departments") public MemberDepartmentsResource getDepartmentsResource() { return memberDepartmentsResource; } @Path("recordtypes") public MemberAttendRecordTypesResource getAttendRecordTypesResource() { return memberAttendRecordTypesResource; } @Path("general") public GeneralResource getGeneralResource() { return generalResource; } }
1,706
0.821805
0.815944
66
24.848484
21.106686
73
false
false
0
0
0
0
0
0
1.015152
false
false
2
5508f754bc96421e48ce462227f3bed2aa1c8ae0
25,391,846,660,987
168ee2eb99f98a988f4b664822697f623e512c13
/configuration-management/src/test/java/configuration/management/rest/CMManageStatementTest.java
83a5f7f2bcc2b539a358c061e23db8fedb45f5e5
[]
no_license
f1l2/alligatorbirne
https://github.com/f1l2/alligatorbirne
b4b35fd0c0805cee9fcc0e8e3530229c75a78b6c
12125590634e99d3be1702feb36036ed2341ccc1
refs/heads/master
2021-01-22T20:54:48.498000
2016-06-18T17:54:49
2016-06-18T17:54:49
37,544,322
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package configuration.management.rest; import static com.jayway.restassured.RestAssured.get; import static com.jayway.restassured.RestAssured.given; import static com.jayway.restassured.RestAssured.when; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.jayway.restassured.response.Response; import common.data.dto.QueryDTO; import common.rest.RESOURCE_NAMING; import common.rest.ResourceUtils; import configuration.management.Application; import configuration.management.model.EventProcessingDLO; import configuration.management.model.RuleDLO; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest("server.port:0") public class CMManageStatementTest extends AbstractTestRestCM { @Test public void getAllQueries1() { Response response = get(RESOURCE_NAMING.CM_GET_ALL_QUERIES.getPath()); List<QueryDTO> result = Arrays.asList(response.getBody().as(QueryDTO[].class)); assertEquals(200, response.getStatusCode()); assertNotNull(result); } @Test public void getAllQueries2() { when().get(RESOURCE_NAMING.CM_GET_ALL_QUERIES.getPath()) .then().statusCode(200); } @Test public void registerQuery() { String query = "CONDITION name = 'device1'"; given().body(query).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_QUERY, queryName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void registerQueryParseError() { String query = "AVC name = 'device1'"; given().body(query).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_QUERY, queryName)) .then().statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void registerQueryQueryExistsError() { String query = "CONDITION name = 'device1'"; String path = ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_QUERY, queryName); given().body(query).when().post(path) .then().statusCode(HttpStatus.OK.value()); given().body(query).when().post(path) .then().statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void deregisterQuery() { registerQuery(); when().delete(ResourceUtils.getPath(RESOURCE_NAMING.CM_DEREGISTRATION_QUERY, queryName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void registerRule() { registerQuery(); String rule = queryName + " TRIGGERS device1, domain1, configurationManagement1 = 1"; given().body(rule).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void registerRule1() { registerQuery(); } @Test public void registerRuleExistsError() { registerQuery(); String rule = queryName + " TRIGGERS device1, domain1, configurationManagement1 = 1"; given().body(rule).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); given().body(rule).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void deregisterRule() { registerRule(); when().delete(ResourceUtils.getPath(RESOURCE_NAMING.CM_DEREGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void activateRule() { String query = "CONDITION name = 'device1'"; given().body(query).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_QUERY, queryName)) .then().statusCode(HttpStatus.OK.value()); String rule = queryName + " TRIGGERS device1, domain1, configurationManagement1 = 1"; given().body(rule).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); when().get(ResourceUtils.getPath(RESOURCE_NAMING.CM_ACTIVATIONS_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void deactivateRule() { activateRule(); /** * Fake assignment of EP */ EventProcessingDLO eventProcessing = new EventProcessingDLO(); eventProcessing.setAuthority("123"); eventProcessingRepository.save(eventProcessing); RuleDLO rule = ruleRepo.findByName(ruleName); rule.setEpDLO(eventProcessing); ruleRepo.save(rule); /** * End */ when().get(ResourceUtils.getPath(RESOURCE_NAMING.CM_DEACTIVATIONS_RULE), ruleName) .then().statusCode(HttpStatus.OK.value()); } }
UTF-8
Java
5,455
java
CMManageStatementTest.java
Java
[]
null
[]
package configuration.management.rest; import static com.jayway.restassured.RestAssured.get; import static com.jayway.restassured.RestAssured.given; import static com.jayway.restassured.RestAssured.when; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.jayway.restassured.response.Response; import common.data.dto.QueryDTO; import common.rest.RESOURCE_NAMING; import common.rest.ResourceUtils; import configuration.management.Application; import configuration.management.model.EventProcessingDLO; import configuration.management.model.RuleDLO; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest("server.port:0") public class CMManageStatementTest extends AbstractTestRestCM { @Test public void getAllQueries1() { Response response = get(RESOURCE_NAMING.CM_GET_ALL_QUERIES.getPath()); List<QueryDTO> result = Arrays.asList(response.getBody().as(QueryDTO[].class)); assertEquals(200, response.getStatusCode()); assertNotNull(result); } @Test public void getAllQueries2() { when().get(RESOURCE_NAMING.CM_GET_ALL_QUERIES.getPath()) .then().statusCode(200); } @Test public void registerQuery() { String query = "CONDITION name = 'device1'"; given().body(query).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_QUERY, queryName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void registerQueryParseError() { String query = "AVC name = 'device1'"; given().body(query).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_QUERY, queryName)) .then().statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void registerQueryQueryExistsError() { String query = "CONDITION name = 'device1'"; String path = ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_QUERY, queryName); given().body(query).when().post(path) .then().statusCode(HttpStatus.OK.value()); given().body(query).when().post(path) .then().statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void deregisterQuery() { registerQuery(); when().delete(ResourceUtils.getPath(RESOURCE_NAMING.CM_DEREGISTRATION_QUERY, queryName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void registerRule() { registerQuery(); String rule = queryName + " TRIGGERS device1, domain1, configurationManagement1 = 1"; given().body(rule).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void registerRule1() { registerQuery(); } @Test public void registerRuleExistsError() { registerQuery(); String rule = queryName + " TRIGGERS device1, domain1, configurationManagement1 = 1"; given().body(rule).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); given().body(rule).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.BAD_REQUEST.value()); } @Test public void deregisterRule() { registerRule(); when().delete(ResourceUtils.getPath(RESOURCE_NAMING.CM_DEREGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void activateRule() { String query = "CONDITION name = 'device1'"; given().body(query).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_QUERY, queryName)) .then().statusCode(HttpStatus.OK.value()); String rule = queryName + " TRIGGERS device1, domain1, configurationManagement1 = 1"; given().body(rule).when().post(ResourceUtils.getPath(RESOURCE_NAMING.CM_REGISTRATION_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); when().get(ResourceUtils.getPath(RESOURCE_NAMING.CM_ACTIVATIONS_RULE, ruleName)) .then().statusCode(HttpStatus.OK.value()); } @Test public void deactivateRule() { activateRule(); /** * Fake assignment of EP */ EventProcessingDLO eventProcessing = new EventProcessingDLO(); eventProcessing.setAuthority("123"); eventProcessingRepository.save(eventProcessing); RuleDLO rule = ruleRepo.findByName(ruleName); rule.setEpDLO(eventProcessing); ruleRepo.save(rule); /** * End */ when().get(ResourceUtils.getPath(RESOURCE_NAMING.CM_DEACTIVATIONS_RULE), ruleName) .then().statusCode(HttpStatus.OK.value()); } }
5,455
0.673877
0.668011
193
27.264248
31.456156
112
false
false
0
0
0
0
0
0
0.409326
false
false
2
ca03b90db4913c75f2cb3588e9345ddc359f0797
16,767,552,353,487
e69abc77761cee792baa341575dc46fc213d68ac
/new/src/elevator_1316/elevator.java
4206130f5aab9c20d4a2bc7c30b9245ec23795af
[]
no_license
sharonmayenkar01/trail1
https://github.com/sharonmayenkar01/trail1
beb6337367bc634a9d1414205f6cdcc3fa594a6e
add27c3803a4127b2855ad33cd0e3708239f34d7
refs/heads/master
2021-01-10T04:19:55.476000
2015-10-20T06:35:38
2015-10-20T06:35:38
44,586,681
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package elevator_1316; public class elevator extends floor{ int numberOfFloors,floorChoice; @Override void switchState(context c) { // TODO Auto-generated method stub } }
UTF-8
Java
197
java
elevator.java
Java
[]
null
[]
package elevator_1316; public class elevator extends floor{ int numberOfFloors,floorChoice; @Override void switchState(context c) { // TODO Auto-generated method stub } }
197
0.690355
0.670051
12
14.416667
14.969181
37
false
false
0
0
0
0
0
0
1
false
false
2
e9c46d9101ea0cefe53e891f1fadc40fa4915bdf
16,174,846,850,562
b59020d326a86e52babbdd0ff30157cc17dcc35e
/listvieew/src/com/example/listvieew/spinner_activity.java
ac4f8a00bfd16eed58575b4c42162263c68d87bc
[]
no_license
priyankacool10/AndroidClass
https://github.com/priyankacool10/AndroidClass
4948d9d5c300c2d28e5e3b41de98fcddd85dccc8
a7f0f169fd22abf6df4e3e685b09b1bf02522f27
refs/heads/master
2016-09-06T02:34:18.949000
2014-05-05T05:01:50
2014-05-05T05:01:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.listvieew; import android.os.Bundle; import android.app.Activity; public class spinner_activity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.spinner_activity); } }
UTF-8
Java
287
java
spinner_activity.java
Java
[]
null
[]
package com.example.listvieew; import android.os.Bundle; import android.app.Activity; public class spinner_activity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.spinner_activity); } }
287
0.797909
0.797909
12
22.916666
18.754814
50
false
false
0
0
0
0
0
0
1
false
false
2
66b09007b25f14484737483a4efd727564e5a8c0
27,805,618,311,550
9fe237640cf74780b724746fe0edac005f81fb24
/src/main/java/com/mt/think/chapter14/practice3/Practice3.java
813e6a6445e5caecd44503a1c02dc04ff40d4e1a
[]
no_license
SmallMT/thinkingj
https://github.com/SmallMT/thinkingj
f36665baadd723292aa5d8519984dc456933147b
91bc0c8e2ffa27f33625fef043547e9ea5f6aa34
refs/heads/master
2018-11-11T08:26:02.135000
2018-08-22T09:51:37
2018-08-22T09:51:37
142,403,140
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mt.think.chapter14.practice3; /** * @author mt 2018.7.27 * 练习3 * 将Rhomboid菱形加入Shaper.java中,创建一个Rhomboid,将 * 其向上转型为Shape,然后向下转型回Rhomboid,试着将其向下转型 * 为Circle,看看会发生什么 * 练习4 * 修改程序在执行想下转型之前先运用instanceof检查类型 * 练习5 * 实现Shaper中rotate(Shaper)方法,让它能判断所旋转的是不是 * Circle(如果是,就不执行) */ public class Practice3 { public static void main(String[] args){ Rhombiod rhombiod = new Rhombiod(); Shaper shaper = (Shaper)rhombiod; //直接进行强转,shaper运行时类型转换抛异常 // Circle circle = (Circle)shaper; //先使用instanceof关键字后判断结果为false //则跳出了该强制类型转换 if (shaper instanceof Circle) { Circle circle = (Circle)shaper; } rhombiod.rotate(); new Circle().rotate(); // print(rhombiod.getClass()); // print(shaper.getClass()); } static void print(Class cc){ System.out.println(cc.getName()); } } abstract class Shaper { abstract void draw(); void rotate(){ if (this instanceof Circle) { System.out.println("是圆形,图形不旋转"); return; } System.out.println("图形旋转"); } } class Circle extends Shaper { @Override void draw() { System.out.println("draw a Circle"); } } class Rhombiod extends Shaper { @Override void draw() { System.out.println("draw a Rhombiod"); } }
UTF-8
Java
1,652
java
Practice3.java
Java
[ { "context": "com.mt.think.chapter14.practice3;\n\n/**\n * @author mt 2018.7.27\n * 练习3\n * 将Rhomboid菱形加入Shaper.java中,创建一", "end": 61, "score": 0.9864706993103027, "start": 59, "tag": "USERNAME", "value": "mt" } ]
null
[]
package com.mt.think.chapter14.practice3; /** * @author mt 2018.7.27 * 练习3 * 将Rhomboid菱形加入Shaper.java中,创建一个Rhomboid,将 * 其向上转型为Shape,然后向下转型回Rhomboid,试着将其向下转型 * 为Circle,看看会发生什么 * 练习4 * 修改程序在执行想下转型之前先运用instanceof检查类型 * 练习5 * 实现Shaper中rotate(Shaper)方法,让它能判断所旋转的是不是 * Circle(如果是,就不执行) */ public class Practice3 { public static void main(String[] args){ Rhombiod rhombiod = new Rhombiod(); Shaper shaper = (Shaper)rhombiod; //直接进行强转,shaper运行时类型转换抛异常 // Circle circle = (Circle)shaper; //先使用instanceof关键字后判断结果为false //则跳出了该强制类型转换 if (shaper instanceof Circle) { Circle circle = (Circle)shaper; } rhombiod.rotate(); new Circle().rotate(); // print(rhombiod.getClass()); // print(shaper.getClass()); } static void print(Class cc){ System.out.println(cc.getName()); } } abstract class Shaper { abstract void draw(); void rotate(){ if (this instanceof Circle) { System.out.println("是圆形,图形不旋转"); return; } System.out.println("图形旋转"); } } class Circle extends Shaper { @Override void draw() { System.out.println("draw a Circle"); } } class Rhombiod extends Shaper { @Override void draw() { System.out.println("draw a Rhombiod"); } }
1,652
0.60438
0.594161
62
21.064516
16.018005
46
false
false
0
0
0
0
0
0
0.403226
false
false
2
e4fbbb7f2b3ac238d869b24fb15a667e3557f1d3
18,734,647,352,505
6333c4781dbb34b6bf67c4cd5c7b633419a050a3
/src/main/java/petr/barsukov/utils/Utils.java
97ad7047c4f3d6015e74aa2f2e6acca58c925db4
[]
no_license
Web-Programmer-B-P/FirstTaskActiveMQ
https://github.com/Web-Programmer-B-P/FirstTaskActiveMQ
b6c2efaa6eea52e427b1a20010f02789055b441c
c2af0d8935e37e092833fca2ec65633e1d94b118
refs/heads/master
2023-03-12T06:29:24.769000
2021-03-02T19:13:27
2021-03-02T19:13:27
342,516,097
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package petr.barsukov.utils; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.TextMessage; public final class Utils { public final static String MAIN_QUEUE = "DISPATCHER_QUEUE"; public final static String TWO_DESTINATIONS = "QUEUE1, QUEUE2"; public final static String TEST_MESSAGE = "Hello world!"; public final static String EMPTY_MESSAGE = " "; public final static String CREATE_PRODUCER = "Билдим отправителя..."; public final static String PRODUCER_SENT_MESSAGE_SUCCESS = "Отправитель успешно отправил сообщение!"; public final static String CREATE_CONSUMER = "Билдим получателя..."; public final static String CONSUMER_RECEIVED_MESSAGE = "Получатель вычитал сообщение успешно!"; public final static String MESSAGE_VALIDATED_SUCCESS = "Сообщение прошло валидацию успешно!"; public final static String MESSAGE_SENT_DESTINATIONS = "Сообщение отправлено в обе очереди успешно!"; public final static String MESSAGE_IS_EMPTY = "Сообщение пустое!"; private Utils() { } public static String getStringOrException(Message msg) throws JMSException { String result = ""; if (msg instanceof TextMessage) { TextMessage textMessage = (TextMessage) msg; if (!textMessage.getText().isBlank()) { result = textMessage.getText(); } else { throw new JMSException(MESSAGE_IS_EMPTY); } } return result; } }
UTF-8
Java
1,675
java
Utils.java
Java
[]
null
[]
package petr.barsukov.utils; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.TextMessage; public final class Utils { public final static String MAIN_QUEUE = "DISPATCHER_QUEUE"; public final static String TWO_DESTINATIONS = "QUEUE1, QUEUE2"; public final static String TEST_MESSAGE = "Hello world!"; public final static String EMPTY_MESSAGE = " "; public final static String CREATE_PRODUCER = "Билдим отправителя..."; public final static String PRODUCER_SENT_MESSAGE_SUCCESS = "Отправитель успешно отправил сообщение!"; public final static String CREATE_CONSUMER = "Билдим получателя..."; public final static String CONSUMER_RECEIVED_MESSAGE = "Получатель вычитал сообщение успешно!"; public final static String MESSAGE_VALIDATED_SUCCESS = "Сообщение прошло валидацию успешно!"; public final static String MESSAGE_SENT_DESTINATIONS = "Сообщение отправлено в обе очереди успешно!"; public final static String MESSAGE_IS_EMPTY = "Сообщение пустое!"; private Utils() { } public static String getStringOrException(Message msg) throws JMSException { String result = ""; if (msg instanceof TextMessage) { TextMessage textMessage = (TextMessage) msg; if (!textMessage.getText().isBlank()) { result = textMessage.getText(); } else { throw new JMSException(MESSAGE_IS_EMPTY); } } return result; } }
1,675
0.68947
0.688129
35
41.599998
32.222618
105
false
false
0
0
0
0
0
0
0.6
false
false
2
2fa7ddfe2a01855b4bfe98c6abcd819e401294f1
8,667,244,055,433
37c34317ca356af275807903522d4eb70967911c
/example/CountExample/app/src/main/java/kr/pe/burt/countexample/MainActivity.java
db4137231a744d49af919dc97a7d94b94debd694
[ "MIT" ]
permissive
xinyer/FAImageView
https://github.com/xinyer/FAImageView
9f30ce1701e9ced7edc504ab71cc4b3811eeb5c8
fb3b6eeac739c74115639a114851dd1e4cc653f8
refs/heads/master
2021-08-08T13:18:54.292000
2017-11-10T10:43:07
2017-11-10T10:43:07
104,875,839
0
0
null
true
2017-09-26T11:24:51
2017-09-26T11:24:51
2017-08-11T09:01:45
2016-08-12T03:39:21
1,932
0
0
0
null
null
null
package kr.pe.burt.countexample; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import kr.pe.burt.android.lib.faimageview.FAImageView; public class MainActivity extends AppCompatActivity { FAImageView faImageView; Boolean didStartedAnimation = false; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); faImageView = (FAImageView) findViewById(R.id.faimageview); faImageView.setInterval(1000); faImageView.setLoop(true); faImageView.setRestoreFirstFrameWhenFinishAnimation(false); faImageView.addImageFrame(R.drawable.number01); faImageView.addImageFrame(R.drawable.number02); faImageView.addImageFrame(R.drawable.number03); faImageView.setOnStartAnimationListener(new FAImageView.OnStartAnimationListener() { @Override public void onStartAnimation() { Log.v("FAImageView", "Animation started"); } }); faImageView.setOnFinishAnimationListener(new FAImageView.OnFinishAnimationListener() { @Override public void onFinishAnimation(boolean isLoopAnimation) { if(isLoopAnimation) { Log.v("FAImageView", "finished an animation cycle."); } else { Log.v("FAImageView", "Animation is completed"); } } }); faImageView.setOnFrameChangedListener(new FAImageView.OnFrameChangedListener() { @Override public void onFrameChanged(int index) { Log.v("FAImageView", String.format("frameIndex : %d", index)); } }); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } void onStartButtonClicked(View sender) { faImageView.startAnimation(); } void onStopButtonClicked(View sender) { faImageView.stopAnimation(); } }
UTF-8
Java
2,233
java
MainActivity.java
Java
[]
null
[]
package kr.pe.burt.countexample; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import kr.pe.burt.android.lib.faimageview.FAImageView; public class MainActivity extends AppCompatActivity { FAImageView faImageView; Boolean didStartedAnimation = false; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); faImageView = (FAImageView) findViewById(R.id.faimageview); faImageView.setInterval(1000); faImageView.setLoop(true); faImageView.setRestoreFirstFrameWhenFinishAnimation(false); faImageView.addImageFrame(R.drawable.number01); faImageView.addImageFrame(R.drawable.number02); faImageView.addImageFrame(R.drawable.number03); faImageView.setOnStartAnimationListener(new FAImageView.OnStartAnimationListener() { @Override public void onStartAnimation() { Log.v("FAImageView", "Animation started"); } }); faImageView.setOnFinishAnimationListener(new FAImageView.OnFinishAnimationListener() { @Override public void onFinishAnimation(boolean isLoopAnimation) { if(isLoopAnimation) { Log.v("FAImageView", "finished an animation cycle."); } else { Log.v("FAImageView", "Animation is completed"); } } }); faImageView.setOnFrameChangedListener(new FAImageView.OnFrameChangedListener() { @Override public void onFrameChanged(int index) { Log.v("FAImageView", String.format("frameIndex : %d", index)); } }); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } void onStartButtonClicked(View sender) { faImageView.startAnimation(); } void onStopButtonClicked(View sender) { faImageView.stopAnimation(); } }
2,233
0.643977
0.639051
73
29.589041
25.725014
94
false
false
0
0
0
0
0
0
0.465753
false
false
2
69c7d3423a771daa7bd12c66bd78d2605da9c7be
22,806,276,374,240
5b526f02d3baa40c39059742fa48ea8792efdfe4
/src/main/java/com/padlet/service/UrlService.java
db4b7335856310e446a76d5b1f781f5cbf6893d7
[]
no_license
prigupta0609/UrlShortener
https://github.com/prigupta0609/UrlShortener
e8e0c9a868affaa77fde9e282cd54ecf5ddd77d6
bd9a705afbfc9a160b9e0087c47b55775db443b1
refs/heads/master
2023-01-04T22:18:49.867000
2020-10-26T02:58:20
2020-10-26T02:58:20
307,246,438
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.padlet.service; import com.padlet.common.Constants; import com.padlet.contract.request.UrlShortenerRequest; import com.padlet.contract.response.Error; import com.padlet.contract.response.UrlShortenerResponse; import com.padlet.dao.IUrlDao; import com.padlet.model.URL; import com.padlet.validator.IValidator; import com.padlet.validator.ValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; // Service layer to process the requests @Service public class UrlService implements IUrlService { @Autowired @Qualifier("UrlDao") private IUrlDao urlDao; @Autowired @Qualifier("UrlValidator") private IValidator urlValidator; private static int counter = 1; /** * Encode the long url to short url * @param request * @return UrlShortenerResponse */ @Override public UrlShortenerResponse encodeUrl(UrlShortenerRequest request) { UrlShortenerResponse response = null; try { urlValidator.validate(request.getUrl()); String shortUrl = getShortUrl(request); response = createResponse(shortUrl, request.getUrl(), null); } catch (ValidationException e) { Error error = new Error(e.getMessage(), e.getErrorCode()); response = createResponse(null, request.getUrl(), error); } return response; } /** * Decode short url to long url * @param shortUrl * @return UrlShortenerResponse */ @Override public UrlShortenerResponse decodeUrl(String shortUrl) { UrlShortenerResponse response = null; URL url = getLongUrl(shortUrl); if (url == null) { Error error = new Error(com.padlet.common.Error.URL_NOT_FOUND.getMessage(), com.padlet.common.Error.URL_NOT_FOUND.getErrorCode()); response = createResponse(shortUrl, null, error); } else { response = createResponse(shortUrl, url.getLongUrl(), null); } return response; } private URL getLongUrl(String shortUrl) { String hashCode = shortUrl.substring(shortUrl.length()-6); return urlDao.getUrlFromHashcode(hashCode); } private String getShortUrl(UrlShortenerRequest request) { String hashCode = UrlUtil.getBase62(counter); String shortUrl = Constants.INITIAL_URL + hashCode; URL url = new URL(shortUrl, request.getUrl()); urlDao.addUrlMapping(hashCode, url); return shortUrl; } private UrlShortenerResponse createResponse(String shortUrl, String longUrl, Error error) { UrlShortenerResponse.UrlShortenerResponseBuilder builder = new UrlShortenerResponse.UrlShortenerResponseBuilder(); return builder.setShortUrl(shortUrl) .setLongUrl(longUrl) .setError(error) .build(); } }
UTF-8
Java
3,067
java
UrlService.java
Java
[]
null
[]
package com.padlet.service; import com.padlet.common.Constants; import com.padlet.contract.request.UrlShortenerRequest; import com.padlet.contract.response.Error; import com.padlet.contract.response.UrlShortenerResponse; import com.padlet.dao.IUrlDao; import com.padlet.model.URL; import com.padlet.validator.IValidator; import com.padlet.validator.ValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; // Service layer to process the requests @Service public class UrlService implements IUrlService { @Autowired @Qualifier("UrlDao") private IUrlDao urlDao; @Autowired @Qualifier("UrlValidator") private IValidator urlValidator; private static int counter = 1; /** * Encode the long url to short url * @param request * @return UrlShortenerResponse */ @Override public UrlShortenerResponse encodeUrl(UrlShortenerRequest request) { UrlShortenerResponse response = null; try { urlValidator.validate(request.getUrl()); String shortUrl = getShortUrl(request); response = createResponse(shortUrl, request.getUrl(), null); } catch (ValidationException e) { Error error = new Error(e.getMessage(), e.getErrorCode()); response = createResponse(null, request.getUrl(), error); } return response; } /** * Decode short url to long url * @param shortUrl * @return UrlShortenerResponse */ @Override public UrlShortenerResponse decodeUrl(String shortUrl) { UrlShortenerResponse response = null; URL url = getLongUrl(shortUrl); if (url == null) { Error error = new Error(com.padlet.common.Error.URL_NOT_FOUND.getMessage(), com.padlet.common.Error.URL_NOT_FOUND.getErrorCode()); response = createResponse(shortUrl, null, error); } else { response = createResponse(shortUrl, url.getLongUrl(), null); } return response; } private URL getLongUrl(String shortUrl) { String hashCode = shortUrl.substring(shortUrl.length()-6); return urlDao.getUrlFromHashcode(hashCode); } private String getShortUrl(UrlShortenerRequest request) { String hashCode = UrlUtil.getBase62(counter); String shortUrl = Constants.INITIAL_URL + hashCode; URL url = new URL(shortUrl, request.getUrl()); urlDao.addUrlMapping(hashCode, url); return shortUrl; } private UrlShortenerResponse createResponse(String shortUrl, String longUrl, Error error) { UrlShortenerResponse.UrlShortenerResponseBuilder builder = new UrlShortenerResponse.UrlShortenerResponseBuilder(); return builder.setShortUrl(shortUrl) .setLongUrl(longUrl) .setError(error) .build(); } }
3,067
0.665145
0.663841
89
33.460674
23.949411
87
false
false
0
0
0
0
0
0
0.573034
false
false
2
311a6d572ecaa1ca0731295940474ab3f5c045a8
23,218,593,269,354
472955b53c03488bc5bd2c52dcba99daa0aba372
/UNIBS_Esercitazioni/src/it/unibs/ing/laboratorio/ElencoIngredienti.java
69027015abb37428b2861ec57a2252e623c1eb57
[]
no_license
JavaUnibs/Esercitazioni
https://github.com/JavaUnibs/Esercitazioni
46ecdaf5852239b73eaa348f4d1b004e2bfaf041
b48b92c6c3f10bd3af5a8773e57ee6b50fed3b04
refs/heads/master
2021-01-22T11:48:12.110000
2015-12-15T09:56:06
2015-12-15T09:56:06
35,491,767
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.unibs.ing.laboratorio; import java.util.*; public class ElencoIngredienti { private ArrayList<Ingrediente> elenco = new ArrayList<Ingrediente>(); public void inserisciIngrediente(Ingrediente ingrediente){ elenco.add(ingrediente); } public Ingrediente cercaIngrediente(String nome){ for(Ingrediente ingrediente: elenco){ if (ingrediente.getNome().equals(nome)) return ingrediente; } System.out.println("Ingrediente non trovato"); return null; } public void visualizzazione(){ for(Ingrediente ingrediente: elenco){ System.out.println(ingrediente.toString()); System.out.println("-------"); } } public ArrayList<Ingrediente> getElencoIngredienti(){ return elenco; } }
UTF-8
Java
754
java
ElencoIngredienti.java
Java
[]
null
[]
package it.unibs.ing.laboratorio; import java.util.*; public class ElencoIngredienti { private ArrayList<Ingrediente> elenco = new ArrayList<Ingrediente>(); public void inserisciIngrediente(Ingrediente ingrediente){ elenco.add(ingrediente); } public Ingrediente cercaIngrediente(String nome){ for(Ingrediente ingrediente: elenco){ if (ingrediente.getNome().equals(nome)) return ingrediente; } System.out.println("Ingrediente non trovato"); return null; } public void visualizzazione(){ for(Ingrediente ingrediente: elenco){ System.out.println(ingrediente.toString()); System.out.println("-------"); } } public ArrayList<Ingrediente> getElencoIngredienti(){ return elenco; } }
754
0.704244
0.704244
30
23.133333
22.177666
70
false
false
0
0
0
0
0
0
1.6
false
false
2
542112a6f7b286e00f65fa8e686f4d025affc7c5
4,174,708,246,902
65bb587587f5824d2f6b7b7dd5ad2363f1f76d0d
/WebdriverPageFactory/src/test/java/Pages/FlightFinderPage.java
58fafce3f3d680786127242a78005cf03df3a544
[]
no_license
Gaurang033/WebdriverPageFactory
https://github.com/Gaurang033/WebdriverPageFactory
870a2e3f34f99c094ed47647b1c90afbce3332b7
3e10f4720c4c106cc78270ac9b0b6a7012fd558f
refs/heads/master
2018-05-03T01:56:56.401000
2013-09-26T09:51:33
2013-09-26T09:51:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Pages; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import Lib.CommonFunc; import ObjectRepo.FlightFinder; import static ObjectRepo.FlightFinder.*; public class FlightFinderPage implements Page{ private static FlightFinderPage FlightFinderPage; private Properties properties; private CommonFunc commonFunc; private WebDriver driver; private WebElement logoutLink; private WebElement PassangerDropDown; public static Object getFlightFinderPage(WebDriver driver) { // TODO Auto-generated method stub if (FlightFinderPage == null){ return new FlightFinderPage(driver); } return FlightFinderPage; } private FlightFinderPage(WebDriver driver){ this.driver = driver; properties = new Properties(); commonFunc = new CommonFunc(driver); try { properties.load(new FileInputStream( System.getProperty("user.dir")+"\\src\\test\\java\\Data\\FlightFinderPage.properties")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public LoginPage Logout() { // TODO Auto-generated method stub logoutLink = commonFunc.getElement((String)properties.get("logout")); logoutLink.click(); return LoginPage.getLoginPage(driver); } @Override public SelectFlight setPageInfo(Map<String, String> flightDetails){ if(flightDetails.containsKey("flightType")) selectFlightType(flightDetails.get("flightType")); if(flightDetails.containsKey("noOfPassengers")) selectPassangers(flightDetails.get("noOfPassengers")); if(flightDetails.containsKey("departingCity")) selectDetpartingCity(flightDetails.get("departingCity")); if(flightDetails.containsKey("departingMonth") && !flightDetails.get("departingMonth").equals("")) selectDepartingMonth(flightDetails.get("departingMonth")); if(flightDetails.containsKey("departingDay") && !flightDetails.get("departingDay").equals("")) selectDepartingDay(flightDetails.get("departingDay")); if(flightDetails.containsKey("arrivingCity") && !flightDetails.get("arrivingCity").equals("")) selectArrivingCity(flightDetails.get("arrivingCity")); if(flightDetails.containsKey("arrivingMonth") && !flightDetails.get("arrivingMonth").equals("")) selectArrivingMonth(flightDetails.get("arrivingMonth")); if(flightDetails.containsKey("arrivingDay")) selectArrivingDay(flightDetails.get("arrivingDay")); return submit(); } public void selectFlightType(String flightType){ if (flightType.equalsIgnoreCase("oneway")){ commonFunc.click(properties.getProperty("onwayRadioButton")); }else if (flightType.equalsIgnoreCase("roundTrip")) { commonFunc.click(properties.getProperty("roundTripRadioButton")); }else{ System.out.println("error: wrong type"); } } public void selectPassangers(String noOfPassengers){ //commonFunc.select(properties.getProperty("passnagers"), noOfPassengers); commonFunc.select(FlightFinder.passnagers, noOfPassengers); } public void selectDetpartingCity(String departingCity){ commonFunc.select(FlightFinder.departingFrom, departingCity); } public void selectDepartingMonth(String departingMonth){ commonFunc.select(FlightFinder.departingMonth, departingMonth); } public void selectDepartingDay(String departingDay){ commonFunc.select(FlightFinder.departingDate, departingDay); } public void selectArrivingCity(String arrivingCity){ commonFunc.select(FlightFinder.ArrivingIn, arrivingCity); } public void selectArrivingMonth(String arrivingMonth){ commonFunc.select(FlightFinder.ReturningMonth, arrivingMonth); } public void selectArrivingDay(String arrivingDay){ commonFunc.select(FlightFinder.ReturningDate, arrivingDay); } public SelectFlight submit(){ commonFunc.click(continueLink); return SelectFlight.getSelectFlight(driver); } @Override public void verifyPageInfo(Map<String, String> Info) { // TODO Auto-generated method stub } }
UTF-8
Java
4,293
java
FlightFinderPage.java
Java
[]
null
[]
package Pages; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import Lib.CommonFunc; import ObjectRepo.FlightFinder; import static ObjectRepo.FlightFinder.*; public class FlightFinderPage implements Page{ private static FlightFinderPage FlightFinderPage; private Properties properties; private CommonFunc commonFunc; private WebDriver driver; private WebElement logoutLink; private WebElement PassangerDropDown; public static Object getFlightFinderPage(WebDriver driver) { // TODO Auto-generated method stub if (FlightFinderPage == null){ return new FlightFinderPage(driver); } return FlightFinderPage; } private FlightFinderPage(WebDriver driver){ this.driver = driver; properties = new Properties(); commonFunc = new CommonFunc(driver); try { properties.load(new FileInputStream( System.getProperty("user.dir")+"\\src\\test\\java\\Data\\FlightFinderPage.properties")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public LoginPage Logout() { // TODO Auto-generated method stub logoutLink = commonFunc.getElement((String)properties.get("logout")); logoutLink.click(); return LoginPage.getLoginPage(driver); } @Override public SelectFlight setPageInfo(Map<String, String> flightDetails){ if(flightDetails.containsKey("flightType")) selectFlightType(flightDetails.get("flightType")); if(flightDetails.containsKey("noOfPassengers")) selectPassangers(flightDetails.get("noOfPassengers")); if(flightDetails.containsKey("departingCity")) selectDetpartingCity(flightDetails.get("departingCity")); if(flightDetails.containsKey("departingMonth") && !flightDetails.get("departingMonth").equals("")) selectDepartingMonth(flightDetails.get("departingMonth")); if(flightDetails.containsKey("departingDay") && !flightDetails.get("departingDay").equals("")) selectDepartingDay(flightDetails.get("departingDay")); if(flightDetails.containsKey("arrivingCity") && !flightDetails.get("arrivingCity").equals("")) selectArrivingCity(flightDetails.get("arrivingCity")); if(flightDetails.containsKey("arrivingMonth") && !flightDetails.get("arrivingMonth").equals("")) selectArrivingMonth(flightDetails.get("arrivingMonth")); if(flightDetails.containsKey("arrivingDay")) selectArrivingDay(flightDetails.get("arrivingDay")); return submit(); } public void selectFlightType(String flightType){ if (flightType.equalsIgnoreCase("oneway")){ commonFunc.click(properties.getProperty("onwayRadioButton")); }else if (flightType.equalsIgnoreCase("roundTrip")) { commonFunc.click(properties.getProperty("roundTripRadioButton")); }else{ System.out.println("error: wrong type"); } } public void selectPassangers(String noOfPassengers){ //commonFunc.select(properties.getProperty("passnagers"), noOfPassengers); commonFunc.select(FlightFinder.passnagers, noOfPassengers); } public void selectDetpartingCity(String departingCity){ commonFunc.select(FlightFinder.departingFrom, departingCity); } public void selectDepartingMonth(String departingMonth){ commonFunc.select(FlightFinder.departingMonth, departingMonth); } public void selectDepartingDay(String departingDay){ commonFunc.select(FlightFinder.departingDate, departingDay); } public void selectArrivingCity(String arrivingCity){ commonFunc.select(FlightFinder.ArrivingIn, arrivingCity); } public void selectArrivingMonth(String arrivingMonth){ commonFunc.select(FlightFinder.ReturningMonth, arrivingMonth); } public void selectArrivingDay(String arrivingDay){ commonFunc.select(FlightFinder.ReturningDate, arrivingDay); } public SelectFlight submit(){ commonFunc.click(continueLink); return SelectFlight.getSelectFlight(driver); } @Override public void verifyPageInfo(Map<String, String> Info) { // TODO Auto-generated method stub } }
4,293
0.739576
0.739576
148
27.006756
27.544189
128
false
false
0
0
0
0
0
0
1.783784
false
false
2
f433447b463a18e4ec70e9fbf4fd32e970dad1de
4,174,708,249,768
95e944448000c08dd3d6915abb468767c9f29d3c
/sources/com/facebook/imagepipeline/p724k/C13711at.java
4f2b2e834bdc1023fb60ff05fca0b34b051d603d
[]
no_license
xrealm/tiktok-src
https://github.com/xrealm/tiktok-src
261b1faaf7b39d64bb7cb4106dc1a35963bd6868
90f305b5f981d39cfb313d75ab231326c9fca597
refs/heads/master
2022-11-12T06:43:07.401000
2020-07-04T20:21:12
2020-07-04T20:21:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.imagepipeline.p724k; import com.facebook.imagepipeline.common.Priority; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequest.RequestLevel; /* renamed from: com.facebook.imagepipeline.k.at */ public final class C13711at extends C13737d { public C13711at(ImageRequest imageRequest, C13700an anVar) { this(imageRequest, anVar.mo33335b(), anVar.mo33336c(), anVar.mo33337d(), anVar.mo33338e(), anVar.mo33339f(), anVar.mo33341h(), anVar.mo33340g()); } public C13711at(ImageRequest imageRequest, String str, C13702ap apVar, Object obj, RequestLevel requestLevel, boolean z, boolean z2, Priority priority) { super(imageRequest, str, apVar, obj, requestLevel, z, z2, priority); } }
UTF-8
Java
787
java
C13711at.java
Java
[]
null
[]
package com.facebook.imagepipeline.p724k; import com.facebook.imagepipeline.common.Priority; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequest.RequestLevel; /* renamed from: com.facebook.imagepipeline.k.at */ public final class C13711at extends C13737d { public C13711at(ImageRequest imageRequest, C13700an anVar) { this(imageRequest, anVar.mo33335b(), anVar.mo33336c(), anVar.mo33337d(), anVar.mo33338e(), anVar.mo33339f(), anVar.mo33341h(), anVar.mo33340g()); } public C13711at(ImageRequest imageRequest, String str, C13702ap apVar, Object obj, RequestLevel requestLevel, boolean z, boolean z2, Priority priority) { super(imageRequest, str, apVar, obj, requestLevel, z, z2, priority); } }
787
0.763659
0.674714
16
48.1875
48.272945
157
false
false
0
0
0
0
0
0
1.75
false
false
2
22e2495e961fe66d7e4bb08b79a4662ffb011faf
28,338,194,268,439
b44dd3ae205952b80aa915800d40e3df18549ee1
/src/com/daguo/util/adapter/SC_HuoDongAdapter.java
900b34e3aaf72eef877c6b40d08c949f219958fa
[]
no_license
loogler/DaGuo
https://github.com/loogler/DaGuo
2a95da52b3c341087fc81dbbd0da47fd5111907a
cb194109b02bbe0813f9002f0a2cf0de49e8b96c
refs/heads/master
2020-05-17T11:54:05.990000
2015-10-20T06:17:25
2015-10-20T06:17:25
39,937,334
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.daguo.util.adapter; import java.util.List; import net.tsz.afinal.FinalBitmap; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.daguo.R; import com.daguo.ui.school.huodong.SC_HuoDong_DetailAty; import com.daguo.util.beans.SC_HuoDong; import com.daguo.utils.HttpUtil; /** * 活动适配器 * * @author Bugs_Rabbit 時間: 2015-10-10 下午3:40:07 */ public class SC_HuoDongAdapter extends BaseAdapter { Context context; List<SC_HuoDong> lists; SC_HuoDong list; LayoutInflater inflater; public SC_HuoDongAdapter(Context context, List<SC_HuoDong> lists) { this.context = context; this.lists = lists; inflater = LayoutInflater.from(context); } @Override public int getCount() { return lists.size(); } @Override public Object getItem(int arg0) { return lists.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(final int p, View v, ViewGroup v2) { v = inflater.inflate(R.layout.adapter_sc_huodong, null); TextView type_name = (TextView) v.findViewById(R.id.type_name); TextView title1 = (TextView) v.findViewById(R.id.title1); TextView start_date = (TextView) v.findViewById(R.id.start_date); TextView end_date = (TextView) v.findViewById(R.id.end_date); TextView type_send = (TextView) v.findViewById(R.id.type_send); TextView content = (TextView) v.findViewById(R.id.content); ImageView img_content = (ImageView) v.findViewById(R.id.img_content); list = lists.get(p); type_name.setText(list.getTag()); title1.setText(list.getTitle()); start_date.setText(list.getS_date() + " " + list.getS_time()); end_date.setText(list.getE_date() + " " + list.getE_time()); type_send.setText("在线提交作品"); content.setText(list.getContent()); FinalBitmap.create(context).display(img_content, HttpUtil.IMG_URL + list.getImg_path()); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(context, "position" + p, 2000).show(); Intent intent = new Intent(context, SC_HuoDong_DetailAty.class); intent.putExtra("type_name", list.getTag()); intent.putExtra("title1", list.getTitle()); intent.putExtra("start_date", list.getS_date() + " " + list.getS_time()); intent.putExtra("end_date", list.getE_date() + " " + list.getE_time()); intent.putExtra("type_send", "在线提交作品"); intent.putExtra("content", list.getContent()); intent.putExtra("img_content", HttpUtil.IMG_URL + list.getImg_path()); context.startActivity(intent); // TODO 设置点击事件 } }); return v; } }
UTF-8
Java
2,887
java
SC_HuoDongAdapter.java
Java
[ { "context": "daguo.utils.HttpUtil;\n\n/**\n * 活动适配器\n * \n * @author Bugs_Rabbit 時間: 2015-10-10 下午3:40:07\n */\npublic class SC_HuoD", "end": 568, "score": 0.9993715882301331, "start": 557, "tag": "USERNAME", "value": "Bugs_Rabbit" } ]
null
[]
package com.daguo.util.adapter; import java.util.List; import net.tsz.afinal.FinalBitmap; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.daguo.R; import com.daguo.ui.school.huodong.SC_HuoDong_DetailAty; import com.daguo.util.beans.SC_HuoDong; import com.daguo.utils.HttpUtil; /** * 活动适配器 * * @author Bugs_Rabbit 時間: 2015-10-10 下午3:40:07 */ public class SC_HuoDongAdapter extends BaseAdapter { Context context; List<SC_HuoDong> lists; SC_HuoDong list; LayoutInflater inflater; public SC_HuoDongAdapter(Context context, List<SC_HuoDong> lists) { this.context = context; this.lists = lists; inflater = LayoutInflater.from(context); } @Override public int getCount() { return lists.size(); } @Override public Object getItem(int arg0) { return lists.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(final int p, View v, ViewGroup v2) { v = inflater.inflate(R.layout.adapter_sc_huodong, null); TextView type_name = (TextView) v.findViewById(R.id.type_name); TextView title1 = (TextView) v.findViewById(R.id.title1); TextView start_date = (TextView) v.findViewById(R.id.start_date); TextView end_date = (TextView) v.findViewById(R.id.end_date); TextView type_send = (TextView) v.findViewById(R.id.type_send); TextView content = (TextView) v.findViewById(R.id.content); ImageView img_content = (ImageView) v.findViewById(R.id.img_content); list = lists.get(p); type_name.setText(list.getTag()); title1.setText(list.getTitle()); start_date.setText(list.getS_date() + " " + list.getS_time()); end_date.setText(list.getE_date() + " " + list.getE_time()); type_send.setText("在线提交作品"); content.setText(list.getContent()); FinalBitmap.create(context).display(img_content, HttpUtil.IMG_URL + list.getImg_path()); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(context, "position" + p, 2000).show(); Intent intent = new Intent(context, SC_HuoDong_DetailAty.class); intent.putExtra("type_name", list.getTag()); intent.putExtra("title1", list.getTitle()); intent.putExtra("start_date", list.getS_date() + " " + list.getS_time()); intent.putExtra("end_date", list.getE_date() + " " + list.getE_time()); intent.putExtra("type_send", "在线提交作品"); intent.putExtra("content", list.getContent()); intent.putExtra("img_content", HttpUtil.IMG_URL + list.getImg_path()); context.startActivity(intent); // TODO 设置点击事件 } }); return v; } }
2,887
0.706464
0.69728
96
28.489584
21.366833
71
false
false
0
0
0
0
0
0
2.208333
false
false
2
1f9f6fd607b5db0ac7ab1de7c534dfa1390b1dab
31,619,549,247,928
17d250b820f3b52e9c929a230f68ff613a0f2ef2
/01_HelloSpring/src/main/java/com/kh/spring/member/controller/MemberController.java
924650a6f5c659ae0e37e84c30292483dfae0140
[]
no_license
sein-coder/viewChatting
https://github.com/sein-coder/viewChatting
00a3335a2c00430dc2d94b4ad153b69bd0069c06
98daea051b7aaff6031626df25a4f9cde9d1c0c0
refs/heads/HEAD
2022-12-22T10:50:18.366000
2019-11-08T07:01:51
2019-11-08T07:01:51
219,442,816
0
0
null
false
2022-11-15T23:31:54
2019-11-04T07:33:31
2019-11-08T07:03:38
2022-11-15T23:31:51
6,543
0
0
7
Java
false
false
package com.kh.spring.member.controller; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kh.spring.common.encrypt.MyEncrypt; import com.kh.spring.member.model.service.MemberService; import com.kh.spring.member.model.vo.Member; @SessionAttributes(value= {"loginMember","msg"}) @Controller public class MemberController { private Logger logger=LoggerFactory.getLogger(MemberController.class); //spring container가 알아서 해당하는 객체를 생성해서 활용해 //범위 : springBean중에서!!!! @Autowired private MemberService service; @Autowired private BCryptPasswordEncoder pwEncoder; @Autowired private MyEncrypt enc; @RequestMapping("/viewChatting") public String viewChatting() { return "common/viewChatting"; } @RequestMapping("/member/memberEnroll.do") public String memberEnroll() { //페이지 전환용 return "member/memberEnroll"; } @RequestMapping("/member/memberView.do") public String memberView(Member m,Model model) { Member result=service.selectMemberOne(m); try { result.setEmail(enc.decrypt(result.getEmail())); result.setPhone(enc.decrypt(result.getPhone())); result.setAddress(enc.decrypt(result.getAddress())); }catch(Exception e) { e.printStackTrace(); } model.addAttribute("member",result); return "member/memberView"; } @RequestMapping("/member/memberEnrollEnd.do") public String memberEnrollEnd(Member m,Model model) { //1. 파라미터 //1) request.getParameter(); //2) vo객체로 받는것 //3) Map객체로 받는것. //4) @RequestParam이용,변수명, name값 매칭선언! //2. 파라미터를 DB저장요청~ //controller -> service -> dao //비밀번호를 암호화 해보자!!! m.setPassword(pwEncoder.encode(m.getPassword())); logger.debug(m.getPassword()); //전화번호, 주소, 이메일까지 암호화처리 해보자 try { m.setPhone(enc.encrypt(m.getPhone())); m.setEmail(enc.encrypt(m.getEmail())); m.setAddress(enc.encrypt(m.getAddress())); }catch(Exception e) { e.printStackTrace(); } int result=service.insertMember(m); logger.debug(""+result); //msg.jsp이용하여 처리해보자. String msg=""; String loc="/"; if(result>0) { msg="회원가입완료!"; }else { msg="회원가입실패!"; } model.addAttribute("msg",msg); model.addAttribute("loc",loc); //가입이 끝나면??? 그냥 view로 연결하면??? //return "redirect:/"; //redirect방식으로 메인화면으로 이동 return "common/msg"; } @RequestMapping(value="/member/memberLogin.do",method=RequestMethod.POST) public String login(Member m, Model model) { //HttpSession session=req.getSession(); logger.debug(""+m); Member result=service.selectMemberOne(m); String msg=""; String loc="/"; logger.debug(m.getPassword()); logger.debug(result.getPassword()); if(result!=null) { if(pwEncoder.matches(m.getPassword(), result.getPassword())) { msg="로그인 성공!"; //session.setAttribute("loginMember", result); model.addAttribute("loginMember", result); } }else { msg="로그인 실패, 다시 시도하세요!"; } model.addAttribute("msg",msg); model.addAttribute("loc",loc); return "common/msg"; } @RequestMapping("/member/memberLogout.do") public String logout(HttpSession session,SessionStatus s) { if(!s.isComplete()) { s.setComplete();//로그아웃 SessionAttributes session.invalidate(); } return "redirect:/"; } //기본 stream방식으로 처리하기 //@ReposeBody이용->jackson라이브러리 필요 @RequestMapping("/member/checkId.do") @ResponseBody public String checkId(Member m,HttpServletResponse res) { //맵핑처리해서 반환해주기 ->어떻게 ObjectMapper mapper=new ObjectMapper(); //자바클래스와 json으로 보낸 자바스크립트객체를 매칭해주는 jackson에서 제공해주는 클래스 Member result = service.selectMemberOne(m); String jsonStr ="";//변경을 못하는 것들도 있어서 exception이 나온것 ->try/catch문 처리해줘야 해 //writeValueAsString: 입력받은 객체를 {키:값, 키:값...} 형식의 자바스크립트 객체로 알아서 반환 try { jsonStr= mapper.writeValueAsString(result); }catch(JsonProcessingException e) { e.printStackTrace(); } res.setContentType("application/json;charset=utf-8"); return jsonStr; } //jsonView를 이용한 ajax처리 //외부 라이브러리 받아와야 함->pom.xml //@RequestMapping("/member/checkId.do") /* * public ModelAndView checkId(Member m) { ModelAndView mv=new ModelAndView(); * Member result=service.selectMemberOne(m); //result!=null아니면 -> 중복된 아이디를 찾았단 뜻 * ->FALSE boolean flag=result!=null?false:true; * mv.addObject("flag",flag);//JSONOBJECT * * //mv.addObject("member",result); 객체?? //위처럼 못하고 jackson이용한 body로 해줘야함 ,그래서 * 아래처럼 각각넣어줘야함 * //mv.addObject("userId",result.getUserId());-->nullpoint에러남=>try/catch처리 하기 * * //Viewname은 반드시 joinView여야함 mv.setViewName("jsonView"); return mv; } */ //기본 Stream방식으로 처리하기 //json-lib //@RequestMapping("/member/checkId.do") //ajax는 비동기적 통신 즉. 화면전환이 일부분만 됨으로 굳이 화면으로 쏴줄 필요가 없다. /* * public void checkId(Member m,HttpServletResponse res) { Member * result=service.selectMemberOne(m); boolean flag =result!=null?false:true; * res.setContentType("application/json;charset=UTF-8"); try { * res.getOutputStream().print(flag); } catch (IOException e) { // TODO * Auto-generated catch block e.printStackTrace(); } } */ }
UTF-8
Java
6,814
java
MemberController.java
Java
[ { "context": "-> dao\r\n\t\t\r\n\t\t//비밀번호를 암호화 해보자!!!\r\n\t\tm.setPassword(pwEncoder.encode(m.getPassword()));\r\n\t\tlogger.debug(", "end": 2503, "score": 0.8735608458518982, "start": 2501, "tag": "PASSWORD", "value": "pw" } ]
null
[]
package com.kh.spring.member.controller; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kh.spring.common.encrypt.MyEncrypt; import com.kh.spring.member.model.service.MemberService; import com.kh.spring.member.model.vo.Member; @SessionAttributes(value= {"loginMember","msg"}) @Controller public class MemberController { private Logger logger=LoggerFactory.getLogger(MemberController.class); //spring container가 알아서 해당하는 객체를 생성해서 활용해 //범위 : springBean중에서!!!! @Autowired private MemberService service; @Autowired private BCryptPasswordEncoder pwEncoder; @Autowired private MyEncrypt enc; @RequestMapping("/viewChatting") public String viewChatting() { return "common/viewChatting"; } @RequestMapping("/member/memberEnroll.do") public String memberEnroll() { //페이지 전환용 return "member/memberEnroll"; } @RequestMapping("/member/memberView.do") public String memberView(Member m,Model model) { Member result=service.selectMemberOne(m); try { result.setEmail(enc.decrypt(result.getEmail())); result.setPhone(enc.decrypt(result.getPhone())); result.setAddress(enc.decrypt(result.getAddress())); }catch(Exception e) { e.printStackTrace(); } model.addAttribute("member",result); return "member/memberView"; } @RequestMapping("/member/memberEnrollEnd.do") public String memberEnrollEnd(Member m,Model model) { //1. 파라미터 //1) request.getParameter(); //2) vo객체로 받는것 //3) Map객체로 받는것. //4) @RequestParam이용,변수명, name값 매칭선언! //2. 파라미터를 DB저장요청~ //controller -> service -> dao //비밀번호를 암호화 해보자!!! m.setPassword(pwEncoder.encode(m.getPassword())); logger.debug(m.getPassword()); //전화번호, 주소, 이메일까지 암호화처리 해보자 try { m.setPhone(enc.encrypt(m.getPhone())); m.setEmail(enc.encrypt(m.getEmail())); m.setAddress(enc.encrypt(m.getAddress())); }catch(Exception e) { e.printStackTrace(); } int result=service.insertMember(m); logger.debug(""+result); //msg.jsp이용하여 처리해보자. String msg=""; String loc="/"; if(result>0) { msg="회원가입완료!"; }else { msg="회원가입실패!"; } model.addAttribute("msg",msg); model.addAttribute("loc",loc); //가입이 끝나면??? 그냥 view로 연결하면??? //return "redirect:/"; //redirect방식으로 메인화면으로 이동 return "common/msg"; } @RequestMapping(value="/member/memberLogin.do",method=RequestMethod.POST) public String login(Member m, Model model) { //HttpSession session=req.getSession(); logger.debug(""+m); Member result=service.selectMemberOne(m); String msg=""; String loc="/"; logger.debug(m.getPassword()); logger.debug(result.getPassword()); if(result!=null) { if(pwEncoder.matches(m.getPassword(), result.getPassword())) { msg="로그인 성공!"; //session.setAttribute("loginMember", result); model.addAttribute("loginMember", result); } }else { msg="로그인 실패, 다시 시도하세요!"; } model.addAttribute("msg",msg); model.addAttribute("loc",loc); return "common/msg"; } @RequestMapping("/member/memberLogout.do") public String logout(HttpSession session,SessionStatus s) { if(!s.isComplete()) { s.setComplete();//로그아웃 SessionAttributes session.invalidate(); } return "redirect:/"; } //기본 stream방식으로 처리하기 //@ReposeBody이용->jackson라이브러리 필요 @RequestMapping("/member/checkId.do") @ResponseBody public String checkId(Member m,HttpServletResponse res) { //맵핑처리해서 반환해주기 ->어떻게 ObjectMapper mapper=new ObjectMapper(); //자바클래스와 json으로 보낸 자바스크립트객체를 매칭해주는 jackson에서 제공해주는 클래스 Member result = service.selectMemberOne(m); String jsonStr ="";//변경을 못하는 것들도 있어서 exception이 나온것 ->try/catch문 처리해줘야 해 //writeValueAsString: 입력받은 객체를 {키:값, 키:값...} 형식의 자바스크립트 객체로 알아서 반환 try { jsonStr= mapper.writeValueAsString(result); }catch(JsonProcessingException e) { e.printStackTrace(); } res.setContentType("application/json;charset=utf-8"); return jsonStr; } //jsonView를 이용한 ajax처리 //외부 라이브러리 받아와야 함->pom.xml //@RequestMapping("/member/checkId.do") /* * public ModelAndView checkId(Member m) { ModelAndView mv=new ModelAndView(); * Member result=service.selectMemberOne(m); //result!=null아니면 -> 중복된 아이디를 찾았단 뜻 * ->FALSE boolean flag=result!=null?false:true; * mv.addObject("flag",flag);//JSONOBJECT * * //mv.addObject("member",result); 객체?? //위처럼 못하고 jackson이용한 body로 해줘야함 ,그래서 * 아래처럼 각각넣어줘야함 * //mv.addObject("userId",result.getUserId());-->nullpoint에러남=>try/catch처리 하기 * * //Viewname은 반드시 joinView여야함 mv.setViewName("jsonView"); return mv; } */ //기본 Stream방식으로 처리하기 //json-lib //@RequestMapping("/member/checkId.do") //ajax는 비동기적 통신 즉. 화면전환이 일부분만 됨으로 굳이 화면으로 쏴줄 필요가 없다. /* * public void checkId(Member m,HttpServletResponse res) { Member * result=service.selectMemberOne(m); boolean flag =result!=null?false:true; * res.setContentType("application/json;charset=UTF-8"); try { * res.getOutputStream().print(flag); } catch (IOException e) { // TODO * Auto-generated catch block e.printStackTrace(); } } */ }
6,814
0.692257
0.690429
201
27.860697
22.326624
81
false
false
0
0
0
0
0
0
2.029851
false
false
2
4034a8408a5460ab30493f78f5476ea1eb037e49
4,526,895,531,328
47cd7d1b74b2b51f842e81f324e5c5ab8fd8804d
/ssm-master/src/test/java/com/soecode/lyf/ApiGenerateUtil.java
e73bdd2a1a544e5dc1539f5732419a9a962f61e7
[]
no_license
xiongzhixing/web-util
https://github.com/xiongzhixing/web-util
e822adfcf7b0bd6dd3cbf7443394a50cc06aece4
0f6306c2eb5652fe0c42d4494eccb4b250fd37c1
refs/heads/master
2021-06-12T13:17:11.450000
2020-11-01T14:55:08
2020-11-01T14:55:08
128,649,795
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.soecode.lyf; import com.alibaba.fastjson.JSON; import com.soecode.lyf.annotation.DocAnnotation; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.text.MessageFormat; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ApiGenerateUtil { //类型 static class ClassType{ private String path; //类路径 private List<MethodType> methodTypeList; //类中方法对象 public String getPath() { return path; } public void setPath(String path) { this.path = path; } public List<MethodType> getMethodTypeList() { return methodTypeList; } public void setMethodTypeList(List<MethodType> methodTypeList) { this.methodTypeList = methodTypeList; } } //类中方法说明 static class MethodType{ private String path; private RequestMethod[] requestMethods = RequestMethod.values(); //请求方式,默认都行 private String common; //方法说明 private List<ParamType> reqList; //请求参数类型 private List<ParamType> respList; //响应参数类型 public String getPath() { return path; } public void setPath(String path) { this.path = path; } public RequestMethod[] getRequestMethods() { return requestMethods; } public void setRequestMethods(RequestMethod[] requestMethods) { this.requestMethods = requestMethods; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public List<ParamType> getReqList() { return reqList; } public void setReqList(List<ParamType> reqList) { this.reqList = reqList; } public List<ParamType> getRespList() { return respList; } public void setRespList(List<ParamType> respList) { this.respList = respList; } } //参数类型 static class ParamType{ private String common; //参数说明 private boolean isFill; //是否必填 private String paramName; //参数名字 private String paramType; //参数类型 private List<ParamType> subParamType; //子参数类型 public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public boolean isFill() { return isFill; } public void setFill(boolean fill) { isFill = fill; } public String getParamName() { return paramName; } public void setParamName(String paramName) { this.paramName = paramName; } public String getParamType() { return paramType; } public void setParamType(String paramType) { this.paramType = paramType; } public List<ParamType> getSubParamType() { return subParamType; } public void setSubParamType(List<ParamType> subParamType) { this.subParamType = subParamType; } } private final static String PACKAGE_PATH = "com.soecode.lyf.web"; private final static String API_PATH = "C:\\Users\\Administrator\\Desktop\\doc"; private final static String API_TEMPLATE = "**简要描述:** \n" + "\n" + "- {0}\n" + "\n" + "**请求URL:** \n" + "- {1}\n" + " \n" + "**请求方式:**\n" + "- {2}\n" + "\n" + "**参数:** \n" + "\n" + "|参数名|必选|类型|说明|\n" + "|:---- |:---|:----- |----- |\n" + "{3}\n" + "\n" + " **返回参数说明** \n" + "\n" + "|参数名|类型|说明|\n" + "|:----- |:-----|----- |\n" + "{4}"; private final static String URI = "http://xxx.com"; public static void main(String[] args) { List<Class<?>> classList = getClasses(PACKAGE_PATH); List<ClassType> classTypeList = new ArrayList<>(); for(Class classes:classList){ if(!(classes.isAnnotationPresent(Controller.class) || classes.isAnnotationPresent(RestController.class))){ //只包含controller的类 continue; } ClassType classType = new ClassType(); //获取contaoller的path if(classes.isAnnotationPresent(RequestMapping.class)){ RequestMapping requestMapping = (RequestMapping)classes.getAnnotation(RequestMapping.class); classType.setPath(requestMapping.value() == null || requestMapping.value().length == 0 ? null : requestMapping.value()[0]); } //获取所有方法 Method[] methods = classes.getDeclaredMethods(); List<MethodType> methodTypeList = new ArrayList<>(); for(Method method:methods){ if(!(method.isAnnotationPresent(RequestMapping.class) || method.isAnnotationPresent(GetMapping.class) || method.isAnnotationPresent(PostMapping.class))){ continue; } MethodType methodType = new MethodType(); if(method.isAnnotationPresent(RequestMapping.class)){ RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); //path methodType.setPath(requestMapping.value() == null || requestMapping.value().length == 0 ? null : requestMapping.value()[0]); //requestMethods if(requestMapping.method() != null && requestMapping.method().length > 0){ methodType.setRequestMethods(requestMapping.method()); } }else if(method.isAnnotationPresent(GetMapping.class)){ GetMapping getMapping = method.getAnnotation(GetMapping.class); //path methodType.setPath(getMapping.value() == null || getMapping.value().length == 0 ? null : getMapping.value()[0]); //requestMethods methodType.setRequestMethods(new RequestMethod[]{RequestMethod.GET}); }else if(method.isAnnotationPresent(PostMapping.class)){ PostMapping postMapping = method.getAnnotation(PostMapping.class); //path methodType.setPath(postMapping.value() == null || postMapping.value().length == 0 ? null : postMapping.value()[0]); //requestMethods methodType.setRequestMethods(new RequestMethod[]{RequestMethod.POST}); } // common if(method.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = method.getAnnotation(DocAnnotation.class); methodType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); } //reqList List<ParamType> paramTypeReqList = new ArrayList<>(); Parameter[] parameters = method.getParameters(); for(Parameter parameter:parameters){ if(isJavaClass(parameter.getType())){ if(isClassCollection(parameter.getType())){ //java集合 if(parameter.getType().getName().contains("List")) { //只考虑List if(parameter.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = parameter.getAnnotation(DocAnnotation.class); ParamType paramType = new ParamType(); paramType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(StringUtils.isEmpty(docAnnotation.name()) ? parameter.getName() : docAnnotation.name()); paramType.setParamType(getSimpleType(parameter.getType().getTypeName())); if(!(parameter.getParameterizedType() instanceof ParameterizedType)){ continue; } Class cls = (Class) ((ParameterizedType)parameter.getParameterizedType()).getActualTypeArguments()[0]; List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:cls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); paramTypeReqList.add(paramType); } } }else{ //java 常用基本类型 if(parameter.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = parameter.getAnnotation(DocAnnotation.class); ParamType paramType = new ParamType(); paramType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(StringUtils.isEmpty(docAnnotation.name()) ? parameter.getName() : docAnnotation.name()); paramType.setParamType(getSimpleType(parameter.getParameterizedType().getTypeName())); paramTypeReqList.add(paramType); } } }else{ //自定义类型不需要写DocAnnoation Class cls = parameter.getType(); List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:cls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramTypeReqList.addAll(paramTypeList); } } methodType.setReqList(paramTypeReqList); //方法设置请求参数列表 //respList List<ParamType> paramTypeResqList = new ArrayList<>(); Field[] fields = method.getReturnType().getDeclaredFields(); //参数类型 String clsPath = ((ParameterizedType)(method.getGenericReturnType())).getActualTypeArguments()[0].getTypeName(); Class tCls = null; boolean isCollection = false; if(clsPath.contains("java.util.List")){ //集合 tCls = (Class)((ParameterizedType)((ParameterizedType)method.getAnnotatedReturnType().getType()).getActualTypeArguments()[0]).getActualTypeArguments()[0]; isCollection = true; }else{ tCls = (Class)((ParameterizedType)(method.getAnnotatedReturnType().getType())).getActualTypeArguments()[0]; //参数中泛型类型 } for(Field field:fields){ if(field.isAnnotationPresent(DocAnnotation.class)){ //只有泛型数据才需要兼容,其他走正常情况 ParamType paramType = null; if("data".equals(field.getName())){ //泛型 paramType = setSubClass(field,tCls,isCollection); }else{ paramType = setSubClass(field,null,false); } if(paramType != null){ paramTypeResqList.add(paramType); } } } methodType.setRespList(paramTypeResqList); //方法设置请求参数列表 methodTypeList.add(methodType); //设置方法列表 } classType.setMethodTypeList(methodTypeList); //设置方法对象 classTypeList.add(classType); //设置类对象 } System.out.println(JSON.toJSONString(classTypeList)); //生成文档 File file = new File(API_PATH); deleteFile(file); file.mkdir(); for(ClassType classType:classTypeList){ for(MethodType methodType:classType.getMethodTypeList()){ String apiDesc = methodType.getCommon() == null ? "" : methodType.getCommon(); String path = getPath(classType.getPath(),methodType.getPath()); String reqMethod = Arrays.toString(methodType.requestMethods); StringBuilder reqStr = new StringBuilder(""); generateParamStr(reqStr,methodType.getReqList(),""); StringBuilder resqStr = new StringBuilder(""); generateParamStr(resqStr,methodType.getRespList(),""); String apiDoc = MessageFormat.format(API_TEMPLATE,new Object[]{apiDesc,path,reqMethod,reqStr.toString(),resqStr.toString()}); writeFile(API_PATH, methodType.path.replace("/",".") + ".txt",apiDoc); } } } private static void writeFile(String path,String fileName,String content){ PrintWriter pw = null; try { pw = new PrintWriter(new FileOutputStream(API_PATH + File.separatorChar + fileName)); pw.print(content); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if(pw != null){ try { pw.close(); } catch (Exception e) { e.printStackTrace(); } } } } private static void deleteFile(File file){ if(file == null){ return; } if(file.isFile()){ file.delete(); return; } for(File tFile:file.listFiles()){ if(tFile.isDirectory()){ deleteFile(tFile); } tFile.delete(); } file.delete(); } private static void generateParamStr(StringBuilder strBul,List<ParamType> paramTypeList,String splitChar){ if(paramTypeList == null || paramTypeList.size() == 0){ return; } for(ParamType paramType:paramTypeList){ strBul.append("|").append(splitChar).append(paramType.getParamName()).append("|") .append(paramType.isFill() ? "是":"否").append("|").append(paramType.getParamType()) .append("|").append(paramType.getParamName()).append("|").append("\n"); if(paramType.getSubParamType() != null){ generateParamStr(strBul,paramType.getSubParamType(),splitChar + " "); } } } private static String getPath(String classPath,String methodPath){ return trim(URI,'/') + "/" + trim(classPath,'/') + '/' + trim(methodPath,'/'); } private static String trim(String str,char ch){ if(str == null){ return str; } if(str.startsWith(ch + "")){ str = str.substring(1); } if(str.endsWith(ch + "")){ str = str.substring(0,str.length() - 1); } return str; } /** * 如果不是java类型,设置子类型 * @param field 域对象,这里如果是泛型,field是object * @param genericCls 如果是泛型,需要传Class对象 * @param isCollection 是否是泛型集合 * @return */ private static ParamType setSubClass(Field field,Class genericCls,boolean isCollection){ if(!field.isAnnotationPresent(DocAnnotation.class)){ return null; } ParamType paramType = new ParamType(); if(genericCls == null){ if(isJavaClass(field.getType())){ //java类型 if(isClassCollection(field.getType())){ //java集合, if(field.getType().getName().contains("List")){ //只考虑List if(field.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(field.getType().getName())); //Class cls = field.getGenericType().getTypeName().getClass(); if(field.getGenericType() instanceof ParameterizedType){ Class cls = (Class) ((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]; List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:cls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); } } } }else{ //java 常用基本类型 if(field.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(field.getType().getName())); } } }else{ //自定义对象 if(field.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(field.getType().getName())); Class cls = field.getType(); List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:cls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); } } }else{ //针对泛型类做兼容 if(isCollection){ if(isJavaClass(genericCls)){ //是java基本类型 DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType("List"); }else{ //自定义类型 DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType("List"); List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:genericCls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); } }else{ //不是集合 DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(genericCls.getName())); List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:genericCls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); } } return paramType; } /*private static void setParamType(List<ParamType> paramTypeReqList, DocAnnotation docAnnotation,Parameter parameter) { ParamType paramType = new ParamType(); paramType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(StringUtils.isEmpty(docAnnotation.name()) ? parameter.getName() : docAnnotation.name()); paramType.setParamType(getSimpleType(parameter.getParameterizedType().getTypeName())); paramTypeReqList.add(paramType); } private static ParamType setParamType(List<ParamType> paramTypeReqList, DocAnnotation docAnnotation,Field field) { ParamType paramType = new ParamType(); paramType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(field.getType().getTypeName())); paramTypeReqList.add(paramType); return paramType; }*/ public static String getSimpleType(String path){ if(StringUtils.isEmpty(path)){ return path; } Pattern pattern = Pattern.compile("^.*(\\.)(\\w+)$"); Matcher matcher = pattern.matcher(path); if(matcher.find()){ return matcher.group(2); }else{ return path; } } /* public static void main(String[] args) { System.out.println(getSimpleType("java.lang.String")); System.out.println(getSimpleType("String")); System.out.println(getSimpleType(null)); System.out.println(getSimpleType(".Integer")); }*/ public static boolean isJavaClass(Class<?> clz) { return clz != null && clz.getClassLoader() == null; } public static boolean isClassCollection(Class c) { return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c); } public static List<Class<?>> getClasses(String packageName){ //第一个class类的集合 List<Class<?>> classes = new ArrayList<Class<?>>(); //是否循环迭代 boolean recursive = true; //获取包的名字 并进行替换 String packageDirName = packageName.replace('.', '/'); //定义一个枚举的集合 并进行循环来处理这个目录下的things Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); //循环迭代下去 while (dirs.hasMoreElements()){ //获取下一个元素 URL url = dirs.nextElement(); //得到协议的名称 String protocol = url.getProtocol(); //如果是以文件的形式保存在服务器上 if ("file".equals(protocol)) { //获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); //以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)){ //如果是jar包文件 //定义一个JarFile JarFile jar; try { //获取jar jar = ((JarURLConnection) url.openConnection()).getJarFile(); //从此jar包 得到一个枚举类 Enumeration<JarEntry> entries = jar.entries(); //同样的进行循环迭代 while (entries.hasMoreElements()) { //获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); //如果是以/开头的 if (name.charAt(0) == '/') { //获取后面的字符串 name = name.substring(1); } //如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); //如果以"/"结尾 是一个包 if (idx != -1) { //获取包名 把"/"替换成"." packageName = name.substring(0, idx).replace('/', '.'); } //如果可以迭代下去 并且是一个包 if ((idx != -1) || recursive){ //如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { //去掉后面的".class" 获取真正的类名 String className = name.substring(packageName.length() + 1, name.length() - 6); try { //添加到classes classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } } } catch (IOException e) { e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } /** * 以文件的形式来获取包下的所有Class * @param packageName * @param packagePath * @param recursive * @param classes */ public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes){ //获取此包的目录 建立一个File File dir = new File(packagePath); //如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { return; } //如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { //自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); //循环所有文件 for (File file : dirfiles) { //如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { //如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { //添加到集合中去 classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } }
UTF-8
Java
30,432
java
ApiGenerateUtil.java
Java
[]
null
[]
package com.soecode.lyf; import com.alibaba.fastjson.JSON; import com.soecode.lyf.annotation.DocAnnotation; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.text.MessageFormat; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ApiGenerateUtil { //类型 static class ClassType{ private String path; //类路径 private List<MethodType> methodTypeList; //类中方法对象 public String getPath() { return path; } public void setPath(String path) { this.path = path; } public List<MethodType> getMethodTypeList() { return methodTypeList; } public void setMethodTypeList(List<MethodType> methodTypeList) { this.methodTypeList = methodTypeList; } } //类中方法说明 static class MethodType{ private String path; private RequestMethod[] requestMethods = RequestMethod.values(); //请求方式,默认都行 private String common; //方法说明 private List<ParamType> reqList; //请求参数类型 private List<ParamType> respList; //响应参数类型 public String getPath() { return path; } public void setPath(String path) { this.path = path; } public RequestMethod[] getRequestMethods() { return requestMethods; } public void setRequestMethods(RequestMethod[] requestMethods) { this.requestMethods = requestMethods; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public List<ParamType> getReqList() { return reqList; } public void setReqList(List<ParamType> reqList) { this.reqList = reqList; } public List<ParamType> getRespList() { return respList; } public void setRespList(List<ParamType> respList) { this.respList = respList; } } //参数类型 static class ParamType{ private String common; //参数说明 private boolean isFill; //是否必填 private String paramName; //参数名字 private String paramType; //参数类型 private List<ParamType> subParamType; //子参数类型 public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public boolean isFill() { return isFill; } public void setFill(boolean fill) { isFill = fill; } public String getParamName() { return paramName; } public void setParamName(String paramName) { this.paramName = paramName; } public String getParamType() { return paramType; } public void setParamType(String paramType) { this.paramType = paramType; } public List<ParamType> getSubParamType() { return subParamType; } public void setSubParamType(List<ParamType> subParamType) { this.subParamType = subParamType; } } private final static String PACKAGE_PATH = "com.soecode.lyf.web"; private final static String API_PATH = "C:\\Users\\Administrator\\Desktop\\doc"; private final static String API_TEMPLATE = "**简要描述:** \n" + "\n" + "- {0}\n" + "\n" + "**请求URL:** \n" + "- {1}\n" + " \n" + "**请求方式:**\n" + "- {2}\n" + "\n" + "**参数:** \n" + "\n" + "|参数名|必选|类型|说明|\n" + "|:---- |:---|:----- |----- |\n" + "{3}\n" + "\n" + " **返回参数说明** \n" + "\n" + "|参数名|类型|说明|\n" + "|:----- |:-----|----- |\n" + "{4}"; private final static String URI = "http://xxx.com"; public static void main(String[] args) { List<Class<?>> classList = getClasses(PACKAGE_PATH); List<ClassType> classTypeList = new ArrayList<>(); for(Class classes:classList){ if(!(classes.isAnnotationPresent(Controller.class) || classes.isAnnotationPresent(RestController.class))){ //只包含controller的类 continue; } ClassType classType = new ClassType(); //获取contaoller的path if(classes.isAnnotationPresent(RequestMapping.class)){ RequestMapping requestMapping = (RequestMapping)classes.getAnnotation(RequestMapping.class); classType.setPath(requestMapping.value() == null || requestMapping.value().length == 0 ? null : requestMapping.value()[0]); } //获取所有方法 Method[] methods = classes.getDeclaredMethods(); List<MethodType> methodTypeList = new ArrayList<>(); for(Method method:methods){ if(!(method.isAnnotationPresent(RequestMapping.class) || method.isAnnotationPresent(GetMapping.class) || method.isAnnotationPresent(PostMapping.class))){ continue; } MethodType methodType = new MethodType(); if(method.isAnnotationPresent(RequestMapping.class)){ RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); //path methodType.setPath(requestMapping.value() == null || requestMapping.value().length == 0 ? null : requestMapping.value()[0]); //requestMethods if(requestMapping.method() != null && requestMapping.method().length > 0){ methodType.setRequestMethods(requestMapping.method()); } }else if(method.isAnnotationPresent(GetMapping.class)){ GetMapping getMapping = method.getAnnotation(GetMapping.class); //path methodType.setPath(getMapping.value() == null || getMapping.value().length == 0 ? null : getMapping.value()[0]); //requestMethods methodType.setRequestMethods(new RequestMethod[]{RequestMethod.GET}); }else if(method.isAnnotationPresent(PostMapping.class)){ PostMapping postMapping = method.getAnnotation(PostMapping.class); //path methodType.setPath(postMapping.value() == null || postMapping.value().length == 0 ? null : postMapping.value()[0]); //requestMethods methodType.setRequestMethods(new RequestMethod[]{RequestMethod.POST}); } // common if(method.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = method.getAnnotation(DocAnnotation.class); methodType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); } //reqList List<ParamType> paramTypeReqList = new ArrayList<>(); Parameter[] parameters = method.getParameters(); for(Parameter parameter:parameters){ if(isJavaClass(parameter.getType())){ if(isClassCollection(parameter.getType())){ //java集合 if(parameter.getType().getName().contains("List")) { //只考虑List if(parameter.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = parameter.getAnnotation(DocAnnotation.class); ParamType paramType = new ParamType(); paramType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(StringUtils.isEmpty(docAnnotation.name()) ? parameter.getName() : docAnnotation.name()); paramType.setParamType(getSimpleType(parameter.getType().getTypeName())); if(!(parameter.getParameterizedType() instanceof ParameterizedType)){ continue; } Class cls = (Class) ((ParameterizedType)parameter.getParameterizedType()).getActualTypeArguments()[0]; List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:cls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); paramTypeReqList.add(paramType); } } }else{ //java 常用基本类型 if(parameter.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = parameter.getAnnotation(DocAnnotation.class); ParamType paramType = new ParamType(); paramType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(StringUtils.isEmpty(docAnnotation.name()) ? parameter.getName() : docAnnotation.name()); paramType.setParamType(getSimpleType(parameter.getParameterizedType().getTypeName())); paramTypeReqList.add(paramType); } } }else{ //自定义类型不需要写DocAnnoation Class cls = parameter.getType(); List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:cls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramTypeReqList.addAll(paramTypeList); } } methodType.setReqList(paramTypeReqList); //方法设置请求参数列表 //respList List<ParamType> paramTypeResqList = new ArrayList<>(); Field[] fields = method.getReturnType().getDeclaredFields(); //参数类型 String clsPath = ((ParameterizedType)(method.getGenericReturnType())).getActualTypeArguments()[0].getTypeName(); Class tCls = null; boolean isCollection = false; if(clsPath.contains("java.util.List")){ //集合 tCls = (Class)((ParameterizedType)((ParameterizedType)method.getAnnotatedReturnType().getType()).getActualTypeArguments()[0]).getActualTypeArguments()[0]; isCollection = true; }else{ tCls = (Class)((ParameterizedType)(method.getAnnotatedReturnType().getType())).getActualTypeArguments()[0]; //参数中泛型类型 } for(Field field:fields){ if(field.isAnnotationPresent(DocAnnotation.class)){ //只有泛型数据才需要兼容,其他走正常情况 ParamType paramType = null; if("data".equals(field.getName())){ //泛型 paramType = setSubClass(field,tCls,isCollection); }else{ paramType = setSubClass(field,null,false); } if(paramType != null){ paramTypeResqList.add(paramType); } } } methodType.setRespList(paramTypeResqList); //方法设置请求参数列表 methodTypeList.add(methodType); //设置方法列表 } classType.setMethodTypeList(methodTypeList); //设置方法对象 classTypeList.add(classType); //设置类对象 } System.out.println(JSON.toJSONString(classTypeList)); //生成文档 File file = new File(API_PATH); deleteFile(file); file.mkdir(); for(ClassType classType:classTypeList){ for(MethodType methodType:classType.getMethodTypeList()){ String apiDesc = methodType.getCommon() == null ? "" : methodType.getCommon(); String path = getPath(classType.getPath(),methodType.getPath()); String reqMethod = Arrays.toString(methodType.requestMethods); StringBuilder reqStr = new StringBuilder(""); generateParamStr(reqStr,methodType.getReqList(),""); StringBuilder resqStr = new StringBuilder(""); generateParamStr(resqStr,methodType.getRespList(),""); String apiDoc = MessageFormat.format(API_TEMPLATE,new Object[]{apiDesc,path,reqMethod,reqStr.toString(),resqStr.toString()}); writeFile(API_PATH, methodType.path.replace("/",".") + ".txt",apiDoc); } } } private static void writeFile(String path,String fileName,String content){ PrintWriter pw = null; try { pw = new PrintWriter(new FileOutputStream(API_PATH + File.separatorChar + fileName)); pw.print(content); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if(pw != null){ try { pw.close(); } catch (Exception e) { e.printStackTrace(); } } } } private static void deleteFile(File file){ if(file == null){ return; } if(file.isFile()){ file.delete(); return; } for(File tFile:file.listFiles()){ if(tFile.isDirectory()){ deleteFile(tFile); } tFile.delete(); } file.delete(); } private static void generateParamStr(StringBuilder strBul,List<ParamType> paramTypeList,String splitChar){ if(paramTypeList == null || paramTypeList.size() == 0){ return; } for(ParamType paramType:paramTypeList){ strBul.append("|").append(splitChar).append(paramType.getParamName()).append("|") .append(paramType.isFill() ? "是":"否").append("|").append(paramType.getParamType()) .append("|").append(paramType.getParamName()).append("|").append("\n"); if(paramType.getSubParamType() != null){ generateParamStr(strBul,paramType.getSubParamType(),splitChar + " "); } } } private static String getPath(String classPath,String methodPath){ return trim(URI,'/') + "/" + trim(classPath,'/') + '/' + trim(methodPath,'/'); } private static String trim(String str,char ch){ if(str == null){ return str; } if(str.startsWith(ch + "")){ str = str.substring(1); } if(str.endsWith(ch + "")){ str = str.substring(0,str.length() - 1); } return str; } /** * 如果不是java类型,设置子类型 * @param field 域对象,这里如果是泛型,field是object * @param genericCls 如果是泛型,需要传Class对象 * @param isCollection 是否是泛型集合 * @return */ private static ParamType setSubClass(Field field,Class genericCls,boolean isCollection){ if(!field.isAnnotationPresent(DocAnnotation.class)){ return null; } ParamType paramType = new ParamType(); if(genericCls == null){ if(isJavaClass(field.getType())){ //java类型 if(isClassCollection(field.getType())){ //java集合, if(field.getType().getName().contains("List")){ //只考虑List if(field.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(field.getType().getName())); //Class cls = field.getGenericType().getTypeName().getClass(); if(field.getGenericType() instanceof ParameterizedType){ Class cls = (Class) ((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]; List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:cls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); } } } }else{ //java 常用基本类型 if(field.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(field.getType().getName())); } } }else{ //自定义对象 if(field.isAnnotationPresent(DocAnnotation.class)){ DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(field.getType().getName())); Class cls = field.getType(); List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:cls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); } } }else{ //针对泛型类做兼容 if(isCollection){ if(isJavaClass(genericCls)){ //是java基本类型 DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType("List"); }else{ //自定义类型 DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType("List"); List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:genericCls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); } }else{ //不是集合 DocAnnotation docAnnotation = field.getAnnotation(DocAnnotation.class); paramType.setCommon(docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(genericCls.getName())); List<ParamType> paramTypeList = new ArrayList<>(); for(Field tField:genericCls.getDeclaredFields()){ ParamType subPparamType = setSubClass(tField,null,false); if(subPparamType != null){ paramTypeList.add(subPparamType); } } paramType.setSubParamType(paramTypeList); } } return paramType; } /*private static void setParamType(List<ParamType> paramTypeReqList, DocAnnotation docAnnotation,Parameter parameter) { ParamType paramType = new ParamType(); paramType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(StringUtils.isEmpty(docAnnotation.name()) ? parameter.getName() : docAnnotation.name()); paramType.setParamType(getSimpleType(parameter.getParameterizedType().getTypeName())); paramTypeReqList.add(paramType); } private static ParamType setParamType(List<ParamType> paramTypeReqList, DocAnnotation docAnnotation,Field field) { ParamType paramType = new ParamType(); paramType.setCommon(StringUtils.isEmpty(docAnnotation.comment()) ? null : docAnnotation.comment()); paramType.setFill(docAnnotation.isFill()); paramType.setParamName(field.getName()); paramType.setParamType(getSimpleType(field.getType().getTypeName())); paramTypeReqList.add(paramType); return paramType; }*/ public static String getSimpleType(String path){ if(StringUtils.isEmpty(path)){ return path; } Pattern pattern = Pattern.compile("^.*(\\.)(\\w+)$"); Matcher matcher = pattern.matcher(path); if(matcher.find()){ return matcher.group(2); }else{ return path; } } /* public static void main(String[] args) { System.out.println(getSimpleType("java.lang.String")); System.out.println(getSimpleType("String")); System.out.println(getSimpleType(null)); System.out.println(getSimpleType(".Integer")); }*/ public static boolean isJavaClass(Class<?> clz) { return clz != null && clz.getClassLoader() == null; } public static boolean isClassCollection(Class c) { return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c); } public static List<Class<?>> getClasses(String packageName){ //第一个class类的集合 List<Class<?>> classes = new ArrayList<Class<?>>(); //是否循环迭代 boolean recursive = true; //获取包的名字 并进行替换 String packageDirName = packageName.replace('.', '/'); //定义一个枚举的集合 并进行循环来处理这个目录下的things Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); //循环迭代下去 while (dirs.hasMoreElements()){ //获取下一个元素 URL url = dirs.nextElement(); //得到协议的名称 String protocol = url.getProtocol(); //如果是以文件的形式保存在服务器上 if ("file".equals(protocol)) { //获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); //以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)){ //如果是jar包文件 //定义一个JarFile JarFile jar; try { //获取jar jar = ((JarURLConnection) url.openConnection()).getJarFile(); //从此jar包 得到一个枚举类 Enumeration<JarEntry> entries = jar.entries(); //同样的进行循环迭代 while (entries.hasMoreElements()) { //获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); //如果是以/开头的 if (name.charAt(0) == '/') { //获取后面的字符串 name = name.substring(1); } //如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); //如果以"/"结尾 是一个包 if (idx != -1) { //获取包名 把"/"替换成"." packageName = name.substring(0, idx).replace('/', '.'); } //如果可以迭代下去 并且是一个包 if ((idx != -1) || recursive){ //如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { //去掉后面的".class" 获取真正的类名 String className = name.substring(packageName.length() + 1, name.length() - 6); try { //添加到classes classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } } } catch (IOException e) { e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } /** * 以文件的形式来获取包下的所有Class * @param packageName * @param packagePath * @param recursive * @param classes */ public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes){ //获取此包的目录 建立一个File File dir = new File(packagePath); //如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { return; } //如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { //自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); //循环所有文件 for (File file : dirfiles) { //如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { //如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { //添加到集合中去 classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } }
30,432
0.518554
0.517315
669
42.421524
34.448704
345
false
false
0
0
0
0
0
0
0.560538
false
false
2
11b8a542cc68876c2de47b4aed36645f124d4499
20,409,684,591,787
fe02b692a3bada4b3218053a87bd7ac30247d37b
/src/main/java/com/ditbit/kyu6/detectpangram/PangramChecker.java
75d21f346b03ac970f00bba11918cceb9231b402
[]
no_license
LotharSattler/codewars
https://github.com/LotharSattler/codewars
5e3b99e692aff28ca59581323558e059980efa01
b788fc565578d7e7e22eaf6f6025475887cc3d30
refs/heads/master
2018-12-22T02:05:21.896000
2018-12-09T10:48:50
2018-12-09T10:48:50
104,702,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ditbit.kyu6.detectpangram; import java.util.Arrays; import java.util.HashSet; /* * https://www.codewars.com/kata/detect-pangram */ public class PangramChecker { public boolean check(String sentence) { sentence = sentence.toLowerCase().replaceAll("[^a-z]", ""); return new HashSet<>(Arrays.asList(sentence.split(""))).size() == 26; } }
UTF-8
Java
376
java
PangramChecker.java
Java
[]
null
[]
package com.ditbit.kyu6.detectpangram; import java.util.Arrays; import java.util.HashSet; /* * https://www.codewars.com/kata/detect-pangram */ public class PangramChecker { public boolean check(String sentence) { sentence = sentence.toLowerCase().replaceAll("[^a-z]", ""); return new HashSet<>(Arrays.asList(sentence.split(""))).size() == 26; } }
376
0.672872
0.664894
15
24.066668
24.917107
77
false
false
0
0
0
0
0
0
0.4
false
false
2
6c11bdb392155583fb1f70c3e8632ffb131ff1c4
9,698,036,156,514
7aab677906dcd295125e32993a49b5c462ea63ee
/app/src/main/java/com/eca/hpcmobile/HinosKimbundoActivity.java
8e583505dc1907351a051f663756ed80ce2b9c7b
[]
no_license
BabaluECA/HPCMobile
https://github.com/BabaluECA/HPCMobile
8fdf8d924377b6b6e6dfea9580c14ea4655cbfa9
367610da3e1d8de6359d9ba7a0c21f2fef6d6f6d
refs/heads/master
2022-12-17T14:19:23.665000
2020-09-21T01:24:44
2020-09-21T01:24:44
297,195,452
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eca.hpcmobile; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class HinosKimbundoActivity extends AppCompatActivity { String [] hinos_kb_num_titulos, hinos_kb_conteudos; private ListView lvHinosKimbundo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hinos_kimbundo); lvHinosKimbundo = findViewById(R.id.lvHinosKimbundo); hinos_kb_num_titulos = getResources().getStringArray(R.array.hinos_kb_num_titulos); hinos_kb_conteudos = getResources().getStringArray(R.array.hinos_kb_conteudos); MyAdapter adapter = new MyAdapter(this, hinos_kb_num_titulos); lvHinosKimbundo.setAdapter(adapter); lvHinosKimbundo.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(HinosKimbundoActivity.this,GetHinoActivity.class); i.putExtra("tituloIndex",hinos_kb_num_titulos[position]); i.putExtra("hinoIndex", hinos_kb_conteudos[position]); startActivity(i); } }); } class MyAdapter extends ArrayAdapter<String> { Context context; String hinosKb[]; MyAdapter (Context c, String numTitulo[]){ super(c, R.layout.row, R.id.tvTitulo, numTitulo); this.context = c; this.hinosKb = numTitulo; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(context.LAYOUT_INFLATER_SERVICE); View row = layoutInflater.inflate(R.layout.row, parent, false); TextView tituloF = row.findViewById(R.id.tvTitulo); tituloF.setText(hinosKb[position]); return row; } } }
UTF-8
Java
2,461
java
HinosKimbundoActivity.java
Java
[]
null
[]
package com.eca.hpcmobile; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class HinosKimbundoActivity extends AppCompatActivity { String [] hinos_kb_num_titulos, hinos_kb_conteudos; private ListView lvHinosKimbundo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hinos_kimbundo); lvHinosKimbundo = findViewById(R.id.lvHinosKimbundo); hinos_kb_num_titulos = getResources().getStringArray(R.array.hinos_kb_num_titulos); hinos_kb_conteudos = getResources().getStringArray(R.array.hinos_kb_conteudos); MyAdapter adapter = new MyAdapter(this, hinos_kb_num_titulos); lvHinosKimbundo.setAdapter(adapter); lvHinosKimbundo.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(HinosKimbundoActivity.this,GetHinoActivity.class); i.putExtra("tituloIndex",hinos_kb_num_titulos[position]); i.putExtra("hinoIndex", hinos_kb_conteudos[position]); startActivity(i); } }); } class MyAdapter extends ArrayAdapter<String> { Context context; String hinosKb[]; MyAdapter (Context c, String numTitulo[]){ super(c, R.layout.row, R.id.tvTitulo, numTitulo); this.context = c; this.hinosKb = numTitulo; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(context.LAYOUT_INFLATER_SERVICE); View row = layoutInflater.inflate(R.layout.row, parent, false); TextView tituloF = row.findViewById(R.id.tvTitulo); tituloF.setText(hinosKb[position]); return row; } } }
2,461
0.688338
0.688338
66
36.28788
30.147499
134
false
false
0
0
0
0
0
0
0.818182
false
false
2
5ef182103d336665a184c5613a103fecd39dc696
26,637,387,186,597
c164d8f1a6068b871372bae8262609fd279d774c
/src/main/java/edu/uiowa/slis/VIVOISF/Country/CountryNameCurrencyZH.java
60561c1eada2f6e96d6d30d87523b0ce3b2abc76
[ "Apache-2.0" ]
permissive
eichmann/VIVOISF
https://github.com/eichmann/VIVOISF
ad0a299df177d303ec851ff2453cbcbd7cae1ef8
e80cd8b74915974fac7ebae8e5e7be8615355262
refs/heads/master
2020-03-19T03:44:27.662000
2018-06-03T22:44:58
2018-06-03T22:44:58
135,757,275
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.uiowa.slis.VIVOISF.Country; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; @SuppressWarnings("serial") public class CountryNameCurrencyZH extends edu.uiowa.slis.VIVOISF.TagLibSupport { static CountryNameCurrencyZH currentInstance = null; private static final Log log = LogFactory.getLog(CountryNameCurrencyZH.class); // non-functional property public int doStartTag() throws JspException { try { CountryNameCurrencyZHIterator theCountry = (CountryNameCurrencyZHIterator)findAncestorWithClass(this, CountryNameCurrencyZHIterator.class); pageContext.getOut().print(theCountry.getNameCurrencyZH()); } catch (Exception e) { log.error("Can't find enclosing Country for nameCurrencyZH tag ", e); throw new JspTagException("Error: Can't find enclosing Country for nameCurrencyZH tag "); } return SKIP_BODY; } }
UTF-8
Java
966
java
CountryNameCurrencyZH.java
Java
[]
null
[]
package edu.uiowa.slis.VIVOISF.Country; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; @SuppressWarnings("serial") public class CountryNameCurrencyZH extends edu.uiowa.slis.VIVOISF.TagLibSupport { static CountryNameCurrencyZH currentInstance = null; private static final Log log = LogFactory.getLog(CountryNameCurrencyZH.class); // non-functional property public int doStartTag() throws JspException { try { CountryNameCurrencyZHIterator theCountry = (CountryNameCurrencyZHIterator)findAncestorWithClass(this, CountryNameCurrencyZHIterator.class); pageContext.getOut().print(theCountry.getNameCurrencyZH()); } catch (Exception e) { log.error("Can't find enclosing Country for nameCurrencyZH tag ", e); throw new JspTagException("Error: Can't find enclosing Country for nameCurrencyZH tag "); } return SKIP_BODY; } }
966
0.796066
0.796066
26
36.115383
35.133072
142
false
false
0
0
0
0
0
0
1.5
false
false
2
8a66f7288014dc46fd8497a33fc4b3e5b7da253a
22,582,938,083,780
412af1933fe33e23c03f09e6f660a30fa0fa2b80
/RestAssured/src/test/java/com/api/testcases/GetEmployeeTest.java
e00a5003c4e789d927d0f5e54b090c6cef6aac3e
[]
no_license
puneetverma0711/Aautomation
https://github.com/puneetverma0711/Aautomation
a034cabb473cf00b4a61ce482a4a67e39051f3cf
56c51fb5ecef312cadaad273c99d7415da77af41
refs/heads/master
2022-07-14T17:28:17.353000
2020-04-03T14:05:38
2020-04-03T14:05:38
238,189,894
0
0
null
false
2022-06-29T17:57:05
2020-02-04T11:26:57
2020-04-03T14:05:47
2022-06-29T17:57:03
11,914
0
0
1
HTML
false
false
package com.api.testcases; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.api.base.ApiBase; import io.restassured.http.Method; public class GetEmployeeTest extends ApiBase { public static String employeedata; @BeforeMethod public void sendrequest() { setup(); ApiBase.response=ApiBase.httprequest.request(Method.GET, "/employees"); } @Test public void getAllEmployees() { employeedata=ApiBase.response.getBody().asString(); System.out.println(employeedata); } }
UTF-8
Java
556
java
GetEmployeeTest.java
Java
[]
null
[]
package com.api.testcases; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.api.base.ApiBase; import io.restassured.http.Method; public class GetEmployeeTest extends ApiBase { public static String employeedata; @BeforeMethod public void sendrequest() { setup(); ApiBase.response=ApiBase.httprequest.request(Method.GET, "/employees"); } @Test public void getAllEmployees() { employeedata=ApiBase.response.getBody().asString(); System.out.println(employeedata); } }
556
0.732014
0.732014
35
14.885715
19.180006
72
false
false
0
0
0
0
0
0
0.971429
false
false
2
10ac25c0d9a0c1674cc36ee01d3b2eb0ccbd24bc
16,827,681,865,744
b7613eaac85fab720dc3d027b9a96e7212415b10
/Java1/BancoZeressemos/ProjetoBancoZeressemos/src/conta/GeradorDeContas.java
4dee9a1406b5119401f3c3ad0c1250c57c056b97
[]
no_license
M4G1Ck/serraTec2021
https://github.com/M4G1Ck/serraTec2021
906bb6e3a37a41968bcdd3dc4f660d444fa42478
dc81171bbf33ed84ceaef0239dc17b479edb3249
refs/heads/main
2023-06-03T16:12:38.430000
2021-06-17T14:51:36
2021-06-17T14:51:36
371,804,696
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package conta; import javax.swing.JOptionPane; public class GeradorDeContas extends Conta { pulblic GeradorDeContas (String titular, int numero, int agencia, String tipo, int cpfTitular){ super(); // TODO Auto-generated constructor stub } public Conta criaConta() { String entradaTeclado; int saidaTeclado; entradaTeclado = JOptionPane.showInputDialog("\nDigite:\n1 - Para nova conta \n" + "0 - Para encerrar"); saidaTeclado = Integer.parseInt(entradaTeclado); if (saidaTeclado == 1) { entradaTeclado = JOptionPane .showInputDialog("Digite:\n1 - Para conta corrente\n" + "2 - Para conta poupança"); saidaTeclado = Integer.parseInt(entradaTeclado); if (saidaTeclado == 1) { return new ContaCorrente(); } else if (saidaTeclado == 2) { return new ContaPoupanca(); } else { System.out.println("Valor inválido"); } } if (saidaTeclado == 0) { System.out.println("Saiu"); } else { System.out.println("Valor digitado inválido"); } return null; } @Override public void consultaTipo() { } @Override public double seguroDeVida(double valor) { return 0; } }
UTF-8
Java
1,208
java
GeradorDeContas.java
Java
[]
null
[]
package conta; import javax.swing.JOptionPane; public class GeradorDeContas extends Conta { pulblic GeradorDeContas (String titular, int numero, int agencia, String tipo, int cpfTitular){ super(); // TODO Auto-generated constructor stub } public Conta criaConta() { String entradaTeclado; int saidaTeclado; entradaTeclado = JOptionPane.showInputDialog("\nDigite:\n1 - Para nova conta \n" + "0 - Para encerrar"); saidaTeclado = Integer.parseInt(entradaTeclado); if (saidaTeclado == 1) { entradaTeclado = JOptionPane .showInputDialog("Digite:\n1 - Para conta corrente\n" + "2 - Para conta poupança"); saidaTeclado = Integer.parseInt(entradaTeclado); if (saidaTeclado == 1) { return new ContaCorrente(); } else if (saidaTeclado == 2) { return new ContaPoupanca(); } else { System.out.println("Valor inválido"); } } if (saidaTeclado == 0) { System.out.println("Saiu"); } else { System.out.println("Valor digitado inválido"); } return null; } @Override public void consultaTipo() { } @Override public double seguroDeVida(double valor) { return 0; } }
1,208
0.647303
0.639834
46
24.195652
25.123711
106
false
false
0
0
0
0
0
0
1.956522
false
false
2
b5d5476d8518c96d5a86d8ac223acbb59fcb5c74
12,068,858,111,158
5825fbb7a4bc465100955d64fe6c8cc52b7e3a67
/parent/core/src/test/java/net/sf/jguiraffe/gui/builder/components/tags/TestTransformerTag.java
325daf8a2a1f736928bc79faf0a6bde243563bff
[ "Apache-2.0" ]
permissive
oheger/jguiraffe
https://github.com/oheger/jguiraffe
ee801097a1b35c65424693e56939136402578aae
546b1241bc672ed2eb7257f02b5b43e91b087d48
refs/heads/master
2022-11-10T21:16:37.300000
2022-11-05T16:23:27
2022-11-05T16:23:27
157,102,785
1
0
Apache-2.0
false
2022-09-30T20:06:42
2018-11-11T17:21:51
2022-09-30T19:28:27
2022-09-30T20:06:41
35,892
1
0
0
Java
false
false
/* * Copyright 2006-2022 The JGUIraffe Team. * * 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 net.sf.jguiraffe.gui.builder.components.tags; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.HashMap; import net.sf.jguiraffe.gui.builder.components.ComponentBuilderData; import net.sf.jguiraffe.gui.builder.components.FormBuilderException; import net.sf.jguiraffe.gui.forms.DefaultTransformerWrapper; import net.sf.jguiraffe.gui.forms.FormRuntimeException; import net.sf.jguiraffe.gui.forms.TransformerContextImpl; import net.sf.jguiraffe.gui.forms.TransformerWrapper; import net.sf.jguiraffe.gui.forms.bind.BeanBindingStrategy; import net.sf.jguiraffe.transform.Transformer; import net.sf.jguiraffe.transform.TransformerContext; import org.apache.commons.jelly.JellyContext; import org.apache.commons.jelly.JellyTagException; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; /** * Test class for TransformerTag. * * @author Oliver Heger * @version $Id: TestTransformerTag.java 205 2012-01-29 18:29:57Z oheger $ */ public class TestTransformerTag { /** An input component tag used as parent. */ private InputComponentTag input; /** A test transformer that will be set. */ private Transformer transformer; /** The tag to be tested. */ private TransformerTag tag; @Before public void setUp() throws Exception { JellyContext context = new JellyContext(); tag = new TransformerTag(); tag.setContext(context); input = new TextFieldTag(); input.setContext(context); ComponentBuilderData cdata = new ComponentBuilderData(); cdata.initializeForm(new TransformerContextImpl(), new BeanBindingStrategy()); cdata.put(context); transformer = EasyMock.createMock(Transformer.class); } /** * Returns the default transformer context. * * @return the default (i.e. global) transformer context */ private TransformerContext getDefaultContext() { return ComponentBuilderData.get(tag.getContext()) .getTransformerContext(); } /** * Tests whether a correct transformer wrapper was set. * * @param wrapper the wrapper to test * @param defCtx a flag whether the default transformer context is expected */ private void checkTransformer(TransformerWrapper wrapper, boolean defCtx) { assertTrue("Wrong transformer wrapper type: " + wrapper, wrapper instanceof DefaultTransformerWrapper); DefaultTransformerWrapper tw = (DefaultTransformerWrapper) wrapper; assertEquals("Wrong wrapped transformer", transformer, tw .getTransformer()); assertEquals("Wrong context", defCtx, getDefaultContext().equals( tw.getTransformerContext())); } /** * Tests creating a transformer for type read. */ @Test public void testReadTransformer() throws JellyTagException { tag.setAttribute("type", "Read"); tag.handleInputComponentTag(input, transformer); checkTransformer(input.getReadTransformer(), true); assertNull("Write transformer was set", input.getWriteTransformer()); } /** * Tests creating a transformer for type write. */ @Test public void testWriteTransformer() throws JellyTagException { tag.setAttribute("type", "write"); tag.handleInputComponentTag(input, transformer); checkTransformer(input.getWriteTransformer(), true); assertNull("Read transformer was set", input.getReadTransformer()); } /** * Tests creating a transformer of the default type. */ @Test public void testDefaultTransformer() throws JellyTagException { tag.handleInputComponentTag(input, transformer); checkTransformer(input.getReadTransformer(), true); assertNull("Write transformer was set", input.getWriteTransformer()); } /** * Tests the behavior of the the tag if an invalid transformer type was set. */ @Test(expected = JellyTagException.class) public void testInvalidTransformer() throws JellyTagException { tag.setAttribute("type", "invalid transformer type"); tag.handleInputComponentTag(input, transformer); } /** * Tests whether properties set for the tag are taken into account. */ @Test public void testTransformerWithProperties() throws JellyTagException { tag.setProperties(new HashMap<String, Object>()); tag.handleInputComponentTag(input, transformer); checkTransformer(input.getReadTransformer(), false); } /** * Tests whether a component type is taken into account. */ @Test public void testComponentType() throws JellyTagException, FormBuilderException { tag.setAttribute("type", "WRITE"); tag.setAttribute("componentType", Integer.class.getName()); tag.handleInputComponentTag(input, transformer); assertEquals("Component type was not set", Integer.class, input .getComponentType()); } /** * Tests the transformer wrapper implementation. */ @Test public void testTransformerWrapper() throws Exception { DefaultTransformerWrapper wrapper = new DefaultTransformerWrapper( transformer, getDefaultContext()); final Object dataObj = "DataObject"; final Object transObj = "TransformedObject"; EasyMock.expect(transformer.transform(dataObj, getDefaultContext())) .andReturn(transObj); EasyMock.replay(transformer); assertEquals("Wrong transformed object", transObj, wrapper .transform(dataObj)); EasyMock.verify(transformer); } /** * Tests the transformer wrapper if the transformer throws an exception. */ @Test public void testTransformerWrapperException() throws Exception { DefaultTransformerWrapper wrapper = new DefaultTransformerWrapper( transformer, getDefaultContext()); final Object dataObj = "DataObject"; EasyMock.expect(transformer.transform(dataObj, getDefaultContext())) .andThrow(new Exception("TestException")); EasyMock.replay(transformer); try { wrapper.transform(dataObj); fail("Exception was not re-thrown!"); } catch (FormRuntimeException frex) { EasyMock.verify(transformer); } } }
UTF-8
Java
7,252
java
TestTransformerTag.java
Java
[ { "context": "**\n * Test class for TransformerTag.\n *\n * @author Oliver Heger\n * @version $Id: TestTransformerTag.java 205 2012", "end": 1627, "score": 0.9997853636741638, "start": 1615, "tag": "NAME", "value": "Oliver Heger" }, { "context": ": TestTransformerTag.java 205 2012-01-29 18:29:57Z oheger $\n */\npublic class TestTransformerTag\n{\n /** A", "end": 1700, "score": 0.9564507603645325, "start": 1694, "tag": "USERNAME", "value": "oheger" } ]
null
[]
/* * Copyright 2006-2022 The JGUIraffe Team. * * 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 net.sf.jguiraffe.gui.builder.components.tags; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.HashMap; import net.sf.jguiraffe.gui.builder.components.ComponentBuilderData; import net.sf.jguiraffe.gui.builder.components.FormBuilderException; import net.sf.jguiraffe.gui.forms.DefaultTransformerWrapper; import net.sf.jguiraffe.gui.forms.FormRuntimeException; import net.sf.jguiraffe.gui.forms.TransformerContextImpl; import net.sf.jguiraffe.gui.forms.TransformerWrapper; import net.sf.jguiraffe.gui.forms.bind.BeanBindingStrategy; import net.sf.jguiraffe.transform.Transformer; import net.sf.jguiraffe.transform.TransformerContext; import org.apache.commons.jelly.JellyContext; import org.apache.commons.jelly.JellyTagException; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; /** * Test class for TransformerTag. * * @author <NAME> * @version $Id: TestTransformerTag.java 205 2012-01-29 18:29:57Z oheger $ */ public class TestTransformerTag { /** An input component tag used as parent. */ private InputComponentTag input; /** A test transformer that will be set. */ private Transformer transformer; /** The tag to be tested. */ private TransformerTag tag; @Before public void setUp() throws Exception { JellyContext context = new JellyContext(); tag = new TransformerTag(); tag.setContext(context); input = new TextFieldTag(); input.setContext(context); ComponentBuilderData cdata = new ComponentBuilderData(); cdata.initializeForm(new TransformerContextImpl(), new BeanBindingStrategy()); cdata.put(context); transformer = EasyMock.createMock(Transformer.class); } /** * Returns the default transformer context. * * @return the default (i.e. global) transformer context */ private TransformerContext getDefaultContext() { return ComponentBuilderData.get(tag.getContext()) .getTransformerContext(); } /** * Tests whether a correct transformer wrapper was set. * * @param wrapper the wrapper to test * @param defCtx a flag whether the default transformer context is expected */ private void checkTransformer(TransformerWrapper wrapper, boolean defCtx) { assertTrue("Wrong transformer wrapper type: " + wrapper, wrapper instanceof DefaultTransformerWrapper); DefaultTransformerWrapper tw = (DefaultTransformerWrapper) wrapper; assertEquals("Wrong wrapped transformer", transformer, tw .getTransformer()); assertEquals("Wrong context", defCtx, getDefaultContext().equals( tw.getTransformerContext())); } /** * Tests creating a transformer for type read. */ @Test public void testReadTransformer() throws JellyTagException { tag.setAttribute("type", "Read"); tag.handleInputComponentTag(input, transformer); checkTransformer(input.getReadTransformer(), true); assertNull("Write transformer was set", input.getWriteTransformer()); } /** * Tests creating a transformer for type write. */ @Test public void testWriteTransformer() throws JellyTagException { tag.setAttribute("type", "write"); tag.handleInputComponentTag(input, transformer); checkTransformer(input.getWriteTransformer(), true); assertNull("Read transformer was set", input.getReadTransformer()); } /** * Tests creating a transformer of the default type. */ @Test public void testDefaultTransformer() throws JellyTagException { tag.handleInputComponentTag(input, transformer); checkTransformer(input.getReadTransformer(), true); assertNull("Write transformer was set", input.getWriteTransformer()); } /** * Tests the behavior of the the tag if an invalid transformer type was set. */ @Test(expected = JellyTagException.class) public void testInvalidTransformer() throws JellyTagException { tag.setAttribute("type", "invalid transformer type"); tag.handleInputComponentTag(input, transformer); } /** * Tests whether properties set for the tag are taken into account. */ @Test public void testTransformerWithProperties() throws JellyTagException { tag.setProperties(new HashMap<String, Object>()); tag.handleInputComponentTag(input, transformer); checkTransformer(input.getReadTransformer(), false); } /** * Tests whether a component type is taken into account. */ @Test public void testComponentType() throws JellyTagException, FormBuilderException { tag.setAttribute("type", "WRITE"); tag.setAttribute("componentType", Integer.class.getName()); tag.handleInputComponentTag(input, transformer); assertEquals("Component type was not set", Integer.class, input .getComponentType()); } /** * Tests the transformer wrapper implementation. */ @Test public void testTransformerWrapper() throws Exception { DefaultTransformerWrapper wrapper = new DefaultTransformerWrapper( transformer, getDefaultContext()); final Object dataObj = "DataObject"; final Object transObj = "TransformedObject"; EasyMock.expect(transformer.transform(dataObj, getDefaultContext())) .andReturn(transObj); EasyMock.replay(transformer); assertEquals("Wrong transformed object", transObj, wrapper .transform(dataObj)); EasyMock.verify(transformer); } /** * Tests the transformer wrapper if the transformer throws an exception. */ @Test public void testTransformerWrapperException() throws Exception { DefaultTransformerWrapper wrapper = new DefaultTransformerWrapper( transformer, getDefaultContext()); final Object dataObj = "DataObject"; EasyMock.expect(transformer.transform(dataObj, getDefaultContext())) .andThrow(new Exception("TestException")); EasyMock.replay(transformer); try { wrapper.transform(dataObj); fail("Exception was not re-thrown!"); } catch (FormRuntimeException frex) { EasyMock.verify(transformer); } } }
7,246
0.682295
0.678296
211
33.369667
26.149876
80
false
false
0
0
0
0
0
0
0.521327
false
false
2
64e5de4303a06d4b7a4885ef20c06f951c891375
17,489,106,835,595
4c0c8d1c709ff3b17079254d6c168e931023fd5e
/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java
838d471c7f5662b873246bbcbb2880a77744f131
[ "Apache-2.0" ]
permissive
alibaba/nacos
https://github.com/alibaba/nacos
b46e8f58c1dcf0314b20d3ec823aab5f8564b004
e4190a8c862f99ab3ce6e969cdd1f13703d15868
refs/heads/develop
2023-08-30T23:26:24.747000
2023-08-30T07:21:15
2023-08-30T07:21:15
137,451,403
29,642
13,818
Apache-2.0
false
2023-09-14T04:06:41
2018-06-15T06:49:27
2023-09-14T03:50:47
2023-09-14T04:06:41
54,406
27,485
12,164
248
Java
false
false
/* * * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.alibaba.nacos.client.naming.remote.http; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.client.request.HttpClientRequest; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.lang.reflect.Field; import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTP_PREFIX; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class NamingHttpClientManagerTest { @Test public void testGetInstance() { Assert.assertNotNull(NamingHttpClientManager.getInstance()); } @Test public void testGetPrefix() { Assert.assertEquals(HTTP_PREFIX, NamingHttpClientManager.getInstance().getPrefix()); } @Test public void testGetNacosRestTemplate() { Assert.assertNotNull(NamingHttpClientManager.getInstance().getNacosRestTemplate()); } @Test public void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosException, IOException { //given NamingHttpClientManager instance = NamingHttpClientManager.getInstance(); HttpClientRequest mockHttpClientRequest = Mockito.mock(HttpClientRequest.class); Field requestClient = NacosRestTemplate.class.getDeclaredField("requestClient"); requestClient.setAccessible(true); requestClient.set(instance.getNacosRestTemplate(), mockHttpClientRequest); // when NamingHttpClientManager.getInstance().shutdown(); // then verify(mockHttpClientRequest, times(1)).close(); } }
UTF-8
Java
2,352
java
NamingHttpClientManagerTest.java
Java
[]
null
[]
/* * * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.alibaba.nacos.client.naming.remote.http; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.client.request.HttpClientRequest; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; import java.lang.reflect.Field; import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTP_PREFIX; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class NamingHttpClientManagerTest { @Test public void testGetInstance() { Assert.assertNotNull(NamingHttpClientManager.getInstance()); } @Test public void testGetPrefix() { Assert.assertEquals(HTTP_PREFIX, NamingHttpClientManager.getInstance().getPrefix()); } @Test public void testGetNacosRestTemplate() { Assert.assertNotNull(NamingHttpClientManager.getInstance().getNacosRestTemplate()); } @Test public void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosException, IOException { //given NamingHttpClientManager instance = NamingHttpClientManager.getInstance(); HttpClientRequest mockHttpClientRequest = Mockito.mock(HttpClientRequest.class); Field requestClient = NacosRestTemplate.class.getDeclaredField("requestClient"); requestClient.setAccessible(true); requestClient.set(instance.getNacosRestTemplate(), mockHttpClientRequest); // when NamingHttpClientManager.getInstance().shutdown(); // then verify(mockHttpClientRequest, times(1)).close(); } }
2,352
0.735969
0.730442
68
33.60294
31.108038
113
false
false
0
0
0
0
0
0
0.485294
false
false
2
fe70113224abeb6c67976ac3d64d87388e84f02e
17,995,912,979,443
8376e7ec968f58460d67a93ee08aacb6efd3c930
/src/prediction/GeoVector.java
cd4c8e70818fd15676650839d4a10e5790ac8f4e
[]
no_license
RowanASRCResearch/AIS-Uncooperative-Tracks
https://github.com/RowanASRCResearch/AIS-Uncooperative-Tracks
ab7a08a5437170cfb2fb7d7e21e39176a73cc65d
966b40d799d8247b1adec2a8a1d9dfc699ecd516
refs/heads/dev
2020-05-22T06:42:07.188000
2016-10-11T12:39:52
2016-10-11T12:39:52
60,731,265
0
1
null
false
2016-10-10T14:59:59
2016-06-08T21:14:35
2016-10-10T13:28:55
2016-10-10T14:59:57
463
0
0
4
Java
null
null
package prediction; //import prediction.Point; /** * Created by nick Laposta on 8/23/2016, Modified by Sean Dale on 9/22/2016. */ public class GeoVector { public float latComponent; public float longComponent; public Point location; public float speed; public float vectorAngle = -1; public GeoVector(Point location, float latComponent, float longComponent) { this.location = location; this.latComponent = latComponent; this.longComponent = longComponent; this.speed = getMagnitude(); this.vectorAngle = getAngle(); } public GeoVector(Point location, float speed, int vectorAngle) { this.location = location; this.vectorAngle = vectorAngle; int count = 0; while (vectorAngle > 90) { vectorAngle -= 90; count++; } double angle = (float) (vectorAngle * (Math.PI / 180)); float x; float y; if (count % 2 == 0) { x = (float) (speed * Math.sin(angle)); y = (float) (speed * Math.cos(angle)); } else { x = (float) (speed * Math.cos(angle)); y = (float) (speed * Math.sin(angle)); } if (count > 1) { x *= -1; } if (count % 3 != 0) { y *= -1; } this.latComponent = y; this.longComponent = x; this.speed = speed; this.vectorAngle = vectorAngle; } // Vector Addition public GeoVector addVectors(GeoVector vec) { return new GeoVector(location, (latComponent + vec.getLatComponent()), (longComponent + vec.getLongComponent())); } // Gets the magnitude of the vector based upon its x and y components public float getMagnitude() { return (float) Math.sqrt(Math.pow(latComponent, 2) + Math.pow(longComponent, 2)); } // Returns the angle of the vector based upon either the x and y coordinates, or just the angle if provided public float getAngle() { if(vectorAngle < 0 ) return (float) Math.toDegrees(Math.atan(longComponent / latComponent)); else return vectorAngle; } public void setLocalAngle(float angle){ vectorAngle = angle; } public float getLatComponent() { return latComponent; } public float getLongComponent() { return longComponent; } public float getSpeed() { return speed; } public String toString() { return Float.toString(latComponent) + "," + Float.toString(longComponent); } }
UTF-8
Java
2,596
java
GeoVector.java
Java
[ { "context": "on;\n\n//import prediction.Point;\n\n/**\n * Created by nick Laposta on 8/23/2016, Modified by Sean Dale on 9/22/2016.", "end": 79, "score": 0.999851405620575, "start": 67, "tag": "NAME", "value": "nick Laposta" }, { "context": " Created by nick Laposta on 8/23/2016, Modified by Sean Dale on 9/22/2016.\n */\npublic class GeoVector {\n\n p", "end": 115, "score": 0.9998918175697327, "start": 106, "tag": "NAME", "value": "Sean Dale" } ]
null
[]
package prediction; //import prediction.Point; /** * Created by <NAME> on 8/23/2016, Modified by <NAME> on 9/22/2016. */ public class GeoVector { public float latComponent; public float longComponent; public Point location; public float speed; public float vectorAngle = -1; public GeoVector(Point location, float latComponent, float longComponent) { this.location = location; this.latComponent = latComponent; this.longComponent = longComponent; this.speed = getMagnitude(); this.vectorAngle = getAngle(); } public GeoVector(Point location, float speed, int vectorAngle) { this.location = location; this.vectorAngle = vectorAngle; int count = 0; while (vectorAngle > 90) { vectorAngle -= 90; count++; } double angle = (float) (vectorAngle * (Math.PI / 180)); float x; float y; if (count % 2 == 0) { x = (float) (speed * Math.sin(angle)); y = (float) (speed * Math.cos(angle)); } else { x = (float) (speed * Math.cos(angle)); y = (float) (speed * Math.sin(angle)); } if (count > 1) { x *= -1; } if (count % 3 != 0) { y *= -1; } this.latComponent = y; this.longComponent = x; this.speed = speed; this.vectorAngle = vectorAngle; } // Vector Addition public GeoVector addVectors(GeoVector vec) { return new GeoVector(location, (latComponent + vec.getLatComponent()), (longComponent + vec.getLongComponent())); } // Gets the magnitude of the vector based upon its x and y components public float getMagnitude() { return (float) Math.sqrt(Math.pow(latComponent, 2) + Math.pow(longComponent, 2)); } // Returns the angle of the vector based upon either the x and y coordinates, or just the angle if provided public float getAngle() { if(vectorAngle < 0 ) return (float) Math.toDegrees(Math.atan(longComponent / latComponent)); else return vectorAngle; } public void setLocalAngle(float angle){ vectorAngle = angle; } public float getLatComponent() { return latComponent; } public float getLongComponent() { return longComponent; } public float getSpeed() { return speed; } public String toString() { return Float.toString(latComponent) + "," + Float.toString(longComponent); } }
2,587
0.58282
0.570108
94
26.627659
25.451658
121
false
false
0
0
0
0
0
0
0.531915
false
false
2
707b307876cb9a277d3c269804da492128cadca6
18,726,057,414,034
cfddcce35c61ccbf32dcc1734a355574ccaf2448
/chanzorClient/chanzorClient-service/src/main/java/com/chanzor/service/impl/AppVatinvoiceCertinfoClientServiceImpl.java
1409d52139ffcaf4fcc05d583166fe4cf6d45574
[]
no_license
wgy1109/BootStarp
https://github.com/wgy1109/BootStarp
43fc674a72a086fc9f8bacd7a21fdcf5f22a92c8
2422c8a722bf21f6937c7651b1bbda37e215767b
refs/heads/master
2021-01-20T15:10:55.215000
2018-08-17T01:51:44
2018-08-17T01:51:44
90,731,508
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chanzor.service.impl; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Service; import com.chanzor.persistence.dao.DaoSupport; import com.chanzor.entity.PageInfo; import com.chanzor.service.AppVatinvoiceCertinfoClientService; import com.chanzor.util.FormData; @Service("AppVatinvoiceCertinfoClientService") @SuppressWarnings("unchecked") public class AppVatinvoiceCertinfoClientServiceImpl implements AppVatinvoiceCertinfoClientService { @Resource(name = "daoSupport") private DaoSupport daoSupport; public List<Map<String, Object>> getAllAppVatinvoiceCertinfoByPage( PageInfo page) throws Exception { return (List<Map<String, Object>>) daoSupport .findForList( "AppVatinvoiceCertinfoClientMapper.getAllAppVatinvoiceCertinfoByPage", page); } public Map<String, Object> getAppVatinvoiceCertinfoInfoById(FormData data) throws Exception { return (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoById", data); } public Map<String, Object> getAppVatinvoiceCertinfoInfoByUserIdService( FormData data) throws Exception { return (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoByUserId", data); } // 修改保存提交的发票信息 public Map<String, Object> saveAppVatinvoiceCertinfo(FormData data, HttpSession session) throws Exception { Map<String, Object> res = new HashMap<String, Object>(); Map<String, Object> Vatinvoice = (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoByUserId", data); int i = 0; data.put("CERTINFO_STATUS", 3); data.put("vatinvoice_type", 1); data.put("CERTINFO_CREATE_TIME", new Date()); if (Vatinvoice == null || Vatinvoice.toString().equals("")) { i = (Integer) daoSupport .save("AppVatinvoiceCertinfoClientMapper.saveAppVatinvoiceCertinfoSpecial", data); } else { String status = (String) Vatinvoice.get("certinfo_status"); if ("2".equals(status) || "3".equals(status)) { data.put("id", Vatinvoice.get("id")); i = (Integer) daoSupport .update("AppVatinvoiceCertinfoClientMapper.updateAppVatinvoiceCertinfoSpecial", data); } else { res.put("code", "01"); res.put("msg", "您已提交认证,不可修改.."); return res; } } if (i > 0) { res.put("code", "00"); res.put("msg", "保存成功"); session.setAttribute("data", getAppVatinvoiceCertinfoInfoByUserIdService(data)); }else{ res.put("code", "03"); res.put("msg", "保存失败"); } return res; } public Map<String, Object> saveAppVatinvoiceCertinfoCommon(FormData data, HttpSession session) throws Exception { Map<String, Object> res = new HashMap<String, Object>(); Map<String, Object> Vatinvoice = (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoByUserId", data); int i = 0; data.put("CERTINFO_STATUS", 3); data.put("CERTINFO_CREATE_TIME", new Date()); data.put("vatinvoice_type", 0); if (Vatinvoice == null || Vatinvoice.toString().equals("")) { i = (Integer) daoSupport .save("AppVatinvoiceCertinfoClientMapper.saveAppVatinvoiceCertinfoCommon", data); } else { data.put("id", Vatinvoice.get("id")); i = (Integer) daoSupport .update("AppVatinvoiceCertinfoClientMapper.updateAppVatinvoiceCertinfoCommon", data); } if (i > 0) { res.put("code", "00"); res.put("msg", "保存成功"); session.setAttribute("data", getAppVatinvoiceCertinfoInfoByUserIdService(data)); }else{ res.put("code", "03"); res.put("msg", "保存失败"); } return res; } /** * 用户提交发票认证信息审核 * * @param data * @return * @throws Exception */ public Map<String, Object> vatinvoiceSub(FormData data) throws Exception { Map<String, Object> res = new HashMap<String, Object>(); Map<String, Object> Vatinvoice = (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoByUserId", data); if (Vatinvoice == null) { res.put("code", "01"); res.put("msg", "请先保存资料"); return res; } String status = (String) Vatinvoice.get("certinfo_status"); if ("2".equals(status) || "3".equals(status)) { int i = (Integer) daoSupport.update( "AppVatinvoiceCertinfoClientMapper.updateInvoiceStatus", data); if (i > 0) { res.put("code", "00"); res.put("msg", "提交成功.."); return res; } else { res.put("code", "02"); res.put("msg", "提交失败,请稍后重试"); } return res; } else { res.put("code", "01"); res.put("msg", "您已提交认证,不可重复提交.."); return res; } } public int deleteAppVatinvoiceCertinfo(FormData data) throws Exception { int result = (Integer) daoSupport .delete("AppVatinvoiceCertinfoClientMapper.deleteAppVatinvoiceCertinfo", data); return result; } public int updateInvoiceStatusService(FormData data) throws Exception { return (Integer) daoSupport.update( "AppVatinvoiceCertinfoClientMapper.updateInvoiceStatus", data); } // 根据用户ID 获取用户是否做了财务认证 public int selectFinanceValidateNumService(FormData data) throws Exception { return (Integer) daoSupport.findForObject( "AppVatinvoiceCertinfoClientMapper.selectFinanceValidateNum", data); } }
UTF-8
Java
5,727
java
AppVatinvoiceCertinfoClientServiceImpl.java
Java
[]
null
[]
package com.chanzor.service.impl; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Service; import com.chanzor.persistence.dao.DaoSupport; import com.chanzor.entity.PageInfo; import com.chanzor.service.AppVatinvoiceCertinfoClientService; import com.chanzor.util.FormData; @Service("AppVatinvoiceCertinfoClientService") @SuppressWarnings("unchecked") public class AppVatinvoiceCertinfoClientServiceImpl implements AppVatinvoiceCertinfoClientService { @Resource(name = "daoSupport") private DaoSupport daoSupport; public List<Map<String, Object>> getAllAppVatinvoiceCertinfoByPage( PageInfo page) throws Exception { return (List<Map<String, Object>>) daoSupport .findForList( "AppVatinvoiceCertinfoClientMapper.getAllAppVatinvoiceCertinfoByPage", page); } public Map<String, Object> getAppVatinvoiceCertinfoInfoById(FormData data) throws Exception { return (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoById", data); } public Map<String, Object> getAppVatinvoiceCertinfoInfoByUserIdService( FormData data) throws Exception { return (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoByUserId", data); } // 修改保存提交的发票信息 public Map<String, Object> saveAppVatinvoiceCertinfo(FormData data, HttpSession session) throws Exception { Map<String, Object> res = new HashMap<String, Object>(); Map<String, Object> Vatinvoice = (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoByUserId", data); int i = 0; data.put("CERTINFO_STATUS", 3); data.put("vatinvoice_type", 1); data.put("CERTINFO_CREATE_TIME", new Date()); if (Vatinvoice == null || Vatinvoice.toString().equals("")) { i = (Integer) daoSupport .save("AppVatinvoiceCertinfoClientMapper.saveAppVatinvoiceCertinfoSpecial", data); } else { String status = (String) Vatinvoice.get("certinfo_status"); if ("2".equals(status) || "3".equals(status)) { data.put("id", Vatinvoice.get("id")); i = (Integer) daoSupport .update("AppVatinvoiceCertinfoClientMapper.updateAppVatinvoiceCertinfoSpecial", data); } else { res.put("code", "01"); res.put("msg", "您已提交认证,不可修改.."); return res; } } if (i > 0) { res.put("code", "00"); res.put("msg", "保存成功"); session.setAttribute("data", getAppVatinvoiceCertinfoInfoByUserIdService(data)); }else{ res.put("code", "03"); res.put("msg", "保存失败"); } return res; } public Map<String, Object> saveAppVatinvoiceCertinfoCommon(FormData data, HttpSession session) throws Exception { Map<String, Object> res = new HashMap<String, Object>(); Map<String, Object> Vatinvoice = (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoByUserId", data); int i = 0; data.put("CERTINFO_STATUS", 3); data.put("CERTINFO_CREATE_TIME", new Date()); data.put("vatinvoice_type", 0); if (Vatinvoice == null || Vatinvoice.toString().equals("")) { i = (Integer) daoSupport .save("AppVatinvoiceCertinfoClientMapper.saveAppVatinvoiceCertinfoCommon", data); } else { data.put("id", Vatinvoice.get("id")); i = (Integer) daoSupport .update("AppVatinvoiceCertinfoClientMapper.updateAppVatinvoiceCertinfoCommon", data); } if (i > 0) { res.put("code", "00"); res.put("msg", "保存成功"); session.setAttribute("data", getAppVatinvoiceCertinfoInfoByUserIdService(data)); }else{ res.put("code", "03"); res.put("msg", "保存失败"); } return res; } /** * 用户提交发票认证信息审核 * * @param data * @return * @throws Exception */ public Map<String, Object> vatinvoiceSub(FormData data) throws Exception { Map<String, Object> res = new HashMap<String, Object>(); Map<String, Object> Vatinvoice = (Map<String, Object>) daoSupport .findForObject( "AppVatinvoiceCertinfoClientMapper.getAppVatinvoiceCertinfoInfoByUserId", data); if (Vatinvoice == null) { res.put("code", "01"); res.put("msg", "请先保存资料"); return res; } String status = (String) Vatinvoice.get("certinfo_status"); if ("2".equals(status) || "3".equals(status)) { int i = (Integer) daoSupport.update( "AppVatinvoiceCertinfoClientMapper.updateInvoiceStatus", data); if (i > 0) { res.put("code", "00"); res.put("msg", "提交成功.."); return res; } else { res.put("code", "02"); res.put("msg", "提交失败,请稍后重试"); } return res; } else { res.put("code", "01"); res.put("msg", "您已提交认证,不可重复提交.."); return res; } } public int deleteAppVatinvoiceCertinfo(FormData data) throws Exception { int result = (Integer) daoSupport .delete("AppVatinvoiceCertinfoClientMapper.deleteAppVatinvoiceCertinfo", data); return result; } public int updateInvoiceStatusService(FormData data) throws Exception { return (Integer) daoSupport.update( "AppVatinvoiceCertinfoClientMapper.updateInvoiceStatus", data); } // 根据用户ID 获取用户是否做了财务认证 public int selectFinanceValidateNumService(FormData data) throws Exception { return (Integer) daoSupport.findForObject( "AppVatinvoiceCertinfoClientMapper.selectFinanceValidateNum", data); } }
5,727
0.703523
0.697922
183
29.245901
24.313068
85
false
false
0
0
0
0
0
0
3.262295
false
false
12
55110b0f1c04a9380db4a6bbbccc225050e4fdc0
14,602,888,870,159
457cd2a730ef22ac1eb34d411ac7d636f2bb4462
/src/diamondThunder/Map/RoomAndMaze.java
51a54964de7a6046a81da01d870da497ac73697e
[]
no_license
elrolfe/DiamondThunder
https://github.com/elrolfe/DiamondThunder
136c4dd1fc6d1f345af28a506eb4f92ecf60fcd1
fcab0378470afc5af60ff250b1131198acd70e93
refs/heads/master
2020-02-28T05:38:56.334000
2017-04-11T23:13:56
2017-04-11T23:13:56
87,113,660
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package diamondThunder.Map; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import diamondThunder.RNG; public class RoomAndMaze extends Map { @Override public void width(int width) { this.width = width + (width % 2 == 1 ? 0 : 1); } @Override public void height(int height) { this.height = height + (height % 2 == 1 ? 0 : 1); } private int minRoomDimension; public int minRoomDimension() { return minRoomDimension; } public void minRoomDimension(int size) { minRoomDimension = size + (size % 2 == 1 ? 0 : 1); } private int maxRoomDimension; public int maxRoomDimension() { return maxRoomDimension; } public void maxRoomDimension(int size) { maxRoomDimension = size - (size % 2 == 1 ? 0 : 1); } private int maxRoomPlacementAttempts; public int maxRoomPlacementAttempts() { return maxRoomPlacementAttempts; } public void maxRoomPlacementAttempts(int attempts) { maxRoomPlacementAttempts = attempts; } private double windingPercentage; public double windingPercentage() { return windingPercentage; } public void windingPercentage(double percent) { windingPercentage = percent; } private double connectorPercentage; public double connectorPercentage() { return connectorPercentage; } public void connectorPercentage(double percent) { connectorPercentage = percent; } private int region; private ArrayList<Rectangle> rooms; private HashMap<String, ArrayList<Point>> connectors; public RoomAndMaze() { this(101, 101); } public RoomAndMaze(int width, int height) { this(101, 101, null); } public RoomAndMaze(int width, int height, RNG rng) { super(width + (width % 2 == 1 ? 0 : 1), height + (height % 2 == 1 ? 0 : 1), rng); minRoomDimension = 5; maxRoomDimension = 13; maxRoomPlacementAttempts = 500; windingPercentage = 0.25; connectorPercentage = 0.05; rooms = new ArrayList<Rectangle>(); connectors = new HashMap<String, ArrayList<Point>>(); } private boolean canCarve(Point cell, Point dir) { int x = (int)(dir.x * 2 + cell.x); int y = (int)(dir.y * 2 + cell.y); if (x < 0 || y < 0 || x >= width || y >= height) return false; return grid[x][y] == 0; } private RoomAndMaze carveMaze() { for (int x = 1; x < width; x += 2) { for (int y = 1; y < width; y += 2) { if (grid[x][y] == 0) this.mazeGrow(x, y); } } return this; } private RoomAndMaze connectRegions() { int newRegion = 0; ArrayList<Point> connections = null; ArrayList<Integer> connected = new ArrayList<Integer>(); connected.add(rng.randomRange(1, region - 1)); findConnectors(); region = connected.get(0); while (!connectors.isEmpty()) { Set<String> keys = connectors.keySet(); for (String key : keys) { String[] regions = key.split(":"); int region1 = Integer.parseInt(regions[0]); int region2 = Integer.parseInt(regions[1]); if (connected.contains(region1) || connected.contains(region2)) { newRegion = connected.contains(region1) ? region2 : region1; connections = new ArrayList<Point>(); for (int j = 0; j < connected.size(); j++) { String newKey = String.format("%d:%d", Math.min(newRegion, connected.get(j)), Math.max(newRegion, connected.get(j))); if (connectors.containsKey(newKey)) connections.addAll(connectors.remove(newKey)); } break; } } int totalConnections = (int)(connections.size() * connectorPercentage) + 1; for (int i = 0; i < totalConnections; i++) { Point randomConnection = connections.get(rng.randomRange(0, connections.size() - 1)); connections.remove(randomConnection); grid[(int)randomConnection.x][(int)randomConnection.y] = region; } connected.add(newRegion); } return this; } private void findConnectors() { connectors = new HashMap<String, ArrayList<Point>>(); for (int x = 1; x < width - 1; x ++) { for (int y = 1; y < height - 1; y++) { if (grid[x][y] == 0) { if (!(grid[x - 1][y] == 0 || grid[x + 1][y] == 0) && grid[x - 1][y] != grid[x + 1][y]) { int r1 = Math.min(grid[x - 1][y], grid[x + 1][y]); int r2 = Math.max(grid[x - 1][y], grid[x + 1][y]); String key = String.format("%d:%d", r1, r2); ArrayList<Point> points = connectors.get(key); if (points == null) points = new ArrayList<Point>(); points.add(new Point(x, y)); connectors.put(key, points); } if (!(grid[x][y - 1] == 0 || grid[x][y + 1] == 0) && grid[x][y - 1] != grid[x][y + 1]) { int r1 = Math.min(grid[x][y - 1], grid[x][y + 1]); int r2 = Math.max(grid[x][y - 1], grid[x][y + 1]); String key = String.format("%d:%d", r1, r2); ArrayList<Point> points = connectors.get(key); if (points == null) points = new ArrayList<Point>(); points.add(new Point(x, y)); connectors.put(key, points); } } } } } @Override public int[][] generate() { region = 1; placeRooms() .carveMaze() .connectRegions() .removeDeadEnds(); return grid; } private int getRange(int min, int max) { int range = (max - min) / 2; int rand = rng.randomRange(0, range); return rand * 2 + min; } private void mazeGrow(int x, int y) { grid[x][y] = region; Point lastDir = new Point(0, 0); Point nextDir; ArrayList<Point> cells = new ArrayList<Point>(); ArrayList<Point> uncarved = new ArrayList<Point>(); cells.add(new Point(x, y)); while (!cells.isEmpty()) { Point cell = cells.get(cells.size() - 1); uncarved.clear(); for (Point dir : directions) { if (canCarve(cell, dir)) uncarved.add(dir); } if (uncarved.size() > 0) { if (uncarved.contains(lastDir) && rng.random() > windingPercentage) nextDir = lastDir; else nextDir = uncarved.get(rng.randomRange(0, uncarved.size() - 1)); grid[(int)(nextDir.x + cell.x)][(int)(nextDir.y + cell.y)] = region; grid[(int)(nextDir.x * 2 + cell.x)][(int)(nextDir.y * 2 + cell.y)] = region; cells.add(new Point(nextDir.x * 2 + cell.x, nextDir.y * 2 + cell.y)); lastDir = nextDir; } else cells.remove(cells.size() - 1); } region++; } private RoomAndMaze placeRooms() { int attempts = maxRoomPlacementAttempts; while (attempts-- > 0) { int roomWidth = getRange(minRoomDimension, maxRoomDimension); int roomHeight = getRange(minRoomDimension, maxRoomDimension); int x = getRange(1, width - roomWidth); int y = getRange(1, height - roomHeight); boolean overlap = false; for (Rectangle room : rooms) { if (x + roomWidth < room.location.x || x > room.location.x + roomWidth) continue; if (y + roomHeight < room.location.y || y > room.location.y + roomHeight) continue; overlap = true; break; } if (!overlap) rooms.add(new Rectangle(x, y, roomWidth, roomHeight)); } for (Rectangle room : rooms) { for (int x = (int)room.location.x; x < (int)room.location.x + room.width; x++) { for (int y = (int)room.location.y; y < (int)room.location.y + room.height; y++) { grid[x][y] = region; } } region++; } return this; } private void removeDeadEnds() { boolean foundDeadEnd; do { foundDeadEnd = false; for (int x = 1; x < width - 1; x++) { for (int y = 1; y < height - 1; y++) { if (grid[x][y] != 0) { int solidNeighbors = 0; for (Point dir : directions) { if (grid[(int)dir.x + x][(int)dir.y + y] == 0) solidNeighbors++; } if (solidNeighbors == 3) { grid[x][y] = 0; foundDeadEnd = true; } } } } } while (foundDeadEnd); } }
UTF-8
Java
7,715
java
RoomAndMaze.java
Java
[ { "context": "1][y], grid[x + 1][y]);\n\t\t\t\t\t\tString key = String.format(\"%d:%d\", r1, r2);\n\t\t\t\t\t\tArrayList<Point> points =", "end": 4221, "score": 0.8689978122711182, "start": 4215, "tag": "KEY", "value": "format" }, { "context": " grid[x + 1][y]);\n\t\t\t\t\t\tString key = String.format(\"%d:%d\", r1, r2);\n\t\t\t\t\t\tArrayList<Point> points = connectors.get(", "end": 4237, "score": 0.9435067176818848, "start": 4223, "tag": "KEY", "value": "%d:%d\", r1, r2" }, { "context": " - 1], grid[x][y + 1]);\n\t\t\t\t\t\tString key = String.format(\"%d:%d\", r1, r2);\n\t\t\t\t\t\tArrayList<Point> points =", "end": 4682, "score": 0.637807309627533, "start": 4676, "tag": "KEY", "value": "format" }, { "context": " grid[x][y + 1]);\n\t\t\t\t\t\tString key = String.format(\"%d:%d\", r1, r2);\n\t\t\t\t\t\tArrayList<Point> points = connectors.get(", "end": 4698, "score": 0.8553394079208374, "start": 4684, "tag": "KEY", "value": "%d:%d\", r1, r2" } ]
null
[]
package diamondThunder.Map; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import diamondThunder.RNG; public class RoomAndMaze extends Map { @Override public void width(int width) { this.width = width + (width % 2 == 1 ? 0 : 1); } @Override public void height(int height) { this.height = height + (height % 2 == 1 ? 0 : 1); } private int minRoomDimension; public int minRoomDimension() { return minRoomDimension; } public void minRoomDimension(int size) { minRoomDimension = size + (size % 2 == 1 ? 0 : 1); } private int maxRoomDimension; public int maxRoomDimension() { return maxRoomDimension; } public void maxRoomDimension(int size) { maxRoomDimension = size - (size % 2 == 1 ? 0 : 1); } private int maxRoomPlacementAttempts; public int maxRoomPlacementAttempts() { return maxRoomPlacementAttempts; } public void maxRoomPlacementAttempts(int attempts) { maxRoomPlacementAttempts = attempts; } private double windingPercentage; public double windingPercentage() { return windingPercentage; } public void windingPercentage(double percent) { windingPercentage = percent; } private double connectorPercentage; public double connectorPercentage() { return connectorPercentage; } public void connectorPercentage(double percent) { connectorPercentage = percent; } private int region; private ArrayList<Rectangle> rooms; private HashMap<String, ArrayList<Point>> connectors; public RoomAndMaze() { this(101, 101); } public RoomAndMaze(int width, int height) { this(101, 101, null); } public RoomAndMaze(int width, int height, RNG rng) { super(width + (width % 2 == 1 ? 0 : 1), height + (height % 2 == 1 ? 0 : 1), rng); minRoomDimension = 5; maxRoomDimension = 13; maxRoomPlacementAttempts = 500; windingPercentage = 0.25; connectorPercentage = 0.05; rooms = new ArrayList<Rectangle>(); connectors = new HashMap<String, ArrayList<Point>>(); } private boolean canCarve(Point cell, Point dir) { int x = (int)(dir.x * 2 + cell.x); int y = (int)(dir.y * 2 + cell.y); if (x < 0 || y < 0 || x >= width || y >= height) return false; return grid[x][y] == 0; } private RoomAndMaze carveMaze() { for (int x = 1; x < width; x += 2) { for (int y = 1; y < width; y += 2) { if (grid[x][y] == 0) this.mazeGrow(x, y); } } return this; } private RoomAndMaze connectRegions() { int newRegion = 0; ArrayList<Point> connections = null; ArrayList<Integer> connected = new ArrayList<Integer>(); connected.add(rng.randomRange(1, region - 1)); findConnectors(); region = connected.get(0); while (!connectors.isEmpty()) { Set<String> keys = connectors.keySet(); for (String key : keys) { String[] regions = key.split(":"); int region1 = Integer.parseInt(regions[0]); int region2 = Integer.parseInt(regions[1]); if (connected.contains(region1) || connected.contains(region2)) { newRegion = connected.contains(region1) ? region2 : region1; connections = new ArrayList<Point>(); for (int j = 0; j < connected.size(); j++) { String newKey = String.format("%d:%d", Math.min(newRegion, connected.get(j)), Math.max(newRegion, connected.get(j))); if (connectors.containsKey(newKey)) connections.addAll(connectors.remove(newKey)); } break; } } int totalConnections = (int)(connections.size() * connectorPercentage) + 1; for (int i = 0; i < totalConnections; i++) { Point randomConnection = connections.get(rng.randomRange(0, connections.size() - 1)); connections.remove(randomConnection); grid[(int)randomConnection.x][(int)randomConnection.y] = region; } connected.add(newRegion); } return this; } private void findConnectors() { connectors = new HashMap<String, ArrayList<Point>>(); for (int x = 1; x < width - 1; x ++) { for (int y = 1; y < height - 1; y++) { if (grid[x][y] == 0) { if (!(grid[x - 1][y] == 0 || grid[x + 1][y] == 0) && grid[x - 1][y] != grid[x + 1][y]) { int r1 = Math.min(grid[x - 1][y], grid[x + 1][y]); int r2 = Math.max(grid[x - 1][y], grid[x + 1][y]); String key = String.format("%d:%d", r1, r2); ArrayList<Point> points = connectors.get(key); if (points == null) points = new ArrayList<Point>(); points.add(new Point(x, y)); connectors.put(key, points); } if (!(grid[x][y - 1] == 0 || grid[x][y + 1] == 0) && grid[x][y - 1] != grid[x][y + 1]) { int r1 = Math.min(grid[x][y - 1], grid[x][y + 1]); int r2 = Math.max(grid[x][y - 1], grid[x][y + 1]); String key = String.format("%d:%d", r1, r2); ArrayList<Point> points = connectors.get(key); if (points == null) points = new ArrayList<Point>(); points.add(new Point(x, y)); connectors.put(key, points); } } } } } @Override public int[][] generate() { region = 1; placeRooms() .carveMaze() .connectRegions() .removeDeadEnds(); return grid; } private int getRange(int min, int max) { int range = (max - min) / 2; int rand = rng.randomRange(0, range); return rand * 2 + min; } private void mazeGrow(int x, int y) { grid[x][y] = region; Point lastDir = new Point(0, 0); Point nextDir; ArrayList<Point> cells = new ArrayList<Point>(); ArrayList<Point> uncarved = new ArrayList<Point>(); cells.add(new Point(x, y)); while (!cells.isEmpty()) { Point cell = cells.get(cells.size() - 1); uncarved.clear(); for (Point dir : directions) { if (canCarve(cell, dir)) uncarved.add(dir); } if (uncarved.size() > 0) { if (uncarved.contains(lastDir) && rng.random() > windingPercentage) nextDir = lastDir; else nextDir = uncarved.get(rng.randomRange(0, uncarved.size() - 1)); grid[(int)(nextDir.x + cell.x)][(int)(nextDir.y + cell.y)] = region; grid[(int)(nextDir.x * 2 + cell.x)][(int)(nextDir.y * 2 + cell.y)] = region; cells.add(new Point(nextDir.x * 2 + cell.x, nextDir.y * 2 + cell.y)); lastDir = nextDir; } else cells.remove(cells.size() - 1); } region++; } private RoomAndMaze placeRooms() { int attempts = maxRoomPlacementAttempts; while (attempts-- > 0) { int roomWidth = getRange(minRoomDimension, maxRoomDimension); int roomHeight = getRange(minRoomDimension, maxRoomDimension); int x = getRange(1, width - roomWidth); int y = getRange(1, height - roomHeight); boolean overlap = false; for (Rectangle room : rooms) { if (x + roomWidth < room.location.x || x > room.location.x + roomWidth) continue; if (y + roomHeight < room.location.y || y > room.location.y + roomHeight) continue; overlap = true; break; } if (!overlap) rooms.add(new Rectangle(x, y, roomWidth, roomHeight)); } for (Rectangle room : rooms) { for (int x = (int)room.location.x; x < (int)room.location.x + room.width; x++) { for (int y = (int)room.location.y; y < (int)room.location.y + room.height; y++) { grid[x][y] = region; } } region++; } return this; } private void removeDeadEnds() { boolean foundDeadEnd; do { foundDeadEnd = false; for (int x = 1; x < width - 1; x++) { for (int y = 1; y < height - 1; y++) { if (grid[x][y] != 0) { int solidNeighbors = 0; for (Point dir : directions) { if (grid[(int)dir.x + x][(int)dir.y + y] == 0) solidNeighbors++; } if (solidNeighbors == 3) { grid[x][y] = 0; foundDeadEnd = true; } } } } } while (foundDeadEnd); } }
7,715
0.606481
0.588853
275
27.054546
24.134033
94
false
false
0
0
0
0
0
0
3.552727
false
false
12
2b8e9fcc30175bd8d307e7824261c89429ff5719
32,409,823,278,542
cd03e615ae14981876bb4ce47cf71b9ad6df3b33
/src/test/java/htw/prog3/ui/cli/control/UpdateStateTest.java
8d46ef1689ea5e81783ad847df3e9b3c391506e3
[]
no_license
jdsee/CargoDepot
https://github.com/jdsee/CargoDepot
fe502b235709072b4141f7d161871ea6952185f7
87e0b4653fb3da11c9a4e3d2264418860b2bdfdb
refs/heads/master
2022-12-05T02:23:15.509000
2020-08-25T18:10:56
2020-08-25T18:10:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package htw.prog3.ui.cli.control; import htw.prog3.routing.error.InputFailureMessages; import htw.prog3.routing.input.update.inspect.InspectCargoEvent; import htw.prog3.ui.cli.control.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; @SuppressWarnings("ResultOfMethodCallIgnored") class UpdateStateTest { @Mock CommandLineReader mockContext; @Captor ArgumentCaptor<InspectCargoEvent> inspectCargoEventCaptor; @Captor ArgumentCaptor<String> stringCaptor; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void factoryMethod_shouldAlwaysReturnSameInstance() { UpdateState state = UpdateState.getInstance(); UpdateState other = UpdateState.getInstance(); assertThat(state) .isNotNull() .isSameAs(other); } @Test void utilizeCmd_shouldFireInspectCargoEventOnDigitInput() { UpdateState state = UpdateState.getInstance(); state.utilizeCmd("123", mockContext); verify(mockContext).fireInspectCargoEvent(inspectCargoEventCaptor.capture()); assertThat(inspectCargoEventCaptor.getValue().getStoragePosition()).isEqualTo(123); } @Test void utilizeCmd_shouldFireIllegalInputEventOnTooLongDigit() { UpdateState state = UpdateState.getInstance(); state.utilizeCmd("123784957430434756546458304", mockContext); verify(mockContext).fireIllegalInputEvent(stringCaptor.capture()); assertThat(stringCaptor.getValue()).isEqualTo(InputFailureMessages.UNKNOWN_STORAGE_POSITION); } @Test void isValidCmd_shouldReturnTrueForDigits() { UpdateState state = UpdateState.getInstance(); boolean actual = state.isValidCmd("123"); assertThat(actual).isTrue(); } @Test void processCmd_shouldFireIllegalInputEventOnNonValidInput() { UpdateState state = UpdateState.getInstance(); state.processCmd("abc", mockContext); verify(mockContext).fireIllegalInputEvent(stringCaptor.capture()); assertThat(stringCaptor.getValue()).isEqualTo(InputFailureMessages.BAD_ARGUMENTS); } @Test void processCmd_shouldFireInspectCargoEventOnValidInput() { UpdateState state = UpdateState.getInstance(); state.processCmd("123", mockContext); verify(mockContext).fireInspectCargoEvent(any(InspectCargoEvent.class)); } @Test void processCmd_shouldInitiateStateChangeToCreateState() { UpdateState state = UpdateState.getInstance(); doReturn(state).when(mockContext).getActualState(); state.processCmd(":c", mockContext); verify(mockContext).setActualState(any(CreateState.class)); } @Test void processCmd_shouldInitiateStateChangeToPresentationState() { UpdateState state = UpdateState.getInstance(); doReturn(state).when(mockContext).getActualState(); state.processCmd(":r", mockContext); verify(mockContext).setActualState(any(PresentationState.class)); } @Test void processCmd_shouldInitiateStateChangeToDeleteState() { UpdateState state = UpdateState.getInstance(); doReturn(state).when(mockContext).getActualState(); state.processCmd(":d", mockContext); verify(mockContext).setActualState(any(DeleteState.class)); } @Test void processCmd_shouldFireIllegalInputEventOnUnknownStateCommand() { UpdateState state = UpdateState.getInstance(); doReturn(state).when(mockContext).getActualState(); state.processCmd(":x", mockContext); verify(mockContext).fireIllegalInputEvent(stringCaptor.capture()); assertThat(stringCaptor.getValue()).isEqualTo(InputFailureMessages.UNKNOWN_STATE); } @Test void getPromptName_shouldReturnProperName() { UpdateState state = UpdateState.getInstance(); String actual = state.getPromptName(); assertThat(actual).isEqualTo("update"); } }
UTF-8
Java
4,347
java
UpdateStateTest.java
Java
[]
null
[]
package htw.prog3.ui.cli.control; import htw.prog3.routing.error.InputFailureMessages; import htw.prog3.routing.input.update.inspect.InspectCargoEvent; import htw.prog3.ui.cli.control.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; @SuppressWarnings("ResultOfMethodCallIgnored") class UpdateStateTest { @Mock CommandLineReader mockContext; @Captor ArgumentCaptor<InspectCargoEvent> inspectCargoEventCaptor; @Captor ArgumentCaptor<String> stringCaptor; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void factoryMethod_shouldAlwaysReturnSameInstance() { UpdateState state = UpdateState.getInstance(); UpdateState other = UpdateState.getInstance(); assertThat(state) .isNotNull() .isSameAs(other); } @Test void utilizeCmd_shouldFireInspectCargoEventOnDigitInput() { UpdateState state = UpdateState.getInstance(); state.utilizeCmd("123", mockContext); verify(mockContext).fireInspectCargoEvent(inspectCargoEventCaptor.capture()); assertThat(inspectCargoEventCaptor.getValue().getStoragePosition()).isEqualTo(123); } @Test void utilizeCmd_shouldFireIllegalInputEventOnTooLongDigit() { UpdateState state = UpdateState.getInstance(); state.utilizeCmd("123784957430434756546458304", mockContext); verify(mockContext).fireIllegalInputEvent(stringCaptor.capture()); assertThat(stringCaptor.getValue()).isEqualTo(InputFailureMessages.UNKNOWN_STORAGE_POSITION); } @Test void isValidCmd_shouldReturnTrueForDigits() { UpdateState state = UpdateState.getInstance(); boolean actual = state.isValidCmd("123"); assertThat(actual).isTrue(); } @Test void processCmd_shouldFireIllegalInputEventOnNonValidInput() { UpdateState state = UpdateState.getInstance(); state.processCmd("abc", mockContext); verify(mockContext).fireIllegalInputEvent(stringCaptor.capture()); assertThat(stringCaptor.getValue()).isEqualTo(InputFailureMessages.BAD_ARGUMENTS); } @Test void processCmd_shouldFireInspectCargoEventOnValidInput() { UpdateState state = UpdateState.getInstance(); state.processCmd("123", mockContext); verify(mockContext).fireInspectCargoEvent(any(InspectCargoEvent.class)); } @Test void processCmd_shouldInitiateStateChangeToCreateState() { UpdateState state = UpdateState.getInstance(); doReturn(state).when(mockContext).getActualState(); state.processCmd(":c", mockContext); verify(mockContext).setActualState(any(CreateState.class)); } @Test void processCmd_shouldInitiateStateChangeToPresentationState() { UpdateState state = UpdateState.getInstance(); doReturn(state).when(mockContext).getActualState(); state.processCmd(":r", mockContext); verify(mockContext).setActualState(any(PresentationState.class)); } @Test void processCmd_shouldInitiateStateChangeToDeleteState() { UpdateState state = UpdateState.getInstance(); doReturn(state).when(mockContext).getActualState(); state.processCmd(":d", mockContext); verify(mockContext).setActualState(any(DeleteState.class)); } @Test void processCmd_shouldFireIllegalInputEventOnUnknownStateCommand() { UpdateState state = UpdateState.getInstance(); doReturn(state).when(mockContext).getActualState(); state.processCmd(":x", mockContext); verify(mockContext).fireIllegalInputEvent(stringCaptor.capture()); assertThat(stringCaptor.getValue()).isEqualTo(InputFailureMessages.UNKNOWN_STATE); } @Test void getPromptName_shouldReturnProperName() { UpdateState state = UpdateState.getInstance(); String actual = state.getPromptName(); assertThat(actual).isEqualTo("update"); } }
4,347
0.715666
0.705774
139
30.280575
28.063656
101
false
false
0
0
0
0
0
0
0.482014
false
false
12
b8e743b97e371440caa8d29c9760afc56fd7e0b1
27,719,718,936,766
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/10/10_32cc17f66a00f4fc9459afdd8b8d07f7fc575674/Placeholders/10_32cc17f66a00f4fc9459afdd8b8d07f7fc575674_Placeholders_t.java
09215f58d35e290377d1be6d80226ae687d12664
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.fs.impl; import java.util.Map.Entry; import java.util.Properties; final class Placeholders { private static final String PREFIX = "${"; private static final String POSTFIX = "}"; public static String replaceAll(final String value) { if(value == null || value.isEmpty()) return value; String replaced = value; Properties sysProps = System.getProperties(); for(Entry<Object, Object> prop : sysProps.entrySet()) { replaced = replaced.replace(PREFIX + prop.getKey() + POSTFIX, prop.getValue().toString()); } return replaced; } }
UTF-8
Java
1,109
java
10_32cc17f66a00f4fc9459afdd8b8d07f7fc575674_Placeholders_t.java
Java
[]
null
[]
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.fs.impl; import java.util.Map.Entry; import java.util.Properties; final class Placeholders { private static final String PREFIX = "${"; private static final String POSTFIX = "}"; public static String replaceAll(final String value) { if(value == null || value.isEmpty()) return value; String replaced = value; Properties sysProps = System.getProperties(); for(Entry<Object, Object> prop : sysProps.entrySet()) { replaced = replaced.replace(PREFIX + prop.getKey() + POSTFIX, prop.getValue().toString()); } return replaced; } }
1,109
0.587015
0.581605
30
35.933334
29.144392
96
false
false
0
0
0
0
0
0
0.5
false
false
12
b9778ee670c34b18ed8617086b2066236ef961a5
15,547,781,627,818
0f68e790aa8895fe39bc27f9331cc33929ec98be
/raw_dataset/64493253@solve@OK.java
91879986ca82e6002377856a8a71885ab81e8212
[ "MIT" ]
permissive
ruanyuan115/code2vec_treelstm
https://github.com/ruanyuan115/code2vec_treelstm
c50b784cbe2a576905c372675270e95e64908575
0c5f98d280b506317738ba603b719cac6036896f
refs/heads/master
2023-04-09T14:11:02.992000
2020-04-16T08:29:59
2020-04-16T08:29:59
256,151,081
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
static void solve() throws IOException { scan = new FastReader(); pw = new PrintWriter(System.out, true); StringBuilder sb = new StringBuilder(); int n = ni(), m = ni(); HashSet<Integer>[] adj = new HashSet[n + 1]; for (int i = 1; i <= n; ++i) { adj[i] = new HashSet<>(); } for (int i = 0; i < m; ++i) { int u = ni(), v = ni(); adj[u].add(v); adj[v].add(u); } HashSet<Integer> remaining = new HashSet<>(); for (int i = 1; i <= n; ++i) { remaining.add(i); } LinkedList<Integer> queue = new LinkedList<>(); int ans = 0; for (int i = 1; i <= n; ++i) { if (remaining.contains(i)) { ans++; queue.add(i); remaining.remove(i); while (!queue.isEmpty()) { int curr = queue.poll(); if (remaining.size() < adj[curr].size()) { ArrayList<Integer> removed = new ArrayList<>(); for (int e : remaining) { if (!adj[curr].contains(e)) { removed.add(e); } } for (int e : removed) { remaining.remove(e); queue.add(e); } } else { HashSet<Integer> new_remaining = new HashSet<>(); ArrayList<Integer> removed = new ArrayList<>(); for (int e : remaining) { if (!adj[curr].contains(e)) { removed.add(e); queue.add(e); } else { new_remaining.add(e); } } remaining = new_remaining; for (int e : removed) { remaining.remove(e); queue.add(e); } } } pl(); } } pl((ans - 1)); pw.flush(); pw.close(); }
UTF-8
Java
2,106
java
64493253@solve@OK.java
Java
[]
null
[]
static void solve() throws IOException { scan = new FastReader(); pw = new PrintWriter(System.out, true); StringBuilder sb = new StringBuilder(); int n = ni(), m = ni(); HashSet<Integer>[] adj = new HashSet[n + 1]; for (int i = 1; i <= n; ++i) { adj[i] = new HashSet<>(); } for (int i = 0; i < m; ++i) { int u = ni(), v = ni(); adj[u].add(v); adj[v].add(u); } HashSet<Integer> remaining = new HashSet<>(); for (int i = 1; i <= n; ++i) { remaining.add(i); } LinkedList<Integer> queue = new LinkedList<>(); int ans = 0; for (int i = 1; i <= n; ++i) { if (remaining.contains(i)) { ans++; queue.add(i); remaining.remove(i); while (!queue.isEmpty()) { int curr = queue.poll(); if (remaining.size() < adj[curr].size()) { ArrayList<Integer> removed = new ArrayList<>(); for (int e : remaining) { if (!adj[curr].contains(e)) { removed.add(e); } } for (int e : removed) { remaining.remove(e); queue.add(e); } } else { HashSet<Integer> new_remaining = new HashSet<>(); ArrayList<Integer> removed = new ArrayList<>(); for (int e : remaining) { if (!adj[curr].contains(e)) { removed.add(e); queue.add(e); } else { new_remaining.add(e); } } remaining = new_remaining; for (int e : removed) { remaining.remove(e); queue.add(e); } } } pl(); } } pl((ans - 1)); pw.flush(); pw.close(); }
2,106
0.367996
0.364672
63
32.444443
15.867285
69
false
false
0
0
0
0
0
0
0.698413
false
false
12
8792bc146fc21b2b4e1f646a5f7343dd854934c3
2,834,678,468,793
d773eeac0e6af5ee890f84b6514f3c136cb57bfc
/api-weixin/src/main/java/cn/iotframe/api/weixin/model/SendXmlModel.java
cfa81cfef45e14676f9bef422a5c78e1eb5cb46e
[]
no_license
yb755/iot
https://github.com/yb755/iot
b797d192204a6554cf827e0c9167621fb3c9e10a
57c949b7f17be712a86c1f04a8d44768f93599e6
refs/heads/master
2023-03-01T04:06:40.910000
2021-02-04T11:51:17
2021-02-04T11:51:17
335,861,461
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.iotframe.api.weixin.model; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import cn.iotframe.api.weixin.adapter.CDATAAdapter; import lombok.Data; @Data @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "xml") @XmlType(propOrder = {}) public class SendXmlModel { @XmlElement(required = true) private String ToUserName; @XmlElement(required = true) private String FromUserName; @XmlElement(required = true) private Integer CreateTime; @XmlElement private String MsgType; @XmlElement @XmlJavaTypeAdapter(value = CDATAAdapter.class) private String Content; @XmlElement private Voice Voice; @XmlElement private Image Image; @XmlElement private Music Music; @XmlElement private Integer ArticleCount; @XmlElement private List<Articles> Articles; }
UTF-8
Java
1,123
java
SendXmlModel.java
Java
[]
null
[]
package cn.iotframe.api.weixin.model; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import cn.iotframe.api.weixin.adapter.CDATAAdapter; import lombok.Data; @Data @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "xml") @XmlType(propOrder = {}) public class SendXmlModel { @XmlElement(required = true) private String ToUserName; @XmlElement(required = true) private String FromUserName; @XmlElement(required = true) private Integer CreateTime; @XmlElement private String MsgType; @XmlElement @XmlJavaTypeAdapter(value = CDATAAdapter.class) private String Content; @XmlElement private Voice Voice; @XmlElement private Image Image; @XmlElement private Music Music; @XmlElement private Integer ArticleCount; @XmlElement private List<Articles> Articles; }
1,123
0.757792
0.757792
51
20.019608
17.048363
61
false
false
0
0
0
0
0
0
0.843137
false
false
12
6cafcdbdb8e471dd7b638f587fcadd8d08dfe019
24,790,551,249,554
a25ec72c9292651b39c63c7d6b0306b160ce4bbe
/src/com/fx/entity/TBlogComment.java
4c5395d149888acfc4aaaba8933e6cd23a990484
[ "Apache-2.0" ]
permissive
darklandowner/fenxiang
https://github.com/darklandowner/fenxiang
f569098bfe0fc2fb73ae990a8cb2aa993226ff27
7af53201407243b615651f5cab99d58fd4bd67b0
refs/heads/master
2021-01-19T12:29:34.896000
2017-09-26T02:43:17
2017-09-26T02:43:17
88,032,957
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fx.entity; // Generated 2017-6-22 11:32:01 by Hibernate Tools 4.3.1.Final import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * TBlogComment generated by hbm2java */ @Entity @Table(name = "t_blog_comment") public class TBlogComment implements java.io.Serializable { private Integer commentId; private String blogId; private Integer refCommentId; private String userCode; private String friendUserCode; private String commentContent; private Long insertTime; private String isRobot; private String atList; public TBlogComment() { } public TBlogComment(String blogId, Integer refCommentId, String userCode, String friendUserCode, String commentContent, Long insertTime, String isRobot, String atList) { this.blogId = blogId; this.refCommentId = refCommentId; this.userCode = userCode; this.friendUserCode = friendUserCode; this.commentContent = commentContent; this.insertTime = insertTime; this.isRobot = isRobot; this.atList = atList; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "COMMENT_ID", unique = true, nullable = false) public Integer getCommentId() { return this.commentId; } public void setCommentId(Integer commentId) { this.commentId = commentId; } @Column(name = "BLOG_ID", length = 36) public String getBlogId() { return this.blogId; } public void setBlogId(String blogId) { this.blogId = blogId; } @Column(name = "REF_COMMENT_ID") public Integer getRefCommentId() { return this.refCommentId; } public void setRefCommentId(Integer refCommentId) { this.refCommentId = refCommentId; } @Column(name = "USER_CODE", length = 36) public String getUserCode() { return this.userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } @Column(name = "FRIEND_USER_CODE", length = 36) public String getFriendUserCode() { return this.friendUserCode; } public void setFriendUserCode(String friendUserCode) { this.friendUserCode = friendUserCode; } @Column(name = "COMMENT_CONTENT", length = 2000) public String getCommentContent() { return this.commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } @Column(name = "INSERT_TIME", precision = 13, scale = 0) public Long getInsertTime() { return this.insertTime; } public void setInsertTime(Long insertTime) { this.insertTime = insertTime; } @Column(name = "IS_ROBOT", length = 6) public String getIsRobot() { return this.isRobot; } public void setIsRobot(String isRobot) { this.isRobot = isRobot; } @Column(name = "AT_LIST", length = 100) public String getAtList() { return this.atList; } public void setAtList(String atList) { this.atList = atList; } }
UTF-8
Java
3,055
java
TBlogComment.java
Java
[]
null
[]
package com.fx.entity; // Generated 2017-6-22 11:32:01 by Hibernate Tools 4.3.1.Final import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * TBlogComment generated by hbm2java */ @Entity @Table(name = "t_blog_comment") public class TBlogComment implements java.io.Serializable { private Integer commentId; private String blogId; private Integer refCommentId; private String userCode; private String friendUserCode; private String commentContent; private Long insertTime; private String isRobot; private String atList; public TBlogComment() { } public TBlogComment(String blogId, Integer refCommentId, String userCode, String friendUserCode, String commentContent, Long insertTime, String isRobot, String atList) { this.blogId = blogId; this.refCommentId = refCommentId; this.userCode = userCode; this.friendUserCode = friendUserCode; this.commentContent = commentContent; this.insertTime = insertTime; this.isRobot = isRobot; this.atList = atList; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "COMMENT_ID", unique = true, nullable = false) public Integer getCommentId() { return this.commentId; } public void setCommentId(Integer commentId) { this.commentId = commentId; } @Column(name = "BLOG_ID", length = 36) public String getBlogId() { return this.blogId; } public void setBlogId(String blogId) { this.blogId = blogId; } @Column(name = "REF_COMMENT_ID") public Integer getRefCommentId() { return this.refCommentId; } public void setRefCommentId(Integer refCommentId) { this.refCommentId = refCommentId; } @Column(name = "USER_CODE", length = 36) public String getUserCode() { return this.userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } @Column(name = "FRIEND_USER_CODE", length = 36) public String getFriendUserCode() { return this.friendUserCode; } public void setFriendUserCode(String friendUserCode) { this.friendUserCode = friendUserCode; } @Column(name = "COMMENT_CONTENT", length = 2000) public String getCommentContent() { return this.commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } @Column(name = "INSERT_TIME", precision = 13, scale = 0) public Long getInsertTime() { return this.insertTime; } public void setInsertTime(Long insertTime) { this.insertTime = insertTime; } @Column(name = "IS_ROBOT", length = 6) public String getIsRobot() { return this.isRobot; } public void setIsRobot(String isRobot) { this.isRobot = isRobot; } @Column(name = "AT_LIST", length = 100) public String getAtList() { return this.atList; } public void setAtList(String atList) { this.atList = atList; } }
3,055
0.707365
0.696236
127
22.055119
19.807064
97
false
false
0
0
0
0
0
0
1.370079
false
false
12
18a99853c42c7b9c19cbbb8726ee7549081c14ba
28,535,762,782,500
b7f69ace8cba9420e92b44b4c0e5408623d0660a
/src/main/java/be/helha/groupe5/controllers/CartController.java
8deb15614fb1401d60f2868d00163ce7c9fcc549
[]
no_license
Yoiro/jeeaout
https://github.com/Yoiro/jeeaout
7ef880b0a9fa07fb43315bddd01c0d88a12327a4
22b1e62da472bff7eef28e03f771c499200a416b
refs/heads/master
2021-01-01T20:19:16.825000
2017-08-31T10:05:33
2017-08-31T10:05:33
98,811,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.helha.groupe5.controllers; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import be.helha.groupe5.daos.DAOPanierLocalBean; import be.helha.groupe5.daos.DAOProduitLocalBean; import be.helha.groupe5.entities.Panier; import be.helha.groupe5.entities.Produit; import be.helha.groupe5.patterns.DBObserver; @ManagedBean @SessionScoped public class CartController implements Serializable, DBObserver{ private Panier panier; private LinkedHashMap<Produit, Integer> hashProduits; private List<Entry<Produit, Integer>> entries; @EJB private DAOProduitLocalBean daoProduitLocalBean; @EJB private DAOPanierLocalBean daoPanierLocalBean; @PostConstruct public void init() { panier = daoPanierLocalBean.getPanier(); hashProduits = panier.getMapProduit(); entries = new ArrayList<>(hashProduits.entrySet()); daoPanierLocalBean.ajouterObserver(this); } @Override public void onUpdate() { panier = daoPanierLocalBean.getPanier(); System.out.println("Cart.onUpdate\n"+panier); hashProduits = panier.getMapProduit(); System.out.println(hashProduits); entries = new ArrayList<>(hashProduits.entrySet()); System.out.println(entries); } public Panier getPanier() { return panier; } public void setPanier(Panier panier) { this.panier = panier; } public LinkedHashMap<Produit, Integer> getHashProduits() { return hashProduits; } public void setHashProduits(LinkedHashMap<Produit, Integer> hashProduits) { this.hashProduits = hashProduits; } public List<Entry<Produit, Integer>> getEntries() { return entries; } public void retirerProduitPanier(Produit p) { daoPanierLocalBean.removeFromCart(p); System.out.println("cérétiré lol"); } }
UTF-8
Java
2,006
java
CartController.java
Java
[]
null
[]
package be.helha.groupe5.controllers; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import be.helha.groupe5.daos.DAOPanierLocalBean; import be.helha.groupe5.daos.DAOProduitLocalBean; import be.helha.groupe5.entities.Panier; import be.helha.groupe5.entities.Produit; import be.helha.groupe5.patterns.DBObserver; @ManagedBean @SessionScoped public class CartController implements Serializable, DBObserver{ private Panier panier; private LinkedHashMap<Produit, Integer> hashProduits; private List<Entry<Produit, Integer>> entries; @EJB private DAOProduitLocalBean daoProduitLocalBean; @EJB private DAOPanierLocalBean daoPanierLocalBean; @PostConstruct public void init() { panier = daoPanierLocalBean.getPanier(); hashProduits = panier.getMapProduit(); entries = new ArrayList<>(hashProduits.entrySet()); daoPanierLocalBean.ajouterObserver(this); } @Override public void onUpdate() { panier = daoPanierLocalBean.getPanier(); System.out.println("Cart.onUpdate\n"+panier); hashProduits = panier.getMapProduit(); System.out.println(hashProduits); entries = new ArrayList<>(hashProduits.entrySet()); System.out.println(entries); } public Panier getPanier() { return panier; } public void setPanier(Panier panier) { this.panier = panier; } public LinkedHashMap<Produit, Integer> getHashProduits() { return hashProduits; } public void setHashProduits(LinkedHashMap<Produit, Integer> hashProduits) { this.hashProduits = hashProduits; } public List<Entry<Produit, Integer>> getEntries() { return entries; } public void retirerProduitPanier(Produit p) { daoPanierLocalBean.removeFromCart(p); System.out.println("cérétiré lol"); } }
2,006
0.748877
0.745881
75
24.706667
20.193579
76
false
false
0
0
0
0
0
0
1.413333
false
false
12
75243cf0d62f795d262f4c518c6d616f2dd4a3b5
21,947,282,952,999
82a0c3f367d274a2c5a791945f320fc29f971e31
/src/main/java/com/somoplay/artonexpress/ups/shipping/ShipConfirmRequest/PackageServiceOptionsNotificationType.java
90a6bc209183dacdcc7f2e264a524e786f067029
[]
no_license
zl20072008zl/arton_nov
https://github.com/zl20072008zl/arton_nov
a21e682e40a2ee4d9e1b416565942c8a62a8951f
c3571a7b31c561691a785e3d2640ea0b5ab770a7
refs/heads/master
2020-03-19T02:22:35.567000
2018-05-20T14:16:43
2018-05-20T14:16:43
135,623,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// // 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.11 生成的 // 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // 在重新编译源模式时, 对此文件的所有修改都将丢失。 // 生成时间: 2017.10.28 时间 03:38:23 PM EDT // package com.somoplay.artonexpress.ups.shipping.ShipConfirmRequest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>PackageServiceOptionsNotificationType complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType name="PackageServiceOptionsNotificationType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="NotificationCode" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="EMailMessage" type="{}PackageServiceOptionsNotificationEMailMessageType"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PackageServiceOptionsNotificationType", propOrder = { "notificationCode", "eMailMessage" }) public class PackageServiceOptionsNotificationType { @XmlElement(name = "NotificationCode", required = true) protected String notificationCode; @XmlElement(name = "EMailMessage", required = true) protected PackageServiceOptionsNotificationEMailMessageType eMailMessage; /** * 获取notificationCode属性的值。 * * @return * possible object is * {@link String } * */ public String getNotificationCode() { return notificationCode; } /** * 设置notificationCode属性的值。 * * @param value * allowed object is * {@link String } * */ public void setNotificationCode(String value) { this.notificationCode = value; } /** * 获取eMailMessage属性的值。 * * @return * possible object is * {@link PackageServiceOptionsNotificationEMailMessageType } * */ public PackageServiceOptionsNotificationEMailMessageType getEMailMessage() { return eMailMessage; } /** * 设置eMailMessage属性的值。 * * @param value * allowed object is * {@link PackageServiceOptionsNotificationEMailMessageType } * */ public void setEMailMessage(PackageServiceOptionsNotificationEMailMessageType value) { this.eMailMessage = value; } }
UTF-8
Java
2,807
java
PackageServiceOptionsNotificationType.java
Java
[]
null
[]
// // 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.11 生成的 // 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // 在重新编译源模式时, 对此文件的所有修改都将丢失。 // 生成时间: 2017.10.28 时间 03:38:23 PM EDT // package com.somoplay.artonexpress.ups.shipping.ShipConfirmRequest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>PackageServiceOptionsNotificationType complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType name="PackageServiceOptionsNotificationType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="NotificationCode" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="EMailMessage" type="{}PackageServiceOptionsNotificationEMailMessageType"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PackageServiceOptionsNotificationType", propOrder = { "notificationCode", "eMailMessage" }) public class PackageServiceOptionsNotificationType { @XmlElement(name = "NotificationCode", required = true) protected String notificationCode; @XmlElement(name = "EMailMessage", required = true) protected PackageServiceOptionsNotificationEMailMessageType eMailMessage; /** * 获取notificationCode属性的值。 * * @return * possible object is * {@link String } * */ public String getNotificationCode() { return notificationCode; } /** * 设置notificationCode属性的值。 * * @param value * allowed object is * {@link String } * */ public void setNotificationCode(String value) { this.notificationCode = value; } /** * 获取eMailMessage属性的值。 * * @return * possible object is * {@link PackageServiceOptionsNotificationEMailMessageType } * */ public PackageServiceOptionsNotificationEMailMessageType getEMailMessage() { return eMailMessage; } /** * 设置eMailMessage属性的值。 * * @param value * allowed object is * {@link PackageServiceOptionsNotificationEMailMessageType } * */ public void setEMailMessage(PackageServiceOptionsNotificationEMailMessageType value) { this.eMailMessage = value; } }
2,807
0.66603
0.655331
97
25.979382
26.169935
106
false
false
0
0
0
0
0
0
0.371134
false
false
12
28bf7a84c1baaf76e385817d61a7e94b21107d45
22,505,628,644,612
c5d54458e4edeec46810062faaaf9a85e270a1ef
/extra/archive/cse_213_intro_to_oop_java/hw/hw0/com/animal/tree2/Test.java
f9488bfd7f73f68f5441e355a25e4b4591e504de
[]
no_license
MintPaw/College
https://github.com/MintPaw/College
88e9421c02c879e7bff354fc2ce4409bb4209bd8
8319589f25fde43f62e48973c2d5d41b8e9d3fc2
refs/heads/master
2016-12-03T18:26:43.675000
2016-10-21T02:19:00
2016-10-21T02:19:00
41,755,676
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.animal.tree2; public class Test { public static void main(String[] args) { Canine bc = new BorderCollie(); System.out.println("barkVolume is " + bc.getBarkVolume()); } }
UTF-8
Java
197
java
Test.java
Java
[]
null
[]
package com.animal.tree2; public class Test { public static void main(String[] args) { Canine bc = new BorderCollie(); System.out.println("barkVolume is " + bc.getBarkVolume()); } }
197
0.670051
0.664975
11
16.90909
19.791893
59
false
false
0
0
0
0
0
0
0.545455
false
false
12
9807897ecf014027190e57a40f2aa3202307e1ca
27,195,732,982,850
c296fbc2d35890fcf0a91ce7296a0ea219cc4f48
/src/kutokit/model/cse/Controller.java
db60df9eeb434056283ed345ff23f32d3dea2b65
[]
no_license
dahye97/KUtoKit
https://github.com/dahye97/KUtoKit
3d038f15bcf2302c9c500e91b2fd25b27e082d3e
fdeebf45a2fee904375b8a1f1acb80779a388bc2
refs/heads/master
2023-01-24T08:16:50.086000
2020-11-26T15:06:54
2020-11-26T15:06:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kutokit.model.cse; import java.util.HashMap; import java.util.Map; import kutokit.view.components.RectangleView; public class Controller { double x, y; String name; int id; Map<Integer, Integer> CA = new HashMap<Integer, Integer>(); //key: CA id, value: 1->controller, 0->controlled Map<Integer, Integer> FB = new HashMap<Integer, Integer>(); //key: FB id, value: 1->controller, 0->controlled int num[] = new int[2]; //0: CA, 1: FB RectangleView r; public Controller() { } public Controller(double x, double y, String name, int id) { this.x = x; this.y = y; this.name = name; this.id = id; } public void setRectangle(RectangleView r) { this.r=r; } public void resizeRectangle(String type) { if(type.equals("ca")) { num[0] = num[0]+1; }else { num[1] = num[1]+1; } r.resizeRectangle(num); } public double getX() { return x; } public double getY() { return y; } public String getName() { return name; } public int getId() { return id; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public void setName(String name) { this.name = name; } public void setId(int id) { this.id = id; } public Map<Integer, Integer> getCA(){ return this.CA; } public void addCA(int id, int type) { this.CA.put(id, type); //num++; } public void removeCA(int id) { this.CA.remove(id); num[0] = num[0]-1; } public Map<Integer, Integer> getFB(){ return this.FB; } public void addFB(int id, int type) { this.FB.put(id, type); //num++; } public void removeFB(int id) { this.FB.remove(id); num[1] = num[1]+1; } public int[] getNum() { return num; } public void clearNum() { this.num[0] = 0; this.num[1] = 0; } }
UTF-8
Java
1,785
java
Controller.java
Java
[]
null
[]
package kutokit.model.cse; import java.util.HashMap; import java.util.Map; import kutokit.view.components.RectangleView; public class Controller { double x, y; String name; int id; Map<Integer, Integer> CA = new HashMap<Integer, Integer>(); //key: CA id, value: 1->controller, 0->controlled Map<Integer, Integer> FB = new HashMap<Integer, Integer>(); //key: FB id, value: 1->controller, 0->controlled int num[] = new int[2]; //0: CA, 1: FB RectangleView r; public Controller() { } public Controller(double x, double y, String name, int id) { this.x = x; this.y = y; this.name = name; this.id = id; } public void setRectangle(RectangleView r) { this.r=r; } public void resizeRectangle(String type) { if(type.equals("ca")) { num[0] = num[0]+1; }else { num[1] = num[1]+1; } r.resizeRectangle(num); } public double getX() { return x; } public double getY() { return y; } public String getName() { return name; } public int getId() { return id; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public void setName(String name) { this.name = name; } public void setId(int id) { this.id = id; } public Map<Integer, Integer> getCA(){ return this.CA; } public void addCA(int id, int type) { this.CA.put(id, type); //num++; } public void removeCA(int id) { this.CA.remove(id); num[0] = num[0]-1; } public Map<Integer, Integer> getFB(){ return this.FB; } public void addFB(int id, int type) { this.FB.put(id, type); //num++; } public void removeFB(int id) { this.FB.remove(id); num[1] = num[1]+1; } public int[] getNum() { return num; } public void clearNum() { this.num[0] = 0; this.num[1] = 0; } }
1,785
0.614006
0.60112
110
15.227273
18.428564
110
false
false
0
0
0
0
0
0
1.736364
false
false
12
db3df14c56b937be796341ff4b959bcf3afec641
27,195,732,984,001
742bdf60c71e893fc381bf6327c662e538494392
/backdoored/client/modules/impl/p/j$x.java
8f2809e3382c5863d60bd1474bb636ea6e2a80f5
[]
no_license
Wenaly/Backdoored-1.7.1-Deobf-Source-Leak
https://github.com/Wenaly/Backdoored-1.7.1-Deobf-Source-Leak
e5cdd27aedb3746515b0462979150ceedd92ff12
ba682e8a6187b757410abf13515ce5a4a0a552f8
refs/heads/master
2023-05-05T23:56:50.152000
2019-11-19T14:49:45
2019-11-19T14:49:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package r.k.d.m.p; class j$x { static final /* synthetic */ int[] sqe; public static final boolean sqo; public static final int sqt; public static final boolean sqn; static final /* synthetic */ int[] sqe; public static final boolean sqo; public static final int sqt; public static final boolean sqn; static { // // This method could not be decompiled. // // Could not show original bytecode, likely due to the same error. // throw new IllegalStateException("An error occurred while decompiling this method."); } static { // // This method could not be decompiled. // // Original Bytecode: // // 1: goto 5 // 4: return // 5: nop // 6: nop // 7: invokestatic r/k/d/m/p/j$s.values:()[Lr/k/d/m/p/j$s; // 10: arraylength // 11: newarray I // 13: putstatic r/k/d/m/p/j$x.sqe:[I // 16: getstatic r/k/d/m/p/j$x.sqe:[I // 19: getstatic r/k/d/m/p/j$s.gt:Lr/k/d/m/p/j$s; // 22: invokevirtual r/k/d/m/p/j$s.ordinal:()I // 25: iconst_1 // 26: iastore // 27: nop // 28: getstatic r/k/d/m/p/j$x.sqe:[I // 31: getstatic r/k/d/m/p/j$s.gn:Lr/k/d/m/p/j$s; // 34: invokevirtual r/k/d/m/p/j$s.ordinal:()I // 37: iconst_2 // 38: iastore // 39: nop // 40: astore_0 // 41: getstatic r/k/d/m/p/j$x.sqe:[I // 44: getstatic r/k/d/m/p/j$s.gi:Lr/k/d/m/p/j$s; // 47: invokevirtual r/k/d/m/p/j$s.ordinal:()I // 50: iconst_3 // 51: iastore // 52: nop // 53: astore_0 // 54: getstatic r/k/d/m/p/j$x.sqe:[I // 57: getstatic r/k/d/m/p/j$s.gp:Lr/k/d/m/p/j$s; // 60: invokevirtual r/k/d/m/p/j$s.ordinal:()I // 63: iconst_4 // 64: iastore // 65: nop // 66: astore_0 // 67: return // Exceptions: // Try Handler // Start End Start End Type // ----- ----- ----- ----- ---------------------------- // 16 27 28 40 Ljava/lang/NoSuchFieldError; // 28 39 40 68 Ljava/lang/NoSuchFieldError; // 41 52 53 68 Ljava/lang/NoSuchFieldError; // 54 65 66 68 Ljava/lang/NoSuchFieldError; // throw new IllegalStateException("An error occurred while decompiling this method."); } }
UTF-8
Java
2,938
java
j$x.java
Java
[]
null
[]
package r.k.d.m.p; class j$x { static final /* synthetic */ int[] sqe; public static final boolean sqo; public static final int sqt; public static final boolean sqn; static final /* synthetic */ int[] sqe; public static final boolean sqo; public static final int sqt; public static final boolean sqn; static { // // This method could not be decompiled. // // Could not show original bytecode, likely due to the same error. // throw new IllegalStateException("An error occurred while decompiling this method."); } static { // // This method could not be decompiled. // // Original Bytecode: // // 1: goto 5 // 4: return // 5: nop // 6: nop // 7: invokestatic r/k/d/m/p/j$s.values:()[Lr/k/d/m/p/j$s; // 10: arraylength // 11: newarray I // 13: putstatic r/k/d/m/p/j$x.sqe:[I // 16: getstatic r/k/d/m/p/j$x.sqe:[I // 19: getstatic r/k/d/m/p/j$s.gt:Lr/k/d/m/p/j$s; // 22: invokevirtual r/k/d/m/p/j$s.ordinal:()I // 25: iconst_1 // 26: iastore // 27: nop // 28: getstatic r/k/d/m/p/j$x.sqe:[I // 31: getstatic r/k/d/m/p/j$s.gn:Lr/k/d/m/p/j$s; // 34: invokevirtual r/k/d/m/p/j$s.ordinal:()I // 37: iconst_2 // 38: iastore // 39: nop // 40: astore_0 // 41: getstatic r/k/d/m/p/j$x.sqe:[I // 44: getstatic r/k/d/m/p/j$s.gi:Lr/k/d/m/p/j$s; // 47: invokevirtual r/k/d/m/p/j$s.ordinal:()I // 50: iconst_3 // 51: iastore // 52: nop // 53: astore_0 // 54: getstatic r/k/d/m/p/j$x.sqe:[I // 57: getstatic r/k/d/m/p/j$s.gp:Lr/k/d/m/p/j$s; // 60: invokevirtual r/k/d/m/p/j$s.ordinal:()I // 63: iconst_4 // 64: iastore // 65: nop // 66: astore_0 // 67: return // Exceptions: // Try Handler // Start End Start End Type // ----- ----- ----- ----- ---------------------------- // 16 27 28 40 Ljava/lang/NoSuchFieldError; // 28 39 40 68 Ljava/lang/NoSuchFieldError; // 41 52 53 68 Ljava/lang/NoSuchFieldError; // 54 65 66 68 Ljava/lang/NoSuchFieldError; // throw new IllegalStateException("An error occurred while decompiling this method."); } }
2,938
0.41661
0.380191
76
37.657894
22.179028
92
false
false
0
0
0
0
0
0
0.276316
false
false
12
d2b9dea69383f58970bcc6ccca7ec6d974cc0750
32,315,333,935,882
654192c1fccac4630da82d05bee5410420af99bd
/src/main/java/com/zource/dao/PageMenuDAO.java
2ac4f3ecfd2ca7d9fb8f3e858ff295bca7982155
[]
no_license
sigachev/Zource
https://github.com/sigachev/Zource
652e58bdc4780d5e94a2d5ea977a9651db240422
3482c65f1e6bdec31fb883a30d3fb73486707ef8
refs/heads/master
2020-05-05T04:43:25.164000
2019-05-21T18:03:41
2019-05-21T18:03:41
179,701,309
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2018. * Author: Mikhail Sigachev */ package com.zource.dao; import com.zource.entity.PageMenu; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static com.zource.utils.HibernateUtils.loadAllData; @Transactional @Repository public class PageMenuDAO { @Autowired private SessionFactory sessionFactory; public List<PageMenu> getAllPageMenus() { Session session = this.sessionFactory.getCurrentSession(); List<PageMenu> menus = (List<PageMenu>) loadAllData(PageMenu.class, session); return menus; } public PageMenu getMenuByID(Integer menuId) { PageMenu result = null; List<PageMenu> menus = (List<PageMenu>) loadAllData(PageMenu.class, sessionFactory.getCurrentSession()); for (PageMenu m : menus) if (m.getId() == menuId) result = m; return result; } public void update(PageMenu m) { Session session = this.sessionFactory.getCurrentSession(); PageMenu menu = null; menu.setId(m.getId()); menu.setTitle(m.getTitle()); session.merge(menu); } }
UTF-8
Java
1,363
java
PageMenuDAO.java
Java
[ { "context": "/*\n * Copyright (c) 2018.\n * Author: Mikhail Sigachev\n */\n\npackage com.zource.dao;\n\nimport com.zource.e", "end": 53, "score": 0.9998634457588196, "start": 37, "tag": "NAME", "value": "Mikhail Sigachev" } ]
null
[]
/* * Copyright (c) 2018. * Author: <NAME> */ package com.zource.dao; import com.zource.entity.PageMenu; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static com.zource.utils.HibernateUtils.loadAllData; @Transactional @Repository public class PageMenuDAO { @Autowired private SessionFactory sessionFactory; public List<PageMenu> getAllPageMenus() { Session session = this.sessionFactory.getCurrentSession(); List<PageMenu> menus = (List<PageMenu>) loadAllData(PageMenu.class, session); return menus; } public PageMenu getMenuByID(Integer menuId) { PageMenu result = null; List<PageMenu> menus = (List<PageMenu>) loadAllData(PageMenu.class, sessionFactory.getCurrentSession()); for (PageMenu m : menus) if (m.getId() == menuId) result = m; return result; } public void update(PageMenu m) { Session session = this.sessionFactory.getCurrentSession(); PageMenu menu = null; menu.setId(m.getId()); menu.setTitle(m.getTitle()); session.merge(menu); } }
1,353
0.689655
0.68672
58
22.5
24.86602
112
false
false
0
0
0
0
0
0
0.413793
false
false
12
3400f2807d6694d6896a0d78a88561a1f3e3c7d0
31,155,692,832,793
b9aeca822e976296c241a90ae06c9361267d0cb6
/src/org/nutz/lang/tmpl/TmplStringEle.java
8aca158a49eb690dbe70152a169baa4bde316fc4
[ "Apache-2.0" ]
permissive
nutzam/nutz
https://github.com/nutzam/nutz
8bf0357da1a959330eac815ecf37ccd43e991268
17c2dbc97e705b9ea670a16bbebbaf63faf7bf2d
refs/heads/master
2023-08-31T19:27:51.325000
2023-06-08T02:26:44
2023-06-08T02:26:44
1,873,881
2,367
930
Apache-2.0
false
2023-07-07T21:38:17
2011-06-10T01:25:43
2023-07-05T08:02:31
2023-07-07T21:38:13
44,419
2,502
965
60
Java
false
false
package org.nutz.lang.tmpl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.nutz.lang.Lang; import org.nutz.lang.Strings; /** * 格式如下(有点复杂 ^_^!) * * <pre> * ${path<:@处理器;@处理器'参数1','参数2';@处理器'参数1';:映射>} * </pre> * * 例如 * * <pre> * ${path<:@trim;@replace'/','-';@replace'~';:0=A,1=B>} * </pre> * * @author zozoh(zozohtnt@gmail.com) */ class TmplStringEle extends TmplDynamicEle { private List<StrEleConvertor> convertors; public TmplStringEle(String key, String fmt, String dft) { super(null, key, null, dft); this.fmt = Strings.sNull(fmt, null); parseFormat(this.fmt); } public void parseFormat(String fmt) { if (null == fmt) { convertors = null; return; } // 先拆分处理器 String[] ss = Strings.split(this.fmt, true, ';'); // 预处理字段 this.convertors = new ArrayList<StrEleConvertor>(ss.length); for (String s : ss) { // 截取空白 if (s.equals("@trim")) { convertors.add(new StrTrimConvertor()); } // 字符串替换 else if (s.startsWith("@replace")) { String input = s.substring("@replace".length()); convertors.add(new StrReplaceConvertor(input)); } // 字符串映射 else if (s.startsWith(":")) { String input = s.substring(1); convertors.add(new StrMappingConvertor(input)); } // 默认是字符串格式化 else { convertors.add(new StrFormatConvertor(s)); } } } @Override protected String _val(Object val) { if (null == val) { return null; } if (null != val) { if (val.getClass().isArray()) { return Lang.concat(", ", (Object[]) val).toString(); } if (val instanceof Collection<?>) { return Strings.join(", ", (Collection<?>) val); } } String re = val.toString(); if (null != convertors && !convertors.isEmpty()) { for (StrEleConvertor co : convertors) { re = co.process(re); } } return re; } }
UTF-8
Java
2,425
java
TmplStringEle.java
Java
[ { "context": "-';@replace'~';:0=A,1=B>}\n * </pre>\n * \n * @author zozoh(zozohtnt@gmail.com)\n */\nclass TmplStringEle exten", "end": 370, "score": 0.9997116923332214, "start": 365, "tag": "USERNAME", "value": "zozoh" }, { "context": "lace'~';:0=A,1=B>}\n * </pre>\n * \n * @author zozoh(zozohtnt@gmail.com)\n */\nclass TmplStringEle extends TmplDynamicEle {", "end": 389, "score": 0.9999269247055054, "start": 371, "tag": "EMAIL", "value": "zozohtnt@gmail.com" } ]
null
[]
package org.nutz.lang.tmpl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.nutz.lang.Lang; import org.nutz.lang.Strings; /** * 格式如下(有点复杂 ^_^!) * * <pre> * ${path<:@处理器;@处理器'参数1','参数2';@处理器'参数1';:映射>} * </pre> * * 例如 * * <pre> * ${path<:@trim;@replace'/','-';@replace'~';:0=A,1=B>} * </pre> * * @author zozoh(<EMAIL>) */ class TmplStringEle extends TmplDynamicEle { private List<StrEleConvertor> convertors; public TmplStringEle(String key, String fmt, String dft) { super(null, key, null, dft); this.fmt = Strings.sNull(fmt, null); parseFormat(this.fmt); } public void parseFormat(String fmt) { if (null == fmt) { convertors = null; return; } // 先拆分处理器 String[] ss = Strings.split(this.fmt, true, ';'); // 预处理字段 this.convertors = new ArrayList<StrEleConvertor>(ss.length); for (String s : ss) { // 截取空白 if (s.equals("@trim")) { convertors.add(new StrTrimConvertor()); } // 字符串替换 else if (s.startsWith("@replace")) { String input = s.substring("@replace".length()); convertors.add(new StrReplaceConvertor(input)); } // 字符串映射 else if (s.startsWith(":")) { String input = s.substring(1); convertors.add(new StrMappingConvertor(input)); } // 默认是字符串格式化 else { convertors.add(new StrFormatConvertor(s)); } } } @Override protected String _val(Object val) { if (null == val) { return null; } if (null != val) { if (val.getClass().isArray()) { return Lang.concat(", ", (Object[]) val).toString(); } if (val instanceof Collection<?>) { return Strings.join(", ", (Collection<?>) val); } } String re = val.toString(); if (null != convertors && !convertors.isEmpty()) { for (StrEleConvertor co : convertors) { re = co.process(re); } } return re; } }
2,414
0.493693
0.491083
89
24.831461
20.119438
68
false
false
0
0
0
0
0
0
0.539326
false
false
12