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
3ec92c1ce58d1c6819e8d7dad1c84a5f30dfaa5a
20,366,734,923,469
5624f5c7c089df2408948bb398d95edc477aa701
/Huffman.java
9d0dde00606031903eac55af9d8a2613bf817ed4
[]
no_license
homnyom/APCS
https://github.com/homnyom/APCS
7ec47e1e799dc5f943a99f7542e6b96fcdb8b73a
d1f65b89eac18ad85b3750e9485d6d744b6af0f6
refs/heads/main
2023-02-11T08:40:56.952000
2021-01-14T03:01:40
2021-01-14T03:01:40
329,489,759
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// name: Natalie Homnyom date: May 20, 2016 import java.util.*; import java.io.*; public class Huffman { public static void main(String[] args) throws IOException { Scanner keyboard = new Scanner(System.in); System.out.print("Encode what message? "); String message = keyboard.nextLine(); Map<String, Integer> m = createFrequencyTable(message); Iterator<String> it = m.keySet().iterator(); Queue<HuffmanTreeNode> q = new PriorityQueue<HuffmanTreeNode>(); while(it.hasNext()) { String character = it.next(); int freq = m.get(character); q.add(new HuffmanTreeNode(character, freq)); } System.out.print("What file name? "); String file = keyboard.nextLine(); HuffmanTreeNode root = createSchemeTree(q); PrintStream scheme = new PrintStream(new File("scheme." + file + ".txt")); createScheme(scheme,root, ""); PrintStream code = new PrintStream(new File("message." + file + ".txt")); createCode(code, m, root, message); //Read the string //Make a frequency table of the letters //Put each letter-frequency pair into a HuffmanTreeNode. Put each // node into a priority queue (or a min-heap). //Use the priority queue of nodes to build the Huffman tree //Process the string letter-by-letter and search the tree for the // letter. As you go, build the binary path, where going // left is 0 and going right is 1. //Write the binary path to the hard drive as message.xxx.txt //Write the scheme to the hard drive as scheme.xxx.txt } public static Map createFrequencyTable(String s) { Map<String, Integer> m = new HashMap<String, Integer>(); for(int x = 0; x < s.length(); x++){ String letter = s.charAt(x) + ""; if(m.containsKey(letter)){ int freq = m.get(letter); m.put(letter, freq + 1); } else m.put(letter, 1); } return m; } public static HuffmanTreeNode createSchemeTree(Queue<HuffmanTreeNode> q) { while(!q.isEmpty()) { HuffmanTreeNode less = q.remove(); if(q.isEmpty()) return less; else{ HuffmanTreeNode greater = q.remove(); q.add(new HuffmanTreeNode("*", less.getFrequency() + greater.getFrequency(), less, greater)); } } return null; } public static void createScheme(PrintStream print, HuffmanTreeNode root, String s) { if(root.getLeft() == null && root.getRight() == null) print.println(root.getValue() + s); else{ s += "0"; createScheme(print, root.getLeft(), s); s = s.substring(0, s.length() - 1) + "1"; createScheme(print, root.getRight(), s); } } public static void createCode(PrintStream code, Map<String, Integer> m, HuffmanTreeNode root, String message) { for(int x = 0; x < message.length(); x++) { String s = message.charAt(x) + ""; code.print(findCode(root, s, m.get(s), "")); } code.close(); } private static String findCode(HuffmanTreeNode current, String target, int freq, String s) { HuffmanTreeNode left = current.getLeft(); HuffmanTreeNode right = current.getRight(); String obj = (String) current.getValue(); if(target.equals(obj)) return s; else if((left == null && right == null) || current.getFrequency() < freq) return ""; else{ String one = findCode(current.getLeft(), target, freq, s + "0"); String two = findCode(current.getRight(), target, freq, s + "1"); if(one.equals("")) return two; return one; } } } /* * This node stores two values. * The compareTo method must ensure that the lowest frequency has the highest priority. */ class HuffmanTreeNode implements Comparable<HuffmanTreeNode> { private Object value; private int frequency; private HuffmanTreeNode left, right; public HuffmanTreeNode(Object initValue, int freq) { value = initValue; frequency = freq; left = null; right = null; } public HuffmanTreeNode(Object initValue, int freq, HuffmanTreeNode l, HuffmanTreeNode r) { value = initValue; frequency = freq; left = l; right = r; } public Object getValue() { return value; } public int getFrequency() { return frequency; } public HuffmanTreeNode getLeft() { return left; } public HuffmanTreeNode getRight() { return right; } public void setValue(Object theNewValue) { value = theNewValue; } public void increment() { frequency++; } public void increment(int n) { frequency += n; } public void setLeft(HuffmanTreeNode theNewLeft) { left = theNewLeft; } public void setRight(HuffmanTreeNode theNewRight) { right = theNewRight; } public int compareTo(HuffmanTreeNode other) { return frequency - other.frequency; } }
UTF-8
Java
5,501
java
Huffman.java
Java
[ { "context": "// name: Natalie Homnyom date: May 20, 2016\r\nimport java.util.*;\r\nim", "end": 24, "score": 0.999893844127655, "start": 9, "tag": "NAME", "value": "Natalie Homnyom" } ]
null
[]
// name: <NAME> date: May 20, 2016 import java.util.*; import java.io.*; public class Huffman { public static void main(String[] args) throws IOException { Scanner keyboard = new Scanner(System.in); System.out.print("Encode what message? "); String message = keyboard.nextLine(); Map<String, Integer> m = createFrequencyTable(message); Iterator<String> it = m.keySet().iterator(); Queue<HuffmanTreeNode> q = new PriorityQueue<HuffmanTreeNode>(); while(it.hasNext()) { String character = it.next(); int freq = m.get(character); q.add(new HuffmanTreeNode(character, freq)); } System.out.print("What file name? "); String file = keyboard.nextLine(); HuffmanTreeNode root = createSchemeTree(q); PrintStream scheme = new PrintStream(new File("scheme." + file + ".txt")); createScheme(scheme,root, ""); PrintStream code = new PrintStream(new File("message." + file + ".txt")); createCode(code, m, root, message); //Read the string //Make a frequency table of the letters //Put each letter-frequency pair into a HuffmanTreeNode. Put each // node into a priority queue (or a min-heap). //Use the priority queue of nodes to build the Huffman tree //Process the string letter-by-letter and search the tree for the // letter. As you go, build the binary path, where going // left is 0 and going right is 1. //Write the binary path to the hard drive as message.xxx.txt //Write the scheme to the hard drive as scheme.xxx.txt } public static Map createFrequencyTable(String s) { Map<String, Integer> m = new HashMap<String, Integer>(); for(int x = 0; x < s.length(); x++){ String letter = s.charAt(x) + ""; if(m.containsKey(letter)){ int freq = m.get(letter); m.put(letter, freq + 1); } else m.put(letter, 1); } return m; } public static HuffmanTreeNode createSchemeTree(Queue<HuffmanTreeNode> q) { while(!q.isEmpty()) { HuffmanTreeNode less = q.remove(); if(q.isEmpty()) return less; else{ HuffmanTreeNode greater = q.remove(); q.add(new HuffmanTreeNode("*", less.getFrequency() + greater.getFrequency(), less, greater)); } } return null; } public static void createScheme(PrintStream print, HuffmanTreeNode root, String s) { if(root.getLeft() == null && root.getRight() == null) print.println(root.getValue() + s); else{ s += "0"; createScheme(print, root.getLeft(), s); s = s.substring(0, s.length() - 1) + "1"; createScheme(print, root.getRight(), s); } } public static void createCode(PrintStream code, Map<String, Integer> m, HuffmanTreeNode root, String message) { for(int x = 0; x < message.length(); x++) { String s = message.charAt(x) + ""; code.print(findCode(root, s, m.get(s), "")); } code.close(); } private static String findCode(HuffmanTreeNode current, String target, int freq, String s) { HuffmanTreeNode left = current.getLeft(); HuffmanTreeNode right = current.getRight(); String obj = (String) current.getValue(); if(target.equals(obj)) return s; else if((left == null && right == null) || current.getFrequency() < freq) return ""; else{ String one = findCode(current.getLeft(), target, freq, s + "0"); String two = findCode(current.getRight(), target, freq, s + "1"); if(one.equals("")) return two; return one; } } } /* * This node stores two values. * The compareTo method must ensure that the lowest frequency has the highest priority. */ class HuffmanTreeNode implements Comparable<HuffmanTreeNode> { private Object value; private int frequency; private HuffmanTreeNode left, right; public HuffmanTreeNode(Object initValue, int freq) { value = initValue; frequency = freq; left = null; right = null; } public HuffmanTreeNode(Object initValue, int freq, HuffmanTreeNode l, HuffmanTreeNode r) { value = initValue; frequency = freq; left = l; right = r; } public Object getValue() { return value; } public int getFrequency() { return frequency; } public HuffmanTreeNode getLeft() { return left; } public HuffmanTreeNode getRight() { return right; } public void setValue(Object theNewValue) { value = theNewValue; } public void increment() { frequency++; } public void increment(int n) { frequency += n; } public void setLeft(HuffmanTreeNode theNewLeft) { left = theNewLeft; } public void setRight(HuffmanTreeNode theNewRight) { right = theNewRight; } public int compareTo(HuffmanTreeNode other) { return frequency - other.frequency; } }
5,492
0.561171
0.557899
191
26.811518
25.002535
112
false
false
0
0
0
0
0
0
0.701571
false
false
7
14f27d632562e96e7e16865911b20208e7cd815b
20,366,734,922,672
3a856a230c169110607c23c2c88bcc931356c7bb
/06-dynamic/HotFix/QZoneHotFixDemo/app/src/test/java/com/enjoy/qzonefix/ExampleUnitTest.java
2139feaa24cf9bc33da169c52e71bfdbd45634aa
[]
no_license
klzhong69/android-code
https://github.com/klzhong69/android-code
de9627fe3c5f890011d3bd0809e73fa8da5b0f3e
7e07776c9dc61e857ca5c36ab81a0fb22cd619c1
refs/heads/main
2023-08-13T16:08:29.994000
2021-10-13T15:22:50
2021-10-13T15:22:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.enjoy.qzonefix; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { // Class.forName除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。 // // 而classloader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容 @Test public void addition_isCorrect() throws IOException, ClassNotFoundException { assertEquals(4, 2 + 2); } }
UTF-8
Java
863
java
ExampleUnitTest.java
Java
[]
null
[]
package com.enjoy.qzonefix; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { // Class.forName除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。 // // 而classloader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容 @Test public void addition_isCorrect() throws IOException, ClassNotFoundException { assertEquals(4, 2 + 2); } }
863
0.745672
0.741678
30
24.066668
25.11697
81
false
false
0
0
0
0
0
0
0.466667
false
false
7
bef4597790ee5f791148746c0940e3b3dc44969e
20,366,734,925,875
2ec8ab9ac2efa9aebfe24092cb737fa95355f726
/jAoUrnToRam/test/jAoUrnToRam/transformation/test/AoUrnSourceTest.java
92b25ba7615775ed66273a1ad00a2546dc33db47
[]
no_license
JUCMNAV/projetseg
https://github.com/JUCMNAV/projetseg
549f474e2de2ae8b0242d5b73ed8d225c9d5d2da
334302cc68f3bbe3f3cbc7a73905a928864ad149
refs/heads/master
2021-08-30T19:32:33.219000
2017-04-26T16:45:14
2017-04-26T16:45:14
81,868,373
3
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package jAoUrnToRam.transformation.test; import static org.junit.Assert.*; import intermediateWorkflow.IwModel; import jAoUrnToRam.transformation.AoUrnSource; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import urn.URNspec; public class AoUrnSourceTest { private List<AoUrnSource> _inputModels; @Before public void setUp() throws Exception { String[] testCases = AoUrnToRamTestCases.getTestCases(); for(String testCase : testCases){ AoUrnSource inputModel = new AoUrnSource(testCase); _inputModels.add(inputModel); } } @Test public void testToIw() { for(AoUrnSource inputModel : _inputModels){ IwModel iwModel = inputModel.toIw(); URNspec root = inputModel.getRoot(); } fail("Not yet implemented"); } @After public void tearDown() throws Exception { } @Test public void testGetPath() { fail("Not yet implemented"); } @Test public void testGetName() { fail("Not yet implemented"); } }
UTF-8
Java
1,122
java
AoUrnSourceTest.java
Java
[]
null
[]
package jAoUrnToRam.transformation.test; import static org.junit.Assert.*; import intermediateWorkflow.IwModel; import jAoUrnToRam.transformation.AoUrnSource; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import urn.URNspec; public class AoUrnSourceTest { private List<AoUrnSource> _inputModels; @Before public void setUp() throws Exception { String[] testCases = AoUrnToRamTestCases.getTestCases(); for(String testCase : testCases){ AoUrnSource inputModel = new AoUrnSource(testCase); _inputModels.add(inputModel); } } @Test public void testToIw() { for(AoUrnSource inputModel : _inputModels){ IwModel iwModel = inputModel.toIw(); URNspec root = inputModel.getRoot(); } fail("Not yet implemented"); } @After public void tearDown() throws Exception { } @Test public void testGetPath() { fail("Not yet implemented"); } @Test public void testGetName() { fail("Not yet implemented"); } }
1,122
0.690731
0.690731
55
18.4
17.175671
59
false
false
0
0
0
0
0
0
1.436364
false
false
7
12a65c26f6e04e00645076dc0e72f69c7a1b5c4a
16,630,113,370,565
058998c9523edf4f065921197e3bba1e94217638
/SonarLysaFX2/src/main/java/model/enums/Action.java
33b968eac7c3ede2a928a38bd792e7fbbca55995
[]
no_license
Tiggytamal/Redmine
https://github.com/Tiggytamal/Redmine
807b6801029d8394a3b18f0341a44b72e2d89bdd
5c0a4121778ff7c99fd5a12c5dac70b3e4a846f5
refs/heads/master
2022-11-19T13:15:25.779000
2020-04-20T11:26:26
2020-04-20T11:26:26
76,201,872
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.enums; /** * Interface pour marquer les énumerations d'action sur les éléments de la base de données * * @author ETP8137 - Grégoier Mathon * @since 2.0 * */ public interface Action { /** * Affichage de la valeur de l'action * * @return */ public String getValeur(); }
UTF-8
Java
342
java
Action.java
Java
[ { "context": "s de la base de données\r\n * \r\n * @author ETP8137 - Grégoier Mathon\r\n * @since 2.0\r\n *\r\n */\r\npublic interface Action\r", "end": 162, "score": 0.9998778700828552, "start": 147, "tag": "NAME", "value": "Grégoier Mathon" } ]
null
[]
package model.enums; /** * Interface pour marquer les énumerations d'action sur les éléments de la base de données * * @author ETP8137 - <NAME> * @since 2.0 * */ public interface Action { /** * Affichage de la valeur de l'action * * @return */ public String getValeur(); }
332
0.593472
0.575668
18
16.722221
21.625103
90
false
false
0
0
0
0
0
0
0.111111
false
false
7
ee7400248d68d19545149c19049862d2d5103ff7
13,262,859,012,552
d3614e98b6525ed012783f490cd5c004cf57e9ca
/src/main/java/com/tizfer/computer/USB1.java
8b1567e053f5d9f22a54c67bedb11b9cc8d076cf
[]
no_license
fancai-cn/fancai-cn
https://github.com/fancai-cn/fancai-cn
e0d819f07c7196482b08aa23fa6061b24d833d3d
d12d3973473c1eaa397f581e2da15c70636f1bcb
refs/heads/master
2020-03-26T07:58:33.569000
2018-08-15T06:27:52
2018-08-15T06:27:52
144,680,193
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tizfer.computer; /** * 第一个usb接口能接哪个驱动 * @author tzf * */ public interface USB1 { String firUsbType(); }
UTF-8
Java
157
java
USB1.java
Java
[ { "context": "r.computer;\r\n\r\n/**\r\n * 第一个usb接口能接哪个驱动\r\n * @author tzf\r\n *\r\n */\r\npublic interface USB1 {\r\n\r\n\tString firU", "end": 71, "score": 0.9995942115783691, "start": 68, "tag": "USERNAME", "value": "tzf" } ]
null
[]
package com.tizfer.computer; /** * 第一个usb接口能接哪个驱动 * @author tzf * */ public interface USB1 { String firUsbType(); }
157
0.607407
0.6
11
10.272727
10.163133
28
false
false
0
0
0
0
0
0
0.272727
false
false
7
c2a6a5e3798c7719c535cf7e0c39c967cb56c183
3,504,693,340,555
1894f0a00ae80732aaf2ba4728494f58a2f901c0
/bvanalytics/src/main/java/com/bazaarvoice/bvandroidsdk/BVTransactionItem.java
7b493d78360d68e3c7afb3462b14a492384ad4c3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
bazaarvoice/bv-android-sdk
https://github.com/bazaarvoice/bv-android-sdk
4da4fd155fbe6f8ffe34e4512ba06e60f3bf17e1
6ffaa54ce7d0999ccd7b1a9326832aad07c9f907
refs/heads/master
2023-07-05T04:24:57.274000
2023-06-08T13:32:24
2023-06-08T13:32:24
4,398,263
17
8
NOASSERTION
false
2021-09-28T10:51:57
2012-05-21T20:22:03
2021-09-21T17:18:02
2021-09-28T10:51:57
68,066
15
7
2
Java
false
false
package com.bazaarvoice.bvandroidsdk; import androidx.annotation.NonNull; import java.util.HashMap; import java.util.Map; import static com.bazaarvoice.bvandroidsdk.BVAnalyticsUtils.mapPutSafe; public final class BVTransactionItem { private final String sku; private final String name; private final String imageUrl; private final String category; private final double price; private final int quantity; private BVTransactionItem(Builder builder) { this.sku = builder.sku; this.name = builder.name; this.imageUrl = builder.imageUrl; this.category = builder.category; this.price = builder.price; this.quantity = builder.quantity; } public String getSku() { return sku; } public String getName() { return name; } public String getImageUrl() { return imageUrl; } public String getCategory() { return category; } public double getPrice() { return price; } public int getQuantity() { return quantity; } public static class Builder { private String sku = ""; private String name = ""; private String imageUrl = ""; private String category = ""; private double price = 0.0; private int quantity = 1; public Builder(@NonNull String sku) { this.sku = sku; } public Builder setName(String name) { this.name = name; return this; } public Builder setImageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public Builder setCategory(String category) { this.category = category; return this; } public Builder setPrice(double price) { this.price = price; return this; } public Builder setQuantity(int quantity) { this.quantity = quantity; return this; } public BVTransactionItem build() { return new BVTransactionItem(this); } } static class Mapper implements BVAnalyticsMapper { private BVTransactionItem transactionItem; public Mapper(@NonNull BVTransactionItem transactionItem) { this.transactionItem = transactionItem; } @Override public Map<String, Object> toRaw() { Map<String, Object> map = new HashMap<>(); mapPutSafe(map, BVEventKeys.TransactionItem.CATEGORY, transactionItem.getCategory()); mapPutSafe(map, BVEventKeys.TransactionItem.IMAGE_URL, transactionItem.getImageUrl()); mapPutSafe(map, BVEventKeys.TransactionItem.NAME, transactionItem.getName()); mapPutSafe(map, BVEventKeys.TransactionItem.QUANTITY, transactionItem.getQuantity()); mapPutSafe(map, BVEventKeys.TransactionItem.PRICE, transactionItem.getPrice()); mapPutSafe(map, BVEventKeys.TransactionItem.SKU, transactionItem.getSku()); return map; } } }
UTF-8
Java
2,773
java
BVTransactionItem.java
Java
[]
null
[]
package com.bazaarvoice.bvandroidsdk; import androidx.annotation.NonNull; import java.util.HashMap; import java.util.Map; import static com.bazaarvoice.bvandroidsdk.BVAnalyticsUtils.mapPutSafe; public final class BVTransactionItem { private final String sku; private final String name; private final String imageUrl; private final String category; private final double price; private final int quantity; private BVTransactionItem(Builder builder) { this.sku = builder.sku; this.name = builder.name; this.imageUrl = builder.imageUrl; this.category = builder.category; this.price = builder.price; this.quantity = builder.quantity; } public String getSku() { return sku; } public String getName() { return name; } public String getImageUrl() { return imageUrl; } public String getCategory() { return category; } public double getPrice() { return price; } public int getQuantity() { return quantity; } public static class Builder { private String sku = ""; private String name = ""; private String imageUrl = ""; private String category = ""; private double price = 0.0; private int quantity = 1; public Builder(@NonNull String sku) { this.sku = sku; } public Builder setName(String name) { this.name = name; return this; } public Builder setImageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public Builder setCategory(String category) { this.category = category; return this; } public Builder setPrice(double price) { this.price = price; return this; } public Builder setQuantity(int quantity) { this.quantity = quantity; return this; } public BVTransactionItem build() { return new BVTransactionItem(this); } } static class Mapper implements BVAnalyticsMapper { private BVTransactionItem transactionItem; public Mapper(@NonNull BVTransactionItem transactionItem) { this.transactionItem = transactionItem; } @Override public Map<String, Object> toRaw() { Map<String, Object> map = new HashMap<>(); mapPutSafe(map, BVEventKeys.TransactionItem.CATEGORY, transactionItem.getCategory()); mapPutSafe(map, BVEventKeys.TransactionItem.IMAGE_URL, transactionItem.getImageUrl()); mapPutSafe(map, BVEventKeys.TransactionItem.NAME, transactionItem.getName()); mapPutSafe(map, BVEventKeys.TransactionItem.QUANTITY, transactionItem.getQuantity()); mapPutSafe(map, BVEventKeys.TransactionItem.PRICE, transactionItem.getPrice()); mapPutSafe(map, BVEventKeys.TransactionItem.SKU, transactionItem.getSku()); return map; } } }
2,773
0.688063
0.686982
112
23.758928
22.536972
92
false
false
0
0
0
0
0
0
0.580357
false
false
7
e77f5e17502366421293ba44182cadb9b8cca346
18,691,697,700,439
79ed468f73e6b9a0184a19e4d70c0ecc378e64a5
/core/src/main/java/org/example/nicop/demo_actuator/util/UriUtils.java
7c2f72fab89bdb8041bbbd229fdafc8eb0cb0b1b
[]
no_license
npayneau/demo-spring-boot-actuator
https://github.com/npayneau/demo-spring-boot-actuator
6b2e0215a1903803aecbaf8b28a91c8469fd5f91
bb215efde1bf7dd6f85739c71c2695b0051e970e
refs/heads/master
2021-01-17T16:02:28.621000
2017-06-26T14:45:02
2017-06-26T14:45:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.example.nicop.demo_actuator.util; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import static java.util.Collections.emptyMap; public final class UriUtils { public static Map<String, String> splitQuery(URI uri) { String query = uri.getQuery(); if(query == null) { return emptyMap(); } Map<String, String> queryPairs = new HashMap<>(); String[] pairs = query.split("&"); for (String pair : pairs) { int idx = pair.indexOf("="); if(idx != -1) queryPairs.put(decodeAsUtf8(pair.substring(0, idx)), decodeAsUtf8(pair.substring(idx + 1))); else queryPairs.put(decodeAsUtf8(pair), ""); } return queryPairs; } private static String decodeAsUtf8(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { return ""; } } }
UTF-8
Java
1,078
java
UriUtils.java
Java
[]
null
[]
package org.example.nicop.demo_actuator.util; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import static java.util.Collections.emptyMap; public final class UriUtils { public static Map<String, String> splitQuery(URI uri) { String query = uri.getQuery(); if(query == null) { return emptyMap(); } Map<String, String> queryPairs = new HashMap<>(); String[] pairs = query.split("&"); for (String pair : pairs) { int idx = pair.indexOf("="); if(idx != -1) queryPairs.put(decodeAsUtf8(pair.substring(0, idx)), decodeAsUtf8(pair.substring(idx + 1))); else queryPairs.put(decodeAsUtf8(pair), ""); } return queryPairs; } private static String decodeAsUtf8(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { return ""; } } }
1,078
0.590909
0.583488
38
27.368422
22.912214
108
false
false
0
0
0
0
0
0
0.605263
false
false
7
c1c9ef7e067741ba09ddcfb92fa7a0c593694df8
25,391,846,672,316
0b090ecd1bbe057bf8c55d74a86cdb44714ef0be
/prime/src/main/java/ucla/si/controlador/gc/ControladorServicio.java
2758c68511b0a121a95d99435ec214072179e964
[]
no_license
liscanojose/prime_desktop
https://github.com/liscanojose/prime_desktop
c5f3aaebb1f558d03076eb3a72233b07a43d0e95
50295f2fa63cbccbba38f9591e4a4d66115e2535
refs/heads/master
2021-04-25T12:08:53.518000
2017-11-23T13:55:29
2017-11-23T13:55:29
111,814,696
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ucla.si.controlador.gc; import java.util.ArrayList; import java.util.Date; import java.util.Map; import org.apache.poi.ss.usermodel.Textbox; import org.zkoss.zhtml.Messagebox; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.CreateEvent; import org.zkoss.zk.ui.select.SelectorComposer; import org.zkoss.zk.ui.select.annotation.Listen; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zul.Button; import org.zkoss.zul.Combobox; import org.zkoss.zul.Intbox; import antlr.collections.List; import ucla.si.dao.ServicioDAO; import ucla.si.modelo.Usuario; import ucla.si.modelo.Servicio; public class ControladorServicio extends SelectorComposer<Component> { private Servicio servicio = new Servicio(); private Button btnGuardar; @Wire private Button btnModificar, btnEliminarRetencion, btnAgregarRetencion, btnAgregarEspecialidad, btnEliminarEspecialidad, btnAgregarTipoPago, btnEliminarTipoPago; @Wire private Combobox cmbEstatus; @Wire private Textbox txt_codigo, txt_descripcion; @Wire private Intbox int_precio; @Listen("onClick =#btnGuardar2") public void msg() { Messagebox.show("hola"); } /* * @Listen("onClick =#btnGuardar") public void aCambiarContrasenna() { * //String dir = "vista/content.zul"; String dir = "vista/content.zul"; * * //Clients.evalJavaScript("document.title = 'ServiAldanas'; "); } */ @Listen("onClick =#btnGuardar") public void guardarServicio() { boolean error = false; try { String codigo; String descripcion; double precio; String estatus; //estatus = cmbEstatus.getValue().trim(); //System.out.println(estatus); // codigo= txt_codigo.toString(); codigo = txt_codigo.toString(); System.out.println(codigo); precio = int_precio.getValue(); System.out.println(precio); // Datos Generales servicio.setCodigo(codigo); //servicio.setEstatus(estatus); servicio.setEstatus("1"); servicio.setPrecio(precio); ServicioDAO servicioDao = new ServicioDAO(); servicioDao.save(servicio); // System.out.println("1"); } catch (org.springframework.transaction.TransactionTimedOutException e) { Messagebox.show("¡Tiempo Expirado para la transacción!", "Información", Messagebox.OK, Messagebox.ERROR); } catch (org.hibernate.TransactionException e) { Messagebox.show("¡Tiempo Expirado para la transacción!", "Información", Messagebox.OK, Messagebox.ERROR); } catch (Exception e) { e.printStackTrace(); error = true; Messagebox.show("¡Error al guardar el servicio!", "Error", Messagebox.OK, Messagebox.ERROR); } Messagebox.show("Servicio registrado exitosamente"); } }
UTF-8
Java
2,670
java
ControladorServicio.java
Java
[]
null
[]
package ucla.si.controlador.gc; import java.util.ArrayList; import java.util.Date; import java.util.Map; import org.apache.poi.ss.usermodel.Textbox; import org.zkoss.zhtml.Messagebox; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.CreateEvent; import org.zkoss.zk.ui.select.SelectorComposer; import org.zkoss.zk.ui.select.annotation.Listen; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zul.Button; import org.zkoss.zul.Combobox; import org.zkoss.zul.Intbox; import antlr.collections.List; import ucla.si.dao.ServicioDAO; import ucla.si.modelo.Usuario; import ucla.si.modelo.Servicio; public class ControladorServicio extends SelectorComposer<Component> { private Servicio servicio = new Servicio(); private Button btnGuardar; @Wire private Button btnModificar, btnEliminarRetencion, btnAgregarRetencion, btnAgregarEspecialidad, btnEliminarEspecialidad, btnAgregarTipoPago, btnEliminarTipoPago; @Wire private Combobox cmbEstatus; @Wire private Textbox txt_codigo, txt_descripcion; @Wire private Intbox int_precio; @Listen("onClick =#btnGuardar2") public void msg() { Messagebox.show("hola"); } /* * @Listen("onClick =#btnGuardar") public void aCambiarContrasenna() { * //String dir = "vista/content.zul"; String dir = "vista/content.zul"; * * //Clients.evalJavaScript("document.title = 'ServiAldanas'; "); } */ @Listen("onClick =#btnGuardar") public void guardarServicio() { boolean error = false; try { String codigo; String descripcion; double precio; String estatus; //estatus = cmbEstatus.getValue().trim(); //System.out.println(estatus); // codigo= txt_codigo.toString(); codigo = txt_codigo.toString(); System.out.println(codigo); precio = int_precio.getValue(); System.out.println(precio); // Datos Generales servicio.setCodigo(codigo); //servicio.setEstatus(estatus); servicio.setEstatus("1"); servicio.setPrecio(precio); ServicioDAO servicioDao = new ServicioDAO(); servicioDao.save(servicio); // System.out.println("1"); } catch (org.springframework.transaction.TransactionTimedOutException e) { Messagebox.show("¡Tiempo Expirado para la transacción!", "Información", Messagebox.OK, Messagebox.ERROR); } catch (org.hibernate.TransactionException e) { Messagebox.show("¡Tiempo Expirado para la transacción!", "Información", Messagebox.OK, Messagebox.ERROR); } catch (Exception e) { e.printStackTrace(); error = true; Messagebox.show("¡Error al guardar el servicio!", "Error", Messagebox.OK, Messagebox.ERROR); } Messagebox.show("Servicio registrado exitosamente"); } }
2,670
0.73451
0.733383
102
25.107843
25.58412
108
false
false
0
0
0
0
0
0
1.813725
false
false
7
fd74f5cdfe07a7ac0ad87b80fd1a6d6ebfb1edb1
20,864,951,128,881
b42c6de4190d62f82d3970d3dfcbe28d970e4b62
/src/main/java/cn/coding/exception/SeckillCloseException.java
aa640a66d796524f228c195df192a8708f5763cf
[]
no_license
BeyondLIG/seckill
https://github.com/BeyondLIG/seckill
5eaa91f8315e0d856542b55116754b664b5c8f9f
5455ae8649df71249db62f4ec9a33ae5e4136d72
refs/heads/master
2021-08-08T20:49:09.954000
2017-11-10T22:21:25
2017-11-10T22:21:25
110,323,295
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.coding.exception; /** * 秒杀关闭异常,当秒杀关闭后,用户继续秒杀会抛出这个错误 */ public class SeckillCloseException extends SeckillException { public SeckillCloseException(String messaeg){ super(messaeg); } public SeckillCloseException(String message, Throwable cause){ super(message, cause); } }
UTF-8
Java
372
java
SeckillCloseException.java
Java
[]
null
[]
package cn.coding.exception; /** * 秒杀关闭异常,当秒杀关闭后,用户继续秒杀会抛出这个错误 */ public class SeckillCloseException extends SeckillException { public SeckillCloseException(String messaeg){ super(messaeg); } public SeckillCloseException(String message, Throwable cause){ super(message, cause); } }
372
0.713836
0.713836
14
21.714285
22.454489
66
false
false
0
0
0
0
0
0
0.357143
false
false
7
64011fefc81e647a24ee50ad75dd1f2c02086df3
23,819,888,646,193
48e835e6f176a8ac9ae3ca718e8922891f1e5a18
/benchmark/validation/io/helidon/config/spi/ConfigSourceTest.java
da5aff83f5f150829660d2ea82b5b8e4d5ed9cf6
[]
no_license
STAMP-project/dspot-experiments
https://github.com/STAMP-project/dspot-experiments
f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5
121487e65cdce6988081b67f21bbc6731354a47f
refs/heads/master
2023-02-07T14:40:12.919000
2019-11-06T07:17:09
2019-11-06T07:17:09
75,710,758
14
19
null
false
2023-01-26T23:57:41
2016-12-06T08:27:42
2022-02-18T17:43:31
2023-01-26T23:57:40
651,434
12
14
5
null
false
false
/** * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 io.helidon.config.spi; import PropertiesConfigParser.MEDIA_TYPE_TEXT_JAVA_PROPERTIES; import io.helidon.common.reactive.Flow; import io.helidon.config.ConfigParsers; import io.helidon.config.ConfigSources; import io.helidon.config.ValueNodeMatcher; import io.helidon.config.spi.ConfigNode.ObjectNode; import io.helidon.config.test.infra.RestoreSystemPropertiesExt; import java.io.StringReader; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import static io.helidon.config.internal.PropertiesConfigParser.MEDIA_TYPE_TEXT_JAVA_PROPERTIES; /** * Tests {@link ConfigSource}. */ @ExtendWith(RestoreSystemPropertiesExt.class) public class ConfigSourceTest { public static final String TEST_ENV_VAR_NAME = "CONFIG_SOURCE_TEST_PROPERTY"; public static final String TEST_ENV_VAR_VALUE = "This Is My ENV VARS Value."; private static final String TEST_SYS_PROP_NAME = "this_is_my_property-ConfigSourceTest"; private static final String TEST_SYS_PROP_VALUE = "This Is My SYS PROPS Value."; @Test public void testFromObjectNodeDescription() { ConfigSource configSource = ConfigSources.create(ObjectNode.empty()); MatcherAssert.assertThat(configSource.description(), Matchers.is("InMemoryConfig[ObjectNode]")); } @Test public void testFromObjectNodeLoad() { ConfigSource configSource = ConfigSources.create(ObjectNode.empty()); configSource.init(Mockito.mock(ConfigContext.class)); MatcherAssert.assertThat(configSource.load().get().entrySet(), Matchers.is(Matchers.empty())); } @Test public void testFromReadableDescription() { ConfigSource configSource = ConfigSources.create(new StringReader("aaa=bbb"), MEDIA_TYPE_TEXT_JAVA_PROPERTIES); MatcherAssert.assertThat(configSource.description(), Matchers.is("InMemoryConfig[Readable]")); } @Test public void testFromReadableLoad() { ConfigContext context = Mockito.mock(ConfigContext.class); Mockito.when(context.findParser(ArgumentMatchers.any())).thenReturn(Optional.of(ConfigParsers.properties())); ConfigSource configSource = ConfigSources.create(new StringReader("aaa=bbb"), MEDIA_TYPE_TEXT_JAVA_PROPERTIES); configSource.init(context); MatcherAssert.assertThat(configSource.load().get().get("aaa"), ValueNodeMatcher.valueNode("bbb")); } @ExtendWith(RestoreSystemPropertiesExt.class) @Test public void testFromTextDescription() { ConfigSource configSource = ConfigSources.create("aaa=bbb", MEDIA_TYPE_TEXT_JAVA_PROPERTIES); MatcherAssert.assertThat(configSource.description(), Matchers.is("InMemoryConfig[String]")); } @Test public void testFromTextLoad() { ConfigContext context = Mockito.mock(ConfigContext.class); Mockito.when(context.findParser(ArgumentMatchers.argThat(MEDIA_TYPE_TEXT_JAVA_PROPERTIES::equals))).thenReturn(Optional.of(ConfigParsers.properties())); ConfigSource configSource = ConfigSources.create("aaa=bbb", MEDIA_TYPE_TEXT_JAVA_PROPERTIES); configSource.init(context); MatcherAssert.assertThat(configSource.load().get().get("aaa"), ValueNodeMatcher.valueNode("bbb")); } @Test public void testFromSystemPropertiesDescription() { ConfigSource configSource = ConfigSources.systemProperties(); MatcherAssert.assertThat(configSource.description(), Matchers.is("MapConfig[sys-props]")); } @Test public void testFromSystemProperties() { System.setProperty(ConfigSourceTest.TEST_SYS_PROP_NAME, ConfigSourceTest.TEST_SYS_PROP_VALUE); ConfigSource configSource = ConfigSources.systemProperties(); configSource.init(Mockito.mock(ConfigContext.class)); MatcherAssert.assertThat(configSource.load().get().get(ConfigSourceTest.TEST_SYS_PROP_NAME), ValueNodeMatcher.valueNode(ConfigSourceTest.TEST_SYS_PROP_VALUE)); } @Test public void testFromEnvironmentVariablesDescription() { ConfigSource configSource = ConfigSources.environmentVariables(); MatcherAssert.assertThat(configSource.description(), Matchers.is("MapConfig[env-vars]")); } @Test public void testFromEnvironmentVariables() { ConfigSource configSource = ConfigSources.environmentVariables(); configSource.init(Mockito.mock(ConfigContext.class)); MatcherAssert.assertThat(configSource.load().get().get(ConfigSourceTest.TEST_ENV_VAR_NAME), ValueNodeMatcher.valueNode(ConfigSourceTest.TEST_ENV_VAR_VALUE)); } @Test public void testChangesDefault() throws InterruptedException { ConfigSource configSource = Optional::empty; CountDownLatch onComplete = new CountDownLatch(1); configSource.changes().subscribe(new Flow.Subscriber<Optional<ObjectNode>>() { @Override public void onSubscribe(Flow.Subscription subscription) { subscription.request(Long.MAX_VALUE); } @Override public void onNext(Optional<ObjectNode> item) { fail("onNext should not be invoked"); } @Override public void onError(Throwable throwable) { fail("onError should not be invoked"); } @Override public void onComplete() { onComplete.countDown(); } }); MatcherAssert.assertThat(onComplete.await(10, TimeUnit.MILLISECONDS), Is.is(true)); } }
UTF-8
Java
6,441
java
ConfigSourceTest.java
Java
[]
null
[]
/** * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 io.helidon.config.spi; import PropertiesConfigParser.MEDIA_TYPE_TEXT_JAVA_PROPERTIES; import io.helidon.common.reactive.Flow; import io.helidon.config.ConfigParsers; import io.helidon.config.ConfigSources; import io.helidon.config.ValueNodeMatcher; import io.helidon.config.spi.ConfigNode.ObjectNode; import io.helidon.config.test.infra.RestoreSystemPropertiesExt; import java.io.StringReader; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import static io.helidon.config.internal.PropertiesConfigParser.MEDIA_TYPE_TEXT_JAVA_PROPERTIES; /** * Tests {@link ConfigSource}. */ @ExtendWith(RestoreSystemPropertiesExt.class) public class ConfigSourceTest { public static final String TEST_ENV_VAR_NAME = "CONFIG_SOURCE_TEST_PROPERTY"; public static final String TEST_ENV_VAR_VALUE = "This Is My ENV VARS Value."; private static final String TEST_SYS_PROP_NAME = "this_is_my_property-ConfigSourceTest"; private static final String TEST_SYS_PROP_VALUE = "This Is My SYS PROPS Value."; @Test public void testFromObjectNodeDescription() { ConfigSource configSource = ConfigSources.create(ObjectNode.empty()); MatcherAssert.assertThat(configSource.description(), Matchers.is("InMemoryConfig[ObjectNode]")); } @Test public void testFromObjectNodeLoad() { ConfigSource configSource = ConfigSources.create(ObjectNode.empty()); configSource.init(Mockito.mock(ConfigContext.class)); MatcherAssert.assertThat(configSource.load().get().entrySet(), Matchers.is(Matchers.empty())); } @Test public void testFromReadableDescription() { ConfigSource configSource = ConfigSources.create(new StringReader("aaa=bbb"), MEDIA_TYPE_TEXT_JAVA_PROPERTIES); MatcherAssert.assertThat(configSource.description(), Matchers.is("InMemoryConfig[Readable]")); } @Test public void testFromReadableLoad() { ConfigContext context = Mockito.mock(ConfigContext.class); Mockito.when(context.findParser(ArgumentMatchers.any())).thenReturn(Optional.of(ConfigParsers.properties())); ConfigSource configSource = ConfigSources.create(new StringReader("aaa=bbb"), MEDIA_TYPE_TEXT_JAVA_PROPERTIES); configSource.init(context); MatcherAssert.assertThat(configSource.load().get().get("aaa"), ValueNodeMatcher.valueNode("bbb")); } @ExtendWith(RestoreSystemPropertiesExt.class) @Test public void testFromTextDescription() { ConfigSource configSource = ConfigSources.create("aaa=bbb", MEDIA_TYPE_TEXT_JAVA_PROPERTIES); MatcherAssert.assertThat(configSource.description(), Matchers.is("InMemoryConfig[String]")); } @Test public void testFromTextLoad() { ConfigContext context = Mockito.mock(ConfigContext.class); Mockito.when(context.findParser(ArgumentMatchers.argThat(MEDIA_TYPE_TEXT_JAVA_PROPERTIES::equals))).thenReturn(Optional.of(ConfigParsers.properties())); ConfigSource configSource = ConfigSources.create("aaa=bbb", MEDIA_TYPE_TEXT_JAVA_PROPERTIES); configSource.init(context); MatcherAssert.assertThat(configSource.load().get().get("aaa"), ValueNodeMatcher.valueNode("bbb")); } @Test public void testFromSystemPropertiesDescription() { ConfigSource configSource = ConfigSources.systemProperties(); MatcherAssert.assertThat(configSource.description(), Matchers.is("MapConfig[sys-props]")); } @Test public void testFromSystemProperties() { System.setProperty(ConfigSourceTest.TEST_SYS_PROP_NAME, ConfigSourceTest.TEST_SYS_PROP_VALUE); ConfigSource configSource = ConfigSources.systemProperties(); configSource.init(Mockito.mock(ConfigContext.class)); MatcherAssert.assertThat(configSource.load().get().get(ConfigSourceTest.TEST_SYS_PROP_NAME), ValueNodeMatcher.valueNode(ConfigSourceTest.TEST_SYS_PROP_VALUE)); } @Test public void testFromEnvironmentVariablesDescription() { ConfigSource configSource = ConfigSources.environmentVariables(); MatcherAssert.assertThat(configSource.description(), Matchers.is("MapConfig[env-vars]")); } @Test public void testFromEnvironmentVariables() { ConfigSource configSource = ConfigSources.environmentVariables(); configSource.init(Mockito.mock(ConfigContext.class)); MatcherAssert.assertThat(configSource.load().get().get(ConfigSourceTest.TEST_ENV_VAR_NAME), ValueNodeMatcher.valueNode(ConfigSourceTest.TEST_ENV_VAR_VALUE)); } @Test public void testChangesDefault() throws InterruptedException { ConfigSource configSource = Optional::empty; CountDownLatch onComplete = new CountDownLatch(1); configSource.changes().subscribe(new Flow.Subscriber<Optional<ObjectNode>>() { @Override public void onSubscribe(Flow.Subscription subscription) { subscription.request(Long.MAX_VALUE); } @Override public void onNext(Optional<ObjectNode> item) { fail("onNext should not be invoked"); } @Override public void onError(Throwable throwable) { fail("onError should not be invoked"); } @Override public void onComplete() { onComplete.countDown(); } }); MatcherAssert.assertThat(onComplete.await(10, TimeUnit.MILLISECONDS), Is.is(true)); } }
6,441
0.721006
0.718677
152
41.36842
38.081921
167
false
false
0
0
0
0
0
0
0.559211
false
false
7
324565dfd3fbebe47228541d6c38c056f2b2f329
18,760,417,184,303
1f63e12faa05e10b78f4590bc2987696600433fa
/app/src/main/java/com/shalate/red/shalate/Model/ChatModel.java
78a0427c14d2f54f5ef360422321dab0d3c2ba41
[]
no_license
abdelmageedesmail/Shalate
https://github.com/abdelmageedesmail/Shalate
3e093ce25e5e6b5e264fbb0f37eeaac06476bf7c
5fdfd76cbedbc8f6c7edb72db554d51b5099c76a
refs/heads/master
2020-05-03T17:18:46.640000
2019-03-31T20:55:40
2019-03-31T20:55:40
178,740,130
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shalate.red.shalate.Model; /** * Created by Ahmed on 8/27/2018. */ public class ChatModel { private long date; private String to; private String message; private String from; private String isLocation; private String lat; private String lon; private String voiceRecrod; private String postImage; private String postId; private int type; public ChatModel() { } public ChatModel(long date, String to, String message, String from, int type) { this.date = date; this.to = to; this.message = message; this.from = from; this.type = type; } public long getDate() { return date; } public void setDate(long date) { this.date = date; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getIsLocation() { return isLocation; } public void setIsLocation(String isLocation) { this.isLocation = isLocation; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getLon() { return lon; } public void setLon(String lon) { this.lon = lon; } public String getVoiceRecrod() { return voiceRecrod; } public void setVoiceRecrod(String voiceRecrod) { this.voiceRecrod = voiceRecrod; } public String getPostImage() { return postImage; } public void setPostImage(String postImage) { this.postImage = postImage; } public String getPostId() { return postId; } public void setPostId(String postId) { this.postId = postId; } }
UTF-8
Java
2,188
java
ChatModel.java
Java
[ { "context": " com.shalate.red.shalate.Model;\n\n/**\n * Created by Ahmed on 8/27/2018.\n */\n\npublic class ChatModel {\n p", "end": 63, "score": 0.9991428852081299, "start": 58, "tag": "NAME", "value": "Ahmed" } ]
null
[]
package com.shalate.red.shalate.Model; /** * Created by Ahmed on 8/27/2018. */ public class ChatModel { private long date; private String to; private String message; private String from; private String isLocation; private String lat; private String lon; private String voiceRecrod; private String postImage; private String postId; private int type; public ChatModel() { } public ChatModel(long date, String to, String message, String from, int type) { this.date = date; this.to = to; this.message = message; this.from = from; this.type = type; } public long getDate() { return date; } public void setDate(long date) { this.date = date; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getIsLocation() { return isLocation; } public void setIsLocation(String isLocation) { this.isLocation = isLocation; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getLon() { return lon; } public void setLon(String lon) { this.lon = lon; } public String getVoiceRecrod() { return voiceRecrod; } public void setVoiceRecrod(String voiceRecrod) { this.voiceRecrod = voiceRecrod; } public String getPostImage() { return postImage; } public void setPostImage(String postImage) { this.postImage = postImage; } public String getPostId() { return postId; } public void setPostId(String postId) { this.postId = postId; } }
2,188
0.578611
0.575411
118
17.542374
15.680412
83
false
false
0
0
0
0
0
0
0.364407
false
false
7
78e11445986aa3709d3f7a94e6c997c9417afd5d
15,942,918,640,994
ef5bec57c4193cc2b449b50b7d049061b3b222e9
/src/main/java/pl/sda/jsondataset/Embedded.java
552476466f2ff721ecbc99e2ae3a40109b78492d
[]
no_license
javabyd6/JSON_DataSets_DW
https://github.com/javabyd6/JSON_DataSets_DW
8b094059cfd58157655292630ff3b7ef8ec505c9
66dab40556a90a184f24634b5747b5486f9e36d8
refs/heads/master
2020-04-28T00:17:23.029000
2019-03-10T12:34:48
2019-03-10T12:34:48
174,809,911
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.sda.jsondataset; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @NoArgsConstructor @AllArgsConstructor @Data public class Embedded { List<Episodes> episodes; }
UTF-8
Java
240
java
Embedded.java
Java
[]
null
[]
package pl.sda.jsondataset; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @NoArgsConstructor @AllArgsConstructor @Data public class Embedded { List<Episodes> episodes; }
240
0.808333
0.808333
13
17.461538
11.593204
33
false
false
0
0
0
0
0
0
0.461538
false
false
7
61e4b75e93784dc5e1173169ee142f10fb9a3357
14,113,262,564,080
da051f242cc94aad44bce13eaaf0aea20377bdfb
/src/main/java/com/revature/reimbursement/TestingDb.java
029880819ca82286448d8079ad81f60a379843ec
[]
no_license
Peacepapi/Reimbursement-Revature
https://github.com/Peacepapi/Reimbursement-Revature
8273f722d1c447c8adb62ba8c9e526f9a27f717d
19e1d6f790d060963ff3d4da1ee8d169d0d2bafe
refs/heads/master
2021-01-21T08:02:32.507000
2017-03-02T16:25:28
2017-03-02T16:25:28
83,333,371
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.revature.reimbursement; import com.revature.reimbursement.DAO.UserDAOImpl; import com.revature.reimbursement.Model.User; public class TestingDb { // public static void main(String[] args){ // UserDAOImpl dao = new UserDAOImpl(); // User user = dao.getUserByUsername("SDippy"); // // String password = "Cambodia"; // String hashed = BCrypt.hashpw(password, BCrypt.gensalt()); // // System.out.println(hashed); // if (BCrypt.checkpw(password, hashed)) // System.out.println("It matches"); // else // System.out.println("It does not match"); // } }
UTF-8
Java
578
java
TestingDb.java
Java
[ { "context": "DAOImpl();\n//\t\tUser user = dao.getUserByUsername(\"SDippy\");\n//\t\t\n//\t\tString password = \"Cambodia\";\n//\t\tStr", "end": 291, "score": 0.9995428919792175, "start": 285, "tag": "USERNAME", "value": "SDippy" }, { "context": "ByUsername(\"SDippy\");\n//\t\t\n//\t\tString password = \"Cambodia\";\n//\t\tString hashed = BCrypt.hashpw(password, BCr", "end": 331, "score": 0.99934983253479, "start": 323, "tag": "PASSWORD", "value": "Cambodia" } ]
null
[]
package com.revature.reimbursement; import com.revature.reimbursement.DAO.UserDAOImpl; import com.revature.reimbursement.Model.User; public class TestingDb { // public static void main(String[] args){ // UserDAOImpl dao = new UserDAOImpl(); // User user = dao.getUserByUsername("SDippy"); // // String password = "<PASSWORD>"; // String hashed = BCrypt.hashpw(password, BCrypt.gensalt()); // // System.out.println(hashed); // if (BCrypt.checkpw(password, hashed)) // System.out.println("It matches"); // else // System.out.println("It does not match"); // } }
580
0.697232
0.697232
21
26.476191
20.037153
62
false
false
0
0
0
0
0
0
1.857143
false
false
7
0c646291f6faa35601e7d33927895cb837e1b44f
6,657,199,361,770
653f3ff85b21877e22a5735940fb475d882c5eaf
/Bridgelabz/src/com/practice/functions/Quadratic.java
00dce3bce85b5f0f31a576a662021ab4aaa7c281
[]
no_license
BL-HONEY/newpracticemodules
https://github.com/BL-HONEY/newpracticemodules
634e16b10a72fff66edd987f823d187a90b36048
2300a57896ef1fbd29c6cac86a0ad49f9760525d
refs/heads/master
2020-04-11T11:09:07.650000
2018-12-20T12:43:05
2018-12-20T12:43:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.practice.functions; import com.resources.utility.Utility; /** * * @author honey * */ public class Quadratic { public static void main(String[] args) { System.out.println("An Quadratic Equation is of form ax2 + bx + c (where '`' represents power means x * x)"); System.out.println("Enter values for a ,b, c"); int a = Utility.getInt(); int b = Utility.getInt(); int c = Utility.getInt(); Utility.representQuadratic(a,b,c); int[] roots = Utility.findRoots(a, b, c); for(int i=0 ; i<2 ; i++) System.out.println("roots are "+ roots[i]); } }
UTF-8
Java
654
java
Quadratic.java
Java
[ { "context": "com.resources.utility.Utility;\n\n/**\n * \n * @author honey\n *\n */\n\npublic class Quadratic \n{\n\n\tpublic static", "end": 96, "score": 0.9793776273727417, "start": 91, "tag": "USERNAME", "value": "honey" } ]
null
[]
package com.practice.functions; import com.resources.utility.Utility; /** * * @author honey * */ public class Quadratic { public static void main(String[] args) { System.out.println("An Quadratic Equation is of form ax2 + bx + c (where '`' represents power means x * x)"); System.out.println("Enter values for a ,b, c"); int a = Utility.getInt(); int b = Utility.getInt(); int c = Utility.getInt(); Utility.representQuadratic(a,b,c); int[] roots = Utility.findRoots(a, b, c); for(int i=0 ; i<2 ; i++) System.out.println("roots are "+ roots[i]); } }
654
0.574924
0.570336
31
20.096775
24.541412
113
false
false
0
0
0
0
0
0
0.774194
false
false
7
5b88fd46e04a3aa50a980455c93666ad8d690c7e
6,657,199,363,140
06279cf6cf1914a60328cc1a735c341132b766ec
/src/general/Pod.java
35e88ad5f418753acc7c792295d060f1410334d1
[]
no_license
MarcoRomani/Thesis
https://github.com/MarcoRomani/Thesis
11b24c18eb199940b16231922387a3f971cca173
c37dbbf4ced32e7c7fbf83e217be64a8e0a6cdb2
refs/heads/master
2021-05-06T08:14:04.196000
2018-05-31T11:10:31
2018-05-31T11:10:31
114,002,274
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package general; import java.util.ArrayList; public abstract class Pod implements Comparable<Pod> { public static int pod_id = 0; protected int id; protected int racks_number; protected ArrayList<Rack> racks = new ArrayList<Rack>(); protected ArrayList<Switch> core; protected ArrayList<Switch> edge = new ArrayList<Switch>(); protected ArrayList<Switch> aggregation = new ArrayList<Switch>(); protected int lower_index; protected int upper_index; protected abstract void build(); public int getId() { return id; } public int getRacks_number() { return racks_number; } public ArrayList<Rack> getRacks() { return racks; } public ArrayList<Switch> getCore() { return core; } public ArrayList<Switch> getEdge() { return edge; } public ArrayList<Switch> getAggregation() { return aggregation; } public int getLower_index() { return lower_index; } public int getUpper_index() { return upper_index; } public boolean containsServer(int i) { return (i >= lower_index && i <= upper_index); } }
UTF-8
Java
1,048
java
Pod.java
Java
[]
null
[]
package general; import java.util.ArrayList; public abstract class Pod implements Comparable<Pod> { public static int pod_id = 0; protected int id; protected int racks_number; protected ArrayList<Rack> racks = new ArrayList<Rack>(); protected ArrayList<Switch> core; protected ArrayList<Switch> edge = new ArrayList<Switch>(); protected ArrayList<Switch> aggregation = new ArrayList<Switch>(); protected int lower_index; protected int upper_index; protected abstract void build(); public int getId() { return id; } public int getRacks_number() { return racks_number; } public ArrayList<Rack> getRacks() { return racks; } public ArrayList<Switch> getCore() { return core; } public ArrayList<Switch> getEdge() { return edge; } public ArrayList<Switch> getAggregation() { return aggregation; } public int getLower_index() { return lower_index; } public int getUpper_index() { return upper_index; } public boolean containsServer(int i) { return (i >= lower_index && i <= upper_index); } }
1,048
0.708969
0.708015
55
18.054546
18.402983
67
false
false
0
0
0
0
0
0
1.272727
false
false
7
57960524a379d801ae4ed7bd1dd74a8a5a4bb69e
27,805,618,329,870
ef68a638ebfe7c1161d3ffee225a89da8f1e6fe4
/src/main/java/com/takeaway/challenge/kafka/producer/EmployeeEvent.java
6f190453dc306c7c9e8eb0831759f86bbe5a517e
[]
no_license
zehrakomurcu/bob-employee-service
https://github.com/zehrakomurcu/bob-employee-service
ab8997d4de025a3e2a998c3d277a937bbb464f93
7ba8bbbdb636b72246b878a407994d45e0219cd7
refs/heads/master
2023-04-17T10:44:51.256000
2021-04-28T08:51:34
2021-04-28T08:51:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.takeaway.challenge.kafka.producer; import lombok.AllArgsConstructor; import lombok.Data; @AllArgsConstructor @Data public class EmployeeEvent { private EventType eventType; private String sourceId; private EmployeeData data; public enum EventType { EMPLOYEE_CREATED, EMPLOYEE_UPDATED, EMPLOYEE_DELETED; } }
UTF-8
Java
350
java
EmployeeEvent.java
Java
[]
null
[]
package com.takeaway.challenge.kafka.producer; import lombok.AllArgsConstructor; import lombok.Data; @AllArgsConstructor @Data public class EmployeeEvent { private EventType eventType; private String sourceId; private EmployeeData data; public enum EventType { EMPLOYEE_CREATED, EMPLOYEE_UPDATED, EMPLOYEE_DELETED; } }
350
0.757143
0.757143
16
20.875
17.585062
61
false
false
0
0
0
0
0
0
0.5625
false
false
7
c10341c76463eccba4d763b7bf20fbd31a30c83e
2,645,699,923,935
6e60ba48ffc35b98121230571cd5145e552d0a2f
/app/src/main/java/com/example/administrator/helloword/fragments/inputcell/MainTabbarFragment.java
f77e4f2d2132e5f4e80c2c7577a2bb901a6d4a55
[]
no_license
LiLingke/pratice_class2_LiLingke_201341410221
https://github.com/LiLingke/pratice_class2_LiLingke_201341410221
c0c22c482369e97fb4617e4dcf82321bcb12e984
afe720abcc878a4a3b0ad99159bb50f6e5e5bfa0
refs/heads/master
2020-06-10T06:59:42.642000
2016-12-07T01:17:36
2016-12-07T01:17:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.helloword.fragments.inputcell; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.administrator.helloword.R; /** * Created by Administrator on 2016/12/6. */ public class MainTabbarFragment extends Fragment{ View btnNew,tabFeeds,tabSearch,tabMe,tabNotes; View [] tabs; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main_tabbar,null); tabFeeds = view.findViewById(R.id.tab_feeds); tabMe = view.findViewById(R.id.tab_me); tabSearch = view.findViewById(R.id.tab_search); tabNotes = view.findViewById(R.id.tab_notes); btnNew = view.findViewById(R.id.tab_new); tabs = new View[]{ tabNotes,tabSearch,tabMe,tabFeeds }; for (final View tab : tabs){ tab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onTabClicked(tab); } }); } return view; } private void onTabClicked(View tab) { for (View otherTab : tabs){ otherTab.setSelected(otherTab == tab); } } }
UTF-8
Java
1,434
java
MainTabbarFragment.java
Java
[]
null
[]
package com.example.administrator.helloword.fragments.inputcell; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.administrator.helloword.R; /** * Created by Administrator on 2016/12/6. */ public class MainTabbarFragment extends Fragment{ View btnNew,tabFeeds,tabSearch,tabMe,tabNotes; View [] tabs; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main_tabbar,null); tabFeeds = view.findViewById(R.id.tab_feeds); tabMe = view.findViewById(R.id.tab_me); tabSearch = view.findViewById(R.id.tab_search); tabNotes = view.findViewById(R.id.tab_notes); btnNew = view.findViewById(R.id.tab_new); tabs = new View[]{ tabNotes,tabSearch,tabMe,tabFeeds }; for (final View tab : tabs){ tab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onTabClicked(tab); } }); } return view; } private void onTabClicked(View tab) { for (View otherTab : tabs){ otherTab.setSelected(otherTab == tab); } } }
1,434
0.640865
0.635983
50
27.68
23.715345
103
false
false
0
0
0
0
0
0
0.62
false
false
7
cc4bba15d94e3471e25d8461531e63229a478bb6
18,210,661,343,526
8a50cb58f39b0336916eb1962a08a6043570e265
/2020/07/src/Prob.java
db365913a5a0df3c54a983ff2904bfd4eb360364
[ "MIT" ]
permissive
fireduck64/adventofcode
https://github.com/fireduck64/adventofcode
7b69b2d4f915552662d887c720da93a4ef5e36a6
e29929b04d25d7c4670fad9937dca2dab5983965
refs/heads/master
2023-01-07T20:55:18.630000
2022-12-27T18:01:04
2022-12-27T18:01:04
229,797,355
4
8
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.FileInputStream; import java.util.*; public class Prob { public static void main(String args[]) throws Exception { new Prob(new Scanner(new FileInputStream(args[0]))); } Random rnd=new Random(); TreeMap<String, BagRule> rulemap = new TreeMap<>(); public Prob(Scanner scan) { while(scan.hasNextLine()) { BagRule br = new BagRule(scan.nextLine()); rulemap.put(br.color, br); } int cnt=0; for(String c : rulemap.keySet()) { if (fullDesc(c).contains("shiny gold")) cnt++; } System.out.println("Part 1"); System.out.println(cnt); System.out.println("Part 2"); System.out.println(fullCount("shiny gold")-1); } TreeSet<String> fullDesc(String color) { BagRule br = rulemap.get(color); TreeSet<String> set = new TreeSet<>(); for(String c : br.contains.keySet()) { set.addAll(fullDesc(c)); set.add(c); } return set; } int fullCount(String color) { BagRule br = rulemap.get(color); int cnt = 1; for(String c : br.contains.keySet()) { cnt += fullCount(c) * br.contains.get(c); } return cnt; } public class BagRule { String color; TreeMap<String, Integer> contains=new TreeMap<>(); public BagRule(String line) { line = line.replace(",",""); line = line.replace(".",""); Scanner scan = new Scanner(line); color = scan.next() + " " + scan.next(); if (line.contains("contain no other bags")) return; scan.next(); // bags scan.next(); // contains while(scan.hasNext()) { int cnt = scan.nextInt(); String c = scan.next() +" "+ scan.next(); scan.next(); // bags contains.put(c, cnt); } } } }
UTF-8
Java
1,805
java
Prob.java
Java
[]
null
[]
import java.io.FileInputStream; import java.util.*; public class Prob { public static void main(String args[]) throws Exception { new Prob(new Scanner(new FileInputStream(args[0]))); } Random rnd=new Random(); TreeMap<String, BagRule> rulemap = new TreeMap<>(); public Prob(Scanner scan) { while(scan.hasNextLine()) { BagRule br = new BagRule(scan.nextLine()); rulemap.put(br.color, br); } int cnt=0; for(String c : rulemap.keySet()) { if (fullDesc(c).contains("shiny gold")) cnt++; } System.out.println("Part 1"); System.out.println(cnt); System.out.println("Part 2"); System.out.println(fullCount("shiny gold")-1); } TreeSet<String> fullDesc(String color) { BagRule br = rulemap.get(color); TreeSet<String> set = new TreeSet<>(); for(String c : br.contains.keySet()) { set.addAll(fullDesc(c)); set.add(c); } return set; } int fullCount(String color) { BagRule br = rulemap.get(color); int cnt = 1; for(String c : br.contains.keySet()) { cnt += fullCount(c) * br.contains.get(c); } return cnt; } public class BagRule { String color; TreeMap<String, Integer> contains=new TreeMap<>(); public BagRule(String line) { line = line.replace(",",""); line = line.replace(".",""); Scanner scan = new Scanner(line); color = scan.next() + " " + scan.next(); if (line.contains("contain no other bags")) return; scan.next(); // bags scan.next(); // contains while(scan.hasNext()) { int cnt = scan.nextInt(); String c = scan.next() +" "+ scan.next(); scan.next(); // bags contains.put(c, cnt); } } } }
1,805
0.563435
0.560111
97
17.608248
18.111656
57
false
false
0
0
0
0
0
0
0.43299
false
false
7
d91e4d3c8f8f25f3a0b7014810bff60d6cccd442
32,719,060,931,260
0f31af4d9c70183a2c364b3ff819d28d63e10deb
/code/Hbase-project/src/IndexLoad.java
12045663b0111570f1766374692e81f0ad5747dd
[]
no_license
marioskogias/hadoop-project
https://github.com/marioskogias/hadoop-project
232fa49ce5c09b1c4b97307df7c8b2bee01ac96d
4040ebb461eb2bb299ebaa7ae86aca30dd6eccf0
refs/heads/master
2016-08-05T09:16:30.166000
2014-05-02T17:32:29
2014-05-02T17:32:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class IndexLoad { static String family = "articles"; public static class Map extends TableMapper<ImmutableBytesWritable, KeyValue> { ImmutableBytesWritable hKey = new ImmutableBytesWritable(); KeyValue kv; protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException { // create value first String article =Bytes.toString(key.get()); byte[] val = value.getValue(Bytes.toBytes("wikipedia"), Bytes.toBytes("titles")); // If we convert the value bytes, we should get back 'Some Value', // the // value we inserted at this location. String valueStr = Bytes.toString(val); String[] words = valueStr.split("_"); // qualifier will be the last 8 chars of the article md5 String qualifier = article.substring(24); for (String word : words) { hKey.set(word.getBytes()); kv = new KeyValue(hKey.get(), family.getBytes(), qualifier.getBytes(), valueStr.getBytes()); context.write(hKey, kv); } } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "indexload"); job.setJarByClass(IndexLoad.class); job.setOutputFormatClass(HFileOutputFormat.class); /* * Input format is an hbase table */ Scan scan = new Scan(); scan.setCaching(500); // 1 is the default in Scan, which will be bad for // MapReduce jobs scan.setCacheBlocks(false); // don't set to true for MR jobs TableMapReduceUtil.initTableMapperJob("content", // input HBase table // name scan, // Scan instance to control CF and attribute selection Map.class, // mapper ImmutableBytesWritable.class, // mapper output key KeyValue.class, // mapper output value job); FileOutputFormat.setOutputPath(job, new Path("3_2_results")); HTable hTable = new HTable(job.getConfiguration(), "index"); // Auto configure partitioner and reducer HFileOutputFormat.configureIncrementalLoad(job, hTable); job.waitForCompletion(true); /* * After that just run * bin/hadoop jar lib/hbase-0.94.17.jar completebulkload /user/root/3_2_results index * to add the new rows to the * table */ } }
UTF-8
Java
2,911
java
IndexLoad.java
Java
[]
null
[]
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class IndexLoad { static String family = "articles"; public static class Map extends TableMapper<ImmutableBytesWritable, KeyValue> { ImmutableBytesWritable hKey = new ImmutableBytesWritable(); KeyValue kv; protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException { // create value first String article =Bytes.toString(key.get()); byte[] val = value.getValue(Bytes.toBytes("wikipedia"), Bytes.toBytes("titles")); // If we convert the value bytes, we should get back 'Some Value', // the // value we inserted at this location. String valueStr = Bytes.toString(val); String[] words = valueStr.split("_"); // qualifier will be the last 8 chars of the article md5 String qualifier = article.substring(24); for (String word : words) { hKey.set(word.getBytes()); kv = new KeyValue(hKey.get(), family.getBytes(), qualifier.getBytes(), valueStr.getBytes()); context.write(hKey, kv); } } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "indexload"); job.setJarByClass(IndexLoad.class); job.setOutputFormatClass(HFileOutputFormat.class); /* * Input format is an hbase table */ Scan scan = new Scan(); scan.setCaching(500); // 1 is the default in Scan, which will be bad for // MapReduce jobs scan.setCacheBlocks(false); // don't set to true for MR jobs TableMapReduceUtil.initTableMapperJob("content", // input HBase table // name scan, // Scan instance to control CF and attribute selection Map.class, // mapper ImmutableBytesWritable.class, // mapper output key KeyValue.class, // mapper output value job); FileOutputFormat.setOutputPath(job, new Path("3_2_results")); HTable hTable = new HTable(job.getConfiguration(), "index"); // Auto configure partitioner and reducer HFileOutputFormat.configureIncrementalLoad(job, hTable); job.waitForCompletion(true); /* * After that just run * bin/hadoop jar lib/hbase-0.94.17.jar completebulkload /user/root/3_2_results index * to add the new rows to the * table */ } }
2,911
0.72415
0.71831
95
29.652632
24.242968
88
false
false
0
0
0
0
0
0
2.389474
false
false
7
22b619bd375bf109d844eca469c8465f6d15a949
17,428,977,353,568
4b5b46edb9c71d4a5a4e3682125f138ea7b76c31
/src/main/java/bg/proxiad/demo/championship/model/GroupingDaoHibernate.java
af79e743b4ca690ff1c5eaf1fb5050745c8f91e0
[]
no_license
smiile/championship
https://github.com/smiile/championship
24bc1c7d1ceec7ca7d986e9dbb5ab93df23f79aa
74692407fc4884e44bbfd5c816f3b4be7079ce25
refs/heads/master
2021-01-10T04:11:35.391000
2015-12-03T16:34:35
2015-12-03T16:34:35
46,409,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bg.proxiad.demo.championship.model; import java.util.Collection; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class GroupingDaoHibernate implements GroupingDao { @Autowired private SessionFactory sessionFactory; @Override public void saveOrUpdate(Grouping group) { sessionFactory.getCurrentSession().saveOrUpdate(group); } @Override public Grouping load(Long id) { return sessionFactory.getCurrentSession().get(Grouping.class, id); } @Override public Collection<Grouping> listAll() { return sessionFactory.getCurrentSession() .createCriteria(Grouping.class) .list(); } @Override public void delete(Grouping group) { sessionFactory.getCurrentSession().delete(Grouping.class.getName(), group); } }
UTF-8
Java
960
java
GroupingDaoHibernate.java
Java
[]
null
[]
package bg.proxiad.demo.championship.model; import java.util.Collection; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class GroupingDaoHibernate implements GroupingDao { @Autowired private SessionFactory sessionFactory; @Override public void saveOrUpdate(Grouping group) { sessionFactory.getCurrentSession().saveOrUpdate(group); } @Override public Grouping load(Long id) { return sessionFactory.getCurrentSession().get(Grouping.class, id); } @Override public Collection<Grouping> listAll() { return sessionFactory.getCurrentSession() .createCriteria(Grouping.class) .list(); } @Override public void delete(Grouping group) { sessionFactory.getCurrentSession().delete(Grouping.class.getName(), group); } }
960
0.710417
0.710417
36
25.666666
24.155745
83
false
false
0
0
0
0
0
0
0.333333
false
false
7
8e6147d72d785a5a66fe9280a0932b28153f873f
21,165,598,898,461
f0b3bdf844e8d53dc2b9e47a8318544ddb4d9056
/src/main/java/net/cliffanderson/handlers/PurchaseHandler.java
958725689eef9d98904a89e8afc8a5772c5b7fa8
[]
no_license
cliffanderson/Bar
https://github.com/cliffanderson/Bar
b983f0c4a9dd228ea1a70a98da1b37791ab4c5c4
b550e890b9ce32de2c19abcc131d4a88c8793bb1
refs/heads/master
2021-01-20T13:21:38.054000
2017-05-27T00:24:29
2017-05-27T00:24:29
90,474,444
0
0
null
false
2017-05-06T18:51:11
2017-05-06T16:00:36
2017-05-06T16:06:07
2017-05-06T18:51:11
1,867
0
0
1
Java
null
null
package net.cliffanderson.handlers; import net.cliffanderson.BarManager; import net.cliffanderson.obj.Drink; import net.cliffanderson.obj.Person; public class PurchaseHandler extends CommandHandler { public PurchaseHandler(String line) { super(line); } @Override public void handle() { if(this.args.size() < 2) { System.err.println("Too few arguments. Usage: purchase [name] [drink name | drink alias] <number>"); return; } String personName = this.args.get(0); String drinkName = this.args.get(1); int amount = 1; if(this.args.size() == 3) { try { amount = Integer.parseInt(args.get(2)); } catch (Exception e){} } // Validate person Person person = BarManager.instance.getPerson(personName); if(person == null) { System.err.println("Error: Could not find person " + personName); return; } // Validate drink Drink drink = BarManager.instance.getDrink(drinkName); if(drink == null) { // Try finding drink by alias drink = BarManager.instance.getDrinkByAlias(drinkName); } // If it's still null, no drink was found if(drink == null) { System.err.println("Error: Could not find drink " + drinkName); return; } if(amount <= 0) { System.err.println("Error: amount must be greater than 0"); return; } // Args are valid, make the purchase BarManager.instance.makePurchase(person, drink, amount); // Print the persons tab for the night BarManager.instance.printItemizedTabForPerson(person); } }
UTF-8
Java
1,778
java
PurchaseHandler.java
Java
[]
null
[]
package net.cliffanderson.handlers; import net.cliffanderson.BarManager; import net.cliffanderson.obj.Drink; import net.cliffanderson.obj.Person; public class PurchaseHandler extends CommandHandler { public PurchaseHandler(String line) { super(line); } @Override public void handle() { if(this.args.size() < 2) { System.err.println("Too few arguments. Usage: purchase [name] [drink name | drink alias] <number>"); return; } String personName = this.args.get(0); String drinkName = this.args.get(1); int amount = 1; if(this.args.size() == 3) { try { amount = Integer.parseInt(args.get(2)); } catch (Exception e){} } // Validate person Person person = BarManager.instance.getPerson(personName); if(person == null) { System.err.println("Error: Could not find person " + personName); return; } // Validate drink Drink drink = BarManager.instance.getDrink(drinkName); if(drink == null) { // Try finding drink by alias drink = BarManager.instance.getDrinkByAlias(drinkName); } // If it's still null, no drink was found if(drink == null) { System.err.println("Error: Could not find drink " + drinkName); return; } if(amount <= 0) { System.err.println("Error: amount must be greater than 0"); return; } // Args are valid, make the purchase BarManager.instance.makePurchase(person, drink, amount); // Print the persons tab for the night BarManager.instance.printItemizedTabForPerson(person); } }
1,778
0.57874
0.574241
60
28.633333
24.848183
112
false
false
0
0
0
0
0
0
0.45
false
false
7
921614b75077d43d42e6ee287aa6c60b686bc305
13,675,175,877,651
6eeeb62b6c22ad05a1ebb4efa96173ffc0f12712
/src/techno/technocredits1/stringDemo/Example4.java
2cc005793453abcdfde75bfa94526c05acf37e28
[]
no_license
MargiSantoki/2021_Java_Practice
https://github.com/MargiSantoki/2021_Java_Practice
fda6aa2a78906d1451fa45352b4f9456f31d440f
4a4b9613c40d68d089c9799fa7084905c225cfa4
refs/heads/master
2023-09-03T05:59:18.813000
2021-10-22T13:18:38
2021-10-22T13:18:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package techno.technocredits1.stringDemo; public class Example4 { public static void main(String[] args) { String str1 = "techno"; String str2 = new String("techno"); String str3 = "techno"; String str4 = new String("techno"); if(str1 == str2) System.out.println(1); if(str1==str3) System.out.println(2); if(str1==str4) System.out.println(3); if(str2==str3) System.out.println(4); if(str2==str4) System.out.println(5); if(str1.equals(str2)) System.out.println(6); if(str1.equals(str3)) System.out.println(7); if(str2.equals(str4)) System.out.println(8); } }
UTF-8
Java
619
java
Example4.java
Java
[]
null
[]
package techno.technocredits1.stringDemo; public class Example4 { public static void main(String[] args) { String str1 = "techno"; String str2 = new String("techno"); String str3 = "techno"; String str4 = new String("techno"); if(str1 == str2) System.out.println(1); if(str1==str3) System.out.println(2); if(str1==str4) System.out.println(3); if(str2==str3) System.out.println(4); if(str2==str4) System.out.println(5); if(str1.equals(str2)) System.out.println(6); if(str1.equals(str3)) System.out.println(7); if(str2.equals(str4)) System.out.println(8); } }
619
0.649435
0.600969
30
19.633333
11.926115
41
false
false
0
0
0
0
0
0
2.3
false
false
7
ed57e02868666fefee6f0a1aba849cb78eb6a021
4,535,485,473,875
296e89eb50dab81f1cd986fd82218ea7233cdb8d
/SGRM_2014/src/com/sgrm_2014/os/relatorio/dao/PesquisaDAO.java
38658d044f59d6bc8900d95f14fa929ee3206c80
[]
no_license
charles7x0/sgrm-desktop
https://github.com/charles7x0/sgrm-desktop
fb9a473e5cc3858bc833d38103885a415b7472aa
872a79bb7b95dcdfb42d019f70b80d0e76cf59bb
refs/heads/master
2020-02-29T19:31:10.821000
2017-09-19T12:37:05
2017-09-19T12:37:05
37,864,197
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sgrm_2014.os.relatorio.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import com.sgrm_2014.geral.config.Configurations; import com.sgrm_2014.geral.dao.GenericDAO; import com.sgrm_2014.geral.fachada.Fachada_Principal; import com.sgrm_2014.geral.utilidades.UtilsData; import com.sgrm_2014.os.modelo.OS; import com.sgrm_2014.os.relatorio.modelo.ModeloPlanilha; import com.sgrm_2014.os.relatorio.modelo.ModeloPlanilhaAnual; import com.sgrm_2014.os.relatorio.modelo.ParametrosPesquisa; public class PesquisaDAO<T> extends GenericDAO<T>{ private List<String> campo = new ArrayList<String>(); private List<String> operador = new ArrayList<String>(); private List<String> valor = new ArrayList<String>(); private List<ParametrosPesquisa> parametros; private Configurations config = new Configurations(); public PesquisaDAO(@SuppressWarnings("rawtypes") Class classe) { super(classe); // TODO Auto-generated constructor stub } private String convertOperator(String operador){ String op = ""; if(operador.equals("IGUAL A")) op = " = "; else if(operador.equals("DIFERENTE DE")) op = " <> "; else if(operador.equals("MENOR QUE")) op = " < "; else if(operador.equals("MAIOR QUE")) op = " > "; else if(operador.equals("MENOR IGUAL")) op = " <= "; else if(operador.equals("MAIOR IGUAL")) op = " >= "; return op; } private String insertCrase(String valor){ return "`" + valor + "`"; } private void extractValues(List<String> listaParametros){ campo = new ArrayList<String>(); operador = new ArrayList<String>(); valor = new ArrayList<String>(); parametros = new ArrayList<ParametrosPesquisa>(); //PERCORRE O ARRAY for (int i = 0; i < listaParametros.size(); i++) { String s[] = listaParametros.get(i).split("\\|"); // O MÉTODO SPLIT SEPARA UMA STRING ATRAVÉS DE UMA EXPRESSÃO REGULAR if(s[0].contains(" ")){ campo.add("`" + s[0].substring(0,s[0].length()-1) + "`"); } else{ campo.add(s[0]); } operador.add(this.convertOperator(s[1])); valor.add(s[2].substring(1)); parametros.add(new ParametrosPesquisa(campo.get(i), operador.get(i), valor.get(i))); } } public List<ArrayList<Object>> listarSelecaoOS(List<String> listaParametros, String[] colunas, String[] ordens, String dataini, String datafim, String horaini, String horafim) throws Exception{ if(colunas == null || ordens == null){ throw new Exception("Valores dos parâmetros nulos!"); } Connection conn = getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<ArrayList<Object>> listaRetorno = new ArrayList<ArrayList<Object>>(); this.extractValues(listaParametros); try{ String sql = "SELECT "; //INSERINDO OS CAMPOS QUE IRÃO APARECER NA PESQUISA for (int i = 0; i < colunas.length; i++) { if(i == 0){ sql += insertCrase(colunas[i]); } else{ sql += " , " + insertCrase(colunas[i]); } }//FIM DO FOR sql += " FROM VW_SELECAO_PARAMETROS WHERE "; //VERIFICAR CAMPOS DUPLICADOS------------------- HashMap<Object, Integer> camposDuplos = new HashMap<Object, Integer>(); for (int i = 0; i < campo.size(); i++) { if(!camposDuplos.containsKey(campo.get(i))){ camposDuplos.put(campo.get(i), 1); } else{ Integer temp = camposDuplos.get(campo.get(i)); camposDuplos.remove(campo.get(i)); camposDuplos.put(campo.get(i), temp+1); } } //REMOVENDO VALORES ÚNICOS for (int i = 0; i < campo.size(); i++) { if(camposDuplos.get(campo.get(i)) < 2){ camposDuplos.remove(campo.get(i)); } } Collections.sort(parametros);//ORDENANDO O ARRAY String sqlWhere = ""; int cont = 0; //INSERINDO AS CLAUSULAS WHERE for (int i = 0; i < parametros.size(); i++) { ParametrosPesquisa parTemp = parametros.get(i); boolean campoDuplicado = camposDuplos.containsKey(parTemp.getCampo()); if(campoDuplicado){ if(cont == 0){ cont = 1; } else{ cont++; } } else{ cont = 0; } if(i == 0){ if(campoDuplicado){ sqlWhere = "(" + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } else{ sqlWhere += parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } else{ //Foi alterado o código, pois quando os operadores eram diferentes do igual a lógica não funcionava. Operadores diferentes do igual devem ser ligados pelo and não pelo or. if(campoDuplicado && camposDuplos.get(parTemp.getCampo()) == cont){ //sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; //cont = 0; if(parTemp.getOperador().equals(" = ")){ sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; cont = 0; }else{ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; cont = 0; } } else if(campoDuplicado & cont == 1){ sqlWhere += " AND (" + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } else if(campoDuplicado && camposDuplos.get(parTemp.getCampo()) > cont){ if(parTemp.getOperador().equals(" = ")){ sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); }else{ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } else if (!campoDuplicado){ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } } sql += sqlWhere; sql += " AND `DATA_INICIO` >= ? AND `HORA_INICIO` >= ? AND `DATA_INICIO` <= ? AND `HORA_INICIO` <= ?"; sql += " ORDER BY "; //INSERINDO AS CLAUSULAS DO ORDER BY for (int i = 0; i < ordens.length; i++) { if(i == 0){ sql += insertCrase(ordens[i]); } else{ sql += " , " + insertCrase(ordens[i]); } }//FIM DO FOR stmt = conn.prepareStatement(sql); stmt.setDate(1, UtilsData.stringToDate(dataini)); stmt.setTime(2, UtilsData.stringToHour(horaini)); stmt.setDate(3, UtilsData.stringToDate(datafim)); stmt.setTime(4, UtilsData.stringToHour(horafim)); rs = stmt.executeQuery(); //ESCREVENDO O NOME DAS COLUNAS for (int i = 0; i < 1; i++) { ArrayList<String> temp = new ArrayList<String>(); for (int i1 = 1; i1 < rs.getMetaData().getColumnCount()+1; i1++) { temp.add(rs.getMetaData().getColumnName(i1)); } listaRetorno.add(new ArrayList<Object>(temp)); } //ESCREVENDO OS DADOS while(rs.next()) { ArrayList<Object> temp = new ArrayList<Object>(); for (int i = 1; i < rs.getMetaData().getColumnCount()+1; i++) { if(rs.getObject(i) == null){ temp.add(new String("")); } else{ temp.add(rs.getObject(i)); } } listaRetorno.add(new ArrayList<Object>(temp)); temp.remove(0); } } catch(Exception e){ e.printStackTrace(); //JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage()); } finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } campo = null; operador = null; valor = null; return listaRetorno; } public List<ArrayList<Object>> listarSelecaoOSPecas(List<String> listaParametros, String[] colunas, String[] ordens, String dataini, String datafim, String horaini, String horafim) throws Exception{ if(colunas == null || ordens == null){ throw new Exception("Valores dos parâmetros nulos!"); } Connection conn = getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<ArrayList<Object>> listaRetorno = new ArrayList<ArrayList<Object>>(); this.extractValues(listaParametros); try{ String sql = "SELECT "; //INSERINDO OS CAMPOS QUE IRÃO APARECER NA PESQUISA for (int i = 0; i < colunas.length; i++) { if(i == 0){ sql += insertCrase(colunas[i]); } else{ sql += " , " + insertCrase(colunas[i]); } }//FIM DO FOR sql += " FROM VW_SELECAO_PARAMETROS_PECAS WHERE "; //VERIFICAR CAMPOS DUPLICADOS------------------- HashMap<Object, Integer> camposDuplos = new HashMap<Object, Integer>(); for (int i = 0; i < campo.size(); i++) { if(!camposDuplos.containsKey(campo.get(i))){ camposDuplos.put(campo.get(i), 1); } else{ Integer temp = camposDuplos.get(campo.get(i)); camposDuplos.remove(campo.get(i)); camposDuplos.put(campo.get(i), temp+1); } } //REMOVENDO VALORES ÚNICOS for (int i = 0; i < campo.size(); i++) { if(camposDuplos.get(campo.get(i)) < 2){ camposDuplos.remove(campo.get(i)); } } Collections.sort(parametros);//ORDENANDO O ARRAY String sqlWhere = ""; int cont = 0; //INSERINDO AS CLAUSULAS WHERE for (int i = 0; i < parametros.size(); i++) { ParametrosPesquisa parTemp = parametros.get(i); boolean campoDuplicado = camposDuplos.containsKey(parTemp.getCampo()); if(campoDuplicado){ if(cont == 0){ cont = 1; } else{ cont++; } } else{ cont = 0; } if(i == 0){ if(campoDuplicado){ sqlWhere = "(" + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } else{ sqlWhere += parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } else{ //Foi alterado o código, pois quando os operadores eram diferentes do igual a lógica não funcionava. Operadores diferentes do igual devem ser ligados pelo and não pelo or. if(campoDuplicado && camposDuplos.get(parTemp.getCampo()) == cont){ //sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; //cont = 0; if(parTemp.getOperador().equals(" = ")){ sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; cont = 0; }else{ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; cont = 0; } } else if(campoDuplicado & cont == 1){ sqlWhere += " AND (" + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } else if(campoDuplicado && camposDuplos.get(parTemp.getCampo()) > cont){ if(parTemp.getOperador().equals(" = ")){ sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); }else{ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } else if (!campoDuplicado){ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } } sql += sqlWhere; sql += " AND `DATA_INICIO` >= ? AND `HORA_INICIO` >= ? AND `DATA_INICIO` <= ? AND `HORA_INICIO` <= ?"; sql += " ORDER BY "; //INSERINDO AS CLAUSULAS DO ORDER BY for (int i = 0; i < ordens.length; i++) { if(i == 0){ sql += insertCrase(ordens[i]); } else{ sql += " , " + insertCrase(ordens[i]); } }//FIM DO FOR stmt = conn.prepareStatement(sql); stmt.setDate(1, UtilsData.stringToDate(dataini)); stmt.setTime(2, UtilsData.stringToHour(horaini)); stmt.setDate(3, UtilsData.stringToDate(datafim)); stmt.setTime(4, UtilsData.stringToHour(horafim)); rs = stmt.executeQuery(); //System.out.println(stmt); //ESCREVENDO O NOME DAS COLUNAS for (int i = 0; i < 1; i++) { ArrayList<String> temp = new ArrayList<String>(); for (int i1 = 1; i1 < rs.getMetaData().getColumnCount()+1; i1++) { temp.add(rs.getMetaData().getColumnName(i1)); } listaRetorno.add(new ArrayList<Object>(temp)); } //ESCREVENDO OS DADOS while(rs.next()) { ArrayList<Object> temp = new ArrayList<Object>(); for (int i = 1; i < rs.getMetaData().getColumnCount()+1; i++) { if(rs.getObject(i) == null){ temp.add(new String("")); } else{ temp.add(rs.getObject(i)); } } listaRetorno.add(new ArrayList<Object>(temp)); temp.remove(0); } } catch(Exception e){ e.printStackTrace(); //JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage()); } finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } campo = null; operador = null; valor = null; return listaRetorno; } //METODO PARA RETORNAR A QUANTIDADE DE QUEBRAS POR DIA public String retornarQuantQuebrasDia(String mes, String ano, String equipamento, String dia){ String cc = "0"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); String sql = "SELECT COUNT(*) AS QUEBRAS FROM OS SM"+ " WHERE SM.CODIGO_TIPO_SERVICO = ? AND SM.CODIGO_EQUIPAMENTO = ?"+ " AND MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ? AND DAY(SM.DATA_INICIO) = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, "CO"); stmt.setString(2, equipamento); stmt.setString(3, mes); stmt.setString(4, ano); stmt.setString(5, dia); try { rs = stmt.executeQuery(); while(rs.next()) { cc = rs.getString("QUEBRAS"); } } catch (Exception e) { // TODO: handle exception throw e; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return cc; } public String retornarQuantHorasDia(String mes, String ano,String equipamento, String dia) { String cc = "0"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); String sql = "SELECT ((SUM(TIME_TO_SEC(TIMEDIFF(CONCAT(HP.DATA_FINAL,' ',HP.HORA_FINAL), CONCAT(HP.DATA_INICIO,' ',HP.HORA_INICIO))))/60)/60) AS HORAS_PARADAS "+ " FROM HORA_PARADA HP " + " JOIN OS SM ON (HP.CODIGO_SERVICO = SM.CODIGO_SERVICO) "+ " WHERE SM.CODIGO_EQUIPAMENTO = ? AND SM.CODIGO_TIPO_SERVICO = ? AND "+ " MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ? AND DAY(SM.DATA_INICIO) = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, equipamento); stmt.setString(2, "CO"); stmt.setString(3, mes); stmt.setString(4, ano); stmt.setString(5, dia); rs = null; try { rs = stmt.executeQuery(); while(rs.next()) { cc= rs.getString("HORAS_PARADAS"); try{ if(cc.equals("")){ //TODO AUTO GENERATE SUB } } catch(Exception e){ cc = "0"; } } } catch (Exception e) { // TODO: handle exception throw e; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return cc; } public String retornarQuantQuebrasMes(String mes, String ano, String equipamento){ String cc = "0"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); String sql = "SELECT COUNT(SM.CODIGO_EQUIPAMENTO) AS QUEBRAS FROM OS SM " + " JOIN EQUIPAMENTO EQ ON (EQ.CODIGO_EQUIPAMENTO = SM.CODIGO_EQUIPAMENTO) " + " JOIN SETOR SE ON (EQ.CODIGO_SETOR = SE.CODIGO_SETOR) " + " JOIN UGB U ON (SE.CODIGO_UGB = U.CODIGO_UGB) " + " WHERE SE.CODIGO_UGB = U.CODIGO_UGB AND SM.CODIGO_TIPO_SERVICO = ? AND eq.CODIGO_EQUIPAMENTO = ? " + " AND MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, "CO"); stmt.setString(2, equipamento); stmt.setString(3, mes); stmt.setString(4, ano); rs = null; try { rs = stmt.executeQuery(); while(rs.next()) { cc = rs.getString("QUEBRAS"); } } catch (Exception e) { // TODO: handle exception throw e; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return cc; } public String retornarQuantHorasMes(String mes, String ano,String equipamento) { String cc = "0"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); String sql = "SELECT ((SUM(TIME_TO_SEC(TIMEDIFF(CONCAT(HP.DATA_FINAL,' ',HP.HORA_FINAL), CONCAT(HP.DATA_INICIO,' ',HP.HORA_INICIO))))/60)/60) AS HORAS_PARADAS "+ " FROM HORA_PARADA HP " + " JOIN OS SM ON (HP.CODIGO_SERVICO = SM.CODIGO_SERVICO) "+ " WHERE SM.CODIGO_EQUIPAMENTO = ? AND SM.CODIGO_TIPO_SERVICO = ? AND "+ " MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, equipamento); stmt.setString(2, "CO"); stmt.setString(3, mes); stmt.setString(4, ano); rs = null; try { rs = stmt.executeQuery(); while(rs.next()) { cc= rs.getString("HORAS_PARADAS"); try{ if(cc.equals("")){ //TODO AUTO GENERATE SUB } } catch(Exception e){ cc = "0"; } } } catch (Exception e) { // TODO: handle exception throw e; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return cc; } public ModeloPlanilha retornarDadosPlanilhaDiaria(String mes, String ano, String ugb){ List<String> meses = new ArrayList<String>(); List<String> maquinas= new ArrayList<String>(); List<String> tipo_servico = new ArrayList<String>(); List<OS> sms = new ArrayList<OS>(); Connection conn = getConnection(); //EXTRAINDO OS DIFERENTES TIPOS DE SERVICOS try { String sql = "SELECT CODIGO_TIPO_SERVICO FROM TIPO_SERVICO WHERE PLANEJADO <> 'SIM';"; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while(rs.next()) { tipo_servico.add(rs.getString("CODIGO_TIPO_SERVICO")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //EXTRAINDO O ULTIMO DIA DO MÊS, ASSIM VERIFICAMOS QUANTOS DIAS TEM O MÊS try { String data = ano + "-" + mes + "-" + "10"; String sql = "SELECT DAY(LAST_DAY(?)) AS DIAS;"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, data); ResultSet rs = stmt.executeQuery(); //System.out.println(stmt.toString()); while(rs.next()) { meses.add(rs.getString("DIAS")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //EXTRAINDO AS MÁQUINAS POR UGB's try { String sql = "SELECT DISTINCT EQ.CODIGO_EQUIPAMENTO AS CODIGO_EQUIPAMENTO FROM EQUIPAMENTO EQ, SETOR SE, UGB U "+ " WHERE EQ.CODIGO_SETOR = SE.CODIGO_SETOR " + " AND SE.CODIGO_UGB = U.CODIGO_UGB AND EQ.EQUIPAMENTO_DESATIVADO <> 'SIM' "+ " AND U.CODIGO_UGB = ? ORDER BY CODIGO_EQUIPAMENTO;"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, ugb); ResultSet rs = stmt.executeQuery(); while(rs.next()) { maquinas.add(rs.getString("CODIGO_EQUIPAMENTO")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //EXTRAINDO AS QUEBRAS NO PERÍODO SELECIONADO //FOI ALTERADO PARA APARECER TODAS AS SOLICITAÇÕES DE MANUTENÇÃO try{ String sql = "SELECT SM.CODIGO_SERVICO, SM.CODIGO_EQUIPAMENTO, SM.DATA_INICIO, SM.HORA_INICIO, SM.DATA_TERMINO, SM.HORA_TERMINO,SM.DESCRICAO, SM.CODIGO_TIPO_SERVICO, SM.COMENTARIOS_INTERVENCAO, "+ " SM.SITUACAO, SM.DATA_PREV_INI, SM.DURACAO_PREVISTA, SM.CODIGO_EQUIPE_MANUTENCAO, " + " SM.SOLICITANTE " + " FROM OS SM, " + " EQUIPAMENTO EQ, SETOR SE, UGB U "+ " WHERE EQ.CODIGO_EQUIPAMENTO = SM.CODIGO_EQUIPAMENTO AND EQ.CODIGO_SETOR = SE.CODIGO_SETOR "+ " AND SE.CODIGO_UGB = U.CODIGO_UGB AND TIPO = 'NORMAL'"+ " AND ((MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ?) OR SM.DATA_INICIO IS NULL AND (MONTH(SM.DATA_PREV_INI) = ? AND YEAR(SM.DATA_PREV_INI) = ?)) " + " AND U.CODIGO_UGB = ? GROUP BY SM.CODIGO_SERVICO ORDER BY DAY(SM.DATA_INICIO), DAY(SM.DATA_PREV_INI), SM.HORA_INICIO ASC;"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, mes); stmt.setString(2, ano); stmt.setString(3, mes); stmt.setString(4, ano); stmt.setString(5, ugb); System.out.println(stmt); ResultSet rs = stmt.executeQuery(); while(rs.next()) { OS temp = new OS(); temp.setCodigo_servico(rs.getString("CODIGO_SERVICO")); temp.setSolicitante(rs.getString("SOLICITANTE")); temp.setCodigo_tipo_servico(rs.getString("CODIGO_TIPO_SERVICO")); temp.setCodigo_equipamento(rs.getString("CODIGO_EQUIPAMENTO")); temp.setData_inicio(rs.getDate("DATA_INICIO")); temp.setHora_inicio(rs.getTime("HORA_INICIO")); temp.setData_termino(rs.getDate("DATA_TERMINO")); temp.setHora_termino(rs.getTime("HORA_TERMINO")); temp.setDescricao(rs.getString("DESCRICAO")); temp.setComentarios_intervencao(rs.getString("COMENTARIOS_INTERVENCAO")); temp.setSituacao(rs.getString("SITUACAO")); temp.setData_prev_ini(rs.getDate("DATA_PREV_INI")); temp.setDuracao_prevista(rs.getDouble("DURACAO_PREVISTA")); temp.setCodigo_equipe_manutencao(rs.getString("CODIGO_EQUIPE_MANUTENCAO")); //temp.setTempo_hp(rs.getString("TEMPO_PARADO")); sms.add(temp); } stmt.close(); rs.close(); } catch(Exception e){ e.printStackTrace(); }finally{ try { conn.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return (new ModeloPlanilha(meses, maquinas, sms, tipo_servico)); } public ModeloPlanilhaAnual retornarDadosPlanilhaAnual(String ano, String ugb){ Connection conn = getConnection(); List<String> meses = new ArrayList<String>(); List<String> maquinas= new ArrayList<String>(); List<String> tipo_servico = new ArrayList<String>(); String[] pref = config.getPreferenciasPlanilhaAnual(Fachada_Principal.obterInstancia().getUser()); String ativos = ""; String tpm = ""; for (int i = 0; i < pref.length; i++) { if(pref[i].equals("**ATIVOS")){ ativos = " AND EQUIPAMENTO_DESATIVADO = 'NÃO' "; } else if(pref[i].equals("**TPM")){ tpm = " AND TPM = 'SIM' "; } } //MESES DO ANO meses.add("01"); meses.add("02"); meses.add("03"); meses.add("04"); meses.add("05"); meses.add("06"); meses.add("07"); meses.add("08"); meses.add("09"); meses.add("10"); meses.add("11"); meses.add("12"); //EXTRAINDO OS DIFERENTES TIPOS DE SERVICOS try { String sql = "SELECT CODIGO_TIPO_SERVICO FROM TIPO_SERVICO WHERE PLANEJADO <> 'SIM';"; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while(rs.next()) { tipo_servico.add(rs.getString("CODIGO_TIPO_SERVICO")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //EXTRAINDO AS MÁQUINAS POR UGB's try { String sql = "SELECT DISTINCT EQ.CODIGO_EQUIPAMENTO AS CODIGO_EQUIPAMENTO FROM EQUIPAMENTO EQ, SETOR SE, UGB U "+ " WHERE EQ.CODIGO_SETOR = SE.CODIGO_SETOR " + " AND SE.CODIGO_UGB = U.CODIGO_UGB AND EQ.EQUIPAMENTO_DESATIVADO <> 'SIM' "+ " AND U.CODIGO_UGB = ? " + ativos +tpm + "ORDER BY CODIGO_EQUIPAMENTO;"; //System.out.println(sql); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, ugb); ResultSet rs = stmt.executeQuery(); while(rs.next()) { maquinas.add(rs.getString("CODIGO_EQUIPAMENTO")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return (new ModeloPlanilhaAnual(meses, maquinas, tipo_servico)); } }
ISO-8859-1
Java
25,901
java
PesquisaDAO.java
Java
[]
null
[]
package com.sgrm_2014.os.relatorio.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import com.sgrm_2014.geral.config.Configurations; import com.sgrm_2014.geral.dao.GenericDAO; import com.sgrm_2014.geral.fachada.Fachada_Principal; import com.sgrm_2014.geral.utilidades.UtilsData; import com.sgrm_2014.os.modelo.OS; import com.sgrm_2014.os.relatorio.modelo.ModeloPlanilha; import com.sgrm_2014.os.relatorio.modelo.ModeloPlanilhaAnual; import com.sgrm_2014.os.relatorio.modelo.ParametrosPesquisa; public class PesquisaDAO<T> extends GenericDAO<T>{ private List<String> campo = new ArrayList<String>(); private List<String> operador = new ArrayList<String>(); private List<String> valor = new ArrayList<String>(); private List<ParametrosPesquisa> parametros; private Configurations config = new Configurations(); public PesquisaDAO(@SuppressWarnings("rawtypes") Class classe) { super(classe); // TODO Auto-generated constructor stub } private String convertOperator(String operador){ String op = ""; if(operador.equals("IGUAL A")) op = " = "; else if(operador.equals("DIFERENTE DE")) op = " <> "; else if(operador.equals("MENOR QUE")) op = " < "; else if(operador.equals("MAIOR QUE")) op = " > "; else if(operador.equals("MENOR IGUAL")) op = " <= "; else if(operador.equals("MAIOR IGUAL")) op = " >= "; return op; } private String insertCrase(String valor){ return "`" + valor + "`"; } private void extractValues(List<String> listaParametros){ campo = new ArrayList<String>(); operador = new ArrayList<String>(); valor = new ArrayList<String>(); parametros = new ArrayList<ParametrosPesquisa>(); //PERCORRE O ARRAY for (int i = 0; i < listaParametros.size(); i++) { String s[] = listaParametros.get(i).split("\\|"); // O MÉTODO SPLIT SEPARA UMA STRING ATRAVÉS DE UMA EXPRESSÃO REGULAR if(s[0].contains(" ")){ campo.add("`" + s[0].substring(0,s[0].length()-1) + "`"); } else{ campo.add(s[0]); } operador.add(this.convertOperator(s[1])); valor.add(s[2].substring(1)); parametros.add(new ParametrosPesquisa(campo.get(i), operador.get(i), valor.get(i))); } } public List<ArrayList<Object>> listarSelecaoOS(List<String> listaParametros, String[] colunas, String[] ordens, String dataini, String datafim, String horaini, String horafim) throws Exception{ if(colunas == null || ordens == null){ throw new Exception("Valores dos parâmetros nulos!"); } Connection conn = getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<ArrayList<Object>> listaRetorno = new ArrayList<ArrayList<Object>>(); this.extractValues(listaParametros); try{ String sql = "SELECT "; //INSERINDO OS CAMPOS QUE IRÃO APARECER NA PESQUISA for (int i = 0; i < colunas.length; i++) { if(i == 0){ sql += insertCrase(colunas[i]); } else{ sql += " , " + insertCrase(colunas[i]); } }//FIM DO FOR sql += " FROM VW_SELECAO_PARAMETROS WHERE "; //VERIFICAR CAMPOS DUPLICADOS------------------- HashMap<Object, Integer> camposDuplos = new HashMap<Object, Integer>(); for (int i = 0; i < campo.size(); i++) { if(!camposDuplos.containsKey(campo.get(i))){ camposDuplos.put(campo.get(i), 1); } else{ Integer temp = camposDuplos.get(campo.get(i)); camposDuplos.remove(campo.get(i)); camposDuplos.put(campo.get(i), temp+1); } } //REMOVENDO VALORES ÚNICOS for (int i = 0; i < campo.size(); i++) { if(camposDuplos.get(campo.get(i)) < 2){ camposDuplos.remove(campo.get(i)); } } Collections.sort(parametros);//ORDENANDO O ARRAY String sqlWhere = ""; int cont = 0; //INSERINDO AS CLAUSULAS WHERE for (int i = 0; i < parametros.size(); i++) { ParametrosPesquisa parTemp = parametros.get(i); boolean campoDuplicado = camposDuplos.containsKey(parTemp.getCampo()); if(campoDuplicado){ if(cont == 0){ cont = 1; } else{ cont++; } } else{ cont = 0; } if(i == 0){ if(campoDuplicado){ sqlWhere = "(" + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } else{ sqlWhere += parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } else{ //Foi alterado o código, pois quando os operadores eram diferentes do igual a lógica não funcionava. Operadores diferentes do igual devem ser ligados pelo and não pelo or. if(campoDuplicado && camposDuplos.get(parTemp.getCampo()) == cont){ //sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; //cont = 0; if(parTemp.getOperador().equals(" = ")){ sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; cont = 0; }else{ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; cont = 0; } } else if(campoDuplicado & cont == 1){ sqlWhere += " AND (" + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } else if(campoDuplicado && camposDuplos.get(parTemp.getCampo()) > cont){ if(parTemp.getOperador().equals(" = ")){ sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); }else{ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } else if (!campoDuplicado){ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } } sql += sqlWhere; sql += " AND `DATA_INICIO` >= ? AND `HORA_INICIO` >= ? AND `DATA_INICIO` <= ? AND `HORA_INICIO` <= ?"; sql += " ORDER BY "; //INSERINDO AS CLAUSULAS DO ORDER BY for (int i = 0; i < ordens.length; i++) { if(i == 0){ sql += insertCrase(ordens[i]); } else{ sql += " , " + insertCrase(ordens[i]); } }//FIM DO FOR stmt = conn.prepareStatement(sql); stmt.setDate(1, UtilsData.stringToDate(dataini)); stmt.setTime(2, UtilsData.stringToHour(horaini)); stmt.setDate(3, UtilsData.stringToDate(datafim)); stmt.setTime(4, UtilsData.stringToHour(horafim)); rs = stmt.executeQuery(); //ESCREVENDO O NOME DAS COLUNAS for (int i = 0; i < 1; i++) { ArrayList<String> temp = new ArrayList<String>(); for (int i1 = 1; i1 < rs.getMetaData().getColumnCount()+1; i1++) { temp.add(rs.getMetaData().getColumnName(i1)); } listaRetorno.add(new ArrayList<Object>(temp)); } //ESCREVENDO OS DADOS while(rs.next()) { ArrayList<Object> temp = new ArrayList<Object>(); for (int i = 1; i < rs.getMetaData().getColumnCount()+1; i++) { if(rs.getObject(i) == null){ temp.add(new String("")); } else{ temp.add(rs.getObject(i)); } } listaRetorno.add(new ArrayList<Object>(temp)); temp.remove(0); } } catch(Exception e){ e.printStackTrace(); //JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage()); } finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } campo = null; operador = null; valor = null; return listaRetorno; } public List<ArrayList<Object>> listarSelecaoOSPecas(List<String> listaParametros, String[] colunas, String[] ordens, String dataini, String datafim, String horaini, String horafim) throws Exception{ if(colunas == null || ordens == null){ throw new Exception("Valores dos parâmetros nulos!"); } Connection conn = getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<ArrayList<Object>> listaRetorno = new ArrayList<ArrayList<Object>>(); this.extractValues(listaParametros); try{ String sql = "SELECT "; //INSERINDO OS CAMPOS QUE IRÃO APARECER NA PESQUISA for (int i = 0; i < colunas.length; i++) { if(i == 0){ sql += insertCrase(colunas[i]); } else{ sql += " , " + insertCrase(colunas[i]); } }//FIM DO FOR sql += " FROM VW_SELECAO_PARAMETROS_PECAS WHERE "; //VERIFICAR CAMPOS DUPLICADOS------------------- HashMap<Object, Integer> camposDuplos = new HashMap<Object, Integer>(); for (int i = 0; i < campo.size(); i++) { if(!camposDuplos.containsKey(campo.get(i))){ camposDuplos.put(campo.get(i), 1); } else{ Integer temp = camposDuplos.get(campo.get(i)); camposDuplos.remove(campo.get(i)); camposDuplos.put(campo.get(i), temp+1); } } //REMOVENDO VALORES ÚNICOS for (int i = 0; i < campo.size(); i++) { if(camposDuplos.get(campo.get(i)) < 2){ camposDuplos.remove(campo.get(i)); } } Collections.sort(parametros);//ORDENANDO O ARRAY String sqlWhere = ""; int cont = 0; //INSERINDO AS CLAUSULAS WHERE for (int i = 0; i < parametros.size(); i++) { ParametrosPesquisa parTemp = parametros.get(i); boolean campoDuplicado = camposDuplos.containsKey(parTemp.getCampo()); if(campoDuplicado){ if(cont == 0){ cont = 1; } else{ cont++; } } else{ cont = 0; } if(i == 0){ if(campoDuplicado){ sqlWhere = "(" + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } else{ sqlWhere += parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } else{ //Foi alterado o código, pois quando os operadores eram diferentes do igual a lógica não funcionava. Operadores diferentes do igual devem ser ligados pelo and não pelo or. if(campoDuplicado && camposDuplos.get(parTemp.getCampo()) == cont){ //sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; //cont = 0; if(parTemp.getOperador().equals(" = ")){ sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; cont = 0; }else{ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor() + ")"; cont = 0; } } else if(campoDuplicado & cont == 1){ sqlWhere += " AND (" + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } else if(campoDuplicado && camposDuplos.get(parTemp.getCampo()) > cont){ if(parTemp.getOperador().equals(" = ")){ sqlWhere += " OR " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); }else{ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } else if (!campoDuplicado){ sqlWhere += " AND " + parTemp.getCampo() + parTemp.getOperador() + parTemp.getValor(); } } } sql += sqlWhere; sql += " AND `DATA_INICIO` >= ? AND `HORA_INICIO` >= ? AND `DATA_INICIO` <= ? AND `HORA_INICIO` <= ?"; sql += " ORDER BY "; //INSERINDO AS CLAUSULAS DO ORDER BY for (int i = 0; i < ordens.length; i++) { if(i == 0){ sql += insertCrase(ordens[i]); } else{ sql += " , " + insertCrase(ordens[i]); } }//FIM DO FOR stmt = conn.prepareStatement(sql); stmt.setDate(1, UtilsData.stringToDate(dataini)); stmt.setTime(2, UtilsData.stringToHour(horaini)); stmt.setDate(3, UtilsData.stringToDate(datafim)); stmt.setTime(4, UtilsData.stringToHour(horafim)); rs = stmt.executeQuery(); //System.out.println(stmt); //ESCREVENDO O NOME DAS COLUNAS for (int i = 0; i < 1; i++) { ArrayList<String> temp = new ArrayList<String>(); for (int i1 = 1; i1 < rs.getMetaData().getColumnCount()+1; i1++) { temp.add(rs.getMetaData().getColumnName(i1)); } listaRetorno.add(new ArrayList<Object>(temp)); } //ESCREVENDO OS DADOS while(rs.next()) { ArrayList<Object> temp = new ArrayList<Object>(); for (int i = 1; i < rs.getMetaData().getColumnCount()+1; i++) { if(rs.getObject(i) == null){ temp.add(new String("")); } else{ temp.add(rs.getObject(i)); } } listaRetorno.add(new ArrayList<Object>(temp)); temp.remove(0); } } catch(Exception e){ e.printStackTrace(); //JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage()); } finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } campo = null; operador = null; valor = null; return listaRetorno; } //METODO PARA RETORNAR A QUANTIDADE DE QUEBRAS POR DIA public String retornarQuantQuebrasDia(String mes, String ano, String equipamento, String dia){ String cc = "0"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); String sql = "SELECT COUNT(*) AS QUEBRAS FROM OS SM"+ " WHERE SM.CODIGO_TIPO_SERVICO = ? AND SM.CODIGO_EQUIPAMENTO = ?"+ " AND MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ? AND DAY(SM.DATA_INICIO) = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, "CO"); stmt.setString(2, equipamento); stmt.setString(3, mes); stmt.setString(4, ano); stmt.setString(5, dia); try { rs = stmt.executeQuery(); while(rs.next()) { cc = rs.getString("QUEBRAS"); } } catch (Exception e) { // TODO: handle exception throw e; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return cc; } public String retornarQuantHorasDia(String mes, String ano,String equipamento, String dia) { String cc = "0"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); String sql = "SELECT ((SUM(TIME_TO_SEC(TIMEDIFF(CONCAT(HP.DATA_FINAL,' ',HP.HORA_FINAL), CONCAT(HP.DATA_INICIO,' ',HP.HORA_INICIO))))/60)/60) AS HORAS_PARADAS "+ " FROM HORA_PARADA HP " + " JOIN OS SM ON (HP.CODIGO_SERVICO = SM.CODIGO_SERVICO) "+ " WHERE SM.CODIGO_EQUIPAMENTO = ? AND SM.CODIGO_TIPO_SERVICO = ? AND "+ " MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ? AND DAY(SM.DATA_INICIO) = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, equipamento); stmt.setString(2, "CO"); stmt.setString(3, mes); stmt.setString(4, ano); stmt.setString(5, dia); rs = null; try { rs = stmt.executeQuery(); while(rs.next()) { cc= rs.getString("HORAS_PARADAS"); try{ if(cc.equals("")){ //TODO AUTO GENERATE SUB } } catch(Exception e){ cc = "0"; } } } catch (Exception e) { // TODO: handle exception throw e; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return cc; } public String retornarQuantQuebrasMes(String mes, String ano, String equipamento){ String cc = "0"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); String sql = "SELECT COUNT(SM.CODIGO_EQUIPAMENTO) AS QUEBRAS FROM OS SM " + " JOIN EQUIPAMENTO EQ ON (EQ.CODIGO_EQUIPAMENTO = SM.CODIGO_EQUIPAMENTO) " + " JOIN SETOR SE ON (EQ.CODIGO_SETOR = SE.CODIGO_SETOR) " + " JOIN UGB U ON (SE.CODIGO_UGB = U.CODIGO_UGB) " + " WHERE SE.CODIGO_UGB = U.CODIGO_UGB AND SM.CODIGO_TIPO_SERVICO = ? AND eq.CODIGO_EQUIPAMENTO = ? " + " AND MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, "CO"); stmt.setString(2, equipamento); stmt.setString(3, mes); stmt.setString(4, ano); rs = null; try { rs = stmt.executeQuery(); while(rs.next()) { cc = rs.getString("QUEBRAS"); } } catch (Exception e) { // TODO: handle exception throw e; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return cc; } public String retornarQuantHorasMes(String mes, String ano,String equipamento) { String cc = "0"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); String sql = "SELECT ((SUM(TIME_TO_SEC(TIMEDIFF(CONCAT(HP.DATA_FINAL,' ',HP.HORA_FINAL), CONCAT(HP.DATA_INICIO,' ',HP.HORA_INICIO))))/60)/60) AS HORAS_PARADAS "+ " FROM HORA_PARADA HP " + " JOIN OS SM ON (HP.CODIGO_SERVICO = SM.CODIGO_SERVICO) "+ " WHERE SM.CODIGO_EQUIPAMENTO = ? AND SM.CODIGO_TIPO_SERVICO = ? AND "+ " MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, equipamento); stmt.setString(2, "CO"); stmt.setString(3, mes); stmt.setString(4, ano); rs = null; try { rs = stmt.executeQuery(); while(rs.next()) { cc= rs.getString("HORAS_PARADAS"); try{ if(cc.equals("")){ //TODO AUTO GENERATE SUB } } catch(Exception e){ cc = "0"; } } } catch (Exception e) { // TODO: handle exception throw e; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); rs.close(); stmt.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return cc; } public ModeloPlanilha retornarDadosPlanilhaDiaria(String mes, String ano, String ugb){ List<String> meses = new ArrayList<String>(); List<String> maquinas= new ArrayList<String>(); List<String> tipo_servico = new ArrayList<String>(); List<OS> sms = new ArrayList<OS>(); Connection conn = getConnection(); //EXTRAINDO OS DIFERENTES TIPOS DE SERVICOS try { String sql = "SELECT CODIGO_TIPO_SERVICO FROM TIPO_SERVICO WHERE PLANEJADO <> 'SIM';"; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while(rs.next()) { tipo_servico.add(rs.getString("CODIGO_TIPO_SERVICO")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //EXTRAINDO O ULTIMO DIA DO MÊS, ASSIM VERIFICAMOS QUANTOS DIAS TEM O MÊS try { String data = ano + "-" + mes + "-" + "10"; String sql = "SELECT DAY(LAST_DAY(?)) AS DIAS;"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, data); ResultSet rs = stmt.executeQuery(); //System.out.println(stmt.toString()); while(rs.next()) { meses.add(rs.getString("DIAS")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //EXTRAINDO AS MÁQUINAS POR UGB's try { String sql = "SELECT DISTINCT EQ.CODIGO_EQUIPAMENTO AS CODIGO_EQUIPAMENTO FROM EQUIPAMENTO EQ, SETOR SE, UGB U "+ " WHERE EQ.CODIGO_SETOR = SE.CODIGO_SETOR " + " AND SE.CODIGO_UGB = U.CODIGO_UGB AND EQ.EQUIPAMENTO_DESATIVADO <> 'SIM' "+ " AND U.CODIGO_UGB = ? ORDER BY CODIGO_EQUIPAMENTO;"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, ugb); ResultSet rs = stmt.executeQuery(); while(rs.next()) { maquinas.add(rs.getString("CODIGO_EQUIPAMENTO")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //EXTRAINDO AS QUEBRAS NO PERÍODO SELECIONADO //FOI ALTERADO PARA APARECER TODAS AS SOLICITAÇÕES DE MANUTENÇÃO try{ String sql = "SELECT SM.CODIGO_SERVICO, SM.CODIGO_EQUIPAMENTO, SM.DATA_INICIO, SM.HORA_INICIO, SM.DATA_TERMINO, SM.HORA_TERMINO,SM.DESCRICAO, SM.CODIGO_TIPO_SERVICO, SM.COMENTARIOS_INTERVENCAO, "+ " SM.SITUACAO, SM.DATA_PREV_INI, SM.DURACAO_PREVISTA, SM.CODIGO_EQUIPE_MANUTENCAO, " + " SM.SOLICITANTE " + " FROM OS SM, " + " EQUIPAMENTO EQ, SETOR SE, UGB U "+ " WHERE EQ.CODIGO_EQUIPAMENTO = SM.CODIGO_EQUIPAMENTO AND EQ.CODIGO_SETOR = SE.CODIGO_SETOR "+ " AND SE.CODIGO_UGB = U.CODIGO_UGB AND TIPO = 'NORMAL'"+ " AND ((MONTH(SM.DATA_INICIO) = ? AND YEAR(SM.DATA_INICIO) = ?) OR SM.DATA_INICIO IS NULL AND (MONTH(SM.DATA_PREV_INI) = ? AND YEAR(SM.DATA_PREV_INI) = ?)) " + " AND U.CODIGO_UGB = ? GROUP BY SM.CODIGO_SERVICO ORDER BY DAY(SM.DATA_INICIO), DAY(SM.DATA_PREV_INI), SM.HORA_INICIO ASC;"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, mes); stmt.setString(2, ano); stmt.setString(3, mes); stmt.setString(4, ano); stmt.setString(5, ugb); System.out.println(stmt); ResultSet rs = stmt.executeQuery(); while(rs.next()) { OS temp = new OS(); temp.setCodigo_servico(rs.getString("CODIGO_SERVICO")); temp.setSolicitante(rs.getString("SOLICITANTE")); temp.setCodigo_tipo_servico(rs.getString("CODIGO_TIPO_SERVICO")); temp.setCodigo_equipamento(rs.getString("CODIGO_EQUIPAMENTO")); temp.setData_inicio(rs.getDate("DATA_INICIO")); temp.setHora_inicio(rs.getTime("HORA_INICIO")); temp.setData_termino(rs.getDate("DATA_TERMINO")); temp.setHora_termino(rs.getTime("HORA_TERMINO")); temp.setDescricao(rs.getString("DESCRICAO")); temp.setComentarios_intervencao(rs.getString("COMENTARIOS_INTERVENCAO")); temp.setSituacao(rs.getString("SITUACAO")); temp.setData_prev_ini(rs.getDate("DATA_PREV_INI")); temp.setDuracao_prevista(rs.getDouble("DURACAO_PREVISTA")); temp.setCodigo_equipe_manutencao(rs.getString("CODIGO_EQUIPE_MANUTENCAO")); //temp.setTempo_hp(rs.getString("TEMPO_PARADO")); sms.add(temp); } stmt.close(); rs.close(); } catch(Exception e){ e.printStackTrace(); }finally{ try { conn.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return (new ModeloPlanilha(meses, maquinas, sms, tipo_servico)); } public ModeloPlanilhaAnual retornarDadosPlanilhaAnual(String ano, String ugb){ Connection conn = getConnection(); List<String> meses = new ArrayList<String>(); List<String> maquinas= new ArrayList<String>(); List<String> tipo_servico = new ArrayList<String>(); String[] pref = config.getPreferenciasPlanilhaAnual(Fachada_Principal.obterInstancia().getUser()); String ativos = ""; String tpm = ""; for (int i = 0; i < pref.length; i++) { if(pref[i].equals("**ATIVOS")){ ativos = " AND EQUIPAMENTO_DESATIVADO = 'NÃO' "; } else if(pref[i].equals("**TPM")){ tpm = " AND TPM = 'SIM' "; } } //MESES DO ANO meses.add("01"); meses.add("02"); meses.add("03"); meses.add("04"); meses.add("05"); meses.add("06"); meses.add("07"); meses.add("08"); meses.add("09"); meses.add("10"); meses.add("11"); meses.add("12"); //EXTRAINDO OS DIFERENTES TIPOS DE SERVICOS try { String sql = "SELECT CODIGO_TIPO_SERVICO FROM TIPO_SERVICO WHERE PLANEJADO <> 'SIM';"; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while(rs.next()) { tipo_servico.add(rs.getString("CODIGO_TIPO_SERVICO")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //EXTRAINDO AS MÁQUINAS POR UGB's try { String sql = "SELECT DISTINCT EQ.CODIGO_EQUIPAMENTO AS CODIGO_EQUIPAMENTO FROM EQUIPAMENTO EQ, SETOR SE, UGB U "+ " WHERE EQ.CODIGO_SETOR = SE.CODIGO_SETOR " + " AND SE.CODIGO_UGB = U.CODIGO_UGB AND EQ.EQUIPAMENTO_DESATIVADO <> 'SIM' "+ " AND U.CODIGO_UGB = ? " + ativos +tpm + "ORDER BY CODIGO_EQUIPAMENTO;"; //System.out.println(sql); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, ugb); ResultSet rs = stmt.executeQuery(); while(rs.next()) { maquinas.add(rs.getString("CODIGO_EQUIPAMENTO")); } stmt.close(); rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { conn.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return (new ModeloPlanilhaAnual(meses, maquinas, tipo_servico)); } }
25,901
0.597472
0.589859
920
26.123913
28.651426
199
false
false
0
0
0
0
0
0
3.390217
false
false
7
1ab579e111e6f1dad905c08769b26f7bb9960ed4
26,980,984,563,933
bff199c7b91d0041dc4074d91894bc3d288107fb
/src/Lab09Interface/Sample/TestEmployee.java
020e28f4294cb4614a643ebd3f00b8ddddfdb594
[]
no_license
thao-nguyent/JavaBasic
https://github.com/thao-nguyent/JavaBasic
55aaa27f581f67581468314241d39ff50e796a90
dca0ad17d01d96f2104a25986328634e40f202ca
refs/heads/master
2023-08-21T06:39:01.979000
2021-10-29T06:47:51
2021-10-29T06:47:51
416,008,182
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Lab09Interface.Sample; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class TestEmployee { public static void main(String[] args) { List<Employee> employeeList = new ArrayList<>(); employeeList.add(new StandardEmployee()); employeeList.add(new Manager()); Collections.sort(employeeList); for (int empIndx = 0; empIndx < employeeList.size(); empIndx++){ System.out.println(employeeList); } } }
UTF-8
Java
545
java
TestEmployee.java
Java
[]
null
[]
package Lab09Interface.Sample; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class TestEmployee { public static void main(String[] args) { List<Employee> employeeList = new ArrayList<>(); employeeList.add(new StandardEmployee()); employeeList.add(new Manager()); Collections.sort(employeeList); for (int empIndx = 0; empIndx < employeeList.size(); empIndx++){ System.out.println(employeeList); } } }
545
0.66789
0.662385
22
23.772728
21.260145
72
false
false
0
0
0
0
0
0
0.545455
false
false
7
b132913ef3160bf9143f589f1e6ba2ffe65ec7b9
26,362,509,284,866
dae462f2e00b514f103bfcdbb0a20016c10ab2a3
/src/main/java/serialize/ExternalizableDemo.java
f2f63069aa9b7a586109448e9ac75f95db218cb8
[]
no_license
yyxd/thinkInJava
https://github.com/yyxd/thinkInJava
c296b51fb7a4a74c63f9f91ee9ba9f60a19f532f
5e8b16e6e9de5ba8c479846239fcbc080f2cfad3
refs/heads/master
2021-06-29T16:25:48.627000
2019-07-05T03:39:56
2019-07-05T03:39:56
161,304,473
0
0
null
false
2020-10-13T11:18:47
2018-12-11T08:48:27
2019-07-05T03:42:07
2020-10-13T11:18:46
15
0
0
1
Java
false
false
package serialize; import java.io.*; /** * Created by Diane on 2019-05-13. * Goal: */ public class ExternalizableDemo { public static void main(String[] args) { User2 user = new User2(); user.setName("Long Deng"); user.setAge(24); user.setEmail("mcpaul@qq.com"); try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile2"))){ oos.writeObject(user); } catch (IOException e) { e.printStackTrace(); } try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("tempFile2")))) { User2 newInstance = (User2)ois.readObject(); System.out.println(newInstance); } catch (IOException|ClassNotFoundException e) { e.printStackTrace(); } } }
UTF-8
Java
830
java
ExternalizableDemo.java
Java
[ { "context": "e serialize;\n\nimport java.io.*;\n\n/**\n * Created by Diane on 2019-05-13.\n * Goal:\n */\npublic class External", "end": 62, "score": 0.9777296185493469, "start": 57, "tag": "NAME", "value": "Diane" }, { "context": " User2 user = new User2();\n user.setName(\"Long Deng\");\n user.setAge(24);\n user.setEmail", "end": 235, "score": 0.9996600151062012, "start": 226, "tag": "NAME", "value": "Long Deng" }, { "context": ";\n user.setAge(24);\n user.setEmail(\"mcpaul@qq.com\");\n\n try(ObjectOutputStream oos = new Obje", "end": 300, "score": 0.9999250173568726, "start": 287, "tag": "EMAIL", "value": "mcpaul@qq.com" } ]
null
[]
package serialize; import java.io.*; /** * Created by Diane on 2019-05-13. * Goal: */ public class ExternalizableDemo { public static void main(String[] args) { User2 user = new User2(); user.setName("<NAME>"); user.setAge(24); user.setEmail("<EMAIL>"); try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile2"))){ oos.writeObject(user); } catch (IOException e) { e.printStackTrace(); } try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("tempFile2")))) { User2 newInstance = (User2)ois.readObject(); System.out.println(newInstance); } catch (IOException|ClassNotFoundException e) { e.printStackTrace(); } } }
821
0.606024
0.586747
29
27.620689
26.139433
104
false
false
0
0
0
0
0
0
0.413793
false
false
7
f610cf6fe3a20241ced145fab4e49379a61706b6
29,180,007,827,246
0721682f9128f387f4109fd341343f711ae1fd76
/parent/springcloud/tms/src/main/java/com/blcultra/dao/UserBehaviorLogMapper.java
ac3380d3321bd65f373a2d12c3c7cf8789694c12
[]
no_license
yuefeiyg/dayu
https://github.com/yuefeiyg/dayu
5c80a29728436eec7337f04a78bfdc5e9b4f7bfe
f01938cb85bc5b5a338cdc72845b93f5a500a5c9
refs/heads/master
2022-12-09T00:03:44.068000
2020-04-28T06:17:50
2020-04-28T06:17:50
99,478,424
0
0
null
false
2022-12-06T00:34:35
2017-08-06T10:08:22
2020-04-28T06:18:02
2022-12-06T00:34:35
487
0
0
10
Java
false
false
package com.blcultra.dao; import com.blcultra.model.UserBehaviorLog; import com.blcultra.model.UserBehaviorLogWithBLOBs; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserBehaviorLogMapper { int deleteByPrimaryKey(String logid); int insert(UserBehaviorLogWithBLOBs record); int insertSelective(UserBehaviorLogWithBLOBs record); UserBehaviorLogWithBLOBs selectByPrimaryKey(String logid); int updateByPrimaryKeySelective(UserBehaviorLogWithBLOBs record); int updateByPrimaryKeyWithBLOBs(UserBehaviorLogWithBLOBs record); int updateByPrimaryKey(UserBehaviorLog record); }
UTF-8
Java
628
java
UserBehaviorLogMapper.java
Java
[]
null
[]
package com.blcultra.dao; import com.blcultra.model.UserBehaviorLog; import com.blcultra.model.UserBehaviorLogWithBLOBs; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserBehaviorLogMapper { int deleteByPrimaryKey(String logid); int insert(UserBehaviorLogWithBLOBs record); int insertSelective(UserBehaviorLogWithBLOBs record); UserBehaviorLogWithBLOBs selectByPrimaryKey(String logid); int updateByPrimaryKeySelective(UserBehaviorLogWithBLOBs record); int updateByPrimaryKeyWithBLOBs(UserBehaviorLogWithBLOBs record); int updateByPrimaryKey(UserBehaviorLog record); }
628
0.824841
0.824841
22
27.59091
26.137154
69
false
false
0
0
0
0
0
0
0.5
false
false
7
70055e0757478797143dfc4bf45df3e78dd66ee8
9,509,057,596,715
0615686709a7b39805c881add85de80302842740
/src/main/java/Components/Government/GovernmentSelectors.java
f8380c63028b27866692d735d226ca8fc0cf131f
[]
no_license
unicef/etools-tests
https://github.com/unicef/etools-tests
9ba5711a905bcbaedebfebf09b863dc4226b5805
24d6013355eb9ee9fca55e65f036207ea5c435ad
refs/heads/master
2020-04-22T17:58:43.958000
2019-01-21T10:12:41
2019-01-21T10:12:41
170,560,744
0
0
null
false
2021-03-23T15:23:26
2019-02-13T18:50:08
2019-02-13T18:55:05
2021-03-23T15:23:26
11,471
0
0
1
Java
false
false
package Components.Government; import org.openqa.selenium.By; import java.util.Arrays; import java.util.List; public class GovernmentSelectors { private static final String ROOT_APP_SHELL = "app-shell"; private static final String ROOT_GOVERNMENT_MODULE = "partners-module"; public static final List<String> SHADOW_ROOT_GOVERNMENT = Arrays.asList( ROOT_APP_SHELL,ROOT_GOVERNMENT_MODULE); public static final By PAGE_TITLE = By.cssSelector("page-content-header > div:nth-child(1) > span:nth-child(2)"); }
UTF-8
Java
539
java
GovernmentSelectors.java
Java
[]
null
[]
package Components.Government; import org.openqa.selenium.By; import java.util.Arrays; import java.util.List; public class GovernmentSelectors { private static final String ROOT_APP_SHELL = "app-shell"; private static final String ROOT_GOVERNMENT_MODULE = "partners-module"; public static final List<String> SHADOW_ROOT_GOVERNMENT = Arrays.asList( ROOT_APP_SHELL,ROOT_GOVERNMENT_MODULE); public static final By PAGE_TITLE = By.cssSelector("page-content-header > div:nth-child(1) > span:nth-child(2)"); }
539
0.734694
0.730983
18
28.944445
33.622864
117
false
false
0
0
0
0
0
0
0.5
false
false
7
b91300118249f1750adf70f125124e1f670076e5
24,833,500,975,082
2fd1787c540f57d6bf2b9c02c116aedaa7946631
/rs837/client/src/com/jagex/Class31.java
8cb628cacd011250f5395bdcdbee5195950dfee3
[]
no_license
im-frizzy/Virtue
https://github.com/im-frizzy/Virtue
bef29a7a9697815f2c906b3cb32e30a617141728
dda4e6d9748c3764e56f82498497943279251db3
refs/heads/master
2015-08-21T02:35:58.815000
2015-03-08T19:10:35
2015-03-08T19:10:35
22,769,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jagex; /* Class31 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ public class Class31 { static Class31 aClass31_397; static Class31 aClass31_398; static Class31 aClass31_399; static Class31 aClass31_400; static Class31 aClass31_401; static Class31 aClass31_402; static Class31 aClass31_403; static Class31 aClass31_404; static Class31 aClass31_405; static Class31 aClass31_406 = new Class31(0, 0); static Class31 aClass31_407; static Class31 aClass31_408; static Class31 aClass31_409; static Class31 aClass31_410; static Class31 aClass31_411; static Class31 aClass31_412; static Class31 aClass31_413; static Class31 aClass31_414; static Class31 aClass31_415; static Class31 aClass31_416; static Class31 aClass31_417; static Class31 aClass31_418; static Class31 aClass31_419; static Class31 aClass31_420; static Class31 aClass31_421; static Class31 aClass31_422; static Class31 aClass31_423; static Class31 aClass31_424; static Class31 aClass31_425; static Class31 aClass31_426; static Class31 aClass31_427; public int anInt428; int anInt429; public static Js5StandartRequester aClass434_430; static { aClass31_398 = new Class31(11, 1); aClass31_399 = new Class31(16, 2); aClass31_400 = new Class31(10, 3); aClass31_401 = new Class31(6, 10); aClass31_409 = new Class31(3, 11); aClass31_403 = new Class31(25, 12); aClass31_404 = new Class31(13, 13); aClass31_410 = new Class31(1, 14); aClass31_426 = new Class31(30, 15); aClass31_407 = new Class31(19, 16); aClass31_408 = new Class31(12, 17); aClass31_427 = new Class31(9, 20); aClass31_412 = new Class31(23, 21); aClass31_405 = new Class31(17, 22); aClass31_411 = new Class31(7, 30); aClass31_413 = new Class31(5, 31); aClass31_418 = new Class31(8, 32); aClass31_415 = new Class31(26, 33); aClass31_416 = new Class31(28, 40); aClass31_417 = new Class31(20, 41); aClass31_397 = new Class31(22, 42); aClass31_419 = new Class31(15, 43); aClass31_402 = new Class31(24, 50); aClass31_421 = new Class31(2, 51); aClass31_420 = new Class31(4, 52); aClass31_423 = new Class31(18, 53); aClass31_424 = new Class31(14, 60); aClass31_425 = new Class31(27, 61); aClass31_414 = new Class31(21, 70); aClass31_422 = new Class31(29, 255); } Class31(int i, int i_0_) { anInt428 = 942246747 * i; ((Class31) this).anInt429 = i_0_ * 645188965; } static final void method717(CS2executor cS2executor, int i) { int i_1_ = (((CS2executor) cS2executor).anIntArray7908[(((CS2executor) cS2executor).anInt7909 -= -2095059855) * 968250513]); ((CS2executor) cS2executor).anIntArray7908[(((CS2executor) cS2executor).anInt7909 += -2095059855) * 968250513 - 1] = client.settings.aClass637_Sub18_10149 .getSupport(i_1_); } public static int method718(int i, int i_2_) { Class254 class254 = (Class254) Class240.aMap2765.get(Integer.valueOf(i)); if (class254 == null) return 0; return class254.method3510(382299287); } public static Class632[] method719(int i) { return (new Class632[] { Class632.aClass632_8075, Class632.aClass632_8071, Class632.aClass632_8074, Class632.aClass632_8077, Class632.aClass632_8073, Class632.aClass632_8078, Class632.aClass632_8076, Class632.aClass632_8072, Class632.aClass632_8079 }); } }
UTF-8
Java
3,301
java
Class31.java
Java
[]
null
[]
package com.jagex; /* Class31 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ public class Class31 { static Class31 aClass31_397; static Class31 aClass31_398; static Class31 aClass31_399; static Class31 aClass31_400; static Class31 aClass31_401; static Class31 aClass31_402; static Class31 aClass31_403; static Class31 aClass31_404; static Class31 aClass31_405; static Class31 aClass31_406 = new Class31(0, 0); static Class31 aClass31_407; static Class31 aClass31_408; static Class31 aClass31_409; static Class31 aClass31_410; static Class31 aClass31_411; static Class31 aClass31_412; static Class31 aClass31_413; static Class31 aClass31_414; static Class31 aClass31_415; static Class31 aClass31_416; static Class31 aClass31_417; static Class31 aClass31_418; static Class31 aClass31_419; static Class31 aClass31_420; static Class31 aClass31_421; static Class31 aClass31_422; static Class31 aClass31_423; static Class31 aClass31_424; static Class31 aClass31_425; static Class31 aClass31_426; static Class31 aClass31_427; public int anInt428; int anInt429; public static Js5StandartRequester aClass434_430; static { aClass31_398 = new Class31(11, 1); aClass31_399 = new Class31(16, 2); aClass31_400 = new Class31(10, 3); aClass31_401 = new Class31(6, 10); aClass31_409 = new Class31(3, 11); aClass31_403 = new Class31(25, 12); aClass31_404 = new Class31(13, 13); aClass31_410 = new Class31(1, 14); aClass31_426 = new Class31(30, 15); aClass31_407 = new Class31(19, 16); aClass31_408 = new Class31(12, 17); aClass31_427 = new Class31(9, 20); aClass31_412 = new Class31(23, 21); aClass31_405 = new Class31(17, 22); aClass31_411 = new Class31(7, 30); aClass31_413 = new Class31(5, 31); aClass31_418 = new Class31(8, 32); aClass31_415 = new Class31(26, 33); aClass31_416 = new Class31(28, 40); aClass31_417 = new Class31(20, 41); aClass31_397 = new Class31(22, 42); aClass31_419 = new Class31(15, 43); aClass31_402 = new Class31(24, 50); aClass31_421 = new Class31(2, 51); aClass31_420 = new Class31(4, 52); aClass31_423 = new Class31(18, 53); aClass31_424 = new Class31(14, 60); aClass31_425 = new Class31(27, 61); aClass31_414 = new Class31(21, 70); aClass31_422 = new Class31(29, 255); } Class31(int i, int i_0_) { anInt428 = 942246747 * i; ((Class31) this).anInt429 = i_0_ * 645188965; } static final void method717(CS2executor cS2executor, int i) { int i_1_ = (((CS2executor) cS2executor).anIntArray7908[(((CS2executor) cS2executor).anInt7909 -= -2095059855) * 968250513]); ((CS2executor) cS2executor).anIntArray7908[(((CS2executor) cS2executor).anInt7909 += -2095059855) * 968250513 - 1] = client.settings.aClass637_Sub18_10149 .getSupport(i_1_); } public static int method718(int i, int i_2_) { Class254 class254 = (Class254) Class240.aMap2765.get(Integer.valueOf(i)); if (class254 == null) return 0; return class254.method3510(382299287); } public static Class632[] method719(int i) { return (new Class632[] { Class632.aClass632_8075, Class632.aClass632_8071, Class632.aClass632_8074, Class632.aClass632_8077, Class632.aClass632_8073, Class632.aClass632_8078, Class632.aClass632_8076, Class632.aClass632_8072, Class632.aClass632_8079 }); } }
3,301
0.720085
0.475916
99
32.343433
23.552719
156
false
false
0
0
0
0
0
0
2.525253
false
false
7
f96c35d9ef633e33ca6ec4f4448d9faf290cdb81
2,980,707,339,199
927aa09869ac5a60145838970cf79536e2be4191
/Prac/src/Basic.java
6d232dce257d49679eab67735a4845f6234eb49e
[]
no_license
Kudrethairet/kudrethairet
https://github.com/Kudrethairet/kudrethairet
43e463a1f7f9e6895bf501554744825fc4bc2810
d80ab62bcf1703aaa0fcf78260a03de10ac021ee
refs/heads/master
2021-01-11T16:45:24.777000
2017-01-21T21:10:37
2017-01-21T21:10:37
79,667,253
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Basic { /** * @param args */ public static void main(String[] args) { //calculateAreaofcirclewithParam(5); // find out the lenght for the string String myString = "Kudret"; String myString2 = "Hairet"; int lenght = myString.length(); int lenght2 = myString.length(); System.out.println("the lenght of mystring1 is : " + lenght); System.out.println("the lenght of myString2 is :" + lenght2); //find of the index of one character in my String int indexofchar1 = myString.indexOf('e'); int indexofchar2 = myString2.indexOf('H'); System.out.println("the index e from myString1 is: "+ indexofchar1); System.out.println("the index H of the String2 is: "+ indexofchar2); //substring String String1 = "hello my name is kudret."; String suString1 = String1.substring(0, 17); System.out.println("the String between index of 0 and index 7: "+ suString1); //equalsignorecase String example1 = "kudret"; String example2 = "KUDREt"; System.out.println(example1.equalsIgnoreCase(example2)); } public static void calculateAreaofcirclewithParam(double raduis) { double rad = raduis; double area = Math.PI * (raduis * raduis); System.out.println("the area of the circle is: " + area); double circumference = Math.PI * 2 * raduis; System.out.println("the circumference of the circle is : " + circumference); } }
UTF-8
Java
1,617
java
Basic.java
Java
[ { "context": "t the lenght for the string\r\n\t\tString myString = \"Kudret\";\r\n\t\tString myString2 = \"Hairet\";\r\n\r\n\t\tint lenght", "end": 214, "score": 0.9997830986976624, "start": 208, "tag": "NAME", "value": "Kudret" }, { "context": "tring myString = \"Kudret\";\r\n\t\tString myString2 = \"Hairet\";\r\n\r\n\t\tint lenght = myString.length();\r\n\t\tint len", "end": 246, "score": 0.9997283816337585, "start": 240, "tag": "NAME", "value": "Hairet" }, { "context": "ubstring\r\n\t\t\r\n\t\tString String1 = \"hello my name is kudret.\";\r\n\t\t\r\n\t\tString suString1 = String1.substring(0,", "end": 829, "score": 0.9997918009757996, "start": 823, "tag": "NAME", "value": "kudret" }, { "context": "\t\r\n\t\t\r\n\t\t//equalsignorecase\r\n\t\tString example1 = \"kudret\";\r\n\t\tString example2 = \"KUDREt\";\r\n\t\t\r\n\t\tSystem.ou", "end": 1028, "score": 0.9991617202758789, "start": 1022, "tag": "NAME", "value": "kudret" }, { "context": "String example1 = \"kudret\";\r\n\t\tString example2 = \"KUDREt\";\r\n\t\t\r\n\t\tSystem.out.println(example1.equalsIgnore", "end": 1059, "score": 0.9997190833091736, "start": 1053, "tag": "NAME", "value": "KUDREt" } ]
null
[]
public class Basic { /** * @param args */ public static void main(String[] args) { //calculateAreaofcirclewithParam(5); // find out the lenght for the string String myString = "Kudret"; String myString2 = "Hairet"; int lenght = myString.length(); int lenght2 = myString.length(); System.out.println("the lenght of mystring1 is : " + lenght); System.out.println("the lenght of myString2 is :" + lenght2); //find of the index of one character in my String int indexofchar1 = myString.indexOf('e'); int indexofchar2 = myString2.indexOf('H'); System.out.println("the index e from myString1 is: "+ indexofchar1); System.out.println("the index H of the String2 is: "+ indexofchar2); //substring String String1 = "hello my name is kudret."; String suString1 = String1.substring(0, 17); System.out.println("the String between index of 0 and index 7: "+ suString1); //equalsignorecase String example1 = "kudret"; String example2 = "KUDREt"; System.out.println(example1.equalsIgnoreCase(example2)); } public static void calculateAreaofcirclewithParam(double raduis) { double rad = raduis; double area = Math.PI * (raduis * raduis); System.out.println("the area of the circle is: " + area); double circumference = Math.PI * 2 * raduis; System.out.println("the circumference of the circle is : " + circumference); } }
1,617
0.595547
0.57885
98
14.479591
22.062634
79
false
false
0
0
0
0
0
0
1.734694
false
false
7
232a6872d128daf287ea822f08540825d16c1f81
1,786,706,401,482
ff9ddab49432d8a2e663b3c4317d60b319565151
/DS/DS-Session-1/queue_using_interface/QueueUsingLinkedListTest.java
65cfec7af0c13566cfa1c88e45b1015bd8e7127d
[]
no_license
meta-rajendra-rathore/GET2018
https://github.com/meta-rajendra-rathore/GET2018
a8989dc42f0d2841d99030f3c86eb73283b44fbb
a6bad8e05475a3ec2e19aa5e045652d604886a1f
refs/heads/master
2020-03-22T23:23:50.571000
2018-10-15T07:44:52
2018-10-15T07:44:52
140,807,775
0
1
null
false
2018-10-17T06:02:22
2018-07-13T06:41:13
2018-10-15T07:44:58
2018-10-17T06:01:38
36,011
0
0
14
Java
false
null
package datastructure_1.queue_using_interface; import static org.junit.Assert.*; import org.junit.Test; public class QueueUsingLinkedListTest { QueueUsingLinkedList queue; public QueueUsingLinkedListTest() { queue = new QueueUsingLinkedList(); } @Test public void testDequeueInEmptyQueueAtFirst() { assertEquals(-1, queue.dequeue()); } @Test public void testEnqueueInEmptyQueueAtFirst() { assertEquals(true, queue.enqueue(3)); } @Test public void testEnqueueDequeueRandom() { assertEquals(true, queue.enqueue(3)); assertEquals(true, queue.enqueue(2)); assertEquals(3, queue.dequeue()); assertEquals(true, queue.enqueue(4)); assertEquals(true, queue.enqueue(1)); assertEquals(true, queue.enqueue(6)); assertEquals(2, queue.dequeue()); assertEquals(4, queue.dequeue()); assertEquals(true, queue.enqueue(9)); assertEquals(true, queue.enqueue(5)); assertEquals(1, queue.dequeue()); assertEquals(6, queue.dequeue()); assertEquals(9, queue.dequeue()); assertEquals(5, queue.dequeue()); assertEquals(-1, queue.dequeue()); } @Test public void testPeekInEmptyQueueAtFirst() { assertEquals(-1, queue.peek()); } @Test public void testPeekInEmptyQueueRandom() { assertEquals(true, queue.enqueue(3)); assertEquals(true, queue.enqueue(2)); assertEquals(3, queue.dequeue()); assertEquals(true, queue.enqueue(4)); assertEquals(true, queue.enqueue(1)); assertEquals(true, queue.enqueue(6)); assertEquals(2, queue.dequeue()); assertEquals(4, queue.dequeue()); assertEquals(true, queue.enqueue(9)); assertEquals(true, queue.enqueue(5)); assertEquals(1, queue.dequeue()); assertEquals(6, queue.dequeue()); assertEquals(9, queue.dequeue()); assertEquals(5, queue.dequeue()); assertEquals(-1, queue.peek()); } @Test public void testPeekInQueueRandom() { assertEquals(true, queue.enqueue(3)); assertEquals(true, queue.enqueue(2)); assertEquals(3, queue.dequeue()); assertEquals(true, queue.enqueue(4)); assertEquals(true, queue.enqueue(1)); assertEquals(true, queue.enqueue(6)); assertEquals(2, queue.dequeue()); assertEquals(4, queue.peek()); } }
UTF-8
Java
2,456
java
QueueUsingLinkedListTest.java
Java
[]
null
[]
package datastructure_1.queue_using_interface; import static org.junit.Assert.*; import org.junit.Test; public class QueueUsingLinkedListTest { QueueUsingLinkedList queue; public QueueUsingLinkedListTest() { queue = new QueueUsingLinkedList(); } @Test public void testDequeueInEmptyQueueAtFirst() { assertEquals(-1, queue.dequeue()); } @Test public void testEnqueueInEmptyQueueAtFirst() { assertEquals(true, queue.enqueue(3)); } @Test public void testEnqueueDequeueRandom() { assertEquals(true, queue.enqueue(3)); assertEquals(true, queue.enqueue(2)); assertEquals(3, queue.dequeue()); assertEquals(true, queue.enqueue(4)); assertEquals(true, queue.enqueue(1)); assertEquals(true, queue.enqueue(6)); assertEquals(2, queue.dequeue()); assertEquals(4, queue.dequeue()); assertEquals(true, queue.enqueue(9)); assertEquals(true, queue.enqueue(5)); assertEquals(1, queue.dequeue()); assertEquals(6, queue.dequeue()); assertEquals(9, queue.dequeue()); assertEquals(5, queue.dequeue()); assertEquals(-1, queue.dequeue()); } @Test public void testPeekInEmptyQueueAtFirst() { assertEquals(-1, queue.peek()); } @Test public void testPeekInEmptyQueueRandom() { assertEquals(true, queue.enqueue(3)); assertEquals(true, queue.enqueue(2)); assertEquals(3, queue.dequeue()); assertEquals(true, queue.enqueue(4)); assertEquals(true, queue.enqueue(1)); assertEquals(true, queue.enqueue(6)); assertEquals(2, queue.dequeue()); assertEquals(4, queue.dequeue()); assertEquals(true, queue.enqueue(9)); assertEquals(true, queue.enqueue(5)); assertEquals(1, queue.dequeue()); assertEquals(6, queue.dequeue()); assertEquals(9, queue.dequeue()); assertEquals(5, queue.dequeue()); assertEquals(-1, queue.peek()); } @Test public void testPeekInQueueRandom() { assertEquals(true, queue.enqueue(3)); assertEquals(true, queue.enqueue(2)); assertEquals(3, queue.dequeue()); assertEquals(true, queue.enqueue(4)); assertEquals(true, queue.enqueue(1)); assertEquals(true, queue.enqueue(6)); assertEquals(2, queue.dequeue()); assertEquals(4, queue.peek()); } }
2,456
0.627036
0.609935
79
30.088608
18.498846
50
false
false
0
0
0
0
0
0
1.101266
false
false
7
404d5f5c58c59eb7757acb8484f533623490577f
31,911,607,042,716
2e6802e7ee2ae8a7fe58a72145a00aed041075bf
/src/storage/FileUtilities.java
e820671b402d93283c4ec9a220d8c7ee00ba96d0
[]
no_license
PhawkesGR/Swiss-Transportation-Project
https://github.com/PhawkesGR/Swiss-Transportation-Project
5063f41d5b7f8a9573135ff73fbdefaa13f88120
a1bf2d1dd9f7c1b43196e4b6b09309f52adddbc7
refs/heads/master
2021-01-25T07:00:58.743000
2017-06-07T13:25:41
2017-06-07T13:25:41
93,637,258
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 storage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import org.json.JSONException; import org.json.simple.parser.ParseException; import basics.Connection; import basics.Location; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class FileUtilities { Connection a = new Connection(); Location b = new Location(); String FileNameForLinks = " "; public void setFileNameForLinks(String FileNameForLinks) { this.FileNameForLinks = FileNameForLinks; } String FileName = " "; public void setFileName(String FileName) { this.FileName = FileName; } public void WriteDirectLinksToFile(String FileNameForLinks) throws IOException, ParseException, JSONException, SQLException, LinksHaveDataException { Scanner input = new Scanner(System.in); System.out.println("Please give a name for the file"); setFileNameForLinks(input.next()); String wr = a.getConnections().toString(); File file = new File(FileName); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file, false); BufferedWriter bw = new BufferedWriter(fw); bw.write(wr); bw.close(); } public void WriteCitiesToFile(String FileName) throws IOException, ParseException, JSONException, SQLException, CitiesHaveDataException { String w = b.GetInfo().toString(); File file = new File(FileName); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file, false); BufferedWriter bw = new BufferedWriter(fw); bw.write(w); bw.close(); } public ArrayList<String> ReadCitiesInfoFromFile(String FileName) { ArrayList<String> cityinfo = null; String line; try (BufferedReader br = new BufferedReader(new FileReader(FileName))) { while ((line = br.readLine()) != null) { cityinfo.add(line); } } catch (IOException e) { e.printStackTrace(); } return cityinfo; } }
UTF-8
Java
2,551
java
FileUtilities.java
Java
[]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package storage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import org.json.JSONException; import org.json.simple.parser.ParseException; import basics.Connection; import basics.Location; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class FileUtilities { Connection a = new Connection(); Location b = new Location(); String FileNameForLinks = " "; public void setFileNameForLinks(String FileNameForLinks) { this.FileNameForLinks = FileNameForLinks; } String FileName = " "; public void setFileName(String FileName) { this.FileName = FileName; } public void WriteDirectLinksToFile(String FileNameForLinks) throws IOException, ParseException, JSONException, SQLException, LinksHaveDataException { Scanner input = new Scanner(System.in); System.out.println("Please give a name for the file"); setFileNameForLinks(input.next()); String wr = a.getConnections().toString(); File file = new File(FileName); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file, false); BufferedWriter bw = new BufferedWriter(fw); bw.write(wr); bw.close(); } public void WriteCitiesToFile(String FileName) throws IOException, ParseException, JSONException, SQLException, CitiesHaveDataException { String w = b.GetInfo().toString(); File file = new File(FileName); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file, false); BufferedWriter bw = new BufferedWriter(fw); bw.write(w); bw.close(); } public ArrayList<String> ReadCitiesInfoFromFile(String FileName) { ArrayList<String> cityinfo = null; String line; try (BufferedReader br = new BufferedReader(new FileReader(FileName))) { while ((line = br.readLine()) != null) { cityinfo.add(line); } } catch (IOException e) { e.printStackTrace(); } return cityinfo; } }
2,551
0.635829
0.635829
82
29.109756
27.456842
153
false
false
0
0
0
0
0
0
0.670732
false
false
7
2389974a28f20299be5094a81caed9b2edd14b77
31,911,607,042,176
6e022fe06ba91c5096646680b669b003d0303160
/labs/11/StringCharacterCounter.java
25a5b52f370cd9b4200eabc1ada16bf9670145b6
[]
no_license
willwainscott/CMPT220Wainscott
https://github.com/willwainscott/CMPT220Wainscott
a7c694016c7f3f28013233cb2c8adbe2fce2dbb5
9a24e693ac7271d0cfff81dc7d20ffba056ebee5
refs/heads/master
2022-04-07T16:25:20.584000
2020-02-14T17:42:23
2020-02-14T17:42:23
117,900,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class StringCharacterCounter { public static int count(String str, char a) { if (str.indexOf(a) != -1) { return 1 + count(str.substring(str.indexOf(a) + 1), a); } else { return 0; } } public static int count(String str, char a, int high) { String shorterString = str.substring(0, high + 1); /* The ending index of the substring is high + 1 because the method * automatically subtracts one from the int parameter, because the nth * number in a string is actually the nth - 1 index of that string */ return count(shorterString,a); } }
UTF-8
Java
578
java
StringCharacterCounter.java
Java
[]
null
[]
public class StringCharacterCounter { public static int count(String str, char a) { if (str.indexOf(a) != -1) { return 1 + count(str.substring(str.indexOf(a) + 1), a); } else { return 0; } } public static int count(String str, char a, int high) { String shorterString = str.substring(0, high + 1); /* The ending index of the substring is high + 1 because the method * automatically subtracts one from the int parameter, because the nth * number in a string is actually the nth - 1 index of that string */ return count(shorterString,a); } }
578
0.67301
0.65917
20
27.85
26.996805
73
false
false
0
0
0
0
0
0
2
false
false
7
b9e5ce8b25f0357927c1df681f14336b3c302cca
3,702,261,877,904
66828521b3ac0288b8116bcd4b68e03d62ad4ec7
/xuelang/vcpSdk/src/main/java/com/temobi/vcp/sdk/data/LivePreview.java
39a53623c8cbc9e16d197d5603d581e0aab82d7c
[]
no_license
loveq2016/NewShiPin
https://github.com/loveq2016/NewShiPin
f323582f333c27487b5e0e4b4dda3e5b7ae761a5
d79bfa82d81105536262f272fa5c0292760c034c
refs/heads/master
2021-01-25T09:38:47.293000
2016-11-26T08:21:57
2016-11-26T08:21:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.temobi.vcp.sdk.data; /** * 实时播放预览依赖的基础数据 * @author Administrator * */ public class LivePreview extends PreviewBase { //视频流ID public int streamId; }
UTF-8
Java
200
java
LivePreview.java
Java
[ { "context": "obi.vcp.sdk.data;\n\n/**\n * 实时播放预览依赖的基础数据\n * @author Administrator\n *\n */\npublic class LivePreview extends PreviewBa", "end": 79, "score": 0.9181127548217773, "start": 66, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.temobi.vcp.sdk.data; /** * 实时播放预览依赖的基础数据 * @author Administrator * */ public class LivePreview extends PreviewBase { //视频流ID public int streamId; }
200
0.714286
0.714286
12
13
14.3527
46
false
false
0
0
0
0
0
0
0.333333
false
false
7
c3ad396570c8253c9953b20a33dccd4b99395eb5
19,267,223,291,205
1980d3636c2aae1de4720f3b271731e87c72b8ee
/app/src/main/java/com/zy/zssh/m_book/bean/BookContent.java
84567b56882c1b140f2ad4e651e3ec394ba6b4b8
[]
no_license
Jokehanj/ZSSH_Android
https://github.com/Jokehanj/ZSSH_Android
604495f630d6f70d8df88195b633785f6edac16d
84c0fb6a260590ca88b531aedbbcb032245e16f0
refs/heads/master
2020-02-28T09:00:34.141000
2017-04-16T10:13:13
2017-04-16T10:13:13
87,379,497
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zy.zssh.m_book.bean; /** * desc:书籍的内容 * author:陈祥龙 * email:shannonc@163.com * created at:2016/7/8 0008 **/ public class BookContent { private String page; private String url; public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
UTF-8
Java
474
java
BookContent.java
Java
[ { "context": "zy.zssh.m_book.bean;\n\n/**\n * desc:书籍的内容\n * author:陈祥龙\n * email:shannonc@163.com\n * created at:2016/7/8 ", "end": 65, "score": 0.9998478293418884, "start": 62, "tag": "NAME", "value": "陈祥龙" }, { "context": "k.bean;\n\n/**\n * desc:书籍的内容\n * author:陈祥龙\n * email:shannonc@163.com\n * created at:2016/7/8 0008\n **/\npublic class Boo", "end": 91, "score": 0.9999249577522278, "start": 75, "tag": "EMAIL", "value": "shannonc@163.com" } ]
null
[]
package com.zy.zssh.m_book.bean; /** * desc:书籍的内容 * author:陈祥龙 * email:<EMAIL> * created at:2016/7/8 0008 **/ public class BookContent { private String page; private String url; public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
465
0.580786
0.552402
29
14.793103
12.535135
38
false
false
0
0
0
0
0
0
0.241379
false
false
7
4826925608eab32725336f911a2fe4dc1466a6d0
19,241,453,488,370
632e721eb664296d089dc294deb3bba530d0f8ef
/app/src/main/java/com/example/slawek/struktaapp/FragmentsAdapter.java
e30291ade3029832365e8e5e95cf76b700e12190
[]
no_license
deaxpero/Strukta_App
https://github.com/deaxpero/Strukta_App
3cba710ed3759ce873f7066ee95996c8140607a4
ce888efcc85b2245807fad6859e49bfcdac6f939
refs/heads/master
2021-01-13T14:54:58.979000
2016-12-16T23:54:05
2016-12-16T23:54:05
76,694,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.slawek.struktaapp; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; /** * Created by Slawek on 11/12/2016. */ public class FragmentsAdapter extends FragmentStatePagerAdapter { private String fragments [] = {"Products", "Stores"}; private Context context; public FragmentsAdapter(FragmentManager supportFragmentManager, Context context) { super(supportFragmentManager); this.context = context; } @Override public Fragment getItem(int position) { switch (position){ case 0: return new ProductFragment(); case 1: return new StoresFragment(); default: return null; } } @Override public int getCount() { return fragments.length; } @Override public CharSequence getPageTitle(int position){ return fragments[position]; } }
UTF-8
Java
1,063
java
FragmentsAdapter.java
Java
[ { "context": ".app.FragmentStatePagerAdapter;\n\n/**\n * Created by Slawek on 11/12/2016.\n */\n\npublic class FragmentsAdapter", "end": 241, "score": 0.837558925151825, "start": 235, "tag": "USERNAME", "value": "Slawek" } ]
null
[]
package com.example.slawek.struktaapp; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; /** * Created by Slawek on 11/12/2016. */ public class FragmentsAdapter extends FragmentStatePagerAdapter { private String fragments [] = {"Products", "Stores"}; private Context context; public FragmentsAdapter(FragmentManager supportFragmentManager, Context context) { super(supportFragmentManager); this.context = context; } @Override public Fragment getItem(int position) { switch (position){ case 0: return new ProductFragment(); case 1: return new StoresFragment(); default: return null; } } @Override public int getCount() { return fragments.length; } @Override public CharSequence getPageTitle(int position){ return fragments[position]; } }
1,063
0.647225
0.634995
45
22.622223
21.004009
84
false
false
0
0
0
0
0
0
0.355556
false
false
7
cefecba041df2703ee04219e1ff2b393e5db741e
6,579,889,967,779
83dfd6cd0121d581fcee7715e8382438114c2b3b
/Airports/Teamaufgabe/src/Grid2D.java
342b6e92438ef45d07fa2d10c215221e18ed1b41
[]
no_license
callida99/Airports
https://github.com/callida99/Airports
0e53b6b834b221cb260d94d20e36870fd90bebfc
5c6040c982620212a9b90de23bbeabc48ff94d95
refs/heads/master
2020-04-08T03:42:56.737000
2018-11-25T01:22:25
2018-11-25T01:22:25
158,987,137
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Representates a grid in 2D-Space. The grid is implemented as a 2D-Array, where * each cell holds a SinglyLinkedList that contains all Junctions that are associated * to that specific cell. */ public class Grid2D { //******************* private Fields ******************************** private SinglyLinkedList grid[][]; private int gridSize; // these two points bound the plane private Point topLeft; private Point bottomRight; //******************* constructor ******************************** /** * Constructor with given boundaries, initialises empty lists in grid cells. * @param topLeft top left Point of the plane. * @param bottomRight bottom right Point of the plane. */ public Grid2D(Point topLeft, Point bottomRight){ double planeSize = (bottomRight.getX() - topLeft.getX()); //round plane size up to an integer value gridSize = (int)Math.ceil(Math.sqrt(planeSize)); grid = new SinglyLinkedList[gridSize][gridSize]; for (int i = 0; i < grid.length; i++){ for (int j = 0; j < grid[0].length; j++){ grid[i][j] = new SinglyLinkedList(); } } this.topLeft = topLeft; this.bottomRight = bottomRight; } //******************* private Methods ******************************** /** * Calculates the index of a cell in the 2D-array for a given Juction based * an it's coordinates. * @param p of type Junction. * @return index of type Point P=(x,y). */ private Point calcIndex(Junction p){ int m = gridSize - 1; double minX = topLeft.getX(); double maxX = bottomRight.getX(); double minY = bottomRight.getY(); double maxY = topLeft.getY(); //calculates a value between 0 and gridSize-1 and rounds it down to integer value. int x = (int)Math.floor(m*((p.xCoord - minX)/(maxX -minX))); int y = m - (int)Math.floor(m*((p.yCoord - minY)/(maxY -minY))); return new Point(x,y); } /** * Calculates the index of a cell in the 2D-array for a given Point based * an it's coordinates. Overloaded method to help find Junctions. * @param p of type Point. * @return index of type Point P=(x,y). */ private Point calcIndex(Point p){ int m = gridSize - 1; double minX = topLeft.getX(); double maxX = bottomRight.getX(); double minY = bottomRight.getY(); double maxY = topLeft.getY(); //calculates a value between 0 and gridSize-1 and rounds it down to integer value. int x = (int)Math.floor(m*((p.getX() - minX)/(maxX -minX))); int y = m - (int)Math.floor(m*((p.getY() - minY)/(maxY -minY))); return new Point(x,y); } /** * Adds a Junction to the 2d-Grid at a calculated index. * @param p of type Junction. */ public void add(Junction p){ Point index = calcIndex(p); grid[(int)index.getY()][(int)index.getX()].add(p); } /** * Calculates the number of Trainstations and Airports inside a specific range from a * startingPoint P. * @param radius defines the radius of the Range. * @param startX X-coordinate of starting point. * @param startY Y-coordinate of starting point. * @return Array of size 2, where Arr[0] represents the number of Airports in * given range and Arr[1] representates the number of Trainstations. */ public int[] findJunctionsInRadius(double radius, double startX, double startY) { int[] counters = new int[2]; //Draws rectangular Quad around Point, to reduce the number of points that have to // be checked. Point topLeftPointIndex = calcIndex(new Point(startX - radius, startY + radius)); Point bottomRightPointIndex = calcIndex(new Point(startX + radius, startY - radius)); //iterates over the cells of the 2D-Array that are touched by the Quad. for (int y = (int) topLeftPointIndex.getY(); y <= (int) bottomRightPointIndex.getY(); y++) { for (int x = (int) topLeftPointIndex.getX(); x <= (int) bottomRightPointIndex.getX(); x++) { int[]temp = grid[y][x].findJunctionsInRadius(radius, startX, startY); // delegates task to list counters[0] += temp[0]; counters[1] += temp[1]; } } return counters; } /** * Calculates number of airports with at least n Trainstations inside of * a given radius. * @param radius of type double. * @param n Minimum number of Trainstations that have to be in radius. * @return returns Integer number of Airports matching the criteria. */ public int findAirports(double radius, int n){ int counter = 0; //Iterates over each SinglyLinkedList in the 2D-Array and calls findJunctionsInRadius() for // each Juction of type Airport. for(int y = 0; y < grid.length; y++){ for(int x = 0; x < grid[0].length; x++){ for (int i = 0; i < grid[y][x].getSize(); i++){ Junction p = grid[y][x].get(i); if (p instanceof Airport) { int[] arr = findJunctionsInRadius(radius, p.getxCoord(), p.getyCoord()); int num = arr[1]; if (num >= n){ counter++; } } } } } return counter; } }
UTF-8
Java
5,717
java
Grid2D.java
Java
[]
null
[]
/** * Representates a grid in 2D-Space. The grid is implemented as a 2D-Array, where * each cell holds a SinglyLinkedList that contains all Junctions that are associated * to that specific cell. */ public class Grid2D { //******************* private Fields ******************************** private SinglyLinkedList grid[][]; private int gridSize; // these two points bound the plane private Point topLeft; private Point bottomRight; //******************* constructor ******************************** /** * Constructor with given boundaries, initialises empty lists in grid cells. * @param topLeft top left Point of the plane. * @param bottomRight bottom right Point of the plane. */ public Grid2D(Point topLeft, Point bottomRight){ double planeSize = (bottomRight.getX() - topLeft.getX()); //round plane size up to an integer value gridSize = (int)Math.ceil(Math.sqrt(planeSize)); grid = new SinglyLinkedList[gridSize][gridSize]; for (int i = 0; i < grid.length; i++){ for (int j = 0; j < grid[0].length; j++){ grid[i][j] = new SinglyLinkedList(); } } this.topLeft = topLeft; this.bottomRight = bottomRight; } //******************* private Methods ******************************** /** * Calculates the index of a cell in the 2D-array for a given Juction based * an it's coordinates. * @param p of type Junction. * @return index of type Point P=(x,y). */ private Point calcIndex(Junction p){ int m = gridSize - 1; double minX = topLeft.getX(); double maxX = bottomRight.getX(); double minY = bottomRight.getY(); double maxY = topLeft.getY(); //calculates a value between 0 and gridSize-1 and rounds it down to integer value. int x = (int)Math.floor(m*((p.xCoord - minX)/(maxX -minX))); int y = m - (int)Math.floor(m*((p.yCoord - minY)/(maxY -minY))); return new Point(x,y); } /** * Calculates the index of a cell in the 2D-array for a given Point based * an it's coordinates. Overloaded method to help find Junctions. * @param p of type Point. * @return index of type Point P=(x,y). */ private Point calcIndex(Point p){ int m = gridSize - 1; double minX = topLeft.getX(); double maxX = bottomRight.getX(); double minY = bottomRight.getY(); double maxY = topLeft.getY(); //calculates a value between 0 and gridSize-1 and rounds it down to integer value. int x = (int)Math.floor(m*((p.getX() - minX)/(maxX -minX))); int y = m - (int)Math.floor(m*((p.getY() - minY)/(maxY -minY))); return new Point(x,y); } /** * Adds a Junction to the 2d-Grid at a calculated index. * @param p of type Junction. */ public void add(Junction p){ Point index = calcIndex(p); grid[(int)index.getY()][(int)index.getX()].add(p); } /** * Calculates the number of Trainstations and Airports inside a specific range from a * startingPoint P. * @param radius defines the radius of the Range. * @param startX X-coordinate of starting point. * @param startY Y-coordinate of starting point. * @return Array of size 2, where Arr[0] represents the number of Airports in * given range and Arr[1] representates the number of Trainstations. */ public int[] findJunctionsInRadius(double radius, double startX, double startY) { int[] counters = new int[2]; //Draws rectangular Quad around Point, to reduce the number of points that have to // be checked. Point topLeftPointIndex = calcIndex(new Point(startX - radius, startY + radius)); Point bottomRightPointIndex = calcIndex(new Point(startX + radius, startY - radius)); //iterates over the cells of the 2D-Array that are touched by the Quad. for (int y = (int) topLeftPointIndex.getY(); y <= (int) bottomRightPointIndex.getY(); y++) { for (int x = (int) topLeftPointIndex.getX(); x <= (int) bottomRightPointIndex.getX(); x++) { int[]temp = grid[y][x].findJunctionsInRadius(radius, startX, startY); // delegates task to list counters[0] += temp[0]; counters[1] += temp[1]; } } return counters; } /** * Calculates number of airports with at least n Trainstations inside of * a given radius. * @param radius of type double. * @param n Minimum number of Trainstations that have to be in radius. * @return returns Integer number of Airports matching the criteria. */ public int findAirports(double radius, int n){ int counter = 0; //Iterates over each SinglyLinkedList in the 2D-Array and calls findJunctionsInRadius() for // each Juction of type Airport. for(int y = 0; y < grid.length; y++){ for(int x = 0; x < grid[0].length; x++){ for (int i = 0; i < grid[y][x].getSize(); i++){ Junction p = grid[y][x].get(i); if (p instanceof Airport) { int[] arr = findJunctionsInRadius(radius, p.getxCoord(), p.getyCoord()); int num = arr[1]; if (num >= n){ counter++; } } } } } return counter; } }
5,717
0.552737
0.54714
145
37.427586
29.569496
110
false
false
0
0
0
0
0
0
0.503448
false
false
7
a81c4cd39fa587ea77ddf819ab3ca8aed04d4c2c
28,140,625,729,479
ef0f15b78f183d6747c042e551ac1d541ce2c911
/src/de/_13ducks/spacebatz/util/mapgen/modules/ResourcePlacer.java
aa88e6174ff2356f9d606dd8b3d57637ff9b89c0
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
tfg13/spacebatz
https://github.com/tfg13/spacebatz
4878013c74ed415375a4df884df5cc381537e6eb
d316bbee90e38a0236b82b6b84dee9a80acd8bcf
refs/heads/master
2020-04-10T14:15:10.939000
2015-09-27T20:54:19
2015-09-27T20:54:19
5,528,232
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de._13ducks.spacebatz.util.mapgen.modules; import de._13ducks.spacebatz.util.mapgen.InternalMap; import de._13ducks.spacebatz.util.mapgen.Module; import de._13ducks.spacebatz.util.geo.MPolygon; import de._13ducks.spacebatz.util.geo.PolyMesh; import de._13ducks.spacebatz.util.mapgen.util.MPolygonSubdivider; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Random; /** * Dieses Modul füllt größere Berge mit Ressourcen. * * @author Tobias Fleig <tobifleig@googlemail.com> */ public class ResourcePlacer extends Module { @Override public String getName() { return "resourceplacer"; } @Override public boolean requiresSeed() { return true; } @Override public String[] provides() { return new String[]{"RESOURCES"}; } @Override public boolean computesPolygons() { return true; } @Override public String[] requires() { return new String[]{"BORDER"}; } @Override public void computeMap(InternalMap map, HashMap<String, String> parameters) { // Die 50 % größten Polygone, die Wand, aber nicht Border sind mit Ressourcen füllen (via SubMesh). // Liste mit nicht-Border Poly erstellen ArrayList<MPolygon> polys = new ArrayList<>(); for (MPolygon poly : map.polygons.polys) { if (!poly.border && poly.solid) { polys.add(poly); } } // Nach Größe sortieren Collections.sort(polys, new Comparator<MPolygon>() { @Override public int compare(MPolygon o1, MPolygon o2) { return Double.compare(o2.getArea(), o1.getArea()); } }); // Teil davon auffüllen: Random random = new Random(Long.parseLong(parameters.get("SEED"))); for (int i = 0; i < polys.size() / 3; i++) { MPolygon poly = polys.get(i); // Mesh erst noch erzeugen if (poly.getMesh() == null) { poly.setMesh(MPolygonSubdivider.createMesh(poly, 20, 0, random.nextLong())); } // SubMesh-Blöcke auffüllen: ArrayList<MPolygon> subPolys = new ArrayList<>(poly.getMesh().polys); Collections.shuffle(subPolys, random); for (int j = 0; j < subPolys.size() / 8; j++) { subPolys.get(j).resource = 1; } } } }
UTF-8
Java
2,493
java
ResourcePlacer.java
Java
[ { "context": " füllt größere Berge mit Ressourcen.\n *\n * @author Tobias Fleig <tobifleig@googlemail.com>\n */\npublic class Resou", "end": 538, "score": 0.999857485294342, "start": 526, "tag": "NAME", "value": "Tobias Fleig" }, { "context": "Berge mit Ressourcen.\n *\n * @author Tobias Fleig <tobifleig@googlemail.com>\n */\npublic class ResourcePlacer extends Module {", "end": 564, "score": 0.9999279975891113, "start": 540, "tag": "EMAIL", "value": "tobifleig@googlemail.com" } ]
null
[]
package de._13ducks.spacebatz.util.mapgen.modules; import de._13ducks.spacebatz.util.mapgen.InternalMap; import de._13ducks.spacebatz.util.mapgen.Module; import de._13ducks.spacebatz.util.geo.MPolygon; import de._13ducks.spacebatz.util.geo.PolyMesh; import de._13ducks.spacebatz.util.mapgen.util.MPolygonSubdivider; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Random; /** * Dieses Modul füllt größere Berge mit Ressourcen. * * @author <NAME> <<EMAIL>> */ public class ResourcePlacer extends Module { @Override public String getName() { return "resourceplacer"; } @Override public boolean requiresSeed() { return true; } @Override public String[] provides() { return new String[]{"RESOURCES"}; } @Override public boolean computesPolygons() { return true; } @Override public String[] requires() { return new String[]{"BORDER"}; } @Override public void computeMap(InternalMap map, HashMap<String, String> parameters) { // Die 50 % größten Polygone, die Wand, aber nicht Border sind mit Ressourcen füllen (via SubMesh). // Liste mit nicht-Border Poly erstellen ArrayList<MPolygon> polys = new ArrayList<>(); for (MPolygon poly : map.polygons.polys) { if (!poly.border && poly.solid) { polys.add(poly); } } // Nach Größe sortieren Collections.sort(polys, new Comparator<MPolygon>() { @Override public int compare(MPolygon o1, MPolygon o2) { return Double.compare(o2.getArea(), o1.getArea()); } }); // Teil davon auffüllen: Random random = new Random(Long.parseLong(parameters.get("SEED"))); for (int i = 0; i < polys.size() / 3; i++) { MPolygon poly = polys.get(i); // Mesh erst noch erzeugen if (poly.getMesh() == null) { poly.setMesh(MPolygonSubdivider.createMesh(poly, 20, 0, random.nextLong())); } // SubMesh-Blöcke auffüllen: ArrayList<MPolygon> subPolys = new ArrayList<>(poly.getMesh().polys); Collections.shuffle(subPolys, random); for (int j = 0; j < subPolys.size() / 8; j++) { subPolys.get(j).resource = 1; } } } }
2,470
0.605963
0.595488
79
30.417721
24.332928
107
false
false
0
0
0
0
0
0
0.518987
false
false
7
c88fbfbace7322ff86cfa85fed60a23271f684ff
360,777,271,868
2a35ed8ee1960aa2ea34c1bb1b2bb294a5c3f9f5
/src/main/java/songbox/house/domain/entity/user/UserInfo.java
7b6a75cc21d5b97fbe4916a41aee7b530132eb22
[]
no_license
albertaleksieiev/songbox-house-core
https://github.com/albertaleksieiev/songbox-house-core
7f852df0a569e938013dba1857309a36ea39e6d4
8e8d76ef913955af95748fd7a4cf240bb6ebe44f
refs/heads/master
2020-07-02T21:33:48.299000
2019-07-28T12:41:34
2019-07-28T16:31:35
201,673,098
0
0
null
true
2019-08-10T19:17:32
2019-08-10T19:17:31
2019-07-28T16:31:44
2019-07-28T16:48:10
261
0
0
0
null
false
false
package songbox.house.domain.entity.user; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import songbox.house.domain.entity.YoutubePlaylist; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.util.ArrayList; import java.util.Date; import java.util.List; @Table @Entity @Getter @Setter public class UserInfo { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long userId; @Column(nullable = false, unique = true) private String userName; @Column @JsonIgnore private String password; @Column private String name; @Column private String surname; @Column private String email; @Column private Boolean active; @CreationTimestamp @Temporal(TemporalType.DATE) @Column private Date createDate; @OneToOne private UserRole role; @OneToMany( mappedBy = "owner", cascade = CascadeType.ALL, orphanRemoval = true ) private List<YoutubePlaylist> youtubePlaylists = new ArrayList<>(); }
UTF-8
Java
1,484
java
UserInfo.java
Java
[]
null
[]
package songbox.house.domain.entity.user; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import songbox.house.domain.entity.YoutubePlaylist; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.util.ArrayList; import java.util.Date; import java.util.List; @Table @Entity @Getter @Setter public class UserInfo { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long userId; @Column(nullable = false, unique = true) private String userName; @Column @JsonIgnore private String password; @Column private String name; @Column private String surname; @Column private String email; @Column private Boolean active; @CreationTimestamp @Temporal(TemporalType.DATE) @Column private Date createDate; @OneToOne private UserRole role; @OneToMany( mappedBy = "owner", cascade = CascadeType.ALL, orphanRemoval = true ) private List<YoutubePlaylist> youtubePlaylists = new ArrayList<>(); }
1,484
0.740566
0.740566
66
21.484848
16.445726
71
false
false
0
0
0
0
0
0
0.5
false
false
7
dcb2a57ecd574418a10a3259f222db68b723427c
11,038,066,016,883
3abdbbd7c1b49c3617fb7da9fd08e131b30eb1bf
/Main.java
6488d7ab915cd387e05727ee839370df5a073429
[]
no_license
striest/Line-Intersection-Project
https://github.com/striest/Line-Intersection-Project
7607f251d66209eae85eed00b1cbc562bac2a5c5
a9f249c3899f6080eea3871517780dd94cf7e93b
refs/heads/master
2019-04-23T05:04:56.209000
2017-06-05T20:22:35
2017-06-05T20:22:35
93,443,061
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project3_v3; import java.awt.geom.Point2D; import javax.swing.JFrame; public class Main { public static void main(String[] args) { IO.read(); // uses IO class to read and create the tree JFrame frame = new JFrame(); frame.setSize(Component.WINDOW_SIZE, Component.WINDOW_SIZE); Component c = new Component(); // constructs the graphics component based on the line tree frame.add(c); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } //test cases //Line l1 = new Line(new Point2D.Double(0, 0.12), new Point2D.Double(0.23, 1)); //Line l2 = new Line(new Point2D.Double(1, 0.41), new Point2D.Double(0, 0.52)); //Line l3 = new Line(new Point2D.Double(1, 0.2), new Point2D.Double(0.3, 1)); //Line l4 = new Line(new Point2D.Double(0, 0.4), new Point2D.Double(0.1, 0)); //Line l5 = new Line(new Point2D.Double(1, 0.35), new Point2D.Double(0.17, 1)); //Line l6 = new Line(new Point2D.Double(.05, 0), new Point2D.Double(.1, 1)); //Point2D.Double p1 = new Point2D.Double(.4, .985); //Point2D.Double p2 = new Point2D.Double(.8, .6); //IO.lines.add(l1); //IO.lines.add(l2); //IO.lines.add(l3); //IO.lines.add(l4); //IO.lines.add(l5); //IO.lines.add(l6); //IO.lines.add(new Line(new Point2D.Double(.5, 0), new Point2D.Double(.5, 1))); //IO.lines.add(new Line(new Point2D.Double(0, .5), new Point2D.Double(1, .5))); //IO.lines.add(new Line(new Point2D.Double(0, .25), new Point2D.Double(1, .25))); //IO.lines.add(new Line(new Point2D.Double(0, .75), new Point2D.Double(1, .75))); //IO.lines.add(new Line(new Point2D.Double(.25, 0), new Point2D.Double(.25, 1))); //IO.lines.add(new Line(new Point2D.Double(.75, 0), new Point2D.Double(.75, 1))); //IO.lines.add(new Line(new Point2D.Double(1, 1), new Point2D.Double(0, 0))); //IO.lines.add(new Line(new Point2D.Double(1, 0), new Point2D.Double(0, 1))); //IO.lines.add(new Line(new Point2D.Double(1, .5), new Point2D.Double(0, .5))); //IO.lines.add(new Line(new Point2D.Double(.5, 0), new Point2D.Double(.5, 1))); //IO.lines.add(new Line(new Point2D.Double(1, .75), new Point2D.Double(0, .25))); //IO.lines.add(new Line(new Point2D.Double(1, .25), new Point2D.Double(0, .75))); //IO.lines.add(new Line(new Point2D.Double(.25, 0), new Point2D.Double(.75, 1))); //IO.lines.add(new Line(new Point2D.Double(.75, 0), new Point2D.Double(.25, 1))); //IO.points.add(p1); //IO.points.add(p2); //for(int a = 0; a < IO.lines.size(); a++) { // IO.tree.insert(a, IO.lines.get(a)); //
UTF-8
Java
2,469
java
Main.java
Java
[]
null
[]
package project3_v3; import java.awt.geom.Point2D; import javax.swing.JFrame; public class Main { public static void main(String[] args) { IO.read(); // uses IO class to read and create the tree JFrame frame = new JFrame(); frame.setSize(Component.WINDOW_SIZE, Component.WINDOW_SIZE); Component c = new Component(); // constructs the graphics component based on the line tree frame.add(c); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } //test cases //Line l1 = new Line(new Point2D.Double(0, 0.12), new Point2D.Double(0.23, 1)); //Line l2 = new Line(new Point2D.Double(1, 0.41), new Point2D.Double(0, 0.52)); //Line l3 = new Line(new Point2D.Double(1, 0.2), new Point2D.Double(0.3, 1)); //Line l4 = new Line(new Point2D.Double(0, 0.4), new Point2D.Double(0.1, 0)); //Line l5 = new Line(new Point2D.Double(1, 0.35), new Point2D.Double(0.17, 1)); //Line l6 = new Line(new Point2D.Double(.05, 0), new Point2D.Double(.1, 1)); //Point2D.Double p1 = new Point2D.Double(.4, .985); //Point2D.Double p2 = new Point2D.Double(.8, .6); //IO.lines.add(l1); //IO.lines.add(l2); //IO.lines.add(l3); //IO.lines.add(l4); //IO.lines.add(l5); //IO.lines.add(l6); //IO.lines.add(new Line(new Point2D.Double(.5, 0), new Point2D.Double(.5, 1))); //IO.lines.add(new Line(new Point2D.Double(0, .5), new Point2D.Double(1, .5))); //IO.lines.add(new Line(new Point2D.Double(0, .25), new Point2D.Double(1, .25))); //IO.lines.add(new Line(new Point2D.Double(0, .75), new Point2D.Double(1, .75))); //IO.lines.add(new Line(new Point2D.Double(.25, 0), new Point2D.Double(.25, 1))); //IO.lines.add(new Line(new Point2D.Double(.75, 0), new Point2D.Double(.75, 1))); //IO.lines.add(new Line(new Point2D.Double(1, 1), new Point2D.Double(0, 0))); //IO.lines.add(new Line(new Point2D.Double(1, 0), new Point2D.Double(0, 1))); //IO.lines.add(new Line(new Point2D.Double(1, .5), new Point2D.Double(0, .5))); //IO.lines.add(new Line(new Point2D.Double(.5, 0), new Point2D.Double(.5, 1))); //IO.lines.add(new Line(new Point2D.Double(1, .75), new Point2D.Double(0, .25))); //IO.lines.add(new Line(new Point2D.Double(1, .25), new Point2D.Double(0, .75))); //IO.lines.add(new Line(new Point2D.Double(.25, 0), new Point2D.Double(.75, 1))); //IO.lines.add(new Line(new Point2D.Double(.75, 0), new Point2D.Double(.25, 1))); //IO.points.add(p1); //IO.points.add(p2); //for(int a = 0; a < IO.lines.size(); a++) { // IO.tree.insert(a, IO.lines.get(a)); //
2,469
0.668287
0.594168
56
43.089287
32.048668
92
false
false
0
0
0
0
0
0
2.267857
false
false
7
c0384555442ed66b519208c1dd2ccac6a8274a47
33,878,702,095,262
f1229d327245a4391327a985901cfc5708179ccd
/src/questionV18/S31.java
cfcbd10825ae85eab685ff130a48dcb28932155f
[]
no_license
Selbinyyaz/Oracle_Java_SE-8_Certification_Prepartion
https://github.com/Selbinyyaz/Oracle_Java_SE-8_Certification_Prepartion
0f5febfcd72a81149c4c372fafc1a975a0a2e7f3
d68076803a8efef4adc6f0a97be6b1b230e661e0
refs/heads/master
2023-03-15T20:43:12.893000
2021-03-07T04:45:55
2021-03-07T04:45:55
297,816,916
0
0
null
false
2021-01-26T01:11:49
2020-09-23T01:23:24
2020-09-23T01:32:11
2021-01-26T01:11:48
6
0
0
0
Java
false
false
package questionV18; public class S31 { public static void main(String[] args) { // TODO Auto-generated method stub int array1[]= {1, 2, 3}; int array2[]=new int [5]; array2=array1;// this will be 1, 2, 3 for (int i : array2) { System.out.print(i+" "); } System.out.println(); int array3[]=new int [3]; array3=array2; for (int i : array3) { System.out.print(i+" "); } } }
UTF-8
Java
425
java
S31.java
Java
[]
null
[]
package questionV18; public class S31 { public static void main(String[] args) { // TODO Auto-generated method stub int array1[]= {1, 2, 3}; int array2[]=new int [5]; array2=array1;// this will be 1, 2, 3 for (int i : array2) { System.out.print(i+" "); } System.out.println(); int array3[]=new int [3]; array3=array2; for (int i : array3) { System.out.print(i+" "); } } }
425
0.569412
0.52
28
14.178572
13.593732
41
false
false
0
0
0
0
0
0
2
false
false
7
b147bef42481f7ff2616dc2df185744e435cb2cc
37,726,992,762,055
961970ed335c4b4bda660e74b3716224c74ba00c
/com.promisepb.utils.emailutils/src/main/java/com/promisepb/utils/emailutils/PBMailUtil.java
f069bd71188ec1eceaa805386ae6e5a276fb4e22
[]
no_license
xingjian/pbutils
https://github.com/xingjian/pbutils
4d11abb8188a0369e1e4f8edd0d747b09c84b631
4385d10d7defdf9d7c02e281572809b8674e4745
refs/heads/master
2021-01-20T23:45:18.822000
2018-04-26T07:08:20
2018-04-26T07:08:20
101,850,502
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.promisepb.utils.emailutils; import java.io.File; import java.util.Date; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * 功能描述:基于java mail进行封装的类 * @author:<a href="mailto:xingjian@tongtusoft.com.cn">邢健</a> * @version: V1.0 * 日期:2016年12月22日 上午11:07:42 */ public class PBMailUtil { /** * 构造发送邮件的参数 * @param protocol eg: smtp * @param host eg:smtp.163.com * @param auth eg:true * @param mailUserName xingjian@yeah.net * @param mailPasswd * @return */ public static Properties CreateProperties(String protocol,String host,String auth,String mailUserName,String mailPasswd){ // 参数配置 Properties props = new Properties(); //使用的协议(JavaMail规范要求) props.setProperty("mail.transport.protocol", protocol); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.host", host); // 请求认证,参数名称与具体实现有关 props.setProperty("mail.smtp.auth", auth); props.setProperty("sendmail.username", mailUserName); props.setProperty("sendmail.passwd", mailPasswd); return props; } /** * 创建一封只包含文本的简单邮件 * @param session 和服务器交互的会话 * @param sendMail 发件人 * @param receiveMails 接收人 * @param ccMails 抄送人 * @param bccMails 密送人 * @param subject 主题 * @param content 内容 * @return * @throws Exception */ public static MimeMessage CreateMimeMessage(Session session,InternetAddress sendMail,List<InternetAddress> receiveMails,List<InternetAddress> ccMails,List<InternetAddress> bccMails,String subject,String content) throws Exception { //创建一封邮件 MimeMessage message = new MimeMessage(session); //From: 发件人 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码 message.setFrom(sendMail); //To: 收件人(可以增加多个收件人、抄送、密送) for(InternetAddress recipientTemp: receiveMails){ message.addRecipient(MimeMessage.RecipientType.TO, recipientTemp); } //Cc: 抄送(可选) if(null!=ccMails){ for(InternetAddress recipientCCTemp: ccMails){ message.addRecipient(MimeMessage.RecipientType.CC, recipientCCTemp); } } //Bcc: 密送(可选) if(null!=bccMails){ for(InternetAddress recipientBCCTemp: bccMails){ message.addRecipient(MimeMessage.RecipientType.BCC, recipientBCCTemp); } } //Subject: 邮件主题 message.setSubject(subject, "UTF-8"); //Content: 邮件正文(可以使用html标签) message.setContent(content, "text/html;charset=UTF-8"); //设置发件时间 message.setSentDate(new Date()); //保存设置 message.saveChanges(); return message; } /** * 发送一封只包含文本的简单邮件 * @param props 必须包含mail.transport.protocol(使用的协议)、mail.host(发件人的邮箱的 SMTP 服务器地址)、mail.smtp.auth、sendmail.username、sendmail.passwd * @param session 和服务器交互的会话 * @param sendMail 发件人 * @param receiveMails 接收人 * @param ccMails 抄送人 * @param bccMails 密送人 * @param subject 主题 * @param content 内容 * @return * @throws Exception */ public static String SendEmailText(Properties props,InternetAddress sendMail,List<InternetAddress> receiveMails,List<InternetAddress> ccMails,List<InternetAddress> bccMails,String subject,String content) throws Exception{ Session session = Session.getDefaultInstance(props); session.setDebug(true);// 设置为debug模式, 可以查看详细的发送 log //创建一封邮件 MimeMessage message = CreateMimeMessage(session, sendMail, receiveMails,ccMails,bccMails,subject,content); return SendMail(message,props); } /** * 创建一个带附件的email * @param session 和服务器交互的回话 * @param sendMail 发送人的email * @param receiveMails 接收人的email地址 * @param ccMails 抄送人的email地址 * @param bccMails 密送人的email地址 * @param subject 邮件主题 * @param content 邮件内容 * @param fileDataSources 邮件附件内容 * @return * @throws Exception */ public static MimeMessage CreateMimeMessageAttachment(Session session,InternetAddress sendMail,List<InternetAddress> receiveMails,List<InternetAddress> ccMails,List<InternetAddress> bccMails,String subject,String content,List<File> files) throws Exception { //创建一封邮件 MimeMessage message = new MimeMessage(session); //From: 发件人 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码 message.setFrom(sendMail); //To: 收件人(可以增加多个收件人、抄送、密送) for(InternetAddress recipientTemp: receiveMails){ message.addRecipient(MimeMessage.RecipientType.TO, recipientTemp); } //Cc: 抄送(可选) if(null!=ccMails){ for(InternetAddress recipientCCTemp: ccMails){ message.addRecipient(MimeMessage.RecipientType.CC, recipientCCTemp); } } //Bcc: 密送(可选) if(null!=bccMails){ for(InternetAddress recipientBCCTemp: bccMails){ message.addRecipient(MimeMessage.RecipientType.BCC, recipientBCCTemp); } } //Subject: 邮件主题 message.setSubject(subject, "UTF-8"); //Content: 邮件正文 MimeBodyPart text = new MimeBodyPart(); text.setContent(content, "text/html;charset=UTF-8"); MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); if(null!=files&&files.size()>0){ for(File fileTemp:files){ MimeBodyPart attachment = new MimeBodyPart(); DataHandler dh2 = new DataHandler(new FileDataSource(fileTemp)); attachment.setDataHandler(dh2); attachment.setFileName(MimeUtility.encodeText(dh2.getName())); mm.addBodyPart(attachment); } } mm.setSubType("mixed"); message.setContent(mm); //设置发件时间 message.setSentDate(new Date()); //保存设置 message.saveChanges(); return message; } /** * 发送一封本和附件的邮件 * @param props 必须包含mail.transport.protocol(使用的协议)、mail.host(发件人的邮箱的 SMTP 服务器地址)、mail.smtp.auth、sendmail.username、sendmail.passwd * @param session 和服务器交互的会话 * @param sendMail 发件人 * @param receiveMails 接收人 * @param ccMails 抄送人 * @param bccMails 密送人 * @param subject 主题 * @param content 内容 * @return * @throws Exception */ public static String SendEmailAttachment(Properties props,InternetAddress sendMail,List<InternetAddress> receiveMails,List<InternetAddress> ccMails,List<InternetAddress> bccMails,String subject,String content,List<File> files) throws Exception{ Session session = Session.getDefaultInstance(props); session.setDebug(true);// 设置为debug模式, 可以查看详细的发送 log //创建一封邮件 MimeMessage message = CreateMimeMessageAttachment(session, sendMail, receiveMails,ccMails,bccMails,subject,content,files); return SendMail(message,props); } /** * 发送邮件 * @param mm 邮件对象 * @param props 邮件配置 必须包含mail.transport.protocol(使用的协议)、mail.host(发件人的邮箱的 SMTP 服务器地址)、mail.smtp.auth、sendmail.username、sendmail.passwd * @return */ public static String SendMail(MimeMessage mm,Properties props) throws Exception{ Session session = Session.getDefaultInstance(props); session.setDebug(true);// 设置为debug模式, 可以查看详细的发送 log // 根据 Session获取邮件传输对象 Transport transport = session.getTransport(); //使用 邮箱账号 和 密码 连接邮件服务器 //这里认证的邮箱必须与 mm 中的发件人邮箱一致,否则报错 transport.connect(props.getProperty("sendmail.username"), props.getProperty("sendmail.passwd")); //发送邮件, 发到所有的收件地址, mm.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(mm, mm.getAllRecipients()); //关闭连接 transport.close(); return "success"; } }
UTF-8
Java
9,738
java
PBMailUtil.java
Java
[ { "context": "能描述:基于java mail进行封装的类\r\n * @author:<a href=\"mailto:xingjian@tongtusoft.com.cn\">邢健</a> \r\n * @version: V1.0\r\n * 日期:2016年12月22日 上", "end": 583, "score": 0.9999329447746277, "start": 557, "tag": "EMAIL", "value": "xingjian@tongtusoft.com.cn" }, { "context": "uthor:<a href=\"mailto:xingjian@tongtusoft.com.cn\">邢健</a> \r\n * @version: V1.0\r\n * 日期:2016年12月22日 上午11:", "end": 587, "score": 0.9994480013847351, "start": 585, "tag": "NAME", "value": "邢健" }, { "context": " * @param auth eg:true\r\n * @param mailUserName xingjian@yeah.net\r\n * @param mailPasswd \r\n * @return\r\n ", "end": 849, "score": 0.9998866319656372, "start": 832, "tag": "EMAIL", "value": "xingjian@yeah.net" } ]
null
[]
package com.promisepb.utils.emailutils; import java.io.File; import java.util.Date; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * 功能描述:基于java mail进行封装的类 * @author:<a href="mailto:<EMAIL>">邢健</a> * @version: V1.0 * 日期:2016年12月22日 上午11:07:42 */ public class PBMailUtil { /** * 构造发送邮件的参数 * @param protocol eg: smtp * @param host eg:smtp.163.com * @param auth eg:true * @param mailUserName <EMAIL> * @param mailPasswd * @return */ public static Properties CreateProperties(String protocol,String host,String auth,String mailUserName,String mailPasswd){ // 参数配置 Properties props = new Properties(); //使用的协议(JavaMail规范要求) props.setProperty("mail.transport.protocol", protocol); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.host", host); // 请求认证,参数名称与具体实现有关 props.setProperty("mail.smtp.auth", auth); props.setProperty("sendmail.username", mailUserName); props.setProperty("sendmail.passwd", mailPasswd); return props; } /** * 创建一封只包含文本的简单邮件 * @param session 和服务器交互的会话 * @param sendMail 发件人 * @param receiveMails 接收人 * @param ccMails 抄送人 * @param bccMails 密送人 * @param subject 主题 * @param content 内容 * @return * @throws Exception */ public static MimeMessage CreateMimeMessage(Session session,InternetAddress sendMail,List<InternetAddress> receiveMails,List<InternetAddress> ccMails,List<InternetAddress> bccMails,String subject,String content) throws Exception { //创建一封邮件 MimeMessage message = new MimeMessage(session); //From: 发件人 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码 message.setFrom(sendMail); //To: 收件人(可以增加多个收件人、抄送、密送) for(InternetAddress recipientTemp: receiveMails){ message.addRecipient(MimeMessage.RecipientType.TO, recipientTemp); } //Cc: 抄送(可选) if(null!=ccMails){ for(InternetAddress recipientCCTemp: ccMails){ message.addRecipient(MimeMessage.RecipientType.CC, recipientCCTemp); } } //Bcc: 密送(可选) if(null!=bccMails){ for(InternetAddress recipientBCCTemp: bccMails){ message.addRecipient(MimeMessage.RecipientType.BCC, recipientBCCTemp); } } //Subject: 邮件主题 message.setSubject(subject, "UTF-8"); //Content: 邮件正文(可以使用html标签) message.setContent(content, "text/html;charset=UTF-8"); //设置发件时间 message.setSentDate(new Date()); //保存设置 message.saveChanges(); return message; } /** * 发送一封只包含文本的简单邮件 * @param props 必须包含mail.transport.protocol(使用的协议)、mail.host(发件人的邮箱的 SMTP 服务器地址)、mail.smtp.auth、sendmail.username、sendmail.passwd * @param session 和服务器交互的会话 * @param sendMail 发件人 * @param receiveMails 接收人 * @param ccMails 抄送人 * @param bccMails 密送人 * @param subject 主题 * @param content 内容 * @return * @throws Exception */ public static String SendEmailText(Properties props,InternetAddress sendMail,List<InternetAddress> receiveMails,List<InternetAddress> ccMails,List<InternetAddress> bccMails,String subject,String content) throws Exception{ Session session = Session.getDefaultInstance(props); session.setDebug(true);// 设置为debug模式, 可以查看详细的发送 log //创建一封邮件 MimeMessage message = CreateMimeMessage(session, sendMail, receiveMails,ccMails,bccMails,subject,content); return SendMail(message,props); } /** * 创建一个带附件的email * @param session 和服务器交互的回话 * @param sendMail 发送人的email * @param receiveMails 接收人的email地址 * @param ccMails 抄送人的email地址 * @param bccMails 密送人的email地址 * @param subject 邮件主题 * @param content 邮件内容 * @param fileDataSources 邮件附件内容 * @return * @throws Exception */ public static MimeMessage CreateMimeMessageAttachment(Session session,InternetAddress sendMail,List<InternetAddress> receiveMails,List<InternetAddress> ccMails,List<InternetAddress> bccMails,String subject,String content,List<File> files) throws Exception { //创建一封邮件 MimeMessage message = new MimeMessage(session); //From: 发件人 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码 message.setFrom(sendMail); //To: 收件人(可以增加多个收件人、抄送、密送) for(InternetAddress recipientTemp: receiveMails){ message.addRecipient(MimeMessage.RecipientType.TO, recipientTemp); } //Cc: 抄送(可选) if(null!=ccMails){ for(InternetAddress recipientCCTemp: ccMails){ message.addRecipient(MimeMessage.RecipientType.CC, recipientCCTemp); } } //Bcc: 密送(可选) if(null!=bccMails){ for(InternetAddress recipientBCCTemp: bccMails){ message.addRecipient(MimeMessage.RecipientType.BCC, recipientBCCTemp); } } //Subject: 邮件主题 message.setSubject(subject, "UTF-8"); //Content: 邮件正文 MimeBodyPart text = new MimeBodyPart(); text.setContent(content, "text/html;charset=UTF-8"); MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); if(null!=files&&files.size()>0){ for(File fileTemp:files){ MimeBodyPart attachment = new MimeBodyPart(); DataHandler dh2 = new DataHandler(new FileDataSource(fileTemp)); attachment.setDataHandler(dh2); attachment.setFileName(MimeUtility.encodeText(dh2.getName())); mm.addBodyPart(attachment); } } mm.setSubType("mixed"); message.setContent(mm); //设置发件时间 message.setSentDate(new Date()); //保存设置 message.saveChanges(); return message; } /** * 发送一封本和附件的邮件 * @param props 必须包含mail.transport.protocol(使用的协议)、mail.host(发件人的邮箱的 SMTP 服务器地址)、mail.smtp.auth、sendmail.username、sendmail.passwd * @param session 和服务器交互的会话 * @param sendMail 发件人 * @param receiveMails 接收人 * @param ccMails 抄送人 * @param bccMails 密送人 * @param subject 主题 * @param content 内容 * @return * @throws Exception */ public static String SendEmailAttachment(Properties props,InternetAddress sendMail,List<InternetAddress> receiveMails,List<InternetAddress> ccMails,List<InternetAddress> bccMails,String subject,String content,List<File> files) throws Exception{ Session session = Session.getDefaultInstance(props); session.setDebug(true);// 设置为debug模式, 可以查看详细的发送 log //创建一封邮件 MimeMessage message = CreateMimeMessageAttachment(session, sendMail, receiveMails,ccMails,bccMails,subject,content,files); return SendMail(message,props); } /** * 发送邮件 * @param mm 邮件对象 * @param props 邮件配置 必须包含mail.transport.protocol(使用的协议)、mail.host(发件人的邮箱的 SMTP 服务器地址)、mail.smtp.auth、sendmail.username、sendmail.passwd * @return */ public static String SendMail(MimeMessage mm,Properties props) throws Exception{ Session session = Session.getDefaultInstance(props); session.setDebug(true);// 设置为debug模式, 可以查看详细的发送 log // 根据 Session获取邮件传输对象 Transport transport = session.getTransport(); //使用 邮箱账号 和 密码 连接邮件服务器 //这里认证的邮箱必须与 mm 中的发件人邮箱一致,否则报错 transport.connect(props.getProperty("sendmail.username"), props.getProperty("sendmail.passwd")); //发送邮件, 发到所有的收件地址, mm.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(mm, mm.getAllRecipients()); //关闭连接 transport.close(); return "success"; } }
9,709
0.641853
0.638637
212
37.603775
38.678326
261
false
false
0
0
0
0
0
0
0.679245
false
false
7
5ed73ea9f4f0a63c75b2a10af5769b56b655cba3
37,726,992,760,581
06cbee736f5610df466fdf30de297006b7d0127a
/tms-qms/src/main/java/edu/baylor/ecs/qms/model/supermodel/ICPCEntity.java
f4f8083d7780809294ae4a889060642d8d3c4420
[]
no_license
cloudhubs/tms-testbed
https://github.com/cloudhubs/tms-testbed
e1773a4946f322244dc103718ed4d4a907fa375f
3cdcefe63f6887180d62c38888402bd82725e7bc
refs/heads/master
2022-12-15T19:05:11.157000
2020-09-11T01:30:17
2020-09-11T01:30:17
294,550,690
0
1
null
false
2020-09-11T01:30:18
2020-09-11T00:09:42
2020-09-11T00:16:00
2020-09-11T01:30:17
357
0
0
0
Java
false
false
package edu.baylor.ecs.qms.model.supermodel; import java.io.Serializable; /** * Interface specifies ICPC entity, which has to contain id. * */ public interface ICPCEntity extends Serializable, Cloneable { Long getId(); }
UTF-8
Java
233
java
ICPCEntity.java
Java
[]
null
[]
package edu.baylor.ecs.qms.model.supermodel; import java.io.Serializable; /** * Interface specifies ICPC entity, which has to contain id. * */ public interface ICPCEntity extends Serializable, Cloneable { Long getId(); }
233
0.729614
0.729614
13
16.846153
22.640488
61
false
false
0
0
0
0
0
0
0.384615
false
false
7
39cfb22d63ef75ff11bb0cfcc177f13b67f4aaca
34,230,889,407,296
5e3235edf3de262f4d10b9e9e1fcc3bd13d6b8b1
/Code Snippet Repository/HyperSQL/HyperSQL2764.java
40ebe8889efeca3d2330b4bfdf62ed0df9ad2dec
[]
no_license
saber13812002/DeepCRM
https://github.com/saber13812002/DeepCRM
3336a244d4852a364800af3181e03e868cf6f9f5
be3e5e50e34a042d5ba7259ff5ff75c08ab32bb9
refs/heads/master
2023-03-16T00:08:06.473000
2018-04-18T05:29:50
2018-04-18T05:29:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
static void testScripts(String directory, StopWatch sw) { TestUtil.deleteDatabase("test1"); try { Class.forName("org.hsqldb.jdbc.JDBCDriver"); String url = "jdbc:hsqldb:test1;sql.enforce_strict_size=true"; String user = "sa"; String password = ""; Connection cConnection = null; String[] filelist; String absolute = new File(directory).getAbsolutePath(); filelist = new File(absolute).list(); ArraySort.sort((Object[]) filelist, 0, filelist.length, new StringComparator()); for (int i = 0; i < filelist.length; i++) { String fname = filelist[i]; if (fname.startsWith("TestSelf") && fname.endsWith(".txt")) { long elapsed = sw.elapsedTime(); if (!oneSessionOnly || cConnection == null) { cConnection = DriverManager.getConnection(url, user, password); } print("Opened DB in " + (double) (sw.elapsedTime() - elapsed) / 1000 + " s"); testScript(cConnection, absolute + File.separator + fname); if (!oneSessionOnly) { cConnection.close(); } } } } catch (Exception e) { e.printStackTrace(); print("TestUtil init error: " + e.toString()); } }
UTF-8
Java
1,618
java
HyperSQL2764.java
Java
[ { "context": "size=true\";\n String user = \"sa\";\n String password = \"\";\n ", "end": 297, "score": 0.9957026839256287, "start": 295, "tag": "USERNAME", "value": "sa" } ]
null
[]
static void testScripts(String directory, StopWatch sw) { TestUtil.deleteDatabase("test1"); try { Class.forName("org.hsqldb.jdbc.JDBCDriver"); String url = "jdbc:hsqldb:test1;sql.enforce_strict_size=true"; String user = "sa"; String password = ""; Connection cConnection = null; String[] filelist; String absolute = new File(directory).getAbsolutePath(); filelist = new File(absolute).list(); ArraySort.sort((Object[]) filelist, 0, filelist.length, new StringComparator()); for (int i = 0; i < filelist.length; i++) { String fname = filelist[i]; if (fname.startsWith("TestSelf") && fname.endsWith(".txt")) { long elapsed = sw.elapsedTime(); if (!oneSessionOnly || cConnection == null) { cConnection = DriverManager.getConnection(url, user, password); } print("Opened DB in " + (double) (sw.elapsedTime() - elapsed) / 1000 + " s"); testScript(cConnection, absolute + File.separator + fname); if (!oneSessionOnly) { cConnection.close(); } } } } catch (Exception e) { e.printStackTrace(); print("TestUtil init error: " + e.toString()); } }
1,618
0.455501
0.450556
45
34.866665
26.021017
79
false
false
0
0
0
0
0
0
0.666667
false
false
7
9f3005becc6205d7f12bac5ae1a6ff342b6fe105
39,625,368,286,153
4c20abac62dd7b65215a0b8e6590e4f9a7c331b3
/src/main/java/com/hyd/simplecache/RedisConfiguration.java
5fcec65abedc9eea8f5b975418bb81f954e04511
[ "Apache-2.0" ]
permissive
yiding-he/simple-cache-deprecated-
https://github.com/yiding-he/simple-cache-deprecated-
0d3917d255cc0fc5e8cae63aaa8072c3e0151c24
631188f196d8da4f872597a08e6079e3ef3693a4
refs/heads/master
2020-03-26T14:20:53.425000
2018-10-23T04:06:43
2018-10-23T04:06:43
144,983,455
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hyd.simplecache; import redis.clients.jedis.JedisShardInfo; import java.util.List; /** * (description) * created at 2015/3/16 * * @author Yiding */ public class RedisConfiguration implements CacheConfiguration { private List<JedisShardInfo> shardInfoList; private int timeToIdleSeconds; private int timeToLiveSeconds; public RedisConfiguration(List<JedisShardInfo> shardInfoList) { this.shardInfoList = shardInfoList; } public List<JedisShardInfo> getShardInfoList() { return shardInfoList; } public int getTimeToIdleSeconds() { return timeToIdleSeconds; } public void setTimeToIdleSeconds(int timeToIdleSeconds) { this.timeToIdleSeconds = timeToIdleSeconds; } public int getTimeToLiveSeconds() { return timeToLiveSeconds; } public void setTimeToLiveSeconds(int timeToLiveSeconds) { this.timeToLiveSeconds = timeToLiveSeconds; } }
UTF-8
Java
968
java
RedisConfiguration.java
Java
[ { "context": "description)\n * created at 2015/3/16\n *\n * @author Yiding\n */\npublic class RedisConfiguration implements Ca", "end": 163, "score": 0.8990692496299744, "start": 157, "tag": "USERNAME", "value": "Yiding" } ]
null
[]
package com.hyd.simplecache; import redis.clients.jedis.JedisShardInfo; import java.util.List; /** * (description) * created at 2015/3/16 * * @author Yiding */ public class RedisConfiguration implements CacheConfiguration { private List<JedisShardInfo> shardInfoList; private int timeToIdleSeconds; private int timeToLiveSeconds; public RedisConfiguration(List<JedisShardInfo> shardInfoList) { this.shardInfoList = shardInfoList; } public List<JedisShardInfo> getShardInfoList() { return shardInfoList; } public int getTimeToIdleSeconds() { return timeToIdleSeconds; } public void setTimeToIdleSeconds(int timeToIdleSeconds) { this.timeToIdleSeconds = timeToIdleSeconds; } public int getTimeToLiveSeconds() { return timeToLiveSeconds; } public void setTimeToLiveSeconds(int timeToLiveSeconds) { this.timeToLiveSeconds = timeToLiveSeconds; } }
968
0.713843
0.706612
44
21
21.904753
67
false
false
0
0
0
0
0
0
0.272727
false
false
7
5ac704ae477bd4210de776845710017d26198afa
15,564,961,524,917
7a22e72facbe1c619e92264ba058dcad973cd9e0
/src/main/java/com/example/demo/domain/ShopItemDomain.java
6945c181d8c4cdd127b467b2d46863a5aa4a3573
[]
no_license
nt1r/Web-Dev-Quiz-Spring
https://github.com/nt1r/Web-Dev-Quiz-Spring
5ca94f150e37468ea9a07ddf49797adfe215e80d
cdca0634b3b7fc4470af7ac7971f85f72dc67112
refs/heads/master
2022-11-30T23:40:43.566000
2020-08-14T08:17:11
2020-08-14T08:17:11
287,450,781
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.domain; import com.sun.istack.NotNull; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class ShopItemDomain { @NotNull private String name; @NotNull private Integer price; @NotNull private String unit; @NotNull private String url; }
UTF-8
Java
386
java
ShopItemDomain.java
Java
[]
null
[]
package com.example.demo.domain; import com.sun.istack.NotNull; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class ShopItemDomain { @NotNull private String name; @NotNull private Integer price; @NotNull private String unit; @NotNull private String url; }
386
0.746114
0.746114
23
15.782609
11.710109
33
false
false
0
0
0
0
0
0
0.391304
false
false
7
63dc9f5d1ec4576ef8b3468895f746c043ea51bf
3,968,549,826,016
6daa08cf0b258a96a5eda9c150f81a312df19e76
/src/main/subtitle/pig/udf/Callbackable.java
24b19b5c0615c4db74580fc8d490891e98967514
[]
no_license
holdfenytolvaj/simlanpro
https://github.com/holdfenytolvaj/simlanpro
99465d50cf363cdf681fde06e8e23b7a3167f13f
58145b01e8346e4431aa03c4cf628e224c7434b2
refs/heads/master
2021-01-01T06:54:39.074000
2020-10-23T13:56:48
2020-10-23T13:56:48
25,778,497
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package subtitle.pig.udf; public interface Callbackable { public void callBackByWord(String word, String pos, String lemma, Integer levelOfWord); public void callBackEndOfSentence(); }
UTF-8
Java
195
java
Callbackable.java
Java
[]
null
[]
package subtitle.pig.udf; public interface Callbackable { public void callBackByWord(String word, String pos, String lemma, Integer levelOfWord); public void callBackEndOfSentence(); }
195
0.774359
0.774359
7
26.857143
30.281672
91
false
false
0
0
0
0
0
0
0.857143
false
false
7
25b2f1f493ecb5cab9d01aa840329f2c183db524
29,162,827,977,910
323e8bf045156ce92417922d80b7a781fc8b94a4
/main/src/main/java/org/terrane/core/BigRational.java
f551b8304599fa5c899dd4d06f3f289f4a27007f
[ "Unlicense" ]
permissive
EchNet/terrane-util
https://github.com/EchNet/terrane-util
197e1166520d1ee8f81a5c4656cff25f07db738c
6a9585fbe70c352b1488a921f47942c565efd09f
refs/heads/master
2021-01-20T07:48:33.526000
2014-01-01T18:17:10
2014-01-21T13:10:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.terrane.core; import java.math.BigInteger; public class BigRational implements Comparable<BigRational> { public final static BigRational ZERO = new BigRational(BigInteger.ZERO); public final static BigRational ONE = new BigRational(BigInteger.ONE); public final static BigRational NaN = new BigRational(0, 0); private BigInteger num, denom; public static BigRational valueOf(long num) { if (num == 0) return ZERO; if (num == 1) return ONE; return new BigRational(num, 1); } public BigRational(long num) { this(BigInteger.valueOf(num)); } public BigRational(BigInteger num) { this.num = num; this.denom = BigInteger.ONE; } public BigRational(long num, long denom) { this(BigInteger.valueOf(num), BigInteger.valueOf(denom)); } public BigRational(BigInteger num, BigInteger denom) { this.num = num; this.denom = denom; reduce(); } private BigRational() { } public BigInteger getNumerator() { return num; } public BigInteger getDenominator() { return denom; } /** * Only approximate. */ public double doubleValue() { return num.doubleValue() / denom.doubleValue(); } public BigRational plus (BigRational that) { BigInteger sumNum = this.num.multiply(that.denom).add(that.num.multiply(this.denom)); BigInteger sumDenom = this.denom.multiply(that.denom); return new BigRational(sumNum, sumDenom); } public BigRational minus (BigRational that) { BigInteger sumNum = this.num.multiply(that.denom).subtract(that.num.multiply(this.denom)); BigInteger sumDenom = this.denom.multiply(that.denom); return new BigRational(sumNum, sumDenom); } public BigRational times (BigRational that) { BigInteger prodNum = this.num.multiply(that.num); BigInteger prodDenom = this.denom.multiply(that.denom); return new BigRational(prodNum, prodDenom); } public BigRational reciprocal () { BigRational r = new BigRational(); r.denom = num; r.num = denom; return r; } public int signum() { return num.signum(); } public String toString() { return num + "/" + denom; } private void reduce() { int signum = denom.signum(); if (signum == 0) { num = BigInteger.ZERO; } else { if (signum < 0) { num = num.negate(); denom = denom.negate(); } BigInteger d = gcd(num, denom); if (!d.equals(BigInteger.ONE)) { num = num.divide(d); denom = denom.divide(d); } } } public static BigInteger gcd (BigInteger a, BigInteger b) { if (a.equals(BigInteger.ZERO)) return b; if (b.equals(BigInteger.ZERO)) return a; a = a.abs(); b = b.abs(); if (b.compareTo(a) < 0) { BigInteger tmp = a; a = b; b = tmp; } BigInteger rem; while (!(rem = b.mod(a)).equals(BigInteger.ZERO)) { b = a; a = rem; } return a; } public int hashCode() { return num.hashCode() ^ denom.hashCode(); } public boolean equalsBigRational(BigRational that) { return that.num.equals(num) && that.denom.equals(denom); } public boolean equals(Object that) { try { return equalsBigRational((BigRational) that); } catch (Exception e) { return false; } } public int compareTo(BigRational that) { if (equalsBigRational(that)) return 0; return this.num.multiply(that.denom).compareTo(that.num.multiply(this.denom)); } }
UTF-8
Java
3,806
java
BigRational.java
Java
[]
null
[]
package org.terrane.core; import java.math.BigInteger; public class BigRational implements Comparable<BigRational> { public final static BigRational ZERO = new BigRational(BigInteger.ZERO); public final static BigRational ONE = new BigRational(BigInteger.ONE); public final static BigRational NaN = new BigRational(0, 0); private BigInteger num, denom; public static BigRational valueOf(long num) { if (num == 0) return ZERO; if (num == 1) return ONE; return new BigRational(num, 1); } public BigRational(long num) { this(BigInteger.valueOf(num)); } public BigRational(BigInteger num) { this.num = num; this.denom = BigInteger.ONE; } public BigRational(long num, long denom) { this(BigInteger.valueOf(num), BigInteger.valueOf(denom)); } public BigRational(BigInteger num, BigInteger denom) { this.num = num; this.denom = denom; reduce(); } private BigRational() { } public BigInteger getNumerator() { return num; } public BigInteger getDenominator() { return denom; } /** * Only approximate. */ public double doubleValue() { return num.doubleValue() / denom.doubleValue(); } public BigRational plus (BigRational that) { BigInteger sumNum = this.num.multiply(that.denom).add(that.num.multiply(this.denom)); BigInteger sumDenom = this.denom.multiply(that.denom); return new BigRational(sumNum, sumDenom); } public BigRational minus (BigRational that) { BigInteger sumNum = this.num.multiply(that.denom).subtract(that.num.multiply(this.denom)); BigInteger sumDenom = this.denom.multiply(that.denom); return new BigRational(sumNum, sumDenom); } public BigRational times (BigRational that) { BigInteger prodNum = this.num.multiply(that.num); BigInteger prodDenom = this.denom.multiply(that.denom); return new BigRational(prodNum, prodDenom); } public BigRational reciprocal () { BigRational r = new BigRational(); r.denom = num; r.num = denom; return r; } public int signum() { return num.signum(); } public String toString() { return num + "/" + denom; } private void reduce() { int signum = denom.signum(); if (signum == 0) { num = BigInteger.ZERO; } else { if (signum < 0) { num = num.negate(); denom = denom.negate(); } BigInteger d = gcd(num, denom); if (!d.equals(BigInteger.ONE)) { num = num.divide(d); denom = denom.divide(d); } } } public static BigInteger gcd (BigInteger a, BigInteger b) { if (a.equals(BigInteger.ZERO)) return b; if (b.equals(BigInteger.ZERO)) return a; a = a.abs(); b = b.abs(); if (b.compareTo(a) < 0) { BigInteger tmp = a; a = b; b = tmp; } BigInteger rem; while (!(rem = b.mod(a)).equals(BigInteger.ZERO)) { b = a; a = rem; } return a; } public int hashCode() { return num.hashCode() ^ denom.hashCode(); } public boolean equalsBigRational(BigRational that) { return that.num.equals(num) && that.denom.equals(denom); } public boolean equals(Object that) { try { return equalsBigRational((BigRational) that); } catch (Exception e) { return false; } } public int compareTo(BigRational that) { if (equalsBigRational(that)) return 0; return this.num.multiply(that.denom).compareTo(that.num.multiply(this.denom)); } }
3,806
0.584603
0.582239
172
21.127907
21.585308
98
false
false
0
0
0
0
0
0
0.755814
false
false
7
c14a14f1de986b661f194be45c85356a2e56c96c
30,262,339,608,674
0641c28fc23b74ea375495726c1c5b1ecee45281
/src/main/java/org/gestion/services/impl/ContactServiceJpa.java
8083f20bae68933fc89f3f08a6f835a0c8481f90
[]
no_license
bewizyu-formation/modis-tipunch-familink-api
https://github.com/bewizyu-formation/modis-tipunch-familink-api
3343239acf08a892f040be63a567661cafface07
e2cfd079ae5ec7bd75f982fdb623fd3eb16a7980
refs/heads/develop
2021-07-15T01:19:48.987000
2017-10-18T12:50:49
2017-10-18T12:50:49
106,188,609
0
1
null
false
2017-10-18T13:14:42
2017-10-08T15:48:21
2017-10-10T10:53:39
2017-10-18T13:14:27
119
0
0
1
Java
null
null
package org.gestion.services.impl; import java.util.List; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.gestion.entite.Contact; import org.gestion.entite.Groupe; import org.gestion.services.IContactService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service(value = "contactServiceJpa") public class ContactServiceJpa implements IContactService { @PersistenceContext private EntityManager em; @Override @Transactional public Contact create(Contact nvContact) { em.persist(nvContact); return nvContact; } @Override @Transactional public void update(Contact contact) { Query query = em.createQuery("FROM Contact c WHERE c.idContact=:IdContact"); query.setParameter("idContact", contact.getIdContact()); Contact oldContact = (Contact) query.getSingleResult(); if (!oldContact.equals(null)) { oldContact.setAdresse(contact.getAdresse()); oldContact.setCodePostal(contact.getCodePostal()); oldContact.setGravatar(contact.getGravatar()); oldContact.setNom(contact.getNom()); oldContact.setNumTel(contact.getNumTel()); oldContact.setPrenom(contact.getPrenom()); oldContact.setProfil(contact.getProfil()); oldContact.setVille(contact.getVille()); em.merge(oldContact); em.flush(); } } @Override public List<Contact> getContacts() { TypedQuery<Contact> query = em.createQuery("FROM Contact", Contact.class); return query.getResultList(); } @Override public void deleteContact(int id) { Contact contact = getContactById(id); em.remove(contact); } @Override public Contact getContactById(int id) { Contact contact = em.find(Contact.class, id); return contact; } @Override public List<Contact> getContactsByGroupId() { TypedQuery<Contact> query = em.createQuery("SELECT idContact FROM Contact c WHERE c.idGroupe=:IdGroupe", Contact.class); return query.getResultList(); } @Override public List<Groupe> getListeGroupes(int IdUtilisateur) { Query q = em.createNativeQuery( "SELECT * FROM groupe INNER JOIN groupe_contact ON groupe.idGroupe = groupe_contact.Groupe_idGroupe " + "INNER JOIN utilisateur on groupe_contact.contactsDuGroupe_idContact = utilisateur.contact_idContact where utilisateur.idUtilisateur = ?"); q.setParameter(1, IdUtilisateur); List<Groupe> groupes = q.getResultList(); return groupes; } @Override @Transactional public void updateListeGroupes(int idcontact, Set<Groupe> listeGroupesContacts) { Contact contact = getContactById(idcontact); contact.setListeGroupesContact(listeGroupesContacts); em.persist(contact); } }
UTF-8
Java
2,776
java
ContactServiceJpa.java
Java
[]
null
[]
package org.gestion.services.impl; import java.util.List; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.gestion.entite.Contact; import org.gestion.entite.Groupe; import org.gestion.services.IContactService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service(value = "contactServiceJpa") public class ContactServiceJpa implements IContactService { @PersistenceContext private EntityManager em; @Override @Transactional public Contact create(Contact nvContact) { em.persist(nvContact); return nvContact; } @Override @Transactional public void update(Contact contact) { Query query = em.createQuery("FROM Contact c WHERE c.idContact=:IdContact"); query.setParameter("idContact", contact.getIdContact()); Contact oldContact = (Contact) query.getSingleResult(); if (!oldContact.equals(null)) { oldContact.setAdresse(contact.getAdresse()); oldContact.setCodePostal(contact.getCodePostal()); oldContact.setGravatar(contact.getGravatar()); oldContact.setNom(contact.getNom()); oldContact.setNumTel(contact.getNumTel()); oldContact.setPrenom(contact.getPrenom()); oldContact.setProfil(contact.getProfil()); oldContact.setVille(contact.getVille()); em.merge(oldContact); em.flush(); } } @Override public List<Contact> getContacts() { TypedQuery<Contact> query = em.createQuery("FROM Contact", Contact.class); return query.getResultList(); } @Override public void deleteContact(int id) { Contact contact = getContactById(id); em.remove(contact); } @Override public Contact getContactById(int id) { Contact contact = em.find(Contact.class, id); return contact; } @Override public List<Contact> getContactsByGroupId() { TypedQuery<Contact> query = em.createQuery("SELECT idContact FROM Contact c WHERE c.idGroupe=:IdGroupe", Contact.class); return query.getResultList(); } @Override public List<Groupe> getListeGroupes(int IdUtilisateur) { Query q = em.createNativeQuery( "SELECT * FROM groupe INNER JOIN groupe_contact ON groupe.idGroupe = groupe_contact.Groupe_idGroupe " + "INNER JOIN utilisateur on groupe_contact.contactsDuGroupe_idContact = utilisateur.contact_idContact where utilisateur.idUtilisateur = ?"); q.setParameter(1, IdUtilisateur); List<Groupe> groupes = q.getResultList(); return groupes; } @Override @Transactional public void updateListeGroupes(int idcontact, Set<Groupe> listeGroupesContacts) { Contact contact = getContactById(idcontact); contact.setListeGroupesContact(listeGroupesContacts); em.persist(contact); } }
2,776
0.76585
0.76549
99
27.040403
26.914724
147
false
false
0
0
0
0
0
0
1.676768
false
false
7
0be86d15983a23ad86cdb35df869b0224b34fd83
7,559,142,483,741
7875e8f76bd014cf7257545e7a73fff844d82185
/src/Cliente/ClienteFrame.java
5b857d158b1c4e964d6fb59d5513bbf4ee9f71f4
[]
no_license
LinK316/DBDistribuida
https://github.com/LinK316/DBDistribuida
1fa267b95b585050a3897cbffb61db4393bb106d
496bcb1c18ba2bbb48fb3cbf0163992dd981b365
refs/heads/master
2016-09-05T13:27:30.081000
2012-12-11T22:30:05
2012-12-11T22:30:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * ClienteFrame.java * * Created on 28-jun-2011, 18:55:15 */ package Cliente; import javax.swing.JOptionPane; /** * * @author link */ public class ClienteFrame extends javax.swing.JFrame { private SocketCliente socketCliente; /** Creates new form ClienteFrame */ public ClienteFrame() { initComponents(); this.setLocationRelativeTo(null); socketCliente = new SocketCliente("192.168.0.100"); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jbEjecutar = new javax.swing.JButton(); jtfSentencia = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jtpDatos = new javax.swing.JTextPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Cliente DBDistribuida"); setResizable(false); jbEjecutar.setFont(new java.awt.Font("Arial", 0, 10)); jbEjecutar.setText("Ejecutar"); jbEjecutar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbEjecutarActionPerformed(evt); } }); jScrollPane1.setBackground(new java.awt.Color(1, 1, 1)); jtpDatos.setBackground(new java.awt.Color(1, 1, 1)); jtpDatos.setEditable(false); jtpDatos.setForeground(new java.awt.Color(248, 248, 248)); jtpDatos.setText("Escribe una sintaxis de SQL y presiona ejecutar..."); jtpDatos.setAutoscrolls(true); jScrollPane1.setViewportView(jtpDatos); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jtfSentencia, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbEjecutar, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbEjecutar, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfSentencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbEjecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEjecutarActionPerformed if(jtfSentencia.getText().equalsIgnoreCase("")) JOptionPane.showMessageDialog(this, "No has escrito alguna sentencia.", "Error", JOptionPane.ERROR_MESSAGE); else{ socketCliente.ejecutarConsulta(jtfSentencia.getText(), jtpDatos); } }//GEN-LAST:event_jbEjecutarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new ClienteFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbEjecutar; private javax.swing.JTextField jtfSentencia; private javax.swing.JTextPane jtpDatos; // End of variables declaration//GEN-END:variables }
UTF-8
Java
4,852
java
ClienteFrame.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author link\n */\npublic class ClienteFrame extends javax.swing", "end": 140, "score": 0.9824522137641907, "start": 136, "tag": "USERNAME", "value": "link" }, { "context": "null);\n socketCliente = new SocketCliente(\"192.168.0.100\");\n }\n\n /** This method is called from with", "end": 435, "score": 0.9997519850730896, "start": 422, "tag": "IP_ADDRESS", "value": "192.168.0.100" } ]
null
[]
/* * ClienteFrame.java * * Created on 28-jun-2011, 18:55:15 */ package Cliente; import javax.swing.JOptionPane; /** * * @author link */ public class ClienteFrame extends javax.swing.JFrame { private SocketCliente socketCliente; /** Creates new form ClienteFrame */ public ClienteFrame() { initComponents(); this.setLocationRelativeTo(null); socketCliente = new SocketCliente("192.168.0.100"); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jbEjecutar = new javax.swing.JButton(); jtfSentencia = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jtpDatos = new javax.swing.JTextPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Cliente DBDistribuida"); setResizable(false); jbEjecutar.setFont(new java.awt.Font("Arial", 0, 10)); jbEjecutar.setText("Ejecutar"); jbEjecutar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbEjecutarActionPerformed(evt); } }); jScrollPane1.setBackground(new java.awt.Color(1, 1, 1)); jtpDatos.setBackground(new java.awt.Color(1, 1, 1)); jtpDatos.setEditable(false); jtpDatos.setForeground(new java.awt.Color(248, 248, 248)); jtpDatos.setText("Escribe una sintaxis de SQL y presiona ejecutar..."); jtpDatos.setAutoscrolls(true); jScrollPane1.setViewportView(jtpDatos); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jtfSentencia, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbEjecutar, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbEjecutar, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtfSentencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbEjecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEjecutarActionPerformed if(jtfSentencia.getText().equalsIgnoreCase("")) JOptionPane.showMessageDialog(this, "No has escrito alguna sentencia.", "Error", JOptionPane.ERROR_MESSAGE); else{ socketCliente.ejecutarConsulta(jtfSentencia.getText(), jtpDatos); } }//GEN-LAST:event_jbEjecutarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new ClienteFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbEjecutar; private javax.swing.JTextField jtfSentencia; private javax.swing.JTextPane jtpDatos; // End of variables declaration//GEN-END:variables }
4,852
0.663438
0.651072
113
41.938053
34.966049
166
false
false
0
0
0
0
0
0
0.60177
false
false
7
50e3ef6bc1f2a5b84e6c434d713fc180df3ed388
31,662,498,950,367
ece8d426a19e521fd137f45e8b1669c792df9bc5
/src/main/java/org/nebularis/defproxy/introspection/TypeConverterFactory.java
bf357660117c1e3ef86cecc7cc433c19a1aa8797
[ "Apache-2.0" ]
permissive
ssouza/def-proxy
https://github.com/ssouza/def-proxy
bd96e368b4469dc1388998c40303df5c4ab37fe2
71450823c35e668cb489429ad62b8c68b69da1d7
refs/heads/master
2021-01-15T19:30:04.816000
2010-12-04T13:48:35
2010-12-04T13:48:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * def-proxy * * Copyright (c) 2010-2011 * Tim Watson (watson.timothy@gmail.com), Charles Care (c.p.care@gmail.com). * All Rights Reserved. * * This file is provided to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.nebularis.defproxy.introspection; /** * A factory for type converters. */ public interface TypeConverterFactory { /** * Create a {@link org.nebularis.defproxy.introspection.TypeConverter} for the specified * input and output classes. * @param inputClass the class of the input domain * @param outputClass the class of the output domain * @param <T1> The type of the input class * @param <T2> The type of the output class * @return a new {@link org.nebularis.defproxy.introspection.TypeConverter} instance, mapping * from type <code>T1</code> to <code>T2</code>, or <code>null</code> if no matching converter * can be set up for these two types. */ <T1,T2> TypeConverter<T1,T2> createTypeConverter(Class<T1> inputClass, Class<T2> outputClass); }
UTF-8
Java
1,601
java
TypeConverterFactory.java
Java
[ { "context": "\r\n * def-proxy\r\n *\r\n * Copyright (c) 2010-2011\r\n * Tim Watson (watson.timothy@gmail.com), Charles Care (c.p.car", "end": 63, "score": 0.9995710849761963, "start": 53, "tag": "NAME", "value": "Tim Watson" }, { "context": "y\r\n *\r\n * Copyright (c) 2010-2011\r\n * Tim Watson (watson.timothy@gmail.com), Charles Care (c.p.care@gmail.com).\r\n * All Righ", "end": 89, "score": 0.99992835521698, "start": 65, "tag": "EMAIL", "value": "watson.timothy@gmail.com" }, { "context": "10-2011\r\n * Tim Watson (watson.timothy@gmail.com), Charles Care (c.p.care@gmail.com).\r\n * All Rights Reserved.\r\n ", "end": 104, "score": 0.9998476505279541, "start": 92, "tag": "NAME", "value": "Charles Care" }, { "context": " Watson (watson.timothy@gmail.com), Charles Care (c.p.care@gmail.com).\r\n * All Rights Reserved.\r\n *\r\n * This file is p", "end": 124, "score": 0.9999261498451233, "start": 106, "tag": "EMAIL", "value": "c.p.care@gmail.com" } ]
null
[]
/* * def-proxy * * Copyright (c) 2010-2011 * <NAME> (<EMAIL>), <NAME> (<EMAIL>). * All Rights Reserved. * * This file is provided to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.nebularis.defproxy.introspection; /** * A factory for type converters. */ public interface TypeConverterFactory { /** * Create a {@link org.nebularis.defproxy.introspection.TypeConverter} for the specified * input and output classes. * @param inputClass the class of the input domain * @param outputClass the class of the output domain * @param <T1> The type of the input class * @param <T2> The type of the output class * @return a new {@link org.nebularis.defproxy.introspection.TypeConverter} instance, mapping * from type <code>T1</code> to <code>T2</code>, or <code>null</code> if no matching converter * can be set up for these two types. */ <T1,T2> TypeConverter<T1,T2> createTypeConverter(Class<T1> inputClass, Class<T2> outputClass); }
1,563
0.68832
0.674578
43
35.232559
30.407188
98
false
false
0
0
0
0
0
0
0.302326
false
false
7
ccd037340d1561224a9db4a6b85325444a86cec0
26,869,315,445,311
f2a4ee2eb536e3817ac5bbf6504ade75f0376cf7
/ace-web/src/main/java/com/quikj/ace/web/client/EmailTranscriptInfo.java
8983045b0b523592c4bdb456af4b1f601bc3b621
[]
no_license
aceoperator/ace
https://github.com/aceoperator/ace
3ef2ce7d489c0625a2cba83d24f535c09871b062
08f7c98896b3cc71793cdea3d1e44c910f0fdb74
refs/heads/master
2020-04-06T04:27:51.734000
2018-06-30T12:25:53
2018-06-30T12:25:53
82,558,405
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * AutoEmailInfo.java * * Created on March 10, 2003, 2:03 AM */ package com.quikj.ace.web.client; import java.util.ArrayList; /** * * @author amit */ public class EmailTranscriptInfo { private boolean emailTranscript = false; private boolean sendSelf; private boolean sendOthers; private String[] toList; private boolean from = false; private boolean fromSelf; private String[] fromList; public EmailTranscriptInfo() { emailTranscript = ClientProperties.getInstance().getBooleanValue( ClientProperties.EMAIL_TRANSCRIPT, false); if (!emailTranscript) { return; } String param = ClientProperties.getInstance().getStringValue( ClientProperties.TRANSCRIPT_EMAIL_FROM, null); if (param != null) { from = true; ArrayList<String> list = new ArrayList<String>(); String[] tokens = param.split(";"); for (int i = 0; i < tokens.length; i++) { String email = tokens[i]; if (email.equals("@SELF")) { fromSelf = true; } else { list.add(email); } } fromList = list.toArray(new String[list.size()]); } param = ClientProperties.getInstance().getStringValue( ClientProperties.TRANSCRIPT_EMAIL_TO, null); if (param != null) { String[] tokens = param.split(";"); ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < tokens.length; i++) { String email = tokens[i]; if (email.equals("@SELF")) { sendSelf = true; } else if (email.equals("@OTHERS")) { sendOthers = true; } else { list.add(email); } } toList = list.toArray(new String[list.size()]); } } public boolean isEmailTranscript() { return emailTranscript; } public void setEmailTranscript(boolean emailTranscript) { this.emailTranscript = emailTranscript; } public boolean isSendSelf() { return sendSelf; } public void setSendSelf(boolean sendSelf) { this.sendSelf = sendSelf; } public boolean isSendOthers() { return sendOthers; } public void setSendOthers(boolean sendOthers) { this.sendOthers = sendOthers; } public String[] getToList() { return toList; } public void setToList(String[] toList) { this.toList = toList; } public boolean isFrom() { return from; } public void setFrom(boolean from) { this.from = from; } public boolean isFromSelf() { return fromSelf; } public void setFromSelf(boolean fromSelf) { this.fromSelf = fromSelf; } public String[] getFromList() { return fromList; } public void setFromList(String[] fromList) { this.fromList = fromList; } }
UTF-8
Java
2,553
java
EmailTranscriptInfo.java
Java
[ { "context": ";\n\nimport java.util.ArrayList;\n\n/**\n * \n * @author amit\n */\npublic class EmailTranscriptInfo {\n\n\tprivate ", "end": 158, "score": 0.9963744878768921, "start": 154, "tag": "USERNAME", "value": "amit" } ]
null
[]
/* * AutoEmailInfo.java * * Created on March 10, 2003, 2:03 AM */ package com.quikj.ace.web.client; import java.util.ArrayList; /** * * @author amit */ public class EmailTranscriptInfo { private boolean emailTranscript = false; private boolean sendSelf; private boolean sendOthers; private String[] toList; private boolean from = false; private boolean fromSelf; private String[] fromList; public EmailTranscriptInfo() { emailTranscript = ClientProperties.getInstance().getBooleanValue( ClientProperties.EMAIL_TRANSCRIPT, false); if (!emailTranscript) { return; } String param = ClientProperties.getInstance().getStringValue( ClientProperties.TRANSCRIPT_EMAIL_FROM, null); if (param != null) { from = true; ArrayList<String> list = new ArrayList<String>(); String[] tokens = param.split(";"); for (int i = 0; i < tokens.length; i++) { String email = tokens[i]; if (email.equals("@SELF")) { fromSelf = true; } else { list.add(email); } } fromList = list.toArray(new String[list.size()]); } param = ClientProperties.getInstance().getStringValue( ClientProperties.TRANSCRIPT_EMAIL_TO, null); if (param != null) { String[] tokens = param.split(";"); ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < tokens.length; i++) { String email = tokens[i]; if (email.equals("@SELF")) { sendSelf = true; } else if (email.equals("@OTHERS")) { sendOthers = true; } else { list.add(email); } } toList = list.toArray(new String[list.size()]); } } public boolean isEmailTranscript() { return emailTranscript; } public void setEmailTranscript(boolean emailTranscript) { this.emailTranscript = emailTranscript; } public boolean isSendSelf() { return sendSelf; } public void setSendSelf(boolean sendSelf) { this.sendSelf = sendSelf; } public boolean isSendOthers() { return sendOthers; } public void setSendOthers(boolean sendOthers) { this.sendOthers = sendOthers; } public String[] getToList() { return toList; } public void setToList(String[] toList) { this.toList = toList; } public boolean isFrom() { return from; } public void setFrom(boolean from) { this.from = from; } public boolean isFromSelf() { return fromSelf; } public void setFromSelf(boolean fromSelf) { this.fromSelf = fromSelf; } public String[] getFromList() { return fromList; } public void setFromList(String[] fromList) { this.fromList = fromList; } }
2,553
0.66745
0.663141
133
18.195488
18.089359
67
false
false
0
0
0
0
0
0
1.834587
false
false
7
ba4303a2031f29988c1827708afb240689713de3
30,631,706,796,129
459805e61f3b1fea89dd5eff4a2b7fb51eb4b36d
/modules/gateway/server/src/main/java/com/l7tech/server/log/syslog/impl/SyslogMessage.java
e62b6d671f9d976b26069ae48d26b7c119a533be
[]
no_license
neelam-007/gateway
https://github.com/neelam-007/gateway
9ae2d04eda96ce510ad7034f4d72efa034f973cd
60e0a4138746803a14d8de070d3319b028fcffe4
refs/heads/master
2023-04-29T01:19:08.369000
2018-11-08T20:03:09
2018-11-08T20:03:09
368,039,344
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.l7tech.server.log.syslog.impl; /** * Syslog message data * * @author Steve Jones */ class SyslogMessage { //- PUBLIC /** * Get the facility value for this message. * * @return The facility */ public int getFacility() { return facility; } /** * Get the severity value for this message. * * @return The severity */ public int getSeverity() { return severity; } /** * Get the priority value for this message. * * <p>The priority is calculated from the facility and severity as follows:</p> * * <code> PRIORITY = ( 8 * FACILITY ) + SEVERITY </code> * * @return The priority */ public int getPriority() { return ((8*getFacility()) + getSeverity()); } /** * Get the host (FQDN) for this log message. * * @return The host */ public String getHost() { return host; } /** * Get the message part of the syslog message. * * @return The message */ public String getMessage() { return message; } /** * Get the "process" name * * @return The process */ public String getProcess() { return process; } /** * Get thread identifier * * @return The thread id * @see Thread#getId() */ public long getThreadId() { return threadId; } /** * Get the time for this log message. * * @return The time in millis */ public long getTime() { return time; } //- PACKAGE /** * Create a new syslog message with the given values. * * @param facility The facility (part of priority) * @param severity The severity (part of priority) * @param host The fully qualified host name * @param process The process name * @param threadId The thread identifier * @param time The time for the log message * @param message The */ SyslogMessage(final int facility, final int severity, final String host, final String process, final long threadId, final long time, final String message) { this.facility = facility; this.severity = severity; this.host = host; this.process = process; this.threadId = threadId; this.time = time; this.message = message; } //- PRIVATE private final int facility; private final int severity; private final String host; private final String process; private final long threadId; private final long time; private final String message; }
UTF-8
Java
2,756
java
SyslogMessage.java
Java
[ { "context": "og.impl;\n\n/**\n * Syslog message data\n *\n * @author Steve Jones\n */\nclass SyslogMessage {\n\n //- PUBLIC\n\n /*", "end": 96, "score": 0.9984866976737976, "start": 85, "tag": "NAME", "value": "Steve Jones" } ]
null
[]
package com.l7tech.server.log.syslog.impl; /** * Syslog message data * * @author <NAME> */ class SyslogMessage { //- PUBLIC /** * Get the facility value for this message. * * @return The facility */ public int getFacility() { return facility; } /** * Get the severity value for this message. * * @return The severity */ public int getSeverity() { return severity; } /** * Get the priority value for this message. * * <p>The priority is calculated from the facility and severity as follows:</p> * * <code> PRIORITY = ( 8 * FACILITY ) + SEVERITY </code> * * @return The priority */ public int getPriority() { return ((8*getFacility()) + getSeverity()); } /** * Get the host (FQDN) for this log message. * * @return The host */ public String getHost() { return host; } /** * Get the message part of the syslog message. * * @return The message */ public String getMessage() { return message; } /** * Get the "process" name * * @return The process */ public String getProcess() { return process; } /** * Get thread identifier * * @return The thread id * @see Thread#getId() */ public long getThreadId() { return threadId; } /** * Get the time for this log message. * * @return The time in millis */ public long getTime() { return time; } //- PACKAGE /** * Create a new syslog message with the given values. * * @param facility The facility (part of priority) * @param severity The severity (part of priority) * @param host The fully qualified host name * @param process The process name * @param threadId The thread identifier * @param time The time for the log message * @param message The */ SyslogMessage(final int facility, final int severity, final String host, final String process, final long threadId, final long time, final String message) { this.facility = facility; this.severity = severity; this.host = host; this.process = process; this.threadId = threadId; this.time = time; this.message = message; } //- PRIVATE private final int facility; private final int severity; private final String host; private final String process; private final long threadId; private final long time; private final String message; }
2,751
0.550435
0.549347
127
20.700787
17.051712
83
false
false
0
0
0
0
0
0
0.228346
false
false
7
377f0c7e4110a4fd8a86a45a33949cf57d47b5fa
21,165,598,873,244
da776a3defea5157b52c9a4a8db362e8c76fdd3b
/parent/common-module-dao/src/main/java/com/microservice/dao/entity/crawler/telecom/shanxi3/TelecomShanxi3MonthBill.java
56eff554ac423927a9445059e86e8eb52ec2b9d6
[]
no_license
moutainhigh/crawler
https://github.com/moutainhigh/crawler
d4f306d74a9f16bce3490d4dbdcedad953120f97
4c201cdf24a025d0b1056188e0f0f4beee0b80aa
refs/heads/master
2020-09-21T12:22:54.075000
2018-11-06T04:33:15
2018-11-06T04:33:15
224,787,613
1
0
null
true
2019-11-29T06:06:28
2019-11-29T06:06:28
2018-12-04T07:12:15
2018-11-06T05:12:35
64,796
0
0
0
null
false
false
package com.microservice.dao.entity.crawler.telecom.shanxi3; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Table; import com.microservice.dao.entity.IdEntity; /** * @Description 月账单 * @author sln * @date 2017年9月6日 下午8:18:19 */ @Entity @Table(name = "telecom_shanxi3_monthbill",indexes = {@Index(name = "index_telecom_shanxi3_monthbill_taskid", columnList = "taskid")}) public class TelecomShanxi3MonthBill extends IdEntity implements Serializable { private static final long serialVersionUID = 2053571341410503484L; //计费月 private String countmonth; //打印日期 private String printdate; // 手机号 private String phonenum; // 费用名称 private String expensename; // 优惠前(元) private String beforediscount; // 优惠费用(元) private String discount; // 费用小计(元) private String totalcost; private String taskid; public String getCountmonth() { return countmonth; } public void setCountmonth(String countmonth) { this.countmonth = countmonth; } public String getPrintdate() { return printdate; } public void setPrintdate(String printdate) { this.printdate = printdate; } public String getPhonenum() { return phonenum; } public void setPhonenum(String phonenum) { this.phonenum = phonenum; } public String getExpensename() { return expensename; } public void setExpensename(String expensename) { this.expensename = expensename; } public String getBeforediscount() { return beforediscount; } public void setBeforediscount(String beforediscount) { this.beforediscount = beforediscount; } public String getDiscount() { return discount; } public void setDiscount(String discount) { this.discount = discount; } public String getTotalcost() { return totalcost; } public void setTotalcost(String totalcost) { this.totalcost = totalcost; } public String getTaskid() { return taskid; } public void setTaskid(String taskid) { this.taskid = taskid; } public TelecomShanxi3MonthBill() { super(); // TODO Auto-generated constructor stub } public TelecomShanxi3MonthBill(String countmonth, String printdate, String phonenum, String expensename, String beforediscount, String discount, String totalcost, String taskid) { super(); this.countmonth = countmonth; this.printdate = printdate; this.phonenum = phonenum; this.expensename = expensename; this.beforediscount = beforediscount; this.discount = discount; this.totalcost = totalcost; this.taskid = taskid; } }
UTF-8
Java
2,596
java
TelecomShanxi3MonthBill.java
Java
[ { "context": "ity.IdEntity;\n\n/**\n * @Description 月账单\n * @author sln\n * @date 2017年9月6日 下午8:18:19\n */\n@Entity\n@Table(n", "end": 275, "score": 0.9996667504310608, "start": 272, "tag": "USERNAME", "value": "sln" } ]
null
[]
package com.microservice.dao.entity.crawler.telecom.shanxi3; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Table; import com.microservice.dao.entity.IdEntity; /** * @Description 月账单 * @author sln * @date 2017年9月6日 下午8:18:19 */ @Entity @Table(name = "telecom_shanxi3_monthbill",indexes = {@Index(name = "index_telecom_shanxi3_monthbill_taskid", columnList = "taskid")}) public class TelecomShanxi3MonthBill extends IdEntity implements Serializable { private static final long serialVersionUID = 2053571341410503484L; //计费月 private String countmonth; //打印日期 private String printdate; // 手机号 private String phonenum; // 费用名称 private String expensename; // 优惠前(元) private String beforediscount; // 优惠费用(元) private String discount; // 费用小计(元) private String totalcost; private String taskid; public String getCountmonth() { return countmonth; } public void setCountmonth(String countmonth) { this.countmonth = countmonth; } public String getPrintdate() { return printdate; } public void setPrintdate(String printdate) { this.printdate = printdate; } public String getPhonenum() { return phonenum; } public void setPhonenum(String phonenum) { this.phonenum = phonenum; } public String getExpensename() { return expensename; } public void setExpensename(String expensename) { this.expensename = expensename; } public String getBeforediscount() { return beforediscount; } public void setBeforediscount(String beforediscount) { this.beforediscount = beforediscount; } public String getDiscount() { return discount; } public void setDiscount(String discount) { this.discount = discount; } public String getTotalcost() { return totalcost; } public void setTotalcost(String totalcost) { this.totalcost = totalcost; } public String getTaskid() { return taskid; } public void setTaskid(String taskid) { this.taskid = taskid; } public TelecomShanxi3MonthBill() { super(); // TODO Auto-generated constructor stub } public TelecomShanxi3MonthBill(String countmonth, String printdate, String phonenum, String expensename, String beforediscount, String discount, String totalcost, String taskid) { super(); this.countmonth = countmonth; this.printdate = printdate; this.phonenum = phonenum; this.expensename = expensename; this.beforediscount = beforediscount; this.discount = discount; this.totalcost = totalcost; this.taskid = taskid; } }
2,596
0.750796
0.736465
100
24.110001
22.268316
133
false
false
0
0
0
0
0
0
1.6
false
false
7
52770c84d984f8acfb8c54153bbd3846219960bd
2,241,972,930,024
836155716eb9f9ca2aaf0159ab91c3180ba5f6e9
/app/src/main/java/com/sproutling/services/SSManagement.java
dae3c3e19198ce9a2a83841c98dfee8a75a34c02
[]
no_license
susheelmattel/sprout-import
https://github.com/susheelmattel/sprout-import
d84bfddc830ad6500dce9e74f5a93c7a8ce56832
6835537b9ee341e43ff0f96862301d9297fff05e
refs/heads/master
2020-04-06T08:12:01.426000
2018-11-13T00:54:45
2018-11-13T00:54:45
157,298,106
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2016 Mattel, Inc. All rights reserved. */ package com.sproutling.services; import android.os.Build; import android.util.Log; import com.sproutling.BuildConfig; import com.sproutling.http.Http; import com.sproutling.http.HttpContent; import com.sproutling.utils.DateTimeUtils; import com.sproutling.utils.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimeZone; /** * Sproutservices * Created by bradylin on 11/18/16. */ public class SSManagement { /** * User role */ public static final String TYPE_GUARDIAN = "Guardian"; public static final String TYPE_CAREGIVER = "Caregiver"; private static final String TAG = "SSManagement"; // Temporary iOS client id // private static final String CLIENT_ID = "c3c04c54bd0a9f3f40517f1670c3c327c17d8d19425b416bc7169593e2563380"; //iOS private static final String CLIENT_ID = "4677a7fc91373cbbb035ad4f43c1ebaddfaa8f95344fd37c9efe3ea7afaca08e"; private static final String AUTH_PREFIX = "Bearer "; private static final String PROTOCOL_SECURE = "https://"; private static final String PROTOCOL = "http://"; // private static final String ENDPOINT = PROTOCOL + "api-dev-"+BuildConfig.RELEASE_TARGET+".sproutlingcloud.com"; private static final String VERSION = "/v1"; private static final String SERVICE_IDENTITY = "identity"; private static final String SERVICE_DEVICE = "device"; private static final String SERVICE_TIMELINE = "timeline"; // OLD Endpoint // private static final String ENDPOINT = PROTOCOL + "35.163.179.218:8090"; // NEW API private static final String SERVICE_UPDATE = "update"; /** * IDENTITY */ private static final String OAUTH = SERVICE_IDENTITY + VERSION + "/oauth2/token"; private static final String TOKENINFO = SERVICE_IDENTITY + VERSION + "/oauth2/token/info"; private static final String LOGOUT = SERVICE_IDENTITY + VERSION + "/oauth2/logout"; private static final String USERS = SERVICE_IDENTITY + VERSION + "/users"; private static final String USER = SERVICE_IDENTITY + VERSION + "/users/{user_id}"; // replace id private static final String ALERTS = USER + "/alerts"; // replace user id private static final String INVITATIONS = SERVICE_IDENTITY + VERSION + "/accounts/{account_id}/invitations"; // replace account_id private static final String CAREGIVERS = SERVICE_IDENTITY + VERSION + "/accounts/{account_id}/caregivers"; // replace account_id private static final String CAREGIVER = SERVICE_IDENTITY + VERSION + "/accounts/{account_id}/caregivers/{caregiver_id}"; // replace account_id, caregiver_id private static final String CHILDREN = SERVICE_IDENTITY + VERSION + "/children"; private static final String CHILD = SERVICE_IDENTITY + VERSION + "/children/{child_id}"; // replace child_id private static final String PHOTO = SERVICE_IDENTITY + VERSION + "/children/{child_id}/photos"; // replace child_id private static final String HANDHELDS = SERVICE_IDENTITY + VERSION + "/handhelds"; private static final String HANDHELD = SERVICE_IDENTITY + VERSION + "/handhelds/{handheld_id}"; // replace id private static final String PIN = SERVICE_IDENTITY + VERSION + "/passwords/reset"; private static final String VALIDATE_PIN = SERVICE_IDENTITY + VERSION + "/passwords/reset/validate_pin"; private static final String RESET_PASSWORD = SERVICE_IDENTITY + VERSION + "/passwords/reset/pin"; /** * TIMELINE */ private static final String CHILDREN_EVENTS = SERVICE_TIMELINE + VERSION + "/children/{child_id}/events"; // ?event_type=&week_of=2017-02-20T19%3A19%3A05.234410974Z private static final String EVENTS = SERVICE_TIMELINE + VERSION + "/events"; private static final String EVENT = SERVICE_TIMELINE + VERSION + "/events/{event_id}"; // replace event_id private static final String ARTICLES = SERVICE_TIMELINE + VERSION + "/articles"; // ?start_age_day=&end_age_day= private static final String ARTICLE = SERVICE_TIMELINE + VERSION + "/articles/{article_id}"; /** * DEVICE */ private static final String DEVICES = SERVICE_DEVICE + VERSION + "/devices"; private static final String DEVICE = SERVICE_DEVICE + VERSION + "/devices/{serial}"; // replace serial /** * UPDATE */ private static final String UPDATE = SERVICE_UPDATE + VERSION + "/versioninfo"; /** * EOL */ private static final String EOL = SERVICE_UPDATE + VERSION + "/eol"; /** * Insertions */ private static final String SERIAL = "serial"; // OLD API // private static final String USERS = ENDPOINT + "/v1/users"; // private static final String USER = ENDPOINT + "/v1/users/{id}"; // replace id // private static final String HANDHELDS = ENDPOINT + "/v1/handhelds"; // private static final String HANDHELD = ENDPOINT + "/v1/handhelds/{id}"; // replace id // private static final String CHILDREN = ENDPOINT + "/v1/children"; // private static final String CHILD = ENDPOINT + "/v1/children/{id}"; // replace id // private static final String DEVICES = ENDPOINT + "/v1/devices"; // private static final String DEVICE = ENDPOINT + "/v1/devices?serial={serial}"; // replace serial // private static final String EVENTS = ENDPOINT + "/v1/events/child"; // private static final String EVENT = ENDPOINT + "/v1/events"; // replace id // "/v1/events?event_id={id}" // private static final String OAUTH = ENDPOINT + "/v1/oauth2/token"; // private static final String PASSWORD = ENDPOINT + "/v1/passwords"; // private static final String STATUS = ENDPOINT + "/v1/status"; // private static final String TOKENINFO = ENDPOINT + "/v1/oauth2/token/info"; // // private static final String MQTTTOKEN = "/v1/devices/tokens"; private static final String EVENT_ID = "event_id"; private static final String CHILD_ID = "child_id"; private static final String WEEK_OF = "week_of"; private static final String EVENT_TYPE = "event_type"; private static final String START_AGE_DAY = "start_age_day"; private static final String END_AGE_DAY = "end_age_day"; private static final String REPLACE_USER_ID = "{user_id}"; private static final String REPLACE_ACCOUNT_ID = "{account_id}"; private static final String REPLACE_CAREGIVER_ID = "{caregiver_id}"; private static final String REPLACE_SERIAL = "{serial}"; private static final String REPLACE_HANDHELD_ID = "{handheld_id}"; private static final String REPLACE_CHILD_ID = "{child_id}"; private static final String REPLACE_WEEK = "{week_of}"; private static final String REPLACE_EVENT_ID = "{event_id}"; private static final String REPLACE_ARTICLE_ID = "{article_id}"; /** * New Endpoint */ // private static final String ENDPOINT = PROTOCOL_SECURE + "api-dev.us.sproutlingcloud.com"; // private static final String ENDPOINT = PROTOCOL + "api-dev-us.sproutlingcloud.com"; // private static final String ENDPOINT = PROTOCOL + "api-dev-cn.sproutlingcloud.com"; public static String ENDPOINT = BuildConfig.SERVER_URL; private SSManagement() { } public static String getChildrenEventsUrl(String childId) { return CHILDREN_EVENTS.replace(REPLACE_CHILD_ID, childId); } public static String getTimelineEventsUrl() { return EVENTS; } private static String getUserAgent() { return "Sproutling/" + BuildConfig.VERSION_NAME + " " + "(Linux; U; Android " + Build.VERSION.RELEASE + ")"; } private static Http getHttpUrl(String url) { if (BuildConfig.DEBUG) { Log.d(TAG, "HTTP Request: " + url); } return Http.url(url) .accept(Http.APPLICATION_JSON) .contentType(Http.APPLICATION_JSON) .header("User-Agent", getUserAgent()) .header("X-TIMEZONE", Utils.getTimeZoneInShort()) .header("Accept-Language", Utils.getLanguageWithCountry()) .timeout(20000); } private static Http getHttpUrlWithToken(String url, String token) { if (BuildConfig.DEBUG) { Log.d(TAG, "HTTP Request: " + url); Log.d(TAG, "Access Token: " + token); } return getHttpUrl(url).authorization(AUTH_PREFIX + token); } static User loginByPassword(String username, String password) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + OAUTH) .post(new JSONObject() .put("username", username) .put("password", password) .put("grant_type", "password") .put("client_id", CLIENT_ID) .put("scope", null)); checkResponseForError(httpContent); return new User(httpContent.json()); } static User refreshToken(String accessToken, String refreshToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + OAUTH, accessToken) .post(new JSONObject() .put("refresh_token", refreshToken) .put("grant_type", "refresh_token") .put("client_id", CLIENT_ID) .put("scope", null)); checkResponseForError(httpContent); return new User(httpContent.json()); } static User getTokenInfo(String accessToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + TOKENINFO, accessToken) .get(); checkResponseForError(httpContent); return new User(httpContent.json()); } static boolean logout(String accessToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + LOGOUT, accessToken) .post(new JSONObject()); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static UserAccountInfo createUser(String email, String firstName, String lastName, String type, String password, String phone, String inviteToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + USERS) .post(new JSONObject() .put("email", email) .put("first_name", firstName) .put("last_name", lastName) .put("role", type) .put("password", password) .put("password_confirmation", password) .put("phone_number", phone) .put("invite_token", inviteToken) ); checkResponseForError(httpContent); return new UserAccountInfo(httpContent.json()); } static UserAccountInfo getUserById(String accessToken, String userId) throws IOException, JSONException, SSException { String userUrl = ENDPOINT + USER; HttpContent httpContent = getHttpUrlWithToken(userUrl.replace(REPLACE_USER_ID, userId), accessToken) .get(); checkResponseForError(httpContent); return new UserAccountInfo(httpContent.json()); } static UserAccountInfo updateUserById(String accessToken, String userId, JSONObject body) throws IOException, JSONException, SSException { String userUrl = ENDPOINT + USER; HttpContent httpContent = getHttpUrlWithToken(userUrl.replace(REPLACE_USER_ID, userId), accessToken) .put(body); checkResponseForError(httpContent); return new UserAccountInfo(httpContent.json()); } static boolean deleteUserById(String accessToken, String userId) throws IOException, JSONException, SSException { String userUrl = ENDPOINT + USER; HttpContent httpContent = getHttpUrlWithToken(userUrl.replace(REPLACE_USER_ID, userId), accessToken) .delete(); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static UserAccountInfo updateAlert(String accessToken, String userId, JSONObject body) throws IOException, JSONException, SSException { String alertUrl = ENDPOINT + ALERTS; HttpContent httpContent = getHttpUrlWithToken(alertUrl.replace(REPLACE_USER_ID, userId), accessToken) .put(body); checkResponseForError(httpContent); return new UserAccountInfo(httpContent.json()); } static String invitations(String accessToken, String accountId) throws IOException, JSONException, SSException { String invitationUrl = ENDPOINT + INVITATIONS; HttpContent httpContent = getHttpUrlWithToken(invitationUrl.replace(REPLACE_ACCOUNT_ID, accountId), accessToken) .post(new JSONObject()); checkResponseForError(httpContent); return checkResponseForInviteToken(httpContent); } static List<UserAccountInfo> listCaregivers(String accessToken, String accountId) throws IOException, JSONException, SSException { String url = ENDPOINT + CAREGIVERS; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_ACCOUNT_ID, accountId), accessToken) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<UserAccountInfo> caregiverList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { caregiverList.add(new UserAccountInfo((JSONObject) jsonArray.get(i))); } return caregiverList; } static boolean removeCaregiver(String accessToken, String accountId, String caregiverId) throws IOException, JSONException, SSException { String url = ENDPOINT + CAREGIVER; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_ACCOUNT_ID, accountId).replace(REPLACE_CAREGIVER_ID, caregiverId), accessToken) .delete(); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static Child createChild(String accessToken, String firstName, String lastName, String gender, String birthDate, String dueDate) throws JSONException, IOException, SSException { String url = ENDPOINT + CHILDREN; HttpContent httpContent = getHttpUrlWithToken(url, accessToken) .post(new JSONObject() .put("first_name", firstName) .put("last_name", lastName) .put("gender", gender) .put("birth_date", birthDate) .put("due_date", dueDate) ); checkResponseForError(httpContent); return new Child(httpContent.json()); } static List<Child> listChildren(String accessToken) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILDREN; HttpContent httpContent = getHttpUrlWithToken(url, accessToken).get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<Child> childrenList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { childrenList.add(new Child((JSONObject) jsonArray.get(i))); } return childrenList; } static Child getChildById(String accessToken, String childId) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .get(); checkResponseForError(httpContent); return new Child(httpContent.json()); } static Child updateChildById(String accessToken, String childId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .put(body); Log.d(TAG, "updateChildById BODY : " + body.toString(2)); checkResponseForError(httpContent); return new Child(httpContent.json()); } static boolean deleteChildById(String accessToken, String childId) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .delete(); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static void uploadChildPhoto(String accessToken, String childId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + PHOTO; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .post(body); checkResponseForError(httpContent); } static void downloadChildPhoto(String accessToken, String childId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + PHOTO; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .post(body); checkResponseForError(httpContent); } static boolean requestPin(String phoneNumber) throws JSONException, IOException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + PIN) .post(new JSONObject() .put("phone_number", phoneNumber) ); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static boolean validatePin(String phoneNumber, String pin) throws JSONException, IOException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + VALIDATE_PIN) .post(new JSONObject() .put("phone_number", phoneNumber) .put("pin", pin) ); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static boolean resetPassword(String phoneNumber, String pin, String password, String passwordConfirmation) throws JSONException, IOException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + RESET_PASSWORD) .put(new JSONObject() .put("phone_number", phoneNumber) .put("pin", pin) .put("password", password) .put("password_confirmation", passwordConfirmation) ); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static DeviceResponse createDevice(String accessToken, JSONObject body) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + DEVICES, accessToken) .post(body); checkResponseForError(httpContent); return new DeviceResponse(httpContent.json()); } static List<DeviceResponse> listDevices(String accessToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + DEVICES, accessToken) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<DeviceResponse> deviceList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { deviceList.add(new DeviceResponse((JSONObject) jsonArray.get(i))); } return deviceList; } static DeviceResponse getDeviceBySerial(String accessToken, String serial) throws IOException, JSONException, SSException { String url = ENDPOINT + DEVICE; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_SERIAL, serial), accessToken) .get(); checkResponseForError(httpContent); return new DeviceResponse(httpContent.json()); } static DeviceResponse updateDevice(String accessToken, String serial, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + DEVICE; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_SERIAL, serial), accessToken) .put(body); checkResponseForError(httpContent); return new DeviceResponse(httpContent.json()); } static boolean deleteDeviceBySerial(String accessToken, String serial) throws IOException, JSONException, SSException { String url = ENDPOINT + DEVICE; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_SERIAL, serial), accessToken) .delete(); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static SSEvent createEvent(String accessToken, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + EVENTS; HttpContent httpContent = getHttpUrlWithToken(url, accessToken) .post(body); checkResponseForError(httpContent); return new SSEvent(httpContent.json()); } static List<SSEvent> listEventsByChild(String accessToken, String childId) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILDREN_EVENTS; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<SSEvent> eventList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { eventList.add(SSEvent.parseEvent((JSONObject) jsonArray.get(i))); // eventList.add(new SSEvent((JSONObject) jsonArray.get(i))); } return eventList; } static List<SSEvent> listEventsByChild(String accessToken, String childId, String eventType) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILDREN_EVENTS; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .parameter("event_type", eventType) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<SSEvent> eventList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { eventList.add(SSEvent.parseEvent((JSONObject) jsonArray.get(i))); // eventList.add(new SSEvent((JSONObject) jsonArray.get(i))); } return eventList; } static SSEvent getEventById(String accessToken, String eventId) throws IOException, JSONException, SSException { String url = ENDPOINT + EVENT; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_EVENT_ID, eventId), accessToken) .get(); checkResponseForError(httpContent); return SSEvent.parseEvent(httpContent.json()); // return new SSEvent(httpContent.json()); } static SSEvent updateEventById(String accessToken, String eventId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + EVENT; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_EVENT_ID, eventId), accessToken) // .keepParametersQuery() .put(body); checkResponseForError(httpContent); return SSEvent.parseEvent(httpContent.json()); // return new SSEvent(httpContent.json()); } static List<SSEvent> getEventsByWeek(String accessToken, String childId, String eventType, String weekOf) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILDREN_EVENTS; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .parameter(EVENT_TYPE, eventType) .parameter(WEEK_OF, weekOf) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<SSEvent> eventList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { eventList.add(SSEvent.parseEvent((JSONObject) jsonArray.get(i))); // eventList.add(new SSEvent((JSONObject) jsonArray.get(i))); } return eventList; } static boolean deleteEventById(String accessToken, String eventId) throws IOException, JSONException, SSException { String url = ENDPOINT + EVENT; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_EVENT_ID, eventId), accessToken) .delete(); checkResponseForError(httpContent); return true; } static List<SSArticle> listArticles(String accessToken, int startAgeDay, int endAgeDay) throws IOException, JSONException, SSException { String url = ENDPOINT + ARTICLES; HttpContent httpContent = getHttpUrlWithToken(url, accessToken) .parameter(START_AGE_DAY, startAgeDay) .parameter(END_AGE_DAY, endAgeDay) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<SSArticle> articles = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { articles.add(new SSArticle((JSONObject) jsonArray.get(i))); } return articles; } static SSArticle getArticleById(String accessToken, String articleId) throws IOException, JSONException, SSException { String url = ENDPOINT + ARTICLE; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_ARTICLE_ID, articleId), accessToken) .get(); checkResponseForError(httpContent); return new SSArticle(httpContent.json()); } static void createHandheld(String accessToken) throws IOException, JSONException, SSException { String url = ENDPOINT + HANDHELDS; HttpContent httpContent = getHttpUrlWithToken(url, accessToken) .post(new JSONObject()); // Required fields // \"uuid\": \"cbb58a2a-8f05-4221-bc5a-315ef7579f6f\", // \"token\": \"eb76e3fe19c2760c6f8d590047d9188fc860c2401a38018f5b6d1294b07013f8\", // \"name\": \"Lisa\'s iPhone 6\", // \"locale\": \"en_US\", // \"language\": \"en-US\", // \"timezone\": \"PST\", checkResponseForError(httpContent); } static void listHandheld(String accessToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + HANDHELDS, accessToken) .get(); checkResponseForError(httpContent); } static void getHandheldById(String accessToken, String handheldId) throws IOException, JSONException, SSException { String url = ENDPOINT + HANDHELD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_HANDHELD_ID, handheldId), accessToken) .get(); checkResponseForError(httpContent); } static void updateHandheldById(String accessToken, String handheldId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + HANDHELD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_HANDHELD_ID, handheldId), accessToken) .put(body); checkResponseForError(httpContent); } static void deleteHandheldById(String accessToken, String handheldId) throws IOException, JSONException, SSException { String url = ENDPOINT + HANDHELD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_HANDHELD_ID, handheldId), accessToken) .delete(); checkResponseForError(httpContent); } static UpdateInfo getUpdateInfo() throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + UPDATE) .get(); checkResponseForError(httpContent); return new UpdateInfo(httpContent.json()); } static EOLData getEOLData() throws IOException, JSONException, SSException { //TODO remove this once we have the final API for Sproutling EOL :( HttpContent httpContent = getHttpUrl("https://s3-us-west-1.amazonaws.com/sproutling-app/eol.json") .get(); checkResponseForError(httpContent); return new EOLData(httpContent.json()); } private static void checkResponseForError(HttpContent httpContent) throws JSONException, SSException { if (BuildConfig.DEBUG) { Log.e(TAG, "HTTP Response(" + httpContent.responseCode() + "): " + httpContent.string()); } int responseCode = httpContent.responseCode(); if (responseCode >= 400 && responseCode <= 404) { String content = httpContent.string(); if (content != null && content.contains("error")) throw new SSException(new SSError(httpContent.json()), responseCode); throw new SSRequestException(new SSError(), responseCode); } else if (responseCode >= 500 && responseCode <= 503) { throw new SSServerException(new SSError(), responseCode); } else if (httpContent.string() != null && httpContent.string().contains("error")) { throw new SSException(new SSError(httpContent.json()), responseCode); } } private static boolean checkResponseForStatus(HttpContent httpContent) throws JSONException, SSException { if (BuildConfig.DEBUG) { Log.d(TAG, "HTTP Response(" + httpContent.responseCode() + "): " + httpContent.string()); } if (SSStatus.hasStatus(httpContent.string())) { SSStatus status = new SSStatus(httpContent.json()); return status.isSuccess(); } return false; } private static String checkResponseForInviteToken(HttpContent httpContent) throws JSONException, SSException { if (BuildConfig.DEBUG) { Log.d(TAG, "HTTP Response(" + httpContent.responseCode() + "): " + httpContent.string()); } if (SSStatus.hasStatus(httpContent.string())) { SSStatus status = new SSStatus(httpContent.json()); return status.isSuccess() ? httpContent.json().getString("token") : null; } return null; } public static class DeviceResponse { private String id; private String ownerId; private String accountId; private String name; private String serial; private String firmwareVersion; private String createdAt; private String updatedAt; private String ownerType; public DeviceResponse() { } public DeviceResponse(JSONObject jsonObject) throws JSONException { id = jsonObject.getString("id"); accountId = jsonObject.getString("account_id"); ownerId = jsonObject.getString("owner_id"); ownerType = jsonObject.getString("owner_type"); name = jsonObject.getString("name"); serial = jsonObject.getString("serial"); firmwareVersion = jsonObject.getString("firmware_version"); createdAt = jsonObject.getString("created_at"); updatedAt = jsonObject.getString("updated_at"); } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } public String getOwnerType() { return ownerType; } public void setOwnerType(String ownerType) { this.ownerType = ownerType; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public String getFirmwareVersion() { return firmwareVersion; } public void setFirmwareVersion(String firmwareVersion) { this.firmwareVersion = firmwareVersion; } } // Processing // Processed Objects public static class UserAccountInfo { public String id; public String accountId; public String firstName; public String lastName; public String email; public String phone; public String inviteToken; public String type; public String createdAt; public String updatedAt; public PushNotification alert; public String jsonString; public UserAccountInfo() { } public UserAccountInfo(JSONObject jsonObject) throws JSONException { id = jsonObject.getString("id"); accountId = jsonObject.getString("account_id"); firstName = jsonObject.getString("first_name"); lastName = jsonObject.getString("last_name"); email = jsonObject.getString("email"); phone = jsonObject.getString("phone_number"); inviteToken = jsonObject.optString("invite_token"); type = jsonObject.getString("role"); createdAt = jsonObject.getString("created_at"); updatedAt = jsonObject.getString("updated_at"); JSONObject pnSettingsJSONObject = jsonObject.optJSONObject("push_notification_alert_settings"); alert = pnSettingsJSONObject != null ? new PushNotification(pnSettingsJSONObject) : null; jsonString = jsonObject.toString(); } public String toJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", id); jsonObject.put("account_id", accountId); jsonObject.put("first_name", firstName); jsonObject.put("last_name", lastName); jsonObject.put("email", email); jsonObject.put("phone_number", phone); jsonObject.put("invite_token", inviteToken); jsonObject.put("role", type); jsonObject.put("created_at", createdAt); jsonObject.put("updated_at", updatedAt); jsonObject.put("push_notification_alert_settings", alert); return jsonObject.toString(); } @Override public String toString() { return jsonString; } } public static class PushNotification { public static final String ENABLED = "0"; public static final String DISABLED = "1"; public static final String DEFAULT_NOTIFICATIONS_DISABLED = "0"; public static final String DEFAULT_ROLLEDOVER_DISABLED = "0"; public static final String DEFAULT_UNUSUAL_HEARTBEAT_DISABLED = "0"; public static final String DEFAULT_AWAKE_DISABLED = "0"; public static final String DEFAULT_ASLEEP_DISABLED = "1"; // public static final String DEFAULT_STIRRING_DISABLED = "1"; public static final String DEFAULT_WEARABLE_FELL_OFF_DISABLED = "0"; public static final String DEFAULT_WEARABLE_NOT_FOUND_DISABLED = "1"; public static final String DEFAULT_WEARABLE_TOO_FAR_AWAY_DISABLED = "1"; public static final String DEFAULT_BATTERY_DISABLED = "1"; public static final String DEFAULT_OUT_OF_BATTERY_DISABLED = "1"; public static final String DEFAULT_HUB_OFFLINE_DISABLED = "1"; public String notificationsDisabled; public String rolledOverDisabled; public String unusualHeartbeatDisabled; public String awakeDisabled; public String asleepDisabled; // public String stirringDisabled; public String wearableFellOffDisabled; public String wearableNotFoundDisabled; public String wearableTooFarAwayDisabled; public String batteryDisabled; public String outOfBatteryDisabled; public String hubOfflineDisabled; public String roomTemperatureDisabled; public String roomHumidityDisabled; public String roomNoiseLevelDisabled; public String roomLightLevelDisabled; public String jsonString; public PushNotification() { } public PushNotification(JSONObject jsonObject) throws JSONException { notificationsDisabled = jsonObject.optString("NotificationsDisabled", "0"); rolledOverDisabled = jsonObject.optString("RolledoverDisabled", "0"); unusualHeartbeatDisabled = jsonObject.optString("UnusualHeartbeatDisabled", "0"); awakeDisabled = jsonObject.optString("AwakeDisabled", "0"); asleepDisabled = jsonObject.optString("AsleepDisabled", "0"); // stirringDisabled = jsonObject.optString("StirringDisabled", "0"); wearableFellOffDisabled = jsonObject.optString("WearableFellOffDisabled", "0"); wearableNotFoundDisabled = jsonObject.optString("WearableNotFoundDisabled", "0"); wearableTooFarAwayDisabled = jsonObject.optString("WearableTooFarAwayDisabled", "0"); batteryDisabled = jsonObject.optString("BatteryDisabled", "0"); outOfBatteryDisabled = jsonObject.optString("OutOfBatteryDisabled", "0"); hubOfflineDisabled = jsonObject.optString("HubOfflineDisabled", "0"); roomTemperatureDisabled = jsonObject.optString("RoomTemperatureDisabled", "0"); roomHumidityDisabled = jsonObject.optString("RoomHumidityDisabled", "0"); roomLightLevelDisabled = jsonObject.optString("RoomLightLevelDisabled", "0"); roomNoiseLevelDisabled = jsonObject.optString("RoomNoiseLevelDisabled", "0"); jsonString = jsonObject.toString(); } public static PushNotification getDefaultSettings() { PushNotification settings = new PushNotification(); settings.notificationsDisabled = DEFAULT_NOTIFICATIONS_DISABLED; settings.rolledOverDisabled = DEFAULT_ROLLEDOVER_DISABLED; settings.unusualHeartbeatDisabled = DEFAULT_UNUSUAL_HEARTBEAT_DISABLED; settings.awakeDisabled = DEFAULT_AWAKE_DISABLED; settings.asleepDisabled = DEFAULT_ASLEEP_DISABLED; // settings.stirringDisabled = DEFAULT_STIRRING_DISABLED; settings.wearableFellOffDisabled = DEFAULT_WEARABLE_FELL_OFF_DISABLED; settings.wearableNotFoundDisabled = DEFAULT_WEARABLE_NOT_FOUND_DISABLED; settings.wearableTooFarAwayDisabled = DEFAULT_WEARABLE_TOO_FAR_AWAY_DISABLED; settings.batteryDisabled = DEFAULT_BATTERY_DISABLED; settings.outOfBatteryDisabled = DEFAULT_OUT_OF_BATTERY_DISABLED; settings.hubOfflineDisabled = DEFAULT_HUB_OFFLINE_DISABLED; return settings; } public static JSONObject getDefaultSettingsJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("NotificationsDisabled", DEFAULT_NOTIFICATIONS_DISABLED); jsonObject.put("RolledoverDisabled", DEFAULT_ROLLEDOVER_DISABLED); jsonObject.put("UnusualHeartbeatDisabled", DEFAULT_UNUSUAL_HEARTBEAT_DISABLED); jsonObject.put("AwakeDisabled", DEFAULT_AWAKE_DISABLED); jsonObject.put("AsleepDisabled", DEFAULT_ASLEEP_DISABLED); // jsonObject.put("StirringDisabled", DEFAULT_STIRRING_DISABLED); jsonObject.put("WearableFellOffDisabled", DEFAULT_WEARABLE_FELL_OFF_DISABLED); jsonObject.put("WearableNotFoundDisabled", DEFAULT_WEARABLE_NOT_FOUND_DISABLED); jsonObject.put("WearableTooFarAwayDisabled", DEFAULT_WEARABLE_TOO_FAR_AWAY_DISABLED); jsonObject.put("BatteryDisabled", DEFAULT_BATTERY_DISABLED); jsonObject.put("OutOfBatteryDisabled", DEFAULT_OUT_OF_BATTERY_DISABLED); jsonObject.put("HubOfflineDisabled", DEFAULT_HUB_OFFLINE_DISABLED); return jsonObject; } public static JSONObject getDefaultSettingsAPIJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("push_notification_alert_settings", getDefaultSettingsJSON()); return jsonObject; } public JSONObject getSettingsJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("NotificationsDisabled", notificationsDisabled); jsonObject.put("RolledoverDisabled", rolledOverDisabled); jsonObject.put("UnusualHeartbeatDisabled", unusualHeartbeatDisabled); jsonObject.put("AwakeDisabled", awakeDisabled); jsonObject.put("AsleepDisabled", asleepDisabled); // jsonObject.put("StirringDisabled", stirringDisabled); jsonObject.put("WearableFellOffDisabled", wearableFellOffDisabled); jsonObject.put("WearableNotFoundDisabled", wearableNotFoundDisabled); jsonObject.put("WearableTooFarAwayDisabled", wearableTooFarAwayDisabled); jsonObject.put("BatteryDisabled", batteryDisabled); jsonObject.put("OutOfBatteryDisabled", outOfBatteryDisabled); jsonObject.put("HubOfflineDisabled", hubOfflineDisabled); return jsonObject; } public JSONObject getSettingsAPIJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("push_notification_alert_settings", getSettingsJSON()); return jsonObject; } } public static class User { public String scope; public String resourceOwnerId; public String createdAt; public String tokenType; public int expiresIn; public String refreshToken; public String accessToken; public String jsonString; public User() { } public User(JSONObject jsonObject) throws JSONException { scope = jsonObject.optString("scope"); resourceOwnerId = jsonObject.getString("resource_owner_id"); createdAt = jsonObject.getString("created_at"); tokenType = jsonObject.getString("token_type"); expiresIn = jsonObject.getInt("expires_in"); refreshToken = jsonObject.optString("refresh_token"); accessToken = jsonObject.getString("access_token"); jsonString = jsonObject.toString(); } @Override public String toString() { return jsonString; } } public static class Child { public static final String GENDER_GIRL = "F"; public static final String GENDER_BOY = "M"; public static final String GENDER_UNKNOWN = "U"; public String id; public String accountId; public String firstName; public String lastName; public String gender; public String birthDate; public String dueDate; public String createdAt; public String updatedAt; public String twinId; public String photoUrl; public String jsonString; public Child() { } public Child(JSONObject jsonObject) throws JSONException { id = jsonObject.optString("id"); accountId = jsonObject.getString("account_id"); firstName = jsonObject.getString("first_name"); lastName = jsonObject.getString("last_name"); gender = jsonObject.getString("gender"); birthDate = jsonObject.optString("birth_date"); dueDate = jsonObject.getString("due_date"); createdAt = jsonObject.getString("created_at"); updatedAt = jsonObject.getString("updated_at"); twinId = jsonObject.optString("twin_id"); photoUrl = jsonObject.getString("photo_url"); jsonString = jsonObject.toString(); } public JSONObject toJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", id); jsonObject.put("account_id", accountId); jsonObject.put("first_name", firstName); jsonObject.put("last_name", lastName); jsonObject.put("gender", gender); jsonObject.put("birth_date", birthDate); jsonObject.put("due_date", dueDate); jsonObject.put("created_at", createdAt); jsonObject.put("updated_at", updatedAt); jsonObject.put("twin_id", twinId); jsonObject.put("photo_url", photoUrl); return jsonObject; } public boolean isMale() { return GENDER_BOY.equalsIgnoreCase(gender); } @Override public String toString() { return jsonString; } } public static class SSEvent { public static final String TYPE_LEARNING_PERIOD = "learningPeriod"; public static final String TYPE_NAP = "nap"; public static final String TYPE_HEART_RATE = "heartRate"; public String id; public String childId; public String eventType; public String startDate; public String endDate; public String createdAt; public String updatedAt; // public String data; public String jsonString; public SSEvent() { } public SSEvent(JSONObject jsonObject) throws JSONException { id = jsonObject.getString("id"); childId = jsonObject.getString("child_id"); eventType = jsonObject.getString("event_type"); startDate = jsonObject.getString("start_date"); endDate = jsonObject.getString("end_date"); createdAt = jsonObject.getString("created_at"); updatedAt = jsonObject.getString("updated_at"); // data = jsonObject.getString("data"); jsonString = jsonObject.toString(); } public static SSEvent parseEvent(JSONObject jsonObject) throws JSONException { return isNapEvent(jsonObject) ? new SSNap(jsonObject) : new SSEvent(jsonObject); } static boolean isNapEvent(JSONObject data) { return data.toString().contains(TYPE_NAP); } @Override public String toString() { return jsonString; } } public static class SSNap extends SSEvent implements Serializable { public List<Spell> spells; public SSNap() { super(); } public SSNap(JSONObject jsonObject) throws JSONException { super(jsonObject); parseData(jsonObject.optJSONObject("data")); } void parseData(JSONObject data) throws JSONException { if (data != null) { spells = new ArrayList<>(); JSONArray spellsJSONArray = data.getJSONArray("spells"); for (int i = 0; i < spellsJSONArray.length(); i++) { spells.add(new Spell((JSONObject) spellsJSONArray.get(i))); } } } public List<Spell> getSpells() { return spells; } public int getNumOfWakings() { int count = 0; for (Spell spell : spells) { count = spell.isWake() ? ++count : count; } return count; } public long getTimeAwake() { long time = 0; for (Spell spell : spells) { time = spell.isWake() ? time + spell.getDuration() : time; } return time; } public long getTimeAsleep() { long time = 0; for (Spell spell : spells) { time = spell.isSleep() ? time + spell.getDuration() : time; } return time; } public long getTimeStirring() { long time = 0; for (Spell spell : spells) { time = spell.isStirring() ? time + spell.getDuration() : time; } return time; } public static class Spell implements Serializable { public static final int TYPE_SLEEP = 0; public static final int TYPE_STIRRING = 1; public static final int TYPE_WAKE = 2; TimeZone tz = TimeZone.getTimeZone("PDT"); Calendar startTime = Calendar.getInstance(); Calendar endTime = Calendar.getInstance(); int type; public Spell() { } public Spell(JSONObject jsonObject) throws JSONException { try { startTime.setTime(DateTimeUtils.parseSpellDate(jsonObject.getString("start_ts"))); endTime.setTime(DateTimeUtils.parseSpellDate(jsonObject.getString("end_ts"))); startTime.setTimeZone(tz); endTime.setTimeZone(tz); type = jsonObject.getInt("swstatus"); } catch (ParseException e) { e.printStackTrace(); } } public Calendar getStartTime() { return startTime; } public void setStartTime(Calendar calendar) { startTime = calendar; } public Calendar getEndTime() { return endTime; } public void setEndTime(Calendar calendar) { endTime = calendar; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getDuration() { return endTime.getTimeInMillis() - startTime.getTimeInMillis(); } public boolean isSleep() { return type == TYPE_SLEEP; } public boolean isStirring() { return type == TYPE_STIRRING; } public boolean isWake() { return type == TYPE_WAKE; } } } public static class SSArticle { public String id; public String language; public int childAge; public String title; public String url; public String imageThumbnailUrl; public String imageSmallUrl; public String imageMediumUrl; public String imageLargeUrl; public String createdAt; public String jsonString; public SSArticle() { } private SSArticle(JSONObject jsonObject) throws JSONException { id = jsonObject.getString("id"); language = jsonObject.getString("language"); childAge = jsonObject.getInt("child_age"); title = jsonObject.getString("title"); url = jsonObject.getString("url"); imageThumbnailUrl = jsonObject.getString("image_thumbnail"); imageSmallUrl = jsonObject.getString("image_small"); imageMediumUrl = jsonObject.getString("image_medium"); imageLargeUrl = jsonObject.getString("image_large"); createdAt = jsonObject.getString("created_at"); jsonString = jsonObject.toString(); } @Override public String toString() { return jsonString; } } public static class EOLData { public String popUpText; public String settingsPopUpTxt; public String settingsPopUpEmail; public String settingsPopUpSupportWebsite; public String postEOLPopUpText; public String isEOL; public String jsonString; public EOLData() { } private EOLData(JSONObject jsonObject) throws JSONException { popUpText = jsonObject.getString("app_launch_popup_notice_text"); settingsPopUpTxt = jsonObject.getString("settings_popup_text"); settingsPopUpEmail = jsonObject.getString("settings_popup_support_email"); settingsPopUpSupportWebsite = jsonObject.getString("settings_popup_support_website"); postEOLPopUpText = jsonObject.getString("post_eol_app_launch_popup_notice_text"); isEOL = jsonObject.getString("is_eol"); jsonString = jsonObject.toString(); } @Override public String toString() { return jsonString; } } public static class UpdateInfo { // private ApiInfo apiInfo; // private IosInfo iosInfo; public AndroidInfo androidInfo; private String jsonString; public UpdateInfo() { } private UpdateInfo(JSONObject jsonObject) throws JSONException { // apiInfo = new ApiInfo(jsonObject.getJSONObject("api")); // iosInfo = new IosInfo(jsonObject.getJSONObject("ios")); androidInfo = new AndroidInfo(jsonObject.getJSONObject("android")); jsonString = jsonObject.toString(); } @Override public String toString() { return jsonString; } // private class ApiInfo { // private String currentVersion; // public String minRequiredVersion; // // private ApiInfo(JSONObject jsonObject) throws JSONException { // currentVersion = jsonObject.getString("current_version"); // minRequiredVersion = jsonObject.getString("min_required_version"); // } // } // private class IosInfo { // private String currentVersion; // public String minRequiredVersion; // private String updateUrl; // // private IosInfo(JSONObject jsonObject) throws JSONException { // currentVersion = jsonObject.getString("current_version"); // minRequiredVersion = jsonObject.getString("min_required_version"); // updateUrl = jsonObject.getString("update_url"); // } // } public class AndroidInfo { public int minRequiredVersion; public String updateUrl; private int currentVersion; private AndroidInfo(JSONObject jsonObject) throws JSONException { currentVersion = jsonObject.getInt("current_version"); minRequiredVersion = jsonObject.getInt("min_required_version"); updateUrl = jsonObject.getString("update_url"); } } } }
UTF-8
Java
55,816
java
SSManagement.java
Java
[ { "context": "til.TimeZone;\n\n/**\n * Sproutservices\n * Created by bradylin on 11/18/16.\n */\n\npublic class SSManagement {\n\n ", "end": 663, "score": 0.9995337128639221, "start": 655, "tag": "USERNAME", "value": "bradylin" }, { "context": "rivate static final String ENDPOINT = PROTOCOL + \"35.163.179.218:8090\";\n\n\n // NEW API\n private static final ", "end": 1794, "score": 0.9997454881668091, "start": 1780, "tag": "IP_ADDRESS", "value": "35.163.179.218" }, { "context": "NObject()\n .put(\"username\", username)\n .put(\"password\", passwor", "end": 8822, "score": 0.9979739189147949, "start": 8814, "tag": "USERNAME", "value": "username" }, { "context": "username)\n .put(\"password\", password)\n .put(\"grant_type\", \"pass", "end": 8873, "score": 0.998128354549408, "start": 8865, "tag": "PASSWORD", "value": "password" }, { "context": "ic UserAccountInfo createUser(String email, String firstName, String lastName, String type, String password, S", "end": 10387, "score": 0.9886534810066223, "start": 10378, "tag": "NAME", "value": "firstName" }, { "context": " createUser(String email, String firstName, String lastName, String type, String password, String phone, Stri", "end": 10404, "score": 0.9922755360603333, "start": 10396, "tag": "NAME", "value": "lastName" }, { "context": " email)\n .put(\"first_name\", firstName)\n .put(\"last_name\", lastNa", "end": 10718, "score": 0.9976110458374023, "start": 10709, "tag": "NAME", "value": "firstName" }, { "context": "rstName)\n .put(\"last_name\", lastName)\n .put(\"role\", type)\n ", "end": 10770, "score": 0.9980185031890869, "start": 10762, "tag": "NAME", "value": "lastName" }, { "context": "e\", type)\n .put(\"password\", password)\n .put(\"password_confirmat", "end": 10864, "score": 0.9831644892692566, "start": 10856, "tag": "PASSWORD", "value": "password" }, { "context": " .put(\"password_confirmation\", password)\n .put(\"phone_number\", pho", "end": 10928, "score": 0.8879183530807495, "start": 10920, "tag": "PASSWORD", "value": "password" }, { "context": "tatic Child createChild(String accessToken, String firstName, String lastName, String gender, String birthDate", "end": 14478, "score": 0.9981488585472107, "start": 14469, "tag": "NAME", "value": "firstName" }, { "context": "Child(String accessToken, String firstName, String lastName, String gender, String birthDate, String dueDate)", "end": 14495, "score": 0.9980373978614807, "start": 14487, "tag": "NAME", "value": "lastName" }, { "context": "bject()\n .put(\"first_name\", firstName)\n .put(\"last_name\", lastNa", "end": 14800, "score": 0.9994500279426575, "start": 14791, "tag": "NAME", "value": "firstName" }, { "context": "rstName)\n .put(\"last_name\", lastName)\n .put(\"gender\", gender)\n ", "end": 14852, "score": 0.9986138343811035, "start": 14844, "tag": "NAME", "value": "lastName" }, { "context": "in\", pin)\n .put(\"password\", password)\n .put(\"password_confirmat", "end": 18895, "score": 0.9753254652023315, "start": 18887, "tag": "PASSWORD", "value": "password" }, { "context": "-4221-bc5a-315ef7579f6f\\\",\n// \\\"token\\\": \\\"eb76e3fe19c2760c6f8d590047d9188fc860c2401a38018f5b6d1294b07013f8\\\",\n// \\\"name\\\": \\\"Lisa\\'s iPhone 6\\\",\n// ", "end": 26772, "score": 0.9961515069007874, "start": 26708, "tag": "KEY", "value": "eb76e3fe19c2760c6f8d590047d9188fc860c2401a38018f5b6d1294b07013f8" }, { "context": "1a38018f5b6d1294b07013f8\\\",\n// \\\"name\\\": \\\"Lisa\\'s iPhone 6\\\",\n// \\\"locale\\\": \\\"en_US\\\",\n/", "end": 26802, "score": 0.9978897571563721, "start": 26798, "tag": "NAME", "value": "Lisa" }, { "context": " public String accountId;\n public String firstName;\n public String lastName;\n public S", "end": 33660, "score": 0.9625536799430847, "start": 33651, "tag": "NAME", "value": "firstName" }, { "context": " public String firstName;\n public String lastName;\n public String email;\n public Stri", "end": 33692, "score": 0.859263002872467, "start": 33684, "tag": "NAME", "value": "lastName" }, { "context": " = jsonObject.getString(\"account_id\");\n firstName = jsonObject.getString(\"first_name\");\n ", "end": 34204, "score": 0.7017738223075867, "start": 34195, "tag": "NAME", "value": "firstName" }, { "context": "countId);\n jsonObject.put(\"first_name\", firstName);\n jsonObject.put(\"last_name\", lastNam", "end": 35161, "score": 0.9984051585197449, "start": 35152, "tag": "NAME", "value": "firstName" }, { "context": "irstName);\n jsonObject.put(\"last_name\", lastName);\n jsonObject.put(\"email\", email);\n ", "end": 35212, "score": 0.9987542629241943, "start": 35204, "tag": "NAME", "value": "lastName" }, { "context": "countId);\n jsonObject.put(\"first_name\", firstName);\n jsonObject.put(\"last_name\", lastNam", "end": 45476, "score": 0.9988246560096741, "start": 45467, "tag": "NAME", "value": "firstName" }, { "context": "irstName);\n jsonObject.put(\"last_name\", lastName);\n jsonObject.put(\"gender\", gender);\n ", "end": 45527, "score": 0.9988760948181152, "start": 45519, "tag": "NAME", "value": "lastName" } ]
null
[]
/* * Copyright (C) 2016 Mattel, Inc. All rights reserved. */ package com.sproutling.services; import android.os.Build; import android.util.Log; import com.sproutling.BuildConfig; import com.sproutling.http.Http; import com.sproutling.http.HttpContent; import com.sproutling.utils.DateTimeUtils; import com.sproutling.utils.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimeZone; /** * Sproutservices * Created by bradylin on 11/18/16. */ public class SSManagement { /** * User role */ public static final String TYPE_GUARDIAN = "Guardian"; public static final String TYPE_CAREGIVER = "Caregiver"; private static final String TAG = "SSManagement"; // Temporary iOS client id // private static final String CLIENT_ID = "c3c04c54bd0a9f3f40517f1670c3c327c17d8d19425b416bc7169593e2563380"; //iOS private static final String CLIENT_ID = "4677a7fc91373cbbb035ad4f43c1ebaddfaa8f95344fd37c9efe3ea7afaca08e"; private static final String AUTH_PREFIX = "Bearer "; private static final String PROTOCOL_SECURE = "https://"; private static final String PROTOCOL = "http://"; // private static final String ENDPOINT = PROTOCOL + "api-dev-"+BuildConfig.RELEASE_TARGET+".sproutlingcloud.com"; private static final String VERSION = "/v1"; private static final String SERVICE_IDENTITY = "identity"; private static final String SERVICE_DEVICE = "device"; private static final String SERVICE_TIMELINE = "timeline"; // OLD Endpoint // private static final String ENDPOINT = PROTOCOL + "172.16.58.3:8090"; // NEW API private static final String SERVICE_UPDATE = "update"; /** * IDENTITY */ private static final String OAUTH = SERVICE_IDENTITY + VERSION + "/oauth2/token"; private static final String TOKENINFO = SERVICE_IDENTITY + VERSION + "/oauth2/token/info"; private static final String LOGOUT = SERVICE_IDENTITY + VERSION + "/oauth2/logout"; private static final String USERS = SERVICE_IDENTITY + VERSION + "/users"; private static final String USER = SERVICE_IDENTITY + VERSION + "/users/{user_id}"; // replace id private static final String ALERTS = USER + "/alerts"; // replace user id private static final String INVITATIONS = SERVICE_IDENTITY + VERSION + "/accounts/{account_id}/invitations"; // replace account_id private static final String CAREGIVERS = SERVICE_IDENTITY + VERSION + "/accounts/{account_id}/caregivers"; // replace account_id private static final String CAREGIVER = SERVICE_IDENTITY + VERSION + "/accounts/{account_id}/caregivers/{caregiver_id}"; // replace account_id, caregiver_id private static final String CHILDREN = SERVICE_IDENTITY + VERSION + "/children"; private static final String CHILD = SERVICE_IDENTITY + VERSION + "/children/{child_id}"; // replace child_id private static final String PHOTO = SERVICE_IDENTITY + VERSION + "/children/{child_id}/photos"; // replace child_id private static final String HANDHELDS = SERVICE_IDENTITY + VERSION + "/handhelds"; private static final String HANDHELD = SERVICE_IDENTITY + VERSION + "/handhelds/{handheld_id}"; // replace id private static final String PIN = SERVICE_IDENTITY + VERSION + "/passwords/reset"; private static final String VALIDATE_PIN = SERVICE_IDENTITY + VERSION + "/passwords/reset/validate_pin"; private static final String RESET_PASSWORD = SERVICE_IDENTITY + VERSION + "/passwords/reset/pin"; /** * TIMELINE */ private static final String CHILDREN_EVENTS = SERVICE_TIMELINE + VERSION + "/children/{child_id}/events"; // ?event_type=&week_of=2017-02-20T19%3A19%3A05.234410974Z private static final String EVENTS = SERVICE_TIMELINE + VERSION + "/events"; private static final String EVENT = SERVICE_TIMELINE + VERSION + "/events/{event_id}"; // replace event_id private static final String ARTICLES = SERVICE_TIMELINE + VERSION + "/articles"; // ?start_age_day=&end_age_day= private static final String ARTICLE = SERVICE_TIMELINE + VERSION + "/articles/{article_id}"; /** * DEVICE */ private static final String DEVICES = SERVICE_DEVICE + VERSION + "/devices"; private static final String DEVICE = SERVICE_DEVICE + VERSION + "/devices/{serial}"; // replace serial /** * UPDATE */ private static final String UPDATE = SERVICE_UPDATE + VERSION + "/versioninfo"; /** * EOL */ private static final String EOL = SERVICE_UPDATE + VERSION + "/eol"; /** * Insertions */ private static final String SERIAL = "serial"; // OLD API // private static final String USERS = ENDPOINT + "/v1/users"; // private static final String USER = ENDPOINT + "/v1/users/{id}"; // replace id // private static final String HANDHELDS = ENDPOINT + "/v1/handhelds"; // private static final String HANDHELD = ENDPOINT + "/v1/handhelds/{id}"; // replace id // private static final String CHILDREN = ENDPOINT + "/v1/children"; // private static final String CHILD = ENDPOINT + "/v1/children/{id}"; // replace id // private static final String DEVICES = ENDPOINT + "/v1/devices"; // private static final String DEVICE = ENDPOINT + "/v1/devices?serial={serial}"; // replace serial // private static final String EVENTS = ENDPOINT + "/v1/events/child"; // private static final String EVENT = ENDPOINT + "/v1/events"; // replace id // "/v1/events?event_id={id}" // private static final String OAUTH = ENDPOINT + "/v1/oauth2/token"; // private static final String PASSWORD = ENDPOINT + "/v1/passwords"; // private static final String STATUS = ENDPOINT + "/v1/status"; // private static final String TOKENINFO = ENDPOINT + "/v1/oauth2/token/info"; // // private static final String MQTTTOKEN = "/v1/devices/tokens"; private static final String EVENT_ID = "event_id"; private static final String CHILD_ID = "child_id"; private static final String WEEK_OF = "week_of"; private static final String EVENT_TYPE = "event_type"; private static final String START_AGE_DAY = "start_age_day"; private static final String END_AGE_DAY = "end_age_day"; private static final String REPLACE_USER_ID = "{user_id}"; private static final String REPLACE_ACCOUNT_ID = "{account_id}"; private static final String REPLACE_CAREGIVER_ID = "{caregiver_id}"; private static final String REPLACE_SERIAL = "{serial}"; private static final String REPLACE_HANDHELD_ID = "{handheld_id}"; private static final String REPLACE_CHILD_ID = "{child_id}"; private static final String REPLACE_WEEK = "{week_of}"; private static final String REPLACE_EVENT_ID = "{event_id}"; private static final String REPLACE_ARTICLE_ID = "{article_id}"; /** * New Endpoint */ // private static final String ENDPOINT = PROTOCOL_SECURE + "api-dev.us.sproutlingcloud.com"; // private static final String ENDPOINT = PROTOCOL + "api-dev-us.sproutlingcloud.com"; // private static final String ENDPOINT = PROTOCOL + "api-dev-cn.sproutlingcloud.com"; public static String ENDPOINT = BuildConfig.SERVER_URL; private SSManagement() { } public static String getChildrenEventsUrl(String childId) { return CHILDREN_EVENTS.replace(REPLACE_CHILD_ID, childId); } public static String getTimelineEventsUrl() { return EVENTS; } private static String getUserAgent() { return "Sproutling/" + BuildConfig.VERSION_NAME + " " + "(Linux; U; Android " + Build.VERSION.RELEASE + ")"; } private static Http getHttpUrl(String url) { if (BuildConfig.DEBUG) { Log.d(TAG, "HTTP Request: " + url); } return Http.url(url) .accept(Http.APPLICATION_JSON) .contentType(Http.APPLICATION_JSON) .header("User-Agent", getUserAgent()) .header("X-TIMEZONE", Utils.getTimeZoneInShort()) .header("Accept-Language", Utils.getLanguageWithCountry()) .timeout(20000); } private static Http getHttpUrlWithToken(String url, String token) { if (BuildConfig.DEBUG) { Log.d(TAG, "HTTP Request: " + url); Log.d(TAG, "Access Token: " + token); } return getHttpUrl(url).authorization(AUTH_PREFIX + token); } static User loginByPassword(String username, String password) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + OAUTH) .post(new JSONObject() .put("username", username) .put("password", <PASSWORD>) .put("grant_type", "password") .put("client_id", CLIENT_ID) .put("scope", null)); checkResponseForError(httpContent); return new User(httpContent.json()); } static User refreshToken(String accessToken, String refreshToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + OAUTH, accessToken) .post(new JSONObject() .put("refresh_token", refreshToken) .put("grant_type", "refresh_token") .put("client_id", CLIENT_ID) .put("scope", null)); checkResponseForError(httpContent); return new User(httpContent.json()); } static User getTokenInfo(String accessToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + TOKENINFO, accessToken) .get(); checkResponseForError(httpContent); return new User(httpContent.json()); } static boolean logout(String accessToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + LOGOUT, accessToken) .post(new JSONObject()); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static UserAccountInfo createUser(String email, String firstName, String lastName, String type, String password, String phone, String inviteToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + USERS) .post(new JSONObject() .put("email", email) .put("first_name", firstName) .put("last_name", lastName) .put("role", type) .put("password", <PASSWORD>) .put("password_confirmation", <PASSWORD>) .put("phone_number", phone) .put("invite_token", inviteToken) ); checkResponseForError(httpContent); return new UserAccountInfo(httpContent.json()); } static UserAccountInfo getUserById(String accessToken, String userId) throws IOException, JSONException, SSException { String userUrl = ENDPOINT + USER; HttpContent httpContent = getHttpUrlWithToken(userUrl.replace(REPLACE_USER_ID, userId), accessToken) .get(); checkResponseForError(httpContent); return new UserAccountInfo(httpContent.json()); } static UserAccountInfo updateUserById(String accessToken, String userId, JSONObject body) throws IOException, JSONException, SSException { String userUrl = ENDPOINT + USER; HttpContent httpContent = getHttpUrlWithToken(userUrl.replace(REPLACE_USER_ID, userId), accessToken) .put(body); checkResponseForError(httpContent); return new UserAccountInfo(httpContent.json()); } static boolean deleteUserById(String accessToken, String userId) throws IOException, JSONException, SSException { String userUrl = ENDPOINT + USER; HttpContent httpContent = getHttpUrlWithToken(userUrl.replace(REPLACE_USER_ID, userId), accessToken) .delete(); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static UserAccountInfo updateAlert(String accessToken, String userId, JSONObject body) throws IOException, JSONException, SSException { String alertUrl = ENDPOINT + ALERTS; HttpContent httpContent = getHttpUrlWithToken(alertUrl.replace(REPLACE_USER_ID, userId), accessToken) .put(body); checkResponseForError(httpContent); return new UserAccountInfo(httpContent.json()); } static String invitations(String accessToken, String accountId) throws IOException, JSONException, SSException { String invitationUrl = ENDPOINT + INVITATIONS; HttpContent httpContent = getHttpUrlWithToken(invitationUrl.replace(REPLACE_ACCOUNT_ID, accountId), accessToken) .post(new JSONObject()); checkResponseForError(httpContent); return checkResponseForInviteToken(httpContent); } static List<UserAccountInfo> listCaregivers(String accessToken, String accountId) throws IOException, JSONException, SSException { String url = ENDPOINT + CAREGIVERS; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_ACCOUNT_ID, accountId), accessToken) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<UserAccountInfo> caregiverList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { caregiverList.add(new UserAccountInfo((JSONObject) jsonArray.get(i))); } return caregiverList; } static boolean removeCaregiver(String accessToken, String accountId, String caregiverId) throws IOException, JSONException, SSException { String url = ENDPOINT + CAREGIVER; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_ACCOUNT_ID, accountId).replace(REPLACE_CAREGIVER_ID, caregiverId), accessToken) .delete(); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static Child createChild(String accessToken, String firstName, String lastName, String gender, String birthDate, String dueDate) throws JSONException, IOException, SSException { String url = ENDPOINT + CHILDREN; HttpContent httpContent = getHttpUrlWithToken(url, accessToken) .post(new JSONObject() .put("first_name", firstName) .put("last_name", lastName) .put("gender", gender) .put("birth_date", birthDate) .put("due_date", dueDate) ); checkResponseForError(httpContent); return new Child(httpContent.json()); } static List<Child> listChildren(String accessToken) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILDREN; HttpContent httpContent = getHttpUrlWithToken(url, accessToken).get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<Child> childrenList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { childrenList.add(new Child((JSONObject) jsonArray.get(i))); } return childrenList; } static Child getChildById(String accessToken, String childId) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .get(); checkResponseForError(httpContent); return new Child(httpContent.json()); } static Child updateChildById(String accessToken, String childId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .put(body); Log.d(TAG, "updateChildById BODY : " + body.toString(2)); checkResponseForError(httpContent); return new Child(httpContent.json()); } static boolean deleteChildById(String accessToken, String childId) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .delete(); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static void uploadChildPhoto(String accessToken, String childId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + PHOTO; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .post(body); checkResponseForError(httpContent); } static void downloadChildPhoto(String accessToken, String childId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + PHOTO; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .post(body); checkResponseForError(httpContent); } static boolean requestPin(String phoneNumber) throws JSONException, IOException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + PIN) .post(new JSONObject() .put("phone_number", phoneNumber) ); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static boolean validatePin(String phoneNumber, String pin) throws JSONException, IOException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + VALIDATE_PIN) .post(new JSONObject() .put("phone_number", phoneNumber) .put("pin", pin) ); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static boolean resetPassword(String phoneNumber, String pin, String password, String passwordConfirmation) throws JSONException, IOException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + RESET_PASSWORD) .put(new JSONObject() .put("phone_number", phoneNumber) .put("pin", pin) .put("password", <PASSWORD>) .put("password_confirmation", passwordConfirmation) ); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static DeviceResponse createDevice(String accessToken, JSONObject body) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + DEVICES, accessToken) .post(body); checkResponseForError(httpContent); return new DeviceResponse(httpContent.json()); } static List<DeviceResponse> listDevices(String accessToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + DEVICES, accessToken) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<DeviceResponse> deviceList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { deviceList.add(new DeviceResponse((JSONObject) jsonArray.get(i))); } return deviceList; } static DeviceResponse getDeviceBySerial(String accessToken, String serial) throws IOException, JSONException, SSException { String url = ENDPOINT + DEVICE; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_SERIAL, serial), accessToken) .get(); checkResponseForError(httpContent); return new DeviceResponse(httpContent.json()); } static DeviceResponse updateDevice(String accessToken, String serial, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + DEVICE; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_SERIAL, serial), accessToken) .put(body); checkResponseForError(httpContent); return new DeviceResponse(httpContent.json()); } static boolean deleteDeviceBySerial(String accessToken, String serial) throws IOException, JSONException, SSException { String url = ENDPOINT + DEVICE; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_SERIAL, serial), accessToken) .delete(); checkResponseForError(httpContent); return checkResponseForStatus(httpContent); } static SSEvent createEvent(String accessToken, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + EVENTS; HttpContent httpContent = getHttpUrlWithToken(url, accessToken) .post(body); checkResponseForError(httpContent); return new SSEvent(httpContent.json()); } static List<SSEvent> listEventsByChild(String accessToken, String childId) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILDREN_EVENTS; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<SSEvent> eventList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { eventList.add(SSEvent.parseEvent((JSONObject) jsonArray.get(i))); // eventList.add(new SSEvent((JSONObject) jsonArray.get(i))); } return eventList; } static List<SSEvent> listEventsByChild(String accessToken, String childId, String eventType) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILDREN_EVENTS; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .parameter("event_type", eventType) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<SSEvent> eventList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { eventList.add(SSEvent.parseEvent((JSONObject) jsonArray.get(i))); // eventList.add(new SSEvent((JSONObject) jsonArray.get(i))); } return eventList; } static SSEvent getEventById(String accessToken, String eventId) throws IOException, JSONException, SSException { String url = ENDPOINT + EVENT; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_EVENT_ID, eventId), accessToken) .get(); checkResponseForError(httpContent); return SSEvent.parseEvent(httpContent.json()); // return new SSEvent(httpContent.json()); } static SSEvent updateEventById(String accessToken, String eventId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + EVENT; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_EVENT_ID, eventId), accessToken) // .keepParametersQuery() .put(body); checkResponseForError(httpContent); return SSEvent.parseEvent(httpContent.json()); // return new SSEvent(httpContent.json()); } static List<SSEvent> getEventsByWeek(String accessToken, String childId, String eventType, String weekOf) throws IOException, JSONException, SSException { String url = ENDPOINT + CHILDREN_EVENTS; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_CHILD_ID, childId), accessToken) .parameter(EVENT_TYPE, eventType) .parameter(WEEK_OF, weekOf) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<SSEvent> eventList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { eventList.add(SSEvent.parseEvent((JSONObject) jsonArray.get(i))); // eventList.add(new SSEvent((JSONObject) jsonArray.get(i))); } return eventList; } static boolean deleteEventById(String accessToken, String eventId) throws IOException, JSONException, SSException { String url = ENDPOINT + EVENT; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_EVENT_ID, eventId), accessToken) .delete(); checkResponseForError(httpContent); return true; } static List<SSArticle> listArticles(String accessToken, int startAgeDay, int endAgeDay) throws IOException, JSONException, SSException { String url = ENDPOINT + ARTICLES; HttpContent httpContent = getHttpUrlWithToken(url, accessToken) .parameter(START_AGE_DAY, startAgeDay) .parameter(END_AGE_DAY, endAgeDay) .get(); checkResponseForError(httpContent); JSONArray jsonArray = httpContent.jsonArray(); List<SSArticle> articles = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { articles.add(new SSArticle((JSONObject) jsonArray.get(i))); } return articles; } static SSArticle getArticleById(String accessToken, String articleId) throws IOException, JSONException, SSException { String url = ENDPOINT + ARTICLE; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_ARTICLE_ID, articleId), accessToken) .get(); checkResponseForError(httpContent); return new SSArticle(httpContent.json()); } static void createHandheld(String accessToken) throws IOException, JSONException, SSException { String url = ENDPOINT + HANDHELDS; HttpContent httpContent = getHttpUrlWithToken(url, accessToken) .post(new JSONObject()); // Required fields // \"uuid\": \"cbb58a2a-8f05-4221-bc5a-315ef7579f6f\", // \"token\": \"<KEY>\", // \"name\": \"Lisa\'s iPhone 6\", // \"locale\": \"en_US\", // \"language\": \"en-US\", // \"timezone\": \"PST\", checkResponseForError(httpContent); } static void listHandheld(String accessToken) throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrlWithToken(ENDPOINT + HANDHELDS, accessToken) .get(); checkResponseForError(httpContent); } static void getHandheldById(String accessToken, String handheldId) throws IOException, JSONException, SSException { String url = ENDPOINT + HANDHELD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_HANDHELD_ID, handheldId), accessToken) .get(); checkResponseForError(httpContent); } static void updateHandheldById(String accessToken, String handheldId, JSONObject body) throws IOException, JSONException, SSException { String url = ENDPOINT + HANDHELD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_HANDHELD_ID, handheldId), accessToken) .put(body); checkResponseForError(httpContent); } static void deleteHandheldById(String accessToken, String handheldId) throws IOException, JSONException, SSException { String url = ENDPOINT + HANDHELD; HttpContent httpContent = getHttpUrlWithToken(url.replace(REPLACE_HANDHELD_ID, handheldId), accessToken) .delete(); checkResponseForError(httpContent); } static UpdateInfo getUpdateInfo() throws IOException, JSONException, SSException { HttpContent httpContent = getHttpUrl(ENDPOINT + UPDATE) .get(); checkResponseForError(httpContent); return new UpdateInfo(httpContent.json()); } static EOLData getEOLData() throws IOException, JSONException, SSException { //TODO remove this once we have the final API for Sproutling EOL :( HttpContent httpContent = getHttpUrl("https://s3-us-west-1.amazonaws.com/sproutling-app/eol.json") .get(); checkResponseForError(httpContent); return new EOLData(httpContent.json()); } private static void checkResponseForError(HttpContent httpContent) throws JSONException, SSException { if (BuildConfig.DEBUG) { Log.e(TAG, "HTTP Response(" + httpContent.responseCode() + "): " + httpContent.string()); } int responseCode = httpContent.responseCode(); if (responseCode >= 400 && responseCode <= 404) { String content = httpContent.string(); if (content != null && content.contains("error")) throw new SSException(new SSError(httpContent.json()), responseCode); throw new SSRequestException(new SSError(), responseCode); } else if (responseCode >= 500 && responseCode <= 503) { throw new SSServerException(new SSError(), responseCode); } else if (httpContent.string() != null && httpContent.string().contains("error")) { throw new SSException(new SSError(httpContent.json()), responseCode); } } private static boolean checkResponseForStatus(HttpContent httpContent) throws JSONException, SSException { if (BuildConfig.DEBUG) { Log.d(TAG, "HTTP Response(" + httpContent.responseCode() + "): " + httpContent.string()); } if (SSStatus.hasStatus(httpContent.string())) { SSStatus status = new SSStatus(httpContent.json()); return status.isSuccess(); } return false; } private static String checkResponseForInviteToken(HttpContent httpContent) throws JSONException, SSException { if (BuildConfig.DEBUG) { Log.d(TAG, "HTTP Response(" + httpContent.responseCode() + "): " + httpContent.string()); } if (SSStatus.hasStatus(httpContent.string())) { SSStatus status = new SSStatus(httpContent.json()); return status.isSuccess() ? httpContent.json().getString("token") : null; } return null; } public static class DeviceResponse { private String id; private String ownerId; private String accountId; private String name; private String serial; private String firmwareVersion; private String createdAt; private String updatedAt; private String ownerType; public DeviceResponse() { } public DeviceResponse(JSONObject jsonObject) throws JSONException { id = jsonObject.getString("id"); accountId = jsonObject.getString("account_id"); ownerId = jsonObject.getString("owner_id"); ownerType = jsonObject.getString("owner_type"); name = jsonObject.getString("name"); serial = jsonObject.getString("serial"); firmwareVersion = jsonObject.getString("firmware_version"); createdAt = jsonObject.getString("created_at"); updatedAt = jsonObject.getString("updated_at"); } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } public String getOwnerType() { return ownerType; } public void setOwnerType(String ownerType) { this.ownerType = ownerType; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public String getFirmwareVersion() { return firmwareVersion; } public void setFirmwareVersion(String firmwareVersion) { this.firmwareVersion = firmwareVersion; } } // Processing // Processed Objects public static class UserAccountInfo { public String id; public String accountId; public String firstName; public String lastName; public String email; public String phone; public String inviteToken; public String type; public String createdAt; public String updatedAt; public PushNotification alert; public String jsonString; public UserAccountInfo() { } public UserAccountInfo(JSONObject jsonObject) throws JSONException { id = jsonObject.getString("id"); accountId = jsonObject.getString("account_id"); firstName = jsonObject.getString("first_name"); lastName = jsonObject.getString("last_name"); email = jsonObject.getString("email"); phone = jsonObject.getString("phone_number"); inviteToken = jsonObject.optString("invite_token"); type = jsonObject.getString("role"); createdAt = jsonObject.getString("created_at"); updatedAt = jsonObject.getString("updated_at"); JSONObject pnSettingsJSONObject = jsonObject.optJSONObject("push_notification_alert_settings"); alert = pnSettingsJSONObject != null ? new PushNotification(pnSettingsJSONObject) : null; jsonString = jsonObject.toString(); } public String toJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", id); jsonObject.put("account_id", accountId); jsonObject.put("first_name", firstName); jsonObject.put("last_name", lastName); jsonObject.put("email", email); jsonObject.put("phone_number", phone); jsonObject.put("invite_token", inviteToken); jsonObject.put("role", type); jsonObject.put("created_at", createdAt); jsonObject.put("updated_at", updatedAt); jsonObject.put("push_notification_alert_settings", alert); return jsonObject.toString(); } @Override public String toString() { return jsonString; } } public static class PushNotification { public static final String ENABLED = "0"; public static final String DISABLED = "1"; public static final String DEFAULT_NOTIFICATIONS_DISABLED = "0"; public static final String DEFAULT_ROLLEDOVER_DISABLED = "0"; public static final String DEFAULT_UNUSUAL_HEARTBEAT_DISABLED = "0"; public static final String DEFAULT_AWAKE_DISABLED = "0"; public static final String DEFAULT_ASLEEP_DISABLED = "1"; // public static final String DEFAULT_STIRRING_DISABLED = "1"; public static final String DEFAULT_WEARABLE_FELL_OFF_DISABLED = "0"; public static final String DEFAULT_WEARABLE_NOT_FOUND_DISABLED = "1"; public static final String DEFAULT_WEARABLE_TOO_FAR_AWAY_DISABLED = "1"; public static final String DEFAULT_BATTERY_DISABLED = "1"; public static final String DEFAULT_OUT_OF_BATTERY_DISABLED = "1"; public static final String DEFAULT_HUB_OFFLINE_DISABLED = "1"; public String notificationsDisabled; public String rolledOverDisabled; public String unusualHeartbeatDisabled; public String awakeDisabled; public String asleepDisabled; // public String stirringDisabled; public String wearableFellOffDisabled; public String wearableNotFoundDisabled; public String wearableTooFarAwayDisabled; public String batteryDisabled; public String outOfBatteryDisabled; public String hubOfflineDisabled; public String roomTemperatureDisabled; public String roomHumidityDisabled; public String roomNoiseLevelDisabled; public String roomLightLevelDisabled; public String jsonString; public PushNotification() { } public PushNotification(JSONObject jsonObject) throws JSONException { notificationsDisabled = jsonObject.optString("NotificationsDisabled", "0"); rolledOverDisabled = jsonObject.optString("RolledoverDisabled", "0"); unusualHeartbeatDisabled = jsonObject.optString("UnusualHeartbeatDisabled", "0"); awakeDisabled = jsonObject.optString("AwakeDisabled", "0"); asleepDisabled = jsonObject.optString("AsleepDisabled", "0"); // stirringDisabled = jsonObject.optString("StirringDisabled", "0"); wearableFellOffDisabled = jsonObject.optString("WearableFellOffDisabled", "0"); wearableNotFoundDisabled = jsonObject.optString("WearableNotFoundDisabled", "0"); wearableTooFarAwayDisabled = jsonObject.optString("WearableTooFarAwayDisabled", "0"); batteryDisabled = jsonObject.optString("BatteryDisabled", "0"); outOfBatteryDisabled = jsonObject.optString("OutOfBatteryDisabled", "0"); hubOfflineDisabled = jsonObject.optString("HubOfflineDisabled", "0"); roomTemperatureDisabled = jsonObject.optString("RoomTemperatureDisabled", "0"); roomHumidityDisabled = jsonObject.optString("RoomHumidityDisabled", "0"); roomLightLevelDisabled = jsonObject.optString("RoomLightLevelDisabled", "0"); roomNoiseLevelDisabled = jsonObject.optString("RoomNoiseLevelDisabled", "0"); jsonString = jsonObject.toString(); } public static PushNotification getDefaultSettings() { PushNotification settings = new PushNotification(); settings.notificationsDisabled = DEFAULT_NOTIFICATIONS_DISABLED; settings.rolledOverDisabled = DEFAULT_ROLLEDOVER_DISABLED; settings.unusualHeartbeatDisabled = DEFAULT_UNUSUAL_HEARTBEAT_DISABLED; settings.awakeDisabled = DEFAULT_AWAKE_DISABLED; settings.asleepDisabled = DEFAULT_ASLEEP_DISABLED; // settings.stirringDisabled = DEFAULT_STIRRING_DISABLED; settings.wearableFellOffDisabled = DEFAULT_WEARABLE_FELL_OFF_DISABLED; settings.wearableNotFoundDisabled = DEFAULT_WEARABLE_NOT_FOUND_DISABLED; settings.wearableTooFarAwayDisabled = DEFAULT_WEARABLE_TOO_FAR_AWAY_DISABLED; settings.batteryDisabled = DEFAULT_BATTERY_DISABLED; settings.outOfBatteryDisabled = DEFAULT_OUT_OF_BATTERY_DISABLED; settings.hubOfflineDisabled = DEFAULT_HUB_OFFLINE_DISABLED; return settings; } public static JSONObject getDefaultSettingsJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("NotificationsDisabled", DEFAULT_NOTIFICATIONS_DISABLED); jsonObject.put("RolledoverDisabled", DEFAULT_ROLLEDOVER_DISABLED); jsonObject.put("UnusualHeartbeatDisabled", DEFAULT_UNUSUAL_HEARTBEAT_DISABLED); jsonObject.put("AwakeDisabled", DEFAULT_AWAKE_DISABLED); jsonObject.put("AsleepDisabled", DEFAULT_ASLEEP_DISABLED); // jsonObject.put("StirringDisabled", DEFAULT_STIRRING_DISABLED); jsonObject.put("WearableFellOffDisabled", DEFAULT_WEARABLE_FELL_OFF_DISABLED); jsonObject.put("WearableNotFoundDisabled", DEFAULT_WEARABLE_NOT_FOUND_DISABLED); jsonObject.put("WearableTooFarAwayDisabled", DEFAULT_WEARABLE_TOO_FAR_AWAY_DISABLED); jsonObject.put("BatteryDisabled", DEFAULT_BATTERY_DISABLED); jsonObject.put("OutOfBatteryDisabled", DEFAULT_OUT_OF_BATTERY_DISABLED); jsonObject.put("HubOfflineDisabled", DEFAULT_HUB_OFFLINE_DISABLED); return jsonObject; } public static JSONObject getDefaultSettingsAPIJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("push_notification_alert_settings", getDefaultSettingsJSON()); return jsonObject; } public JSONObject getSettingsJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("NotificationsDisabled", notificationsDisabled); jsonObject.put("RolledoverDisabled", rolledOverDisabled); jsonObject.put("UnusualHeartbeatDisabled", unusualHeartbeatDisabled); jsonObject.put("AwakeDisabled", awakeDisabled); jsonObject.put("AsleepDisabled", asleepDisabled); // jsonObject.put("StirringDisabled", stirringDisabled); jsonObject.put("WearableFellOffDisabled", wearableFellOffDisabled); jsonObject.put("WearableNotFoundDisabled", wearableNotFoundDisabled); jsonObject.put("WearableTooFarAwayDisabled", wearableTooFarAwayDisabled); jsonObject.put("BatteryDisabled", batteryDisabled); jsonObject.put("OutOfBatteryDisabled", outOfBatteryDisabled); jsonObject.put("HubOfflineDisabled", hubOfflineDisabled); return jsonObject; } public JSONObject getSettingsAPIJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("push_notification_alert_settings", getSettingsJSON()); return jsonObject; } } public static class User { public String scope; public String resourceOwnerId; public String createdAt; public String tokenType; public int expiresIn; public String refreshToken; public String accessToken; public String jsonString; public User() { } public User(JSONObject jsonObject) throws JSONException { scope = jsonObject.optString("scope"); resourceOwnerId = jsonObject.getString("resource_owner_id"); createdAt = jsonObject.getString("created_at"); tokenType = jsonObject.getString("token_type"); expiresIn = jsonObject.getInt("expires_in"); refreshToken = jsonObject.optString("refresh_token"); accessToken = jsonObject.getString("access_token"); jsonString = jsonObject.toString(); } @Override public String toString() { return jsonString; } } public static class Child { public static final String GENDER_GIRL = "F"; public static final String GENDER_BOY = "M"; public static final String GENDER_UNKNOWN = "U"; public String id; public String accountId; public String firstName; public String lastName; public String gender; public String birthDate; public String dueDate; public String createdAt; public String updatedAt; public String twinId; public String photoUrl; public String jsonString; public Child() { } public Child(JSONObject jsonObject) throws JSONException { id = jsonObject.optString("id"); accountId = jsonObject.getString("account_id"); firstName = jsonObject.getString("first_name"); lastName = jsonObject.getString("last_name"); gender = jsonObject.getString("gender"); birthDate = jsonObject.optString("birth_date"); dueDate = jsonObject.getString("due_date"); createdAt = jsonObject.getString("created_at"); updatedAt = jsonObject.getString("updated_at"); twinId = jsonObject.optString("twin_id"); photoUrl = jsonObject.getString("photo_url"); jsonString = jsonObject.toString(); } public JSONObject toJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", id); jsonObject.put("account_id", accountId); jsonObject.put("first_name", firstName); jsonObject.put("last_name", lastName); jsonObject.put("gender", gender); jsonObject.put("birth_date", birthDate); jsonObject.put("due_date", dueDate); jsonObject.put("created_at", createdAt); jsonObject.put("updated_at", updatedAt); jsonObject.put("twin_id", twinId); jsonObject.put("photo_url", photoUrl); return jsonObject; } public boolean isMale() { return GENDER_BOY.equalsIgnoreCase(gender); } @Override public String toString() { return jsonString; } } public static class SSEvent { public static final String TYPE_LEARNING_PERIOD = "learningPeriod"; public static final String TYPE_NAP = "nap"; public static final String TYPE_HEART_RATE = "heartRate"; public String id; public String childId; public String eventType; public String startDate; public String endDate; public String createdAt; public String updatedAt; // public String data; public String jsonString; public SSEvent() { } public SSEvent(JSONObject jsonObject) throws JSONException { id = jsonObject.getString("id"); childId = jsonObject.getString("child_id"); eventType = jsonObject.getString("event_type"); startDate = jsonObject.getString("start_date"); endDate = jsonObject.getString("end_date"); createdAt = jsonObject.getString("created_at"); updatedAt = jsonObject.getString("updated_at"); // data = jsonObject.getString("data"); jsonString = jsonObject.toString(); } public static SSEvent parseEvent(JSONObject jsonObject) throws JSONException { return isNapEvent(jsonObject) ? new SSNap(jsonObject) : new SSEvent(jsonObject); } static boolean isNapEvent(JSONObject data) { return data.toString().contains(TYPE_NAP); } @Override public String toString() { return jsonString; } } public static class SSNap extends SSEvent implements Serializable { public List<Spell> spells; public SSNap() { super(); } public SSNap(JSONObject jsonObject) throws JSONException { super(jsonObject); parseData(jsonObject.optJSONObject("data")); } void parseData(JSONObject data) throws JSONException { if (data != null) { spells = new ArrayList<>(); JSONArray spellsJSONArray = data.getJSONArray("spells"); for (int i = 0; i < spellsJSONArray.length(); i++) { spells.add(new Spell((JSONObject) spellsJSONArray.get(i))); } } } public List<Spell> getSpells() { return spells; } public int getNumOfWakings() { int count = 0; for (Spell spell : spells) { count = spell.isWake() ? ++count : count; } return count; } public long getTimeAwake() { long time = 0; for (Spell spell : spells) { time = spell.isWake() ? time + spell.getDuration() : time; } return time; } public long getTimeAsleep() { long time = 0; for (Spell spell : spells) { time = spell.isSleep() ? time + spell.getDuration() : time; } return time; } public long getTimeStirring() { long time = 0; for (Spell spell : spells) { time = spell.isStirring() ? time + spell.getDuration() : time; } return time; } public static class Spell implements Serializable { public static final int TYPE_SLEEP = 0; public static final int TYPE_STIRRING = 1; public static final int TYPE_WAKE = 2; TimeZone tz = TimeZone.getTimeZone("PDT"); Calendar startTime = Calendar.getInstance(); Calendar endTime = Calendar.getInstance(); int type; public Spell() { } public Spell(JSONObject jsonObject) throws JSONException { try { startTime.setTime(DateTimeUtils.parseSpellDate(jsonObject.getString("start_ts"))); endTime.setTime(DateTimeUtils.parseSpellDate(jsonObject.getString("end_ts"))); startTime.setTimeZone(tz); endTime.setTimeZone(tz); type = jsonObject.getInt("swstatus"); } catch (ParseException e) { e.printStackTrace(); } } public Calendar getStartTime() { return startTime; } public void setStartTime(Calendar calendar) { startTime = calendar; } public Calendar getEndTime() { return endTime; } public void setEndTime(Calendar calendar) { endTime = calendar; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getDuration() { return endTime.getTimeInMillis() - startTime.getTimeInMillis(); } public boolean isSleep() { return type == TYPE_SLEEP; } public boolean isStirring() { return type == TYPE_STIRRING; } public boolean isWake() { return type == TYPE_WAKE; } } } public static class SSArticle { public String id; public String language; public int childAge; public String title; public String url; public String imageThumbnailUrl; public String imageSmallUrl; public String imageMediumUrl; public String imageLargeUrl; public String createdAt; public String jsonString; public SSArticle() { } private SSArticle(JSONObject jsonObject) throws JSONException { id = jsonObject.getString("id"); language = jsonObject.getString("language"); childAge = jsonObject.getInt("child_age"); title = jsonObject.getString("title"); url = jsonObject.getString("url"); imageThumbnailUrl = jsonObject.getString("image_thumbnail"); imageSmallUrl = jsonObject.getString("image_small"); imageMediumUrl = jsonObject.getString("image_medium"); imageLargeUrl = jsonObject.getString("image_large"); createdAt = jsonObject.getString("created_at"); jsonString = jsonObject.toString(); } @Override public String toString() { return jsonString; } } public static class EOLData { public String popUpText; public String settingsPopUpTxt; public String settingsPopUpEmail; public String settingsPopUpSupportWebsite; public String postEOLPopUpText; public String isEOL; public String jsonString; public EOLData() { } private EOLData(JSONObject jsonObject) throws JSONException { popUpText = jsonObject.getString("app_launch_popup_notice_text"); settingsPopUpTxt = jsonObject.getString("settings_popup_text"); settingsPopUpEmail = jsonObject.getString("settings_popup_support_email"); settingsPopUpSupportWebsite = jsonObject.getString("settings_popup_support_website"); postEOLPopUpText = jsonObject.getString("post_eol_app_launch_popup_notice_text"); isEOL = jsonObject.getString("is_eol"); jsonString = jsonObject.toString(); } @Override public String toString() { return jsonString; } } public static class UpdateInfo { // private ApiInfo apiInfo; // private IosInfo iosInfo; public AndroidInfo androidInfo; private String jsonString; public UpdateInfo() { } private UpdateInfo(JSONObject jsonObject) throws JSONException { // apiInfo = new ApiInfo(jsonObject.getJSONObject("api")); // iosInfo = new IosInfo(jsonObject.getJSONObject("ios")); androidInfo = new AndroidInfo(jsonObject.getJSONObject("android")); jsonString = jsonObject.toString(); } @Override public String toString() { return jsonString; } // private class ApiInfo { // private String currentVersion; // public String minRequiredVersion; // // private ApiInfo(JSONObject jsonObject) throws JSONException { // currentVersion = jsonObject.getString("current_version"); // minRequiredVersion = jsonObject.getString("min_required_version"); // } // } // private class IosInfo { // private String currentVersion; // public String minRequiredVersion; // private String updateUrl; // // private IosInfo(JSONObject jsonObject) throws JSONException { // currentVersion = jsonObject.getString("current_version"); // minRequiredVersion = jsonObject.getString("min_required_version"); // updateUrl = jsonObject.getString("update_url"); // } // } public class AndroidInfo { public int minRequiredVersion; public String updateUrl; private int currentVersion; private AndroidInfo(JSONObject jsonObject) throws JSONException { currentVersion = jsonObject.getInt("current_version"); minRequiredVersion = jsonObject.getInt("min_required_version"); updateUrl = jsonObject.getString("update_url"); } } } }
55,762
0.636896
0.631916
1,344
40.529762
33.704212
199
false
false
0
0
0
0
64
0.00344
0.747768
false
false
7
b8965b2e511e6b9698838f294f9cecc23f256a83
21,440,476,792,446
80536099392038463c7f6af0b2f1b86603c74808
/src/test/java/lotto/domain/result/GameResultTest.java
4d95878095907e91de0f1fd417e9ad048cf494ef
[]
no_license
chae-heechan/java-lotto-1
https://github.com/chae-heechan/java-lotto-1
47cab817a88ebd4b021e8f59ff5280dda9c3c9c2
2e40f105de298aa74e2655229f37b6c8b4818c6b
refs/heads/main
2023-04-06T20:04:03.347000
2021-04-09T21:52:33
2021-04-09T21:52:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lotto.domain.result; import lotto.domain.MatchCount; import lotto.domain.result.GameResult; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.*; class GameResultTest { @DisplayName("일치 결과에 따른 GameResult 생성 테스트") @MethodSource(value = "provideEvaluate") @ParameterizedTest(name = "matchCount = {0}, isBonusMatch = {1}, expected = {2}") void evaluate(int count, boolean isBonusMatch, GameResult expected) { //given MatchCount matchCount = new MatchCount(count, isBonusMatch); //when GameResult gameResult = GameResult.evaluate(matchCount); //then assertThat(gameResult).isEqualTo(expected); } private static Stream<Arguments> provideEvaluate() { return Stream.of( Arguments.of(0, true, GameResult.UNDER_THREE_MATCHED), Arguments.of(0, false, GameResult.UNDER_THREE_MATCHED), Arguments.of(1, true, GameResult.UNDER_THREE_MATCHED), Arguments.of(1, false, GameResult.UNDER_THREE_MATCHED), Arguments.of(2, true, GameResult.UNDER_THREE_MATCHED), Arguments.of(2, false, GameResult.UNDER_THREE_MATCHED), Arguments.of(3, true, GameResult.THREE_MATCHED), Arguments.of(3, false, GameResult.THREE_MATCHED), Arguments.of(4, true, GameResult.FOUR_MATCHED), Arguments.of(4, false, GameResult.FOUR_MATCHED), Arguments.of(5, true, GameResult.FIVE_MATCHED_WITH_BONUS), Arguments.of(5, false, GameResult.FIVE_MATCHED_WITHOUT_BONUS), Arguments.of(6, false, GameResult.ALL_MATCHED) ); } @DisplayName("비정상적인 일치 결과에 따른 예외 발생") @Test void evaluateException() { //given MatchCount matchCount = new MatchCount(7, true); //when //then assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> GameResult.evaluate(matchCount)) .withMessage("일치하는 게임 결과가 없습니다."); } @DisplayName("description getter 테스트") @Test void getDescription() { //given GameResult gameResult = GameResult.ALL_MATCHED; //when then assertThat(gameResult.getDescription()).isEqualTo("6개 일치"); } }
UTF-8
Java
2,654
java
GameResultTest.java
Java
[]
null
[]
package lotto.domain.result; import lotto.domain.MatchCount; import lotto.domain.result.GameResult; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.*; class GameResultTest { @DisplayName("일치 결과에 따른 GameResult 생성 테스트") @MethodSource(value = "provideEvaluate") @ParameterizedTest(name = "matchCount = {0}, isBonusMatch = {1}, expected = {2}") void evaluate(int count, boolean isBonusMatch, GameResult expected) { //given MatchCount matchCount = new MatchCount(count, isBonusMatch); //when GameResult gameResult = GameResult.evaluate(matchCount); //then assertThat(gameResult).isEqualTo(expected); } private static Stream<Arguments> provideEvaluate() { return Stream.of( Arguments.of(0, true, GameResult.UNDER_THREE_MATCHED), Arguments.of(0, false, GameResult.UNDER_THREE_MATCHED), Arguments.of(1, true, GameResult.UNDER_THREE_MATCHED), Arguments.of(1, false, GameResult.UNDER_THREE_MATCHED), Arguments.of(2, true, GameResult.UNDER_THREE_MATCHED), Arguments.of(2, false, GameResult.UNDER_THREE_MATCHED), Arguments.of(3, true, GameResult.THREE_MATCHED), Arguments.of(3, false, GameResult.THREE_MATCHED), Arguments.of(4, true, GameResult.FOUR_MATCHED), Arguments.of(4, false, GameResult.FOUR_MATCHED), Arguments.of(5, true, GameResult.FIVE_MATCHED_WITH_BONUS), Arguments.of(5, false, GameResult.FIVE_MATCHED_WITHOUT_BONUS), Arguments.of(6, false, GameResult.ALL_MATCHED) ); } @DisplayName("비정상적인 일치 결과에 따른 예외 발생") @Test void evaluateException() { //given MatchCount matchCount = new MatchCount(7, true); //when //then assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> GameResult.evaluate(matchCount)) .withMessage("일치하는 게임 결과가 없습니다."); } @DisplayName("description getter 테스트") @Test void getDescription() { //given GameResult gameResult = GameResult.ALL_MATCHED; //when then assertThat(gameResult.getDescription()).isEqualTo("6개 일치"); } }
2,654
0.650391
0.643359
59
42.40678
24.031137
85
false
false
0
0
0
0
0
0
1.050847
false
false
7
190f690c7397f98065e8d6412468d33500b04cc3
21,440,476,789,483
d6717415d1275c02024f5f3e320e4372941de1c1
/app/src/main/java/com/acuteksolutions/uhotel/ui/fragment/concierge/HouseFragment.java
4b4bb7d3301bc4ba0f5ecc2e2303f7bd7414c882
[ "MIT" ]
permissive
ToanMobile/uHotel
https://github.com/ToanMobile/uHotel
038ce8363ce46f3eb9073767a00afe8cbe449775
240c9d28132ed8246144aabb45e54877ea87277f
refs/heads/master
2021-08-23T01:42:39.892000
2017-12-02T07:32:58
2017-12-02T07:32:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.acuteksolutions.uhotel.ui.fragment.concierge; import android.widget.ImageView; import android.widget.TextView; import com.acuteksolutions.uhotel.R; import com.acuteksolutions.uhotel.ui.fragment.base.BaseFragment; import butterknife.BindView; import butterknife.OnClick; /** * Created by Toan.IT * Date:22/04/2017 */ public class HouseFragment extends BaseFragment { @BindView(R.id.img_house) ImageView img_house; @BindView(R.id.txt_bottom) TextView txtBottom; private boolean isClicked; public static HouseFragment newInstance() { return new HouseFragment(); } @Override protected String getTAG() { return null; } @Override protected void injectDependencies() { } @Override protected void initViews() { } @Override protected int setLayoutResourceID() { return R.layout.concierge_house_fragment; } @Override protected void initData() { } @OnClick(R.id.img_house) void imageClick() { if (!isClicked) { img_house.setSelected(true); txtBottom.setText("Housekeeping coming!"); txtBottom.setTextColor(getResources().getColor(R.color.white)); isClicked = true; }else img_house.setSelected(false); } }
UTF-8
Java
1,209
java
HouseFragment.java
Java
[ { "context": "ew;\nimport butterknife.OnClick;\n\n/**\n * Created by Toan.IT\n * Date:22/04/2017\n */\npublic class HouseFragm", "end": 308, "score": 0.6955969333648682, "start": 304, "tag": "NAME", "value": "Toan" }, { "context": "mport butterknife.OnClick;\n\n/**\n * Created by Toan.IT\n * Date:22/04/2017\n */\npublic class HouseFragment", "end": 311, "score": 0.5758309364318848, "start": 309, "tag": "USERNAME", "value": "IT" } ]
null
[]
package com.acuteksolutions.uhotel.ui.fragment.concierge; import android.widget.ImageView; import android.widget.TextView; import com.acuteksolutions.uhotel.R; import com.acuteksolutions.uhotel.ui.fragment.base.BaseFragment; import butterknife.BindView; import butterknife.OnClick; /** * Created by Toan.IT * Date:22/04/2017 */ public class HouseFragment extends BaseFragment { @BindView(R.id.img_house) ImageView img_house; @BindView(R.id.txt_bottom) TextView txtBottom; private boolean isClicked; public static HouseFragment newInstance() { return new HouseFragment(); } @Override protected String getTAG() { return null; } @Override protected void injectDependencies() { } @Override protected void initViews() { } @Override protected int setLayoutResourceID() { return R.layout.concierge_house_fragment; } @Override protected void initData() { } @OnClick(R.id.img_house) void imageClick() { if (!isClicked) { img_house.setSelected(true); txtBottom.setText("Housekeeping coming!"); txtBottom.setTextColor(getResources().getColor(R.color.white)); isClicked = true; }else img_house.setSelected(false); } }
1,209
0.718776
0.712159
55
20.981817
20.400972
69
false
false
0
0
0
0
0
0
0.327273
false
false
7
fc3752cdffa43c5aed0e981fd0bc6fe194cdb104
5,866,925,373,649
0bfa21c0fb948c0d412d68c36fc5a79b3aab542f
/src/test/java/com/playtomic/tests/wallet/service/WalletServiceImplTest.java
bf4833edb41b8a77c4154c5fbf7caa22cdd9f803
[]
no_license
diegogomezlopez/playtomic-wallet
https://github.com/diegogomezlopez/playtomic-wallet
8dc5305579e0a3fc3f8485a82f708db83520e1d1
3fba9f047cb9f0d64c0329162a24dede9d4144f0
refs/heads/master
2023-08-25T02:21:11.159000
2021-09-16T12:25:38
2021-09-16T12:25:38
393,040,698
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.playtomic.tests.wallet.service; import com.playtomic.tests.wallet.converter.WalletConverter; import com.playtomic.tests.wallet.domain.Wallet; import com.playtomic.tests.wallet.dto.WalletDTO; import com.playtomic.tests.wallet.exception.WalletNotFoundException; import com.playtomic.tests.wallet.exception.WalletServiceException; import com.playtomic.tests.wallet.repository.WalletRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.math.BigDecimal; import java.util.Optional; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) public class WalletServiceImplTest { private static final Long ID = 1L; private static final BigDecimal BALANCE = new BigDecimal(100); @InjectMocks private WalletServiceImpl walletService; @Mock private WalletRepository walletRepository; @Mock private WalletConverter walletConverter; private Wallet wallet; private WalletDTO walletDTO; @BeforeEach public void setup() { wallet = Wallet.builder() .id(ID) .balance(BALANCE) .build(); walletDTO = WalletDTO.builder() .id(ID) .balance(BALANCE) .build(); } @Test public void findWalletById_whenWalletExists_thenReturnWallet() { when(walletRepository.findById(ID)).thenReturn(Optional.of(wallet)); Wallet wallet = walletService.findWalletById(ID); assertThat(wallet.getId()).isEqualTo(ID); assertThat(wallet.getBalance()).isEqualTo(BALANCE); } @Test public void findWalletById_whenWalletIdNull_thenThrowWalletServiceException() { Assertions.assertThrows(WalletServiceException.class, () -> walletService.findWalletById(null)); } @Test public void findWalletById_whenWalletNotExists_thenThrowWalletNotFoundException() { Assertions.assertThrows(WalletNotFoundException.class, () -> walletService.findWalletById(ID)); } @Test public void createWallet_whenWalletDTO_thenCreateWallet() { when(walletConverter.convertToEntity(walletDTO)).thenReturn(wallet); walletService.createWallet(walletDTO); verify(walletRepository, times(1)).save(wallet); } @Test public void getWallet_whenWalletExists_thenReturnWalletDTO() { when(walletRepository.findById(ID)).thenReturn(Optional.of(wallet)); walletService.getWallet(ID); verify(walletConverter, times(1)).convertToDTO(wallet); } }
UTF-8
Java
2,834
java
WalletServiceImplTest.java
Java
[]
null
[]
package com.playtomic.tests.wallet.service; import com.playtomic.tests.wallet.converter.WalletConverter; import com.playtomic.tests.wallet.domain.Wallet; import com.playtomic.tests.wallet.dto.WalletDTO; import com.playtomic.tests.wallet.exception.WalletNotFoundException; import com.playtomic.tests.wallet.exception.WalletServiceException; import com.playtomic.tests.wallet.repository.WalletRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.math.BigDecimal; import java.util.Optional; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) public class WalletServiceImplTest { private static final Long ID = 1L; private static final BigDecimal BALANCE = new BigDecimal(100); @InjectMocks private WalletServiceImpl walletService; @Mock private WalletRepository walletRepository; @Mock private WalletConverter walletConverter; private Wallet wallet; private WalletDTO walletDTO; @BeforeEach public void setup() { wallet = Wallet.builder() .id(ID) .balance(BALANCE) .build(); walletDTO = WalletDTO.builder() .id(ID) .balance(BALANCE) .build(); } @Test public void findWalletById_whenWalletExists_thenReturnWallet() { when(walletRepository.findById(ID)).thenReturn(Optional.of(wallet)); Wallet wallet = walletService.findWalletById(ID); assertThat(wallet.getId()).isEqualTo(ID); assertThat(wallet.getBalance()).isEqualTo(BALANCE); } @Test public void findWalletById_whenWalletIdNull_thenThrowWalletServiceException() { Assertions.assertThrows(WalletServiceException.class, () -> walletService.findWalletById(null)); } @Test public void findWalletById_whenWalletNotExists_thenThrowWalletNotFoundException() { Assertions.assertThrows(WalletNotFoundException.class, () -> walletService.findWalletById(ID)); } @Test public void createWallet_whenWalletDTO_thenCreateWallet() { when(walletConverter.convertToEntity(walletDTO)).thenReturn(wallet); walletService.createWallet(walletDTO); verify(walletRepository, times(1)).save(wallet); } @Test public void getWallet_whenWalletExists_thenReturnWalletDTO() { when(walletRepository.findById(ID)).thenReturn(Optional.of(wallet)); walletService.getWallet(ID); verify(walletConverter, times(1)).convertToDTO(wallet); } }
2,834
0.726535
0.724418
91
30.153847
27.647278
104
false
false
0
0
0
0
0
0
0.472527
false
false
7
95ed31aa6a3400efa62dece35c1adf4e3c33a1c4
5,866,925,371,705
68e50c58128c426ea1423623907a7001c6cd1122
/0prac/Prac2.java
da8b9d86d6b1b746667721ac21331b6ba7dee892
[]
no_license
RobersonGSU/Java-Stuff
https://github.com/RobersonGSU/Java-Stuff
47b6096ee808e024b8b1735232e4289cef5871b1
8ee4e7cb5d7362477d39ffd27c60911589e0a9d5
refs/heads/master
2020-03-26T09:47:13.955000
2018-08-14T19:39:33
2018-08-14T19:39:33
144,764,845
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Still june june 7 */ import java.util.*; import java.io.*; import javax.swing.*; import java.math.*; import java.net.*; public class Prac2{ public static void main(String[]args){ System.out.println("Program 2"); String random = "Man23"; Scanner in = new Scanner(System.in); System.out.println("Enter a name"); String name = in.next(); System.out.println("Your name is " + name + " ? "); System.out.println("Substring is " + name.substring(0, (name.length()/2))); System.out.println(Character.isDigit(random.charAt(2))); BigInteger j = new BigInteger("4"); BigInteger k = new BigInteger("532323"); BigInteger total = j.add(k); System.out.println(total); total = j.subtract(k); System.out.println(total); System.out.println("Enter the first integer "); double usersFirstInteger = in.nextDouble(); System.out.println("Enter the second integer"); double usersSecondInteger = in.nextDouble(); double product = usersFirstInteger * usersSecondInteger; double sum = usersFirstInteger * usersSecondInteger; double difference = usersFirstInteger - usersSecondInteger; double average = (usersFirstInteger + usersSecondInteger)/2; double distance = Math.abs(usersFirstInteger) - Math.abs(usersSecondInteger); distance = Math.abs(distance); double max = Math.max(usersFirstInteger,usersSecondInteger); double min = Math.min(usersFirstInteger,usersSecondInteger); System.out.printf("product : %10.2f \n sum : %10.2f \n difference : %10.2f \n average : %10.2f \n distance : %10.2f \n max : %10.2f \n min: %10.2f " , product , sum , difference , average , distance , max, min); int floor = 16; floor = floor < 13 ? floor : floor -1; System.out.println(" \n Floor is " + floor); } }
UTF-8
Java
1,850
java
Prac2.java
Java
[]
null
[]
/* Still june june 7 */ import java.util.*; import java.io.*; import javax.swing.*; import java.math.*; import java.net.*; public class Prac2{ public static void main(String[]args){ System.out.println("Program 2"); String random = "Man23"; Scanner in = new Scanner(System.in); System.out.println("Enter a name"); String name = in.next(); System.out.println("Your name is " + name + " ? "); System.out.println("Substring is " + name.substring(0, (name.length()/2))); System.out.println(Character.isDigit(random.charAt(2))); BigInteger j = new BigInteger("4"); BigInteger k = new BigInteger("532323"); BigInteger total = j.add(k); System.out.println(total); total = j.subtract(k); System.out.println(total); System.out.println("Enter the first integer "); double usersFirstInteger = in.nextDouble(); System.out.println("Enter the second integer"); double usersSecondInteger = in.nextDouble(); double product = usersFirstInteger * usersSecondInteger; double sum = usersFirstInteger * usersSecondInteger; double difference = usersFirstInteger - usersSecondInteger; double average = (usersFirstInteger + usersSecondInteger)/2; double distance = Math.abs(usersFirstInteger) - Math.abs(usersSecondInteger); distance = Math.abs(distance); double max = Math.max(usersFirstInteger,usersSecondInteger); double min = Math.min(usersFirstInteger,usersSecondInteger); System.out.printf("product : %10.2f \n sum : %10.2f \n difference : %10.2f \n average : %10.2f \n distance : %10.2f \n max : %10.2f \n min: %10.2f " , product , sum , difference , average , distance , max, min); int floor = 16; floor = floor < 13 ? floor : floor -1; System.out.println(" \n Floor is " + floor); } }
1,850
0.656757
0.634054
54
33.277779
28.895351
160
false
false
0
0
0
0
0
0
0.833333
false
false
7
0c22038104bd1f0869ce83e7dd97e52617a48bb7
19,679,540,202,633
409851fc7567ea1a9ae139ccba984269f9cbbeb8
/src/main/java/com/example/finalpaper/Service/buildingService.java
f42590122952bda064c3c0b86e1b926794cabb86
[]
no_license
Rainbowxh/Administrator
https://github.com/Rainbowxh/Administrator
693da0270ef70cbe80ea3a34402fcd4348cd1e53
767eb264c6ccf7396bc03c3fa54ca64c94f1423b
refs/heads/master
2021-10-23T01:59:06.206000
2019-03-14T07:58:50
2019-03-14T07:58:50
103,359,218
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.finalpaper.Service; import com.example.finalpaper.Entity.building; import com.example.finalpaper.Mapper.buildingMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class buildingService extends baseService{ @Autowired private buildingMapper buildingMapper; //通过房间id查询 public String getById(String buildingId) { building buildingResult = buildingMapper.selectbyid(buildingId); return formatBody(buildingResult); } //查询所有房间 public String getAll() { List<building> buildingAll = buildingMapper.selectAll(); return transferBody(buildingAll) ; } //删除数据 public int deleteById(String userId){ return buildingMapper.deleteBuildingById(userId); } //增加数据 public int insertById(building buildingEntity){ return buildingMapper.insertbuilding(buildingEntity); } //修改数据 public int updateById(building buildingEntity){ return buildingMapper.updateBuildingById(buildingEntity); } }
UTF-8
Java
1,173
java
buildingService.java
Java
[]
null
[]
package com.example.finalpaper.Service; import com.example.finalpaper.Entity.building; import com.example.finalpaper.Mapper.buildingMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class buildingService extends baseService{ @Autowired private buildingMapper buildingMapper; //通过房间id查询 public String getById(String buildingId) { building buildingResult = buildingMapper.selectbyid(buildingId); return formatBody(buildingResult); } //查询所有房间 public String getAll() { List<building> buildingAll = buildingMapper.selectAll(); return transferBody(buildingAll) ; } //删除数据 public int deleteById(String userId){ return buildingMapper.deleteBuildingById(userId); } //增加数据 public int insertById(building buildingEntity){ return buildingMapper.insertbuilding(buildingEntity); } //修改数据 public int updateById(building buildingEntity){ return buildingMapper.updateBuildingById(buildingEntity); } }
1,173
0.734222
0.734222
42
25.785715
23.865232
72
false
false
0
0
0
0
0
0
0.333333
false
false
7
3ec9d3444887c95436bb568bbe69e726bde47b0a
14,525,579,447,985
93b02ee32ee0d1846de09ccb11f26bc39a52779c
/TopReport1.1/report.workconfirmed/com/huateng/report/workconfirmed/getter/BOPForBiExecConfirmedGetter.java
d7c9075cc763a9059f3b38ead4622e2431b8672e
[]
no_license
alcading/AMS
https://github.com/alcading/AMS
ba1ed3ee66c359e6e7193ed0155f509583a9f233
76009a88126304617cdc4fdc732c79c1f95fb761
refs/heads/master
2021-07-25T02:13:28.731000
2018-07-12T10:14:49
2018-07-12T10:14:49
114,340,797
0
6
null
false
2018-07-12T10:14:50
2017-12-15T07:31:25
2017-12-15T07:56:56
2018-07-12T10:14:50
36,371
0
2
0
Java
false
null
package com.huateng.report.workconfirmed.getter; import java.util.ArrayList; import java.util.List; import resource.bean.report.BiExecConfirm; import com.huateng.common.err.Module; import com.huateng.common.err.Rescode; import com.huateng.commquery.result.Result; import com.huateng.commquery.result.ResultMng; import com.huateng.ebank.business.common.GlobalInfo; import com.huateng.ebank.business.common.PageQueryResult; import com.huateng.ebank.framework.exceptions.CommonException; import com.huateng.ebank.framework.web.commQuery.BaseGetter; import com.huateng.exception.AppException; import com.huateng.report.execconfirm.service.BiExecConfirmService; public class BOPForBiExecConfirmedGetter extends BaseGetter { @Override public Result call() throws AppException { try { PageQueryResult pageQueryResult = getData(); ResultMng.fillResultByList(getCommonQueryBean(), getCommQueryServletRequest(), pageQueryResult.getQueryResult(), getResult()); result.setContent(pageQueryResult.getQueryResult()); result.getPage().setTotalPage(pageQueryResult.getPageCount(getResult().getPage().getEveryPage())); result.init(); return result; }catch(AppException appEx){ throw appEx; }catch(Exception ex){ throw new AppException(Module.SYSTEM_MODULE, Rescode.DEFAULT_RESCODE, ex.getMessage(),ex); } } private PageQueryResult getData() throws CommonException { GlobalInfo gInfo = GlobalInfo.getCurrentInstance(); String busiType = this.getCommQueryServletRequest().getParameter("busiType"); String qappType = this.getCommQueryServletRequest().getParameter("qappType"); BiExecConfirm biExecConfirm = BiExecConfirmService.getInstance().getBiExecConfirmByPk(busiType, qappType, gInfo.getBrno(), gInfo.getTxdate().toString().replaceAll("-", "")); PageQueryResult queryResult = new PageQueryResult(); if(biExecConfirm != null){ List<BiExecConfirm> biExecConList = new ArrayList<BiExecConfirm>(); biExecConList.add(biExecConfirm); queryResult.setQueryResult(biExecConList); queryResult.setTotalCount(1); } return queryResult; } }
UTF-8
Java
2,110
java
BOPForBiExecConfirmedGetter.java
Java
[]
null
[]
package com.huateng.report.workconfirmed.getter; import java.util.ArrayList; import java.util.List; import resource.bean.report.BiExecConfirm; import com.huateng.common.err.Module; import com.huateng.common.err.Rescode; import com.huateng.commquery.result.Result; import com.huateng.commquery.result.ResultMng; import com.huateng.ebank.business.common.GlobalInfo; import com.huateng.ebank.business.common.PageQueryResult; import com.huateng.ebank.framework.exceptions.CommonException; import com.huateng.ebank.framework.web.commQuery.BaseGetter; import com.huateng.exception.AppException; import com.huateng.report.execconfirm.service.BiExecConfirmService; public class BOPForBiExecConfirmedGetter extends BaseGetter { @Override public Result call() throws AppException { try { PageQueryResult pageQueryResult = getData(); ResultMng.fillResultByList(getCommonQueryBean(), getCommQueryServletRequest(), pageQueryResult.getQueryResult(), getResult()); result.setContent(pageQueryResult.getQueryResult()); result.getPage().setTotalPage(pageQueryResult.getPageCount(getResult().getPage().getEveryPage())); result.init(); return result; }catch(AppException appEx){ throw appEx; }catch(Exception ex){ throw new AppException(Module.SYSTEM_MODULE, Rescode.DEFAULT_RESCODE, ex.getMessage(),ex); } } private PageQueryResult getData() throws CommonException { GlobalInfo gInfo = GlobalInfo.getCurrentInstance(); String busiType = this.getCommQueryServletRequest().getParameter("busiType"); String qappType = this.getCommQueryServletRequest().getParameter("qappType"); BiExecConfirm biExecConfirm = BiExecConfirmService.getInstance().getBiExecConfirmByPk(busiType, qappType, gInfo.getBrno(), gInfo.getTxdate().toString().replaceAll("-", "")); PageQueryResult queryResult = new PageQueryResult(); if(biExecConfirm != null){ List<BiExecConfirm> biExecConList = new ArrayList<BiExecConfirm>(); biExecConList.add(biExecConfirm); queryResult.setQueryResult(biExecConList); queryResult.setTotalCount(1); } return queryResult; } }
2,110
0.784834
0.78436
60
34.166668
31.671316
175
false
false
0
0
0
0
0
0
2.116667
false
false
7
65b8f655a3877d88524914d8fcf1a89fdeeaff88
14,525,579,448,702
f75139937a1b1474059e9bddba58c45f9b6a2b6f
/src/test/java/pkgEmpty/TestPS2.java
f1cd999cf558ee1fe506556c4cd81393ec158a31
[]
no_license
gcorella/PS2
https://github.com/gcorella/PS2
0da1aa898ed480ba346290214d50551d67cfb023
0e516a89412a53bb2e48f68b0b5839a1bead628f
refs/heads/master
2021-01-21T06:52:46.800000
2017-02-27T09:06:00
2017-02-27T09:06:00
83,290,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pkgEmpty; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import pkgEmpty.MyInteger; public class TestPS2 { public static MyInteger one; public static MyInteger two; public static MyInteger three; @BeforeClass public static void setUpBeforeClass() throws Exception { one = new MyInteger(5); two = new MyInteger(3); three = new MyInteger(8); } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } //****************************************************** public void isNotEvenTest(){ assertFalse("5 is no an even number", one.isEven(5)); } public void isEvenTest(){ assertTrue("8 is an even number", three.isEven(8)); } public void isOddTest(){ assertTrue("5 is an odd number",one.isOdd(5)); } public void isNotOddTest(){ assertFalse("8 is not an odd number",three.isOdd(8)); } public void isPrimeTest(){ assertTrue("3 is a prime number",two.isPrime(3)); } public void isNotPrimeTest(){ assertFalse("8 is not a prime number",three.isPrime(8)); } public void isEven(){ assertTrue("This is an even number",three.isEven(8)); } public void isNotEven(){ assertFalse("This is not an even number",one.isEven(5)); } public void isOdd(){ assertTrue("This is an odd number",two.isOdd(3)); } public void isNotOdd(){ assertFalse("This is not an odd number",three.isOdd(8)); } public void isPrime(){ assertTrue("This is a prime number",two.isPrime(3)); } public void isNotPrime(){ assertFalse("This is not a prime number",three.isPrime(8)); } //************************************** public void isEvenMyInteger(){ assertTrue("This is an even number",three.isEven(8)); } public void isNotEvenMyInteger(){ assertFalse("This is not an even number",one.isEven(5)); } public void isOddMyInteger(){ assertTrue("This is an odd number",two.isOdd(3)); } public void isNotOddMyInteger(){ assertFalse("This is not an odd number",three.isOdd(8)); } public void isPrimeMyIntger(){ assertTrue("This is a prime number",two.isPrime(3)); } public void isNotPrimeMyInteger(){ assertFalse("This is not a prime number",three.isPrime(8)); } //********************************************************* public void isEqualsInt(){ assertTrue("This number is equal to 5",one.equals(5)); } public void isNotEqualsInt(){ assertFalse("This number is not equal to 5",two.equals(5)); } //************************EQUALS******************************* public void isEqualsMyInteger(){ assertTrue("This number is equal to 3",two.equals(3)); } public void isNotEqualsMyInteger(){ assertFalse("This number is not equal to 3",three.equals(3)); } }
UTF-8
Java
3,310
java
TestPS2.java
Java
[]
null
[]
package pkgEmpty; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import pkgEmpty.MyInteger; public class TestPS2 { public static MyInteger one; public static MyInteger two; public static MyInteger three; @BeforeClass public static void setUpBeforeClass() throws Exception { one = new MyInteger(5); two = new MyInteger(3); three = new MyInteger(8); } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } //****************************************************** public void isNotEvenTest(){ assertFalse("5 is no an even number", one.isEven(5)); } public void isEvenTest(){ assertTrue("8 is an even number", three.isEven(8)); } public void isOddTest(){ assertTrue("5 is an odd number",one.isOdd(5)); } public void isNotOddTest(){ assertFalse("8 is not an odd number",three.isOdd(8)); } public void isPrimeTest(){ assertTrue("3 is a prime number",two.isPrime(3)); } public void isNotPrimeTest(){ assertFalse("8 is not a prime number",three.isPrime(8)); } public void isEven(){ assertTrue("This is an even number",three.isEven(8)); } public void isNotEven(){ assertFalse("This is not an even number",one.isEven(5)); } public void isOdd(){ assertTrue("This is an odd number",two.isOdd(3)); } public void isNotOdd(){ assertFalse("This is not an odd number",three.isOdd(8)); } public void isPrime(){ assertTrue("This is a prime number",two.isPrime(3)); } public void isNotPrime(){ assertFalse("This is not a prime number",three.isPrime(8)); } //************************************** public void isEvenMyInteger(){ assertTrue("This is an even number",three.isEven(8)); } public void isNotEvenMyInteger(){ assertFalse("This is not an even number",one.isEven(5)); } public void isOddMyInteger(){ assertTrue("This is an odd number",two.isOdd(3)); } public void isNotOddMyInteger(){ assertFalse("This is not an odd number",three.isOdd(8)); } public void isPrimeMyIntger(){ assertTrue("This is a prime number",two.isPrime(3)); } public void isNotPrimeMyInteger(){ assertFalse("This is not a prime number",three.isPrime(8)); } //********************************************************* public void isEqualsInt(){ assertTrue("This number is equal to 5",one.equals(5)); } public void isNotEqualsInt(){ assertFalse("This number is not equal to 5",two.equals(5)); } //************************EQUALS******************************* public void isEqualsMyInteger(){ assertTrue("This number is equal to 3",two.equals(3)); } public void isNotEqualsMyInteger(){ assertFalse("This number is not equal to 3",three.equals(3)); } }
3,310
0.569789
0.558912
101
30.752476
22.227182
69
false
false
0
0
0
0
0
0
0.574257
false
false
7
021c07f676728af162ed2c4e82285ff3345cbc06
1,640,677,558,663
3be0f25cd8899062cd6d2246ad813d45909d9709
/src/main/java/com/runfeng/hibernate/SalaryDAO/SSBasicDAO.java
2d978ee86610147bfb426c72802a15e7ca0cb6d1
[]
no_license
waterNeeeeeed/OA
https://github.com/waterNeeeeeed/OA
521236d7be016d72f9712ed5d21d9dfff5ad0f4a
932f7bb2f0cac2082b046f64d8b9273684792c7f
refs/heads/master
2021-01-21T17:28:31.873000
2017-06-12T09:47:37
2017-06-12T09:47:37
85,483,172
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.runfeng.hibernate.SalaryDAO; import com.runfeng.hibernate.BaseDAO; import com.runfeng.hibernate.SalaryEntity.SSBasic; /** * Created by lenovo on 2017/5/9. */ public interface SSBasicDAO extends BaseDAO<SSBasic> { }
UTF-8
Java
232
java
SSBasicDAO.java
Java
[ { "context": "hibernate.SalaryEntity.SSBasic;\n\n/**\n * Created by lenovo on 2017/5/9.\n */\npublic interface SSBasicDAO exte", "end": 156, "score": 0.9995734095573425, "start": 150, "tag": "USERNAME", "value": "lenovo" } ]
null
[]
package com.runfeng.hibernate.SalaryDAO; import com.runfeng.hibernate.BaseDAO; import com.runfeng.hibernate.SalaryEntity.SSBasic; /** * Created by lenovo on 2017/5/9. */ public interface SSBasicDAO extends BaseDAO<SSBasic> { }
232
0.775862
0.75
11
20.09091
21.432577
54
false
false
0
0
0
0
0
0
0.272727
false
false
7
f633da4ee56f169a283be63588a1b52ea2ba86eb
9,715,216,075,267
27bc871734edf1a6f07ae6937d3b948d00bda081
/src/osrswrapper/players/OSRSSeasonal.java
95e6682958513cf931ee3e9fa8e5e52b798e589e
[]
no_license
SheepWizard/OSRS-API-WRAPPER
https://github.com/SheepWizard/OSRS-API-WRAPPER
68083f84cf411cd9563e25ca6b99b56ffd0c3833
ebd754683d1db0ffc5d09315c3a2f37c4b4d7c76
refs/heads/master
2020-03-07T11:46:29.551000
2018-03-31T19:40:57
2018-03-31T19:40:57
127,463,471
0
1
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 osrswrapper.players; import java.io.IOException; public class OSRSSeasonal extends OSRSUser { private static final String url = "http://services.runescape.com/m=hiscore_oldschool_seasonal/index_lite.ws?player="; public OSRSSeasonal(String userName) throws IOException { super(userName, url, "Seasonal"); } }
UTF-8
Java
538
java
OSRSSeasonal.java
Java
[]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package osrswrapper.players; import java.io.IOException; public class OSRSSeasonal extends OSRSUser { private static final String url = "http://services.runescape.com/m=hiscore_oldschool_seasonal/index_lite.ws?player="; public OSRSSeasonal(String userName) throws IOException { super(userName, url, "Seasonal"); } }
538
0.723048
0.723048
20
25.9
32.227161
121
false
false
0
0
0
0
0
0
0.45
false
false
7
ce4b5ba5de3253a1d84fe0e1920816f8284810e1
8,770,323,274,117
6276f00a0a4824ca7f48553f992fe9ad47b3c360
/app/src/main/java/com/drizzle/glideprogressproject/MainActivity.java
4af27ed7d85fe4165321e908848fa115d02cee94
[]
no_license
Drizzlezhang/GlideProgressTarget
https://github.com/Drizzlezhang/GlideProgressTarget
5315ced85a487e4394dfab77c5671abff25c5a5e
ead3f3d31408432471882a7abe04ae4d66b9cef0
refs/heads/master
2021-01-22T10:36:05.091000
2017-02-17T05:37:50
2017-02-17T05:37:50
82,016,919
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.drizzle.glideprogressproject; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.bumptech.glide.request.target.Target; import java.util.Arrays; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView list = (RecyclerView) findViewById(R.id.recyclerview); list.setLayoutManager(new LinearLayoutManager(this)); list.setAdapter(new ProgressAdapter(Arrays.asList( // few results from https://www.google.com/search?tbm=isch&q=image&tbs=isz:lt,islt:4mp "http://www.noaanews.noaa.gov/stories/images/goes-12%2Dfirstimage-large081701%2Ejpg", "http://www.spektyr.com/PrintImages/Cerulean%20Cross%203%20Large.jpg", "https://cdn.photographylife.com/wp-content/uploads/2014/06/Nikon-D810-Image-Sample-6.jpg", "https://upload.wikimedia.org/wikipedia/commons/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg", "https://upload.wikimedia.org/wikipedia/commons/c/c5/Polarlicht_2_kmeans_16_large.png", "https://www.hq.nasa.gov/alsj/a15/M1123519889LCRC_isometric_min-8000_g0dot5_enhanced_labeled.jpg", "http://oceanexplorer.noaa.gov/explorations/02fire/logs/hirez/octopus_hires.jpg", "https://upload.wikimedia.org/wikipedia/commons/b/bf/GOES-13_First_Image_jun_22_2006_1730Z.jpg", "http://www.zastavki.com/pictures/originals/2013/Photoshop_Image_of_the_horse_053857_.jpg", "http://www.marcogiordanotd.com/blog/wp-content/uploads/2014/01/image9Kcomp.jpg", "https://cdn.photographylife.com/wp-content/uploads/2014/06/Nikon-D810-Image-Sample-7.jpg", "https://www.apple.com/v/imac-with-retina/a/images/overview/5k_image.jpg", "https://www.gimp.org/tutorials/Lite_Quickies/lordofrings_hst_big.jpg", "http://www.cesbio.ups-tlse.fr/multitemp/wp-content/uploads/2015/07/Mad%C3%A8re-022_0_1.jpg", "https://www.spacetelescope.org/static/archives/fitsimages/large/slawomir_lipinski_04.jpg", "https://upload.wikimedia.org/wikipedia/commons/b/b4/Mardin_1350660_1350692_33_images.jpg", "http://4k.com/wp-content/uploads/2014/06/4k-image-tiger-jumping.jpg" ))); } private static class ProgressViewHolder extends RecyclerView.ViewHolder { private final ImageView image; private final TextView text; private final ProgressBar progress; /** Cache target because all the views are tied to this view holder. */ private final ProgressTarget<String, Bitmap> target; ProgressViewHolder(View root) { super(root); image = (ImageView)root.findViewById(R.id.image); text = (TextView)root.findViewById(R.id.text); progress = (ProgressBar)root.findViewById(R.id.progress); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bind(target.getModel()); } }); target = new MyProgressTarget<>(new BitmapImageViewTarget(image), progress, image, text); } void bind(String url) { target.setModel(url); // update target's cache Glide .with(image.getContext()) .load(url) .asBitmap() .placeholder(R.drawable.progress) .centerCrop() // needs explicit transformation, because we're using a custom target .into(target) ; } } /** * Demonstrates 3 different ways of showing the progress: * <ul> * <li>Update a full fledged progress bar</li> * <li>Update a text view to display size/percentage</li> * <li>Update the placeholder via Drawable.level</li> * </ul> * This last one is tricky: the placeholder that Glide sets can be used as a progress drawable * without any extra Views in the view hierarchy if it supports levels via <code>usesLevel="true"</code> * or <code>level-list</code>. * * @param <Z> automatically match any real Glide target so it can be used flexibly without reimplementing. */ private static class MyProgressTarget<Z> extends ProgressTarget<String, Z> { private final TextView text; private final ProgressBar progress; private final ImageView image; public MyProgressTarget(Target<Z> target, ProgressBar progress, ImageView image, TextView text) { super(target); this.progress = progress; this.image = image; this.text = text; } @Override public float getGranualityPercentage() { return 0.1f; // this matches the format string for #text below } @Override protected void onConnecting() { progress.setIndeterminate(true); progress.setVisibility(View.VISIBLE); image.setImageLevel(0); text.setVisibility(View.VISIBLE); text.setText("connecting"); } @Override protected void onDownloading(long bytesRead, long expectedLength) { progress.setIndeterminate(false); progress.setProgress((int)(100 * bytesRead / expectedLength)); image.setImageLevel((int)(10000 * bytesRead / expectedLength)); text.setText(String.format("downloading %.2f/%.2f MB %.1f%%", bytesRead / 1e6, expectedLength / 1e6, 100f * bytesRead / expectedLength)); } @Override protected void onDownloaded() { progress.setIndeterminate(true); image.setImageLevel(10000); text.setText("decoding and transforming"); } @Override protected void onDelivered() { progress.setVisibility(View.INVISIBLE); image.setImageLevel(0); // reset ImageView default text.setVisibility(View.INVISIBLE); } } private static class ProgressAdapter extends RecyclerView.Adapter<ProgressViewHolder> { private final List<String> models; public ProgressAdapter(List<String> models) { this.models = models; } @Override public ProgressViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false); return new ProgressViewHolder(view); } @Override public void onBindViewHolder(ProgressViewHolder holder, int position) { holder.bind(models.get(position)); } @Override public int getItemCount() { return models.size(); } } }
UTF-8
Java
7,419
java
MainActivity.java
Java
[]
null
[]
package com.drizzle.glideprogressproject; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.bumptech.glide.request.target.Target; import java.util.Arrays; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView list = (RecyclerView) findViewById(R.id.recyclerview); list.setLayoutManager(new LinearLayoutManager(this)); list.setAdapter(new ProgressAdapter(Arrays.asList( // few results from https://www.google.com/search?tbm=isch&q=image&tbs=isz:lt,islt:4mp "http://www.noaanews.noaa.gov/stories/images/goes-12%2Dfirstimage-large081701%2Ejpg", "http://www.spektyr.com/PrintImages/Cerulean%20Cross%203%20Large.jpg", "https://cdn.photographylife.com/wp-content/uploads/2014/06/Nikon-D810-Image-Sample-6.jpg", "https://upload.wikimedia.org/wikipedia/commons/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg", "https://upload.wikimedia.org/wikipedia/commons/c/c5/Polarlicht_2_kmeans_16_large.png", "https://www.hq.nasa.gov/alsj/a15/M1123519889LCRC_isometric_min-8000_g0dot5_enhanced_labeled.jpg", "http://oceanexplorer.noaa.gov/explorations/02fire/logs/hirez/octopus_hires.jpg", "https://upload.wikimedia.org/wikipedia/commons/b/bf/GOES-13_First_Image_jun_22_2006_1730Z.jpg", "http://www.zastavki.com/pictures/originals/2013/Photoshop_Image_of_the_horse_053857_.jpg", "http://www.marcogiordanotd.com/blog/wp-content/uploads/2014/01/image9Kcomp.jpg", "https://cdn.photographylife.com/wp-content/uploads/2014/06/Nikon-D810-Image-Sample-7.jpg", "https://www.apple.com/v/imac-with-retina/a/images/overview/5k_image.jpg", "https://www.gimp.org/tutorials/Lite_Quickies/lordofrings_hst_big.jpg", "http://www.cesbio.ups-tlse.fr/multitemp/wp-content/uploads/2015/07/Mad%C3%A8re-022_0_1.jpg", "https://www.spacetelescope.org/static/archives/fitsimages/large/slawomir_lipinski_04.jpg", "https://upload.wikimedia.org/wikipedia/commons/b/b4/Mardin_1350660_1350692_33_images.jpg", "http://4k.com/wp-content/uploads/2014/06/4k-image-tiger-jumping.jpg" ))); } private static class ProgressViewHolder extends RecyclerView.ViewHolder { private final ImageView image; private final TextView text; private final ProgressBar progress; /** Cache target because all the views are tied to this view holder. */ private final ProgressTarget<String, Bitmap> target; ProgressViewHolder(View root) { super(root); image = (ImageView)root.findViewById(R.id.image); text = (TextView)root.findViewById(R.id.text); progress = (ProgressBar)root.findViewById(R.id.progress); image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bind(target.getModel()); } }); target = new MyProgressTarget<>(new BitmapImageViewTarget(image), progress, image, text); } void bind(String url) { target.setModel(url); // update target's cache Glide .with(image.getContext()) .load(url) .asBitmap() .placeholder(R.drawable.progress) .centerCrop() // needs explicit transformation, because we're using a custom target .into(target) ; } } /** * Demonstrates 3 different ways of showing the progress: * <ul> * <li>Update a full fledged progress bar</li> * <li>Update a text view to display size/percentage</li> * <li>Update the placeholder via Drawable.level</li> * </ul> * This last one is tricky: the placeholder that Glide sets can be used as a progress drawable * without any extra Views in the view hierarchy if it supports levels via <code>usesLevel="true"</code> * or <code>level-list</code>. * * @param <Z> automatically match any real Glide target so it can be used flexibly without reimplementing. */ private static class MyProgressTarget<Z> extends ProgressTarget<String, Z> { private final TextView text; private final ProgressBar progress; private final ImageView image; public MyProgressTarget(Target<Z> target, ProgressBar progress, ImageView image, TextView text) { super(target); this.progress = progress; this.image = image; this.text = text; } @Override public float getGranualityPercentage() { return 0.1f; // this matches the format string for #text below } @Override protected void onConnecting() { progress.setIndeterminate(true); progress.setVisibility(View.VISIBLE); image.setImageLevel(0); text.setVisibility(View.VISIBLE); text.setText("connecting"); } @Override protected void onDownloading(long bytesRead, long expectedLength) { progress.setIndeterminate(false); progress.setProgress((int)(100 * bytesRead / expectedLength)); image.setImageLevel((int)(10000 * bytesRead / expectedLength)); text.setText(String.format("downloading %.2f/%.2f MB %.1f%%", bytesRead / 1e6, expectedLength / 1e6, 100f * bytesRead / expectedLength)); } @Override protected void onDownloaded() { progress.setIndeterminate(true); image.setImageLevel(10000); text.setText("decoding and transforming"); } @Override protected void onDelivered() { progress.setVisibility(View.INVISIBLE); image.setImageLevel(0); // reset ImageView default text.setVisibility(View.INVISIBLE); } } private static class ProgressAdapter extends RecyclerView.Adapter<ProgressViewHolder> { private final List<String> models; public ProgressAdapter(List<String> models) { this.models = models; } @Override public ProgressViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false); return new ProgressViewHolder(view); } @Override public void onBindViewHolder(ProgressViewHolder holder, int position) { holder.bind(models.get(position)); } @Override public int getItemCount() { return models.size(); } } }
7,419
0.647661
0.625421
156
46.557693
33.605412
123
false
false
0
0
0
0
0
0
0.628205
false
false
7
5c2ec25a5844cb246239de7bb767bb554ef5a38a
10,041,633,601,025
aa4ea7b0acc65a12e94e43e11bbdbfabf2a366a5
/src/br/com/persistenciafa7/main/MudancaDeTecnico.java
c79c8bbd226da88f9dcd4956a5415c5d186029f4
[]
no_license
erinaldosouza/PersistenciaFa7
https://github.com/erinaldosouza/PersistenciaFa7
166b8ffea6b0b9e2a327e41042426c7130fd74f2
9ec5ce81bfaf3880ec2b9c1b46f761ab1388e5e7
refs/heads/master
2021-01-10T12:38:46.227000
2016-03-23T17:03:28
2016-03-23T17:03:28
54,163,965
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.persistenciafa7.main; import java.util.Collection; import java.util.Iterator; import org.hibernate.Session; import br.com.persistenciafa7.dao.TimeDao; import br.com.persistenciafa7.model.Pessoa; import br.com.persistenciafa7.model.Tecnico; import br.com.persistenciafa7.model.Time; import br.com.persistenciafa7.util.HibernateUtil; public class MudancaDeTecnico { public static void main(String[] args) { Session s = HibernateUtil.getHibernateSession(); s.getTransaction().begin(); contratarNovoTecnico("Fortaleza", "Ceará"); s.getTransaction().commit(); } /** * Desvincula o técnico atual dos times passados por parâmetro e insere um novo técnico * * @author erinaldo.souza * @since 2016-03-22 * * @param nomeTime */ public static void contratarNovoTecnico(String... nomeTime) { TimeDao td = new TimeDao(); Time time = null; for (String nome : nomeTime) { time = td.findByName(nome); Collection<Pessoa> pessoas = time.getPessoas(); Iterator<Pessoa> ite = pessoas.iterator(); while (ite.hasNext()) { Pessoa pessoa = ite.next(); if(pessoa instanceof Tecnico) { pessoa.setNome("EX" + pessoa.getNome().replaceAll("NOVO", "")); pessoa.setTime(null); break; } } time.getPessoas().add(new Tecnico("Novo Tecnico do " + time.getNome(), "Times de 2º Divisão", time)); td.saveOrUpdate(time); } } }
ISO-8859-1
Java
1,473
java
MudancaDeTecnico.java
Java
[ { "context": "âmetro e insere um novo técnico\r\n\t * \r\n\t * @author erinaldo.souza\r\n\t * @since 2016-03-22\r\n\t * \r\n\t * @pa", "end": 734, "score": 0.6723304390907288, "start": 732, "tag": "NAME", "value": "er" }, { "context": "tro e insere um novo técnico\r\n\t * \r\n\t * @author erinaldo.souza\r\n\t * @since 2016-03-22\r\n\t * \r\n\t * @param nom", "end": 740, "score": 0.6778655052185059, "start": 734, "tag": "USERNAME", "value": "inaldo" }, { "context": "nsere um novo técnico\r\n\t * \r\n\t * @author erinaldo.souza\r\n\t * @since 2016-03-22\r\n\t * \r\n\t * @param nomeTime", "end": 746, "score": 0.6854462623596191, "start": 741, "tag": "NAME", "value": "souza" } ]
null
[]
package br.com.persistenciafa7.main; import java.util.Collection; import java.util.Iterator; import org.hibernate.Session; import br.com.persistenciafa7.dao.TimeDao; import br.com.persistenciafa7.model.Pessoa; import br.com.persistenciafa7.model.Tecnico; import br.com.persistenciafa7.model.Time; import br.com.persistenciafa7.util.HibernateUtil; public class MudancaDeTecnico { public static void main(String[] args) { Session s = HibernateUtil.getHibernateSession(); s.getTransaction().begin(); contratarNovoTecnico("Fortaleza", "Ceará"); s.getTransaction().commit(); } /** * Desvincula o técnico atual dos times passados por parâmetro e insere um novo técnico * * @author erinaldo.souza * @since 2016-03-22 * * @param nomeTime */ public static void contratarNovoTecnico(String... nomeTime) { TimeDao td = new TimeDao(); Time time = null; for (String nome : nomeTime) { time = td.findByName(nome); Collection<Pessoa> pessoas = time.getPessoas(); Iterator<Pessoa> ite = pessoas.iterator(); while (ite.hasNext()) { Pessoa pessoa = ite.next(); if(pessoa instanceof Tecnico) { pessoa.setNome("EX" + pessoa.getNome().replaceAll("NOVO", "")); pessoa.setTime(null); break; } } time.getPessoas().add(new Tecnico("Novo Tecnico do " + time.getNome(), "Times de 2º Divisão", time)); td.saveOrUpdate(time); } } }
1,473
0.669393
0.659168
55
24.709091
23.070385
104
false
false
0
0
0
0
0
0
2.163636
false
false
7
f3025ee8ab25c4b487cba8c0eeabaf76a978fdb1
10,041,633,603,691
beca90634399d5d3459c0a16ae881142af17cd3e
/src/main/java/ec/edu/espe/monster/GR10COMERCIALIZADORA/DAOs/ISystemDAO.java
78eac72215aee088596279c80d78404a035dd540
[]
no_license
ESPE-STUDENTS-GENERATION-1997/G1OCOMERCIALIZADORA
https://github.com/ESPE-STUDENTS-GENERATION-1997/G1OCOMERCIALIZADORA
14684886d2de6d0964ffd558e5be2588c099d5d6
0ecc7f1b4909a1da258f41e2803accf6c85bcee8
refs/heads/master
2023-07-08T00:14:51.891000
2021-07-26T03:16:35
2021-07-26T03:16:35
341,641,473
0
0
null
false
2021-03-14T02:56:49
2021-02-23T17:53:45
2021-02-28T06:04:03
2021-03-14T02:56:48
3,654
0
0
0
CSS
false
false
package ec.edu.espe.monster.GR10COMERCIALIZADORA.DAOs; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import ec.edu.espe.monster.GR10COMERCIALIZADORA.models.entitys.SystemApp; public interface ISystemDAO extends JpaRepository<SystemApp, Long>{ List<SystemApp> findByCurrent(Boolean current); Optional<SystemApp> findByKeyword(String keyword); }
UTF-8
Java
421
java
ISystemDAO.java
Java
[]
null
[]
package ec.edu.espe.monster.GR10COMERCIALIZADORA.DAOs; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import ec.edu.espe.monster.GR10COMERCIALIZADORA.models.entitys.SystemApp; public interface ISystemDAO extends JpaRepository<SystemApp, Long>{ List<SystemApp> findByCurrent(Boolean current); Optional<SystemApp> findByKeyword(String keyword); }
421
0.821853
0.812352
16
25.3125
27.69413
73
false
false
0
0
0
0
0
0
0.75
false
false
7
86695021bb612c031979ec083fd6dc5e1d7b587f
1,322,849,929,708
8c356768138f5a53b7d30063eea290dd7ae30e84
/src/edu/stanford/sulair/dlss/was/metadata/MetadataExtractorEngine.java
8c7a0686895b8ed649e67f05cc31576f149ca27b
[ "Apache-2.0" ]
permissive
sul-dlss/WASMetadataExtractor
https://github.com/sul-dlss/WASMetadataExtractor
0eb4e105a03f0ffa2442edf2b68fb3afe93cad54
4ce467c13f7d36d7f06ab9b838917e535c6ce2c5
refs/heads/master
2021-06-11T05:55:10.901000
2021-05-05T13:22:23
2021-05-05T13:22:23
23,780,342
0
1
Apache-2.0
false
2021-05-05T13:22:23
2014-09-08T05:34:52
2020-08-04T16:00:59
2021-05-05T13:22:23
92,118
0
1
3
Java
false
false
package edu.stanford.sulair.dlss.was.metadata; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import edu.stanford.sulair.dlss.was.metadata.parser.MetadataParser; import edu.stanford.sulair.dlss.was.metadata.writer.IMetadataWriter; import edu.stanford.sulair.dlss.was.metadata.writer.MetadataWriterDefault; /** * Runs the extractor based on the inputs * @author aalsum * */ public class MetadataExtractorEngine { private ArrayList<File> fileList = null; private String configFile = null; private IMetadataWriter writer = null; public MetadataExtractorEngine(ArrayList<File> fileList) { this.fileList = fileList; writer = new MetadataWriterDefault(System.out); } public MetadataExtractorEngine(ArrayList<File> fileList, IMetadataWriter writer) { this.fileList = fileList; this.writer = writer; } public MetadataExtractorEngine(ArrayList<File> fileList, String configFile, IMetadataWriter writer) { this.fileList = fileList; this.writer = writer; this.configFile = configFile; } /** * @param file */ public MetadataExtractorEngine(File file) { fileList = new ArrayList<File>(1); fileList.add(file); } /** * @param fileName */ public MetadataExtractorEngine(String fileName) { File file = new File(fileName); fileList = new ArrayList<File>(1); fileList.add(file); } public MetadataExtractorEngine(ArrayList<File> fileList, String configFile) { this.fileList = fileList; this.configFile = configFile; } /** * @param file */ public MetadataExtractorEngine(File file, String configFile) { fileList = new ArrayList<File>(1); fileList.add(file); this.configFile = configFile; } /** * @param fileName */ public MetadataExtractorEngine(String fileName, String configFile) { File file = new File(fileName); fileList = new ArrayList<File>(1); fileList.add(file); this.configFile = configFile; } public void runExtractor() { ArrayList<MetadataRepository> repoList = new ArrayList<MetadataRepository>(); MetadataParser parser = null; if (configFile == null) { parser = new MetadataParser(); } else { parser = new MetadataParser(configFile); } for (File f : fileList) { try { repoList.add(parser.extractWAMetadata(f)); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } writer.setMetadataRepositoryList(repoList); } public void runExtractorToFile() { } public IMetadataWriter getWriter() { return this.writer; } }
UTF-8
Java
2,627
java
MetadataExtractorEngine.java
Java
[ { "context": " Runs the extractor based on the inputs\n * @author aalsum\n *\n */\npublic class MetadataExtractorEngine {\n\n\tp", "end": 440, "score": 0.9996085166931152, "start": 434, "tag": "USERNAME", "value": "aalsum" } ]
null
[]
package edu.stanford.sulair.dlss.was.metadata; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import edu.stanford.sulair.dlss.was.metadata.parser.MetadataParser; import edu.stanford.sulair.dlss.was.metadata.writer.IMetadataWriter; import edu.stanford.sulair.dlss.was.metadata.writer.MetadataWriterDefault; /** * Runs the extractor based on the inputs * @author aalsum * */ public class MetadataExtractorEngine { private ArrayList<File> fileList = null; private String configFile = null; private IMetadataWriter writer = null; public MetadataExtractorEngine(ArrayList<File> fileList) { this.fileList = fileList; writer = new MetadataWriterDefault(System.out); } public MetadataExtractorEngine(ArrayList<File> fileList, IMetadataWriter writer) { this.fileList = fileList; this.writer = writer; } public MetadataExtractorEngine(ArrayList<File> fileList, String configFile, IMetadataWriter writer) { this.fileList = fileList; this.writer = writer; this.configFile = configFile; } /** * @param file */ public MetadataExtractorEngine(File file) { fileList = new ArrayList<File>(1); fileList.add(file); } /** * @param fileName */ public MetadataExtractorEngine(String fileName) { File file = new File(fileName); fileList = new ArrayList<File>(1); fileList.add(file); } public MetadataExtractorEngine(ArrayList<File> fileList, String configFile) { this.fileList = fileList; this.configFile = configFile; } /** * @param file */ public MetadataExtractorEngine(File file, String configFile) { fileList = new ArrayList<File>(1); fileList.add(file); this.configFile = configFile; } /** * @param fileName */ public MetadataExtractorEngine(String fileName, String configFile) { File file = new File(fileName); fileList = new ArrayList<File>(1); fileList.add(file); this.configFile = configFile; } public void runExtractor() { ArrayList<MetadataRepository> repoList = new ArrayList<MetadataRepository>(); MetadataParser parser = null; if (configFile == null) { parser = new MetadataParser(); } else { parser = new MetadataParser(configFile); } for (File f : fileList) { try { repoList.add(parser.extractWAMetadata(f)); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } writer.setMetadataRepositoryList(repoList); } public void runExtractorToFile() { } public IMetadataWriter getWriter() { return this.writer; } }
2,627
0.723258
0.720975
112
22.455357
20.971447
79
false
false
0
0
0
0
0
0
1.696429
false
false
7
52feecd2176d741722cf249dbb14082892c8e81f
36,000,415,883,762
ea6744f949315fb5e15c70434bb731dc5863a876
/src/com/mathisonian/android/citysecrets/CreateSecretActivity.java
dcfe9591642997f5cab955170056012d0112c749
[]
no_license
mathisonian/citysecrets-android
https://github.com/mathisonian/citysecrets-android
26e4cb77d82719ec6b06c23d1d9b151acda5c101
e4e7d8474e30bc4e28f6bc63910c79bb6b8f74e4
refs/heads/master
2016-08-05T13:12:35.030000
2011-12-04T17:50:37
2011-12-04T17:50:37
2,863,719
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mathisonian.android.citysecrets; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Matrix; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; public class CreateSecretActivity extends Activity { private static final int IMAGE_ACTIVITY = 1; private final Secret secret; private Bitmap image; private Location mostRecentLocation; private ProgressDialog postProgressDialog; public CreateSecretActivity() { secret = new Secret(); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.create_secret); CitySecsApp.locator = (LocationManager) getSystemService(Context.LOCATION_SERVICE); final ImageButton cameraButton = (ImageButton) findViewById(R.id.imageButtonCamera); final Button submitButton = (Button) findViewById(R.id.submitSecretButton); final EditText nameField = (EditText) findViewById(R.id.secretCaptionField); cameraButton.setEnabled(isGPSOn()); cameraButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, IMAGE_ACTIVITY); secret.updateLocationIfNeeded(mostRecentLocation); } }); submitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { secret.caption = nameField.getText().toString(); secret.updateLocationIfNeeded(mostRecentLocation); if (isSubmissionReady()) { try { DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { finish(); } }; postProgressDialog = ProgressDialog.show(CreateSecretActivity.this, getString(R.string.createSecretDialogTitle), getString(R.string.createSecretDialogMessage), true, true, cancelListener); new CreateSecretTask().execute(getCreationPost()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { AlertDialog.Builder builder = new Builder(CreateSecretActivity.this); builder.setCancelable(true); builder.setMessage("You must enter a name, take a photo, and have GPS location to submit a secret."); builder.setNegativeButton("got it, thanks, ass hole", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } } }); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // TODO: apply some filtering so that this doesn't get changed to a noisy sample. // http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate mostRecentLocation = location; } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { if (provider.equals(LocationManager.GPS_PROVIDER)) { cameraButton.setEnabled(true); } } public void onProviderDisabled(String provider) { if (provider.equals(LocationManager.GPS_PROVIDER)) { cameraButton.setEnabled(false); } } }; // The two 0's mean update as frequently as possible. We may want to // reduce the update frequency for power concerns later on. String provider = LocationManager.GPS_PROVIDER; CitySecsApp.locator.requestLocationUpdates(provider, 0, 0, locationListener); } public HttpPost getCreationPost() throws UnsupportedEncodingException { HttpPost post = new HttpPost(CitySecsApp.APIDIRURL + "createSecret.php"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("u", new StringBody(CitySecsApp.USER_TOKEN, CitySecsApp.CHARSET_UTF8)); entity.addPart("c", new StringBody(secret.caption, CitySecsApp.CHARSET_UTF8)); entity.addPart("lat", new StringBody("10", CitySecsApp.CHARSET_UTF8)); entity.addPart("lon", new StringBody("10", CitySecsApp.CHARSET_UTF8)); entity.addPart("alt", new StringBody("10", CitySecsApp.CHARSET_UTF8)); if (image != null) { Matrix rotationMatrix = new Matrix(); rotationMatrix.postRotate(-90); Bitmap rotatedBitmap = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), rotationMatrix, true); ByteArrayOutputStream stream = new ByteArrayOutputStream(); rotatedBitmap.compress(CompressFormat.PNG, 100, stream); entity.addPart("pictureUpload", new ByteArrayBody(stream.toByteArray(), "temp.png")); } post.setEntity(entity); return post; } private boolean isSubmissionReady() { return image != null && secret.isReady(); } private boolean isGPSOn() { return CitySecsApp.locator != null && CitySecsApp.locator.isProviderEnabled(LocationManager.GPS_PROVIDER); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == IMAGE_ACTIVITY) { if (resultCode == RESULT_CANCELED) { return; } image = (Bitmap) data.getExtras().get("data"); secret.updateLocationIfNeeded(mostRecentLocation); ImageView iview = (ImageView) findViewById(R.id.imageIconView); iview.setImageBitmap(image); LinearLayout cameraContainer = (LinearLayout) findViewById(R.id.carmeraButtonLayout); cameraContainer.setVisibility(View.INVISIBLE); } } private class CreateSecretTask extends AsyncTask<HttpPost, Void, HttpResponse> { @Override protected HttpResponse doInBackground(HttpPost... params) { try { return new DefaultHttpClient().execute(params[0]); } catch (Exception e) { return null; } } @Override protected void onPostExecute(HttpResponse resultResponse) { Intent resultIntent = new Intent(); if (resultResponse != null) { HttpEntity entity = resultResponse.getEntity(); try { BufferedReader responseReader = new BufferedReader(new InputStreamReader(entity.getContent())); String result = responseReader.readLine(); if (result.equals(getString(R.string.successResponse))) { setResult(Activity.RESULT_OK, resultIntent); } } catch (Exception e) { e.printStackTrace(); } } postProgressDialog.dismiss(); finish(); } } }
UTF-8
Java
7,508
java
CreateSecretActivity.java
Java
[]
null
[]
package com.mathisonian.android.citysecrets; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Matrix; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; public class CreateSecretActivity extends Activity { private static final int IMAGE_ACTIVITY = 1; private final Secret secret; private Bitmap image; private Location mostRecentLocation; private ProgressDialog postProgressDialog; public CreateSecretActivity() { secret = new Secret(); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.create_secret); CitySecsApp.locator = (LocationManager) getSystemService(Context.LOCATION_SERVICE); final ImageButton cameraButton = (ImageButton) findViewById(R.id.imageButtonCamera); final Button submitButton = (Button) findViewById(R.id.submitSecretButton); final EditText nameField = (EditText) findViewById(R.id.secretCaptionField); cameraButton.setEnabled(isGPSOn()); cameraButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, IMAGE_ACTIVITY); secret.updateLocationIfNeeded(mostRecentLocation); } }); submitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { secret.caption = nameField.getText().toString(); secret.updateLocationIfNeeded(mostRecentLocation); if (isSubmissionReady()) { try { DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { finish(); } }; postProgressDialog = ProgressDialog.show(CreateSecretActivity.this, getString(R.string.createSecretDialogTitle), getString(R.string.createSecretDialogMessage), true, true, cancelListener); new CreateSecretTask().execute(getCreationPost()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { AlertDialog.Builder builder = new Builder(CreateSecretActivity.this); builder.setCancelable(true); builder.setMessage("You must enter a name, take a photo, and have GPS location to submit a secret."); builder.setNegativeButton("got it, thanks, ass hole", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } } }); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // TODO: apply some filtering so that this doesn't get changed to a noisy sample. // http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate mostRecentLocation = location; } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { if (provider.equals(LocationManager.GPS_PROVIDER)) { cameraButton.setEnabled(true); } } public void onProviderDisabled(String provider) { if (provider.equals(LocationManager.GPS_PROVIDER)) { cameraButton.setEnabled(false); } } }; // The two 0's mean update as frequently as possible. We may want to // reduce the update frequency for power concerns later on. String provider = LocationManager.GPS_PROVIDER; CitySecsApp.locator.requestLocationUpdates(provider, 0, 0, locationListener); } public HttpPost getCreationPost() throws UnsupportedEncodingException { HttpPost post = new HttpPost(CitySecsApp.APIDIRURL + "createSecret.php"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("u", new StringBody(CitySecsApp.USER_TOKEN, CitySecsApp.CHARSET_UTF8)); entity.addPart("c", new StringBody(secret.caption, CitySecsApp.CHARSET_UTF8)); entity.addPart("lat", new StringBody("10", CitySecsApp.CHARSET_UTF8)); entity.addPart("lon", new StringBody("10", CitySecsApp.CHARSET_UTF8)); entity.addPart("alt", new StringBody("10", CitySecsApp.CHARSET_UTF8)); if (image != null) { Matrix rotationMatrix = new Matrix(); rotationMatrix.postRotate(-90); Bitmap rotatedBitmap = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), rotationMatrix, true); ByteArrayOutputStream stream = new ByteArrayOutputStream(); rotatedBitmap.compress(CompressFormat.PNG, 100, stream); entity.addPart("pictureUpload", new ByteArrayBody(stream.toByteArray(), "temp.png")); } post.setEntity(entity); return post; } private boolean isSubmissionReady() { return image != null && secret.isReady(); } private boolean isGPSOn() { return CitySecsApp.locator != null && CitySecsApp.locator.isProviderEnabled(LocationManager.GPS_PROVIDER); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == IMAGE_ACTIVITY) { if (resultCode == RESULT_CANCELED) { return; } image = (Bitmap) data.getExtras().get("data"); secret.updateLocationIfNeeded(mostRecentLocation); ImageView iview = (ImageView) findViewById(R.id.imageIconView); iview.setImageBitmap(image); LinearLayout cameraContainer = (LinearLayout) findViewById(R.id.carmeraButtonLayout); cameraContainer.setVisibility(View.INVISIBLE); } } private class CreateSecretTask extends AsyncTask<HttpPost, Void, HttpResponse> { @Override protected HttpResponse doInBackground(HttpPost... params) { try { return new DefaultHttpClient().execute(params[0]); } catch (Exception e) { return null; } } @Override protected void onPostExecute(HttpResponse resultResponse) { Intent resultIntent = new Intent(); if (resultResponse != null) { HttpEntity entity = resultResponse.getEntity(); try { BufferedReader responseReader = new BufferedReader(new InputStreamReader(entity.getContent())); String result = responseReader.readLine(); if (result.equals(getString(R.string.successResponse))) { setResult(Activity.RESULT_OK, resultIntent); } } catch (Exception e) { e.printStackTrace(); } } postProgressDialog.dismiss(); finish(); } } }
7,508
0.753063
0.75
207
35.270531
28.607864
118
false
false
0
0
0
0
0
0
2.966184
false
false
7
11fd881cf62914eb42b13d07f01b9af1478c6948
12,781,822,708,309
3af60e7e393bebe0796d2da974323ee760cf52dd
/src/main/java/com/life/org/GameOfLife.java
c56c449626d054716456546700255371db90ece1
[]
no_license
stonefix/Typical-Game-of-Life
https://github.com/stonefix/Typical-Game-of-Life
8b2c5efc1c4a752961b3500f6e2d015544ff9f99
769a95d31f404fc1b3df2ba459af202dac389e79
refs/heads/main
2023-03-11T19:26:39.907000
2021-02-27T01:52:59
2021-02-27T01:52:59
342,443,467
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.life.org; public class GameOfLife { private final static int ROW = 40; private final static int COL = 40; private boolean[][] gridArray = new boolean[getROW()][getCOL()]; private int generation = 0; public void goToNextGeneration() { boolean[][] futureArray = new boolean[getROW()][getCOL()]; for (int i = 0; i < getROW(); i++) { for (int j = 0; j < getCOL(); j++) { int aliveNeighbors = calculateAliveNeighbors(i, j); futureArray[i][j] = aliveNeighbors == 3 || (gridArray[i][j] && aliveNeighbors == 2); } } gridArray = futureArray; this.generation = this.getGeneration() + 1; } public int calculateAliveNeighbors(int row, int column) { int aliveNeighbors = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if ((row + i) != -1 && (column + j) != -1 && (row + i != row || column + j != column) && row + i != getROW() && column + j != getCOL() && gridArray[row + i][column + j]) { aliveNeighbors++; } } } return aliveNeighbors; } public void clearGrid() { for (int i = 0; i < getROW(); i++) { for (int j = 0; j < getCOL(); j++) { gridArray[i][j] = false; } } generation = 0; } public boolean getCell(int row, int col) { return gridArray[row][col]; } public void setCell(int row, int col, boolean value) { gridArray[row][col] = value; } public void setRow(int row, boolean[] value) { for (int i = 0; i < COL; i++) { gridArray[row][i] = value[i]; } } public int getCountLives() { int count = 0; for (int i = 0; i < getROW(); i++) { for (int j = 0; j < getCOL(); j++) { if (gridArray[i][j]) { count++; } } } return count; } public int getGeneration() { return generation; } public static int getROW() { return ROW; } public static int getCOL() { return COL; } }
UTF-8
Java
2,314
java
GameOfLife.java
Java
[]
null
[]
package com.life.org; public class GameOfLife { private final static int ROW = 40; private final static int COL = 40; private boolean[][] gridArray = new boolean[getROW()][getCOL()]; private int generation = 0; public void goToNextGeneration() { boolean[][] futureArray = new boolean[getROW()][getCOL()]; for (int i = 0; i < getROW(); i++) { for (int j = 0; j < getCOL(); j++) { int aliveNeighbors = calculateAliveNeighbors(i, j); futureArray[i][j] = aliveNeighbors == 3 || (gridArray[i][j] && aliveNeighbors == 2); } } gridArray = futureArray; this.generation = this.getGeneration() + 1; } public int calculateAliveNeighbors(int row, int column) { int aliveNeighbors = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if ((row + i) != -1 && (column + j) != -1 && (row + i != row || column + j != column) && row + i != getROW() && column + j != getCOL() && gridArray[row + i][column + j]) { aliveNeighbors++; } } } return aliveNeighbors; } public void clearGrid() { for (int i = 0; i < getROW(); i++) { for (int j = 0; j < getCOL(); j++) { gridArray[i][j] = false; } } generation = 0; } public boolean getCell(int row, int col) { return gridArray[row][col]; } public void setCell(int row, int col, boolean value) { gridArray[row][col] = value; } public void setRow(int row, boolean[] value) { for (int i = 0; i < COL; i++) { gridArray[row][i] = value[i]; } } public int getCountLives() { int count = 0; for (int i = 0; i < getROW(); i++) { for (int j = 0; j < getCOL(); j++) { if (gridArray[i][j]) { count++; } } } return count; } public int getGeneration() { return generation; } public static int getROW() { return ROW; } public static int getCOL() { return COL; } }
2,314
0.454192
0.44382
86
25.906977
22.2369
100
false
false
0
0
0
0
0
0
0.604651
false
false
7
061ae764bc7eb2a777393d55c160a42cf698050a
28,269,474,793,331
f1f14650ef28653e674736f3d181400e7aea3911
/app/src/main/java/br/com/neolog/cplmobile/transition/TransitionGroup.java
fc3df85a3ddb98fca106c741b2d0664e8154f022
[]
no_license
DenisHDG/cpl-mobile
https://github.com/DenisHDG/cpl-mobile
efc9ee1f620ad31a910ad0a997d54aa82057540b
7090761de335f25c6a7eec2702b2033aa505fdee
refs/heads/master
2020-04-10T07:20:06.649000
2018-12-07T21:45:52
2018-12-07T21:45:52
160,878,055
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.neolog.cplmobile.transition; import static br.com.neolog.cplmobile.monitorable.repo.MonitorableSignalTimeCalculator.calculateLateStatus; import static br.com.neolog.monitoring.monitorable.model.api.transition.TransitionStatus.IN_EXECUTION; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.joda.time.DateTime; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import br.com.neolog.cplmobile.monitorable.model.LateStatus; import br.com.neolog.monitoring.monitorable.model.rest.RestLocality; import br.com.neolog.monitoring.monitorable.model.rest.transition.RestTransition; import br.com.neolog.monitoring.monitorable.model.rest.transition.RestTransitionLocation; public class TransitionGroup { private final int index; private final RestTransitionLocation location; private final List<MonitorableAndTransition> monitorableAndTransitions = new ArrayList<>(); private transient TransitionGroupStatus status; TransitionGroup( final int index, final RestTransitionLocation location ) { this.index = index; this.location = Preconditions.checkNotNull( location, "location is null" ); } public int getIndex() { return index; } public String getAddress() { final RestLocality locality = location.getLocality(); if( locality == null ) { return ""; } return Joiner.on( ", " ) .skipNulls() .join( locality.getStreet(), locality.getNumber(), locality.getComplement(), locality.getZipCode() ); } public String getLocalityName() { final RestLocality locality = location.getLocality(); if( locality == null ) { return ""; } return locality.getName(); } public DateTime getEstimatedArrival() { return monitorableAndTransitions.get( 0 ).getTransition().getEstimatedTimestamp(); } public TransitionGroupStatus getStatus() { if( status != null ) { return status; } if( monitorableAndTransitions.isEmpty() ) { return status = TransitionGroupStatus.DONE; } int count = 0; for( final MonitorableAndTransition monitorableAndTransition : monitorableAndTransitions ) { if( ! IN_EXECUTION.equals( monitorableAndTransition.getTransition().getStatus() ) ) { count++; } } if( count == 0 ) { return status = TransitionGroupStatus.OPEN; } if( count < monitorableAndTransitions.size() ) { return status = TransitionGroupStatus.IN_PROGRESS; } return status = TransitionGroupStatus.DONE; } List<MonitorableAndTransition> getMonitorableAndTransitions() { return monitorableAndTransitions; } @Nullable RestTransition getNextTransition() { RestTransition nextTransition = null; for( final MonitorableAndTransition monitorableAndTransition : Lists.reverse( monitorableAndTransitions ) ) { final RestTransition transition = monitorableAndTransition.getTransition(); if( ! IN_EXECUTION.equals( transition.getStatus() ) ) { return nextTransition; } nextTransition = transition; } return nextTransition; } public LateStatus getLateStatus() { final RestTransition nextTransition = getNextTransition(); return calculateLateStatus( nextTransition ); } void addTransition( final MonitorableAndTransition transition ) { monitorableAndTransitions.add( transition ); status = null; } @Override public boolean equals( final Object o ) { if( this == o ) return true; if( o == null || getClass() != o.getClass() ) return false; final TransitionGroup that = (TransitionGroup) o; return Objects.equal( location, that.location ) && Objects.equal( monitorableAndTransitions, that.monitorableAndTransitions ); } @Override public int hashCode() { return Objects.hashCode( location, monitorableAndTransitions ); } @Override public String toString() { return MoreObjects.toStringHelper( this ) .add( "location", location ) .add( "monitorableAndTransitions", monitorableAndTransitions ) .toString(); } }
UTF-8
Java
4,682
java
TransitionGroup.java
Java
[]
null
[]
package br.com.neolog.cplmobile.transition; import static br.com.neolog.cplmobile.monitorable.repo.MonitorableSignalTimeCalculator.calculateLateStatus; import static br.com.neolog.monitoring.monitorable.model.api.transition.TransitionStatus.IN_EXECUTION; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.joda.time.DateTime; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import br.com.neolog.cplmobile.monitorable.model.LateStatus; import br.com.neolog.monitoring.monitorable.model.rest.RestLocality; import br.com.neolog.monitoring.monitorable.model.rest.transition.RestTransition; import br.com.neolog.monitoring.monitorable.model.rest.transition.RestTransitionLocation; public class TransitionGroup { private final int index; private final RestTransitionLocation location; private final List<MonitorableAndTransition> monitorableAndTransitions = new ArrayList<>(); private transient TransitionGroupStatus status; TransitionGroup( final int index, final RestTransitionLocation location ) { this.index = index; this.location = Preconditions.checkNotNull( location, "location is null" ); } public int getIndex() { return index; } public String getAddress() { final RestLocality locality = location.getLocality(); if( locality == null ) { return ""; } return Joiner.on( ", " ) .skipNulls() .join( locality.getStreet(), locality.getNumber(), locality.getComplement(), locality.getZipCode() ); } public String getLocalityName() { final RestLocality locality = location.getLocality(); if( locality == null ) { return ""; } return locality.getName(); } public DateTime getEstimatedArrival() { return monitorableAndTransitions.get( 0 ).getTransition().getEstimatedTimestamp(); } public TransitionGroupStatus getStatus() { if( status != null ) { return status; } if( monitorableAndTransitions.isEmpty() ) { return status = TransitionGroupStatus.DONE; } int count = 0; for( final MonitorableAndTransition monitorableAndTransition : monitorableAndTransitions ) { if( ! IN_EXECUTION.equals( monitorableAndTransition.getTransition().getStatus() ) ) { count++; } } if( count == 0 ) { return status = TransitionGroupStatus.OPEN; } if( count < monitorableAndTransitions.size() ) { return status = TransitionGroupStatus.IN_PROGRESS; } return status = TransitionGroupStatus.DONE; } List<MonitorableAndTransition> getMonitorableAndTransitions() { return monitorableAndTransitions; } @Nullable RestTransition getNextTransition() { RestTransition nextTransition = null; for( final MonitorableAndTransition monitorableAndTransition : Lists.reverse( monitorableAndTransitions ) ) { final RestTransition transition = monitorableAndTransition.getTransition(); if( ! IN_EXECUTION.equals( transition.getStatus() ) ) { return nextTransition; } nextTransition = transition; } return nextTransition; } public LateStatus getLateStatus() { final RestTransition nextTransition = getNextTransition(); return calculateLateStatus( nextTransition ); } void addTransition( final MonitorableAndTransition transition ) { monitorableAndTransitions.add( transition ); status = null; } @Override public boolean equals( final Object o ) { if( this == o ) return true; if( o == null || getClass() != o.getClass() ) return false; final TransitionGroup that = (TransitionGroup) o; return Objects.equal( location, that.location ) && Objects.equal( monitorableAndTransitions, that.monitorableAndTransitions ); } @Override public int hashCode() { return Objects.hashCode( location, monitorableAndTransitions ); } @Override public String toString() { return MoreObjects.toStringHelper( this ) .add( "location", location ) .add( "monitorableAndTransitions", monitorableAndTransitions ) .toString(); } }
4,682
0.655916
0.655276
151
30.006622
28.50967
117
false
false
0
0
0
0
0
0
0.437086
false
false
7
308c9b0f6cd3b8c5658eb6b75bae0de3335f0294
9,938,554,389,142
a9cd1c4105a7b64b48ced7a6dba9e865df2d8588
/Selection.java
1d643f46d373c75e09072bc714a96cbb73b1fe23
[]
no_license
hammmmm/Sorting-Algorithms
https://github.com/hammmmm/Sorting-Algorithms
f31113ca62a658cab45b2461e4a70b240c975e9e
406660d3a12f70b6c331ad26810cb7526247810b
refs/heads/master
2021-01-25T09:10:46.978000
2017-06-08T22:31:37
2017-06-08T22:31:37
93,796,739
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Selection { /* * SELECTION SORT * * @params: int[] array * @throws: none * @return: none */ public void selectionSort(int arr[]) { int n = arr.length; for(int i = 0; i < n; i++) { //outer loop that continues until last index int small = arr[i]; //small is now the first index of the array int pos = i; //keep track of position for(int j = i + 1; j < n; j++) {//innerloop thats offset by 1 if(arr[j] < small) { //checks if arr[j] is smaller than 'small', if true, that is now new small small = arr[j]; //new small if true pos = j; } } //swap the minimum element with the current index int temp = arr[pos]; arr[pos] = arr[i]; arr[i] = temp; } } }
UTF-8
Java
862
java
Selection.java
Java
[]
null
[]
class Selection { /* * SELECTION SORT * * @params: int[] array * @throws: none * @return: none */ public void selectionSort(int arr[]) { int n = arr.length; for(int i = 0; i < n; i++) { //outer loop that continues until last index int small = arr[i]; //small is now the first index of the array int pos = i; //keep track of position for(int j = i + 1; j < n; j++) {//innerloop thats offset by 1 if(arr[j] < small) { //checks if arr[j] is smaller than 'small', if true, that is now new small small = arr[j]; //new small if true pos = j; } } //swap the minimum element with the current index int temp = arr[pos]; arr[pos] = arr[i]; arr[i] = temp; } } }
862
0.484919
0.481439
31
26.838709
26.302332
107
false
false
0
0
0
0
0
0
0.451613
false
false
7
997e208569ad13e3c7321a5d410bd345de49bd9c
5,188,320,513,199
fe876d6ca452a0f786c4e49f71f2b7075658f57c
/graph/GraphObj.java
282405b319628f0e49266025366af112b685c5a0
[]
no_license
rajandutta/CS61B-Graphs
https://github.com/rajandutta/CS61B-Graphs
43cc95b2a24278c70d296938fa37c1471abac00d
f4fe9a045320e5077c54dda4cdc14173689bb696
refs/heads/master
2018-02-08T19:36:50.637000
2017-01-30T06:22:40
2017-01-30T06:22:40
80,398,447
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package graph; /* See restrictions in Graph.java. */ /** A partial implementation of Graph containing elements common to * directed and undirected graphs. * * @author Raju Dutta * * !! Collaborated with Karthik Kadalabalu Matha */ abstract class GraphObj extends Graph { /** A new, empty Graph. */ GraphObj() { _vertices = new int[8][3][]; for (int i = 0; i < _vertices.length; i++) { _vertices[i][0] = new int[] {}; _vertices[i][1] = new int[] {}; _vertices[i][2] = new int[] { -1 }; } _avlVertex = 1; _numVertices = 0; _maxVertex = 0; _edges = new LinkedListOfArrs(); } @Override public int vertexSize() { return _numVertices; } @Override public int maxVertex() { return _maxVertex; } @Override public int edgeSize() { return _edges.getSize(); } @Override public abstract boolean isDirected(); @Override public abstract int outDegree(int v); @Override public abstract int inDegree(int v); @Override public boolean contains(int u) { if (u <= 0 || u >= _vertices.length) { return false; } if (_vertices[u][0] == null && _vertices[u][1] == null) { return false; } else if (_vertices[u][0].length == 0 && _vertices[u][1].length == 0) { return false; } return _vertices[u][0][0] != -1; } /** Checks list of edges to see if edge u-v is an edge. */ @Override public boolean contains(int u, int v) { int k = 0; if (!contains(u) || !contains(v)) { return false; } while (k < _edges.getSize()) { int a = _edges.getArr(k)[0]; int b = _edges.getArr(k)[1]; if (!isDirected() && ((a == u && b == v) || (a == v && b == u))) { return true; } else if (isDirected() && (a == u && b == v)) { return true; } k++; } return false; } /** Adds a vertex to _vertices and returns the index of the new vertex. */ @Override public int add() { if (_avlVertex >= _vertices.length) { resizeVertices(); } _vertices[_avlVertex][0] = new int[] { 0 }; _vertices[_avlVertex][1] = new int[] { 0 }; _vertices[_avlVertex][2] = new int[] { -1 }; int loc = _avlVertex; _numVertices++; if (_avlVertex == _maxVertex + 1) { _maxVertex = _avlVertex; } _avlVertex++; while (contains(_avlVertex) && _avlVertex != _vertices.length) { _avlVertex++; } return loc; } /** Adds an edge to _EDGES and returns the ID of the edge. * If succ == true, then add v to the successor list of u. * If succ == false, then add u to the predecessor list of v. */ @Override public int add(int u, int v) { int e = edgeId(u, v); int[] x = new int[] {u, v}; if (!contains(u, v) && contains(u) && contains(v)) { _edges.insertAtEnd(x); updateVertexPredSucc(u, v, true); if (!isDirected() && u != v) { updateVertexPredSucc(v, u, true); } } return e; } /** Helper method for updating predecessor lists and successor lists in * _vertices. * If ADD == true, then add v in u's succ list and add u in v's pred list. * If ADD == f, delete v from u's succ list & delete u from v's pred list. * * @param u represents the vertex u * @param v represents the vertex v * @param add true if adding, false if deleting * */ private void updateVertexPredSucc(int u, int v, boolean add) { if (add) { boolean addedSucc = false; boolean addedPred = false; int i; for (i = 0; i < _vertices[u][1].length; i++) { if (_vertices[u][1][i] == 0) { _vertices[u][1][i] = v; addedSucc = true; break; } } if (!addedSucc) { resizeConnections(u, 1); _vertices[u][1][i] = v; } int j; for (j = 0; j < _vertices[v][0].length; j++) { if (_vertices[v][0][j] == 0) { _vertices[v][0][j] = u; addedPred = true; break; } } if (!addedPred) { resizeConnections(v, 0); _vertices[v][0][j] = u; } } else { for (int a = 0; a < _vertices[u][1].length; a++) { if (_vertices[u][1][a] == v) { _vertices[u][1][a] = 0; break; } } for (int b = 0; b < _vertices[v][0].length; b++) { if (_vertices[v][0][b] == u) { _vertices[v][0][b] = 0; break; } } } } @Override public void remove(int v) { if (contains(v)) { _vertices[v][0] = new int[] {}; _vertices[v][1] = new int[] {}; _vertices[v][2] = new int[] { -1 }; for (int k = 1; k < _vertices.length; k++) { for (int h = 0; h < _vertices[k].length - 1; h++) { for (int j = 0; j < _vertices[k][h].length; j++) { if (_vertices[k][h][j] == v) { _vertices[k][h][j] = 0; } } } } _numVertices--; if (_maxVertex == v) { for (int j = v - 1; j > 0; j--) { if (contains(j)) { _maxVertex = j; break; } } } if (_avlVertex > v) { _avlVertex = v; } int k = 0; while (k < _edges.getSize()) { if ((_edges.getArr(k)[0] == v || _edges.getArr(k)[1] == v)) { _edges.delete(_edges.getArr(k)); k--; } k++; } } } /** Removes an edge from _EDGES. */ @Override public void remove(int u, int v) { if (_edges.getArr(0) != null) { int k = 0; if (!isDirected()) { while (k < _edges.getSize()) { int a = _edges.getArr(k)[0]; int b = _edges.getArr(k)[1]; if ((a == u && b == v) || (a == u && b == v)) { _edges.delete(_edges.getArr(k)); } k++; } updateVertexPredSucc(u, v, false); updateVertexPredSucc(v, u, false); } else { int a = _edges.getArr(k)[0]; int b = _edges.getArr(k)[1]; while (k < _edges.getSize()) { if ((a == u && b == v)) { _edges.delete(_edges.getArr(k)); } k++; } updateVertexPredSucc(u, v, false); } } } @Override public Iteration<Integer> vertices() { Iteration<Integer> iterator = new Iteration<Integer>() { private int k = 1; @Override public boolean hasNext() { return k < _vertices.length && k <= maxVertex(); } @Override public Integer next() { while (hasNext()) { if (contains(k)) { k++; return k - 1; } else { k++; } } return 0; } private int getK() { return k; } }; return iterator; } @Override public int successor(int v, int k) { int[] successors = _vertices[v][1]; int counter = 0; int whileCounter = 0; while (whileCounter < successors.length && counter < successors.length && counter != k) { if (successors[counter] != 0) { counter++; } whileCounter++; } if (counter == k) { return successors[counter]; } return 0; } @Override public abstract int predecessor(int v, int k); @Override public Iteration<Integer> successors(int v) { Iteration<Integer> iterator = new Iteration<Integer>() { private int k = 0; @Override public boolean hasNext() { while (k < _vertices[v][1].length && _vertices[v][1][k] == 0) { k++; } if (k < _vertices[v][1].length) { return true; } return false; } @Override public Integer next() { return _vertices[v][1][k++]; } private int getK() { return k; } }; return iterator; } @Override public abstract Iteration<Integer> predecessors(int v); @Override public Iteration<int[]> edges() { Iteration<int[]> iterator = new Iteration<int[]>() { private ArrNode current = _edges.head; @Override public boolean hasNext() { return current != null; } @Override public int[] next() { int[] toReturn = current.getRoot(); current = current.getNext(); return toReturn; } private ArrNode getCurrent() { return current; } }; return iterator; } @Override protected void checkMyVertex(int v) { if (!contains(v)) { throw new IllegalArgumentException("Vertex V not in graph."); } } @Override protected int edgeId(int u, int v) { return (u + 1) * v + (v - 1) * u; } /** Added Methods. */ @Override protected int[][][] getVertices() { return _vertices; } @Override protected LinkedListOfArrs getEdges() { return _edges; } /** Returns first available (empty) vertex. */ protected int getAvlVertex() { return _avlVertex; } /** If vertex i has more connections than the size of its list, this method * increases the size of the array at index i of _vertices. * Also uses amortized time and doubles size of list. * To be used right before adding a succ/pred to vertex v, if needed. * * @param a 0 if should resize pred list, 1 if succ list * @param v vertex v * * */ protected void resizeConnections(int v, int a) { int[] original = _vertices[v][a]; if (original.length >= 1) { int[] newArr = new int[original.length * 2]; boolean negOnes = _vertices[v][a][0] == -1 && _vertices[v][a][1] == -1; for (int i = 0; i < newArr.length; i++) { if (i < original.length) { newArr[i] = original[i]; } else { if (negOnes) { newArr[i] = -1; } else { newArr[i] = 0; } } } _vertices[v][a] = newArr; } else { _vertices[v][a] = new int[] {-1}; } } /** Used to resize _vertices, doubling size to get amortized time. */ protected void resizeVertices() { int[][][] newVertices = new int[_vertices.length * 2][3][]; for (int i = 0; i < newVertices.length; i++) { if (i < _vertices.length) { newVertices[i] = new int[3][]; for (int j = 0; j < newVertices[i].length; j++) { newVertices[i][j] = new int[_vertices[i][j].length]; for (int k = 0; k < newVertices[i][j].length; k++) { newVertices[i][j][k] = _vertices[i][j][k]; } } } else { newVertices[i][0] = new int[] {-1, -1}; newVertices[i][1] = new int[] {-1, -1}; newVertices[i][2] = new int[] { -1}; } } _vertices = newVertices; } /** Return the # of elements in A that aren't 0 nor -1. * @param a 1D array to be printed * @return count of nonzero/non-negative-one elements * * */ protected int arrSize(int[] a) { int count = 0; for (int i : a) { if (i != 0 && i != -1) { count++; } } return count; } /** Given a 3D array a, print out all values. * @param a 3D array to be printed. * @return String to be printed * * */ protected String printTripleArray(int[][][] a) { String result = ""; int breakCount = 0; for (int i = 0; i < a.length; i++) { result += "["; for (int j = 0; j < a[i].length; j++) { result += "["; for (int k = 0; k < a[i][j].length; k++) { result += a[i][j][k] + ", "; } result += "]"; } result += "] "; breakCount++; if (breakCount == 4) { result += "\n"; breakCount = 0; } } return result; } /** Print all edges. * @return the String to be printed * */ protected String printEdges() { return _edges.printList(); } /** I am implementing the list of edges as a linked list. This way, * if an edge gets deleted, I would not have to reassign everything after * it like I would have for an array. * The only insert method is for inserting at the end. */ protected class LinkedListOfArrs { /** Represents the head of the linked list. */ private ArrNode head; /** Keeps track of length of linked list. */ private int size; /** Constructor for this class. */ LinkedListOfArrs() { head = null; size = 0; } /** Getter method for head. * @return the ArrNode at the head position. */ private ArrNode getHead() { return head; } /** Getter method for size. * @return the size of the linked list. * */ private int getsize() { return size; } /** Getter method for size. * @return the size of the linked list. * */ protected int getSize() { return getsize(); } /** Method to set size. * @param s set the size to s. * */ protected void setSize(int s) { size = s; } /** Method to increment size by i. * @param i the amount to increase size by. * */ private void incrementSize(int i) { size += i; } /** Returns the array that is k spots from the beginning. * @param k find the ArrNode with value k. * */ protected int[] getArr(int k) { if (this != null) { if (k == 0) { return head.getRoot(); } else { ArrNode current = head.getNext(); k--; while (k > 0 && current != null) { current = current.getNext(); k--; } if (current == null) { return null; } return current.getRoot(); } } return new int[] {}; } /** Inserts a new ArrNode with value k at end of list. * @param k create ArrNode with value k and insert at end of list. * */ protected void insertAtEnd(int[] k) { ArrNode toAdd = new ArrNode(k); if (this.head == null) { this.head = toAdd; this.head.setNext(null); } else { ArrNode current = this.head; while (current != null) { if (current.getNext() == null) { current.setNext(toAdd); break; } current = current.getNext(); } } size++; } /** Find and deletes the ArrNode with value k. * @param k find the ArrNode with value k and delete it * */ protected void delete(int[] k) { if (this != null) { ArrNode current = head.getNext(); ArrNode prev = head; if (prev.getRoot() == k) { head = current; } else { while (current != null && !current.getRoot().equals(k)) { current = current.getNext(); prev = prev.getNext(); } if (current != null) { if (current.getNext() == null) { prev.setNext(null); } else { prev.setNext(current.getNext()); } } } } size--; } /** Prints out this linked list. * @return the string to be printed */ protected String printList() { String result = "<< "; ArrNode current = this.head; if (current != null) { int breakCount = 0; while (current != null) { result += printArr(current.getRoot()); breakCount++; if (breakCount == 5) { result += "\n"; breakCount = 0; } current = current.getNext(); } } result += " >>"; return result; } /** Prints out an array contained in one of the ArrNodes in this. * @param a the array to be printed * @return string to print. */ private String printArr(int[] a) { String s = "["; for (int i : a) { s += i + ", "; } s += "] "; return s; } } /** In each node of the linked list of edges is an array representing * an edge. This class is the object for that array. */ protected class ArrNode { /** Represents the array contained in the node. */ private int[] _root; /** Points to the next ArrNode. */ private ArrNode _next; /** Constructor for this class. * @param n the array that root will be set to */ ArrNode(int[] n) { _root = n; _next = null; } /** Getter method for root. * @return the root array */ private int[] getRoot() { return _root; } /** Getter method for next ArrNode. * @return the next ArrNode */ private ArrNode getNext() { return _next; } /** Setter method for root. * @param x the array that the root should be set to */ private void setRoot(int[] x) { _root = x; } /** Setter method for next ArrNode. * @param a the ArrNode that _next should be set to */ private void setNext(ArrNode a) { _next = a; } } /** Array of arrays where the index represents the vertex number * and the array at each index i contains another array such that: * inner_array[0] is a list of predecessors, * inner_array[1] = list of successors, * inner_array[2] = 1 if marked, -1 if not * Initially has space for 8 vertices, each having 2 spots for pred/succ * to begin with. -1 acts as a "no connection": * If the array at _vertices[i] = {}, it does not have any connections. * When adding a vertex to spot i (just adding, not connecting yet), * increase size of its pred & succ lists to 1, and populate with 0. * If _vertices[i] = {4, 0}, then only points to vertex 4. * NOTE: if add edge [1, 2], add 2 to 1's succs and add 1 to 2's preds * */ private int[][][] _vertices; /** Keeps track of important data of _vertices. Format: * _avlVertex = first available index (>=1) for a vertex to be added * __numVertices = number of vertices * _maxVertex = largest vertex. */ private int _avlVertex; /** Read above javadoc. */ private int _numVertices; /** Read above javadoc. */ private int _maxVertex; /** Linked list of arrays where each array within the LL is a 3-element * array of the form ['from' vertex, 'to' vertex]. weight = 1 unless * is a labeled graph. */ private LinkedListOfArrs _edges; }
UTF-8
Java
21,823
java
GraphObj.java
Java
[ { "context": " * directed and undirected graphs.\n *\n * @author Raju Dutta\n *\n * !! Collaborated with Karthik Kadalabalu Ma", "end": 184, "score": 0.9998877644538879, "start": 174, "tag": "NAME", "value": "Raju Dutta" }, { "context": " * @author Raju Dutta\n *\n * !! Collaborated with Karthik Kadalabalu Matha\n */\nabstract class GraphObj extends Graph {\n\n ", "end": 237, "score": 0.9997211694717407, "start": 213, "tag": "NAME", "value": "Karthik Kadalabalu Matha" } ]
null
[]
package graph; /* See restrictions in Graph.java. */ /** A partial implementation of Graph containing elements common to * directed and undirected graphs. * * @author <NAME> * * !! Collaborated with <NAME> */ abstract class GraphObj extends Graph { /** A new, empty Graph. */ GraphObj() { _vertices = new int[8][3][]; for (int i = 0; i < _vertices.length; i++) { _vertices[i][0] = new int[] {}; _vertices[i][1] = new int[] {}; _vertices[i][2] = new int[] { -1 }; } _avlVertex = 1; _numVertices = 0; _maxVertex = 0; _edges = new LinkedListOfArrs(); } @Override public int vertexSize() { return _numVertices; } @Override public int maxVertex() { return _maxVertex; } @Override public int edgeSize() { return _edges.getSize(); } @Override public abstract boolean isDirected(); @Override public abstract int outDegree(int v); @Override public abstract int inDegree(int v); @Override public boolean contains(int u) { if (u <= 0 || u >= _vertices.length) { return false; } if (_vertices[u][0] == null && _vertices[u][1] == null) { return false; } else if (_vertices[u][0].length == 0 && _vertices[u][1].length == 0) { return false; } return _vertices[u][0][0] != -1; } /** Checks list of edges to see if edge u-v is an edge. */ @Override public boolean contains(int u, int v) { int k = 0; if (!contains(u) || !contains(v)) { return false; } while (k < _edges.getSize()) { int a = _edges.getArr(k)[0]; int b = _edges.getArr(k)[1]; if (!isDirected() && ((a == u && b == v) || (a == v && b == u))) { return true; } else if (isDirected() && (a == u && b == v)) { return true; } k++; } return false; } /** Adds a vertex to _vertices and returns the index of the new vertex. */ @Override public int add() { if (_avlVertex >= _vertices.length) { resizeVertices(); } _vertices[_avlVertex][0] = new int[] { 0 }; _vertices[_avlVertex][1] = new int[] { 0 }; _vertices[_avlVertex][2] = new int[] { -1 }; int loc = _avlVertex; _numVertices++; if (_avlVertex == _maxVertex + 1) { _maxVertex = _avlVertex; } _avlVertex++; while (contains(_avlVertex) && _avlVertex != _vertices.length) { _avlVertex++; } return loc; } /** Adds an edge to _EDGES and returns the ID of the edge. * If succ == true, then add v to the successor list of u. * If succ == false, then add u to the predecessor list of v. */ @Override public int add(int u, int v) { int e = edgeId(u, v); int[] x = new int[] {u, v}; if (!contains(u, v) && contains(u) && contains(v)) { _edges.insertAtEnd(x); updateVertexPredSucc(u, v, true); if (!isDirected() && u != v) { updateVertexPredSucc(v, u, true); } } return e; } /** Helper method for updating predecessor lists and successor lists in * _vertices. * If ADD == true, then add v in u's succ list and add u in v's pred list. * If ADD == f, delete v from u's succ list & delete u from v's pred list. * * @param u represents the vertex u * @param v represents the vertex v * @param add true if adding, false if deleting * */ private void updateVertexPredSucc(int u, int v, boolean add) { if (add) { boolean addedSucc = false; boolean addedPred = false; int i; for (i = 0; i < _vertices[u][1].length; i++) { if (_vertices[u][1][i] == 0) { _vertices[u][1][i] = v; addedSucc = true; break; } } if (!addedSucc) { resizeConnections(u, 1); _vertices[u][1][i] = v; } int j; for (j = 0; j < _vertices[v][0].length; j++) { if (_vertices[v][0][j] == 0) { _vertices[v][0][j] = u; addedPred = true; break; } } if (!addedPred) { resizeConnections(v, 0); _vertices[v][0][j] = u; } } else { for (int a = 0; a < _vertices[u][1].length; a++) { if (_vertices[u][1][a] == v) { _vertices[u][1][a] = 0; break; } } for (int b = 0; b < _vertices[v][0].length; b++) { if (_vertices[v][0][b] == u) { _vertices[v][0][b] = 0; break; } } } } @Override public void remove(int v) { if (contains(v)) { _vertices[v][0] = new int[] {}; _vertices[v][1] = new int[] {}; _vertices[v][2] = new int[] { -1 }; for (int k = 1; k < _vertices.length; k++) { for (int h = 0; h < _vertices[k].length - 1; h++) { for (int j = 0; j < _vertices[k][h].length; j++) { if (_vertices[k][h][j] == v) { _vertices[k][h][j] = 0; } } } } _numVertices--; if (_maxVertex == v) { for (int j = v - 1; j > 0; j--) { if (contains(j)) { _maxVertex = j; break; } } } if (_avlVertex > v) { _avlVertex = v; } int k = 0; while (k < _edges.getSize()) { if ((_edges.getArr(k)[0] == v || _edges.getArr(k)[1] == v)) { _edges.delete(_edges.getArr(k)); k--; } k++; } } } /** Removes an edge from _EDGES. */ @Override public void remove(int u, int v) { if (_edges.getArr(0) != null) { int k = 0; if (!isDirected()) { while (k < _edges.getSize()) { int a = _edges.getArr(k)[0]; int b = _edges.getArr(k)[1]; if ((a == u && b == v) || (a == u && b == v)) { _edges.delete(_edges.getArr(k)); } k++; } updateVertexPredSucc(u, v, false); updateVertexPredSucc(v, u, false); } else { int a = _edges.getArr(k)[0]; int b = _edges.getArr(k)[1]; while (k < _edges.getSize()) { if ((a == u && b == v)) { _edges.delete(_edges.getArr(k)); } k++; } updateVertexPredSucc(u, v, false); } } } @Override public Iteration<Integer> vertices() { Iteration<Integer> iterator = new Iteration<Integer>() { private int k = 1; @Override public boolean hasNext() { return k < _vertices.length && k <= maxVertex(); } @Override public Integer next() { while (hasNext()) { if (contains(k)) { k++; return k - 1; } else { k++; } } return 0; } private int getK() { return k; } }; return iterator; } @Override public int successor(int v, int k) { int[] successors = _vertices[v][1]; int counter = 0; int whileCounter = 0; while (whileCounter < successors.length && counter < successors.length && counter != k) { if (successors[counter] != 0) { counter++; } whileCounter++; } if (counter == k) { return successors[counter]; } return 0; } @Override public abstract int predecessor(int v, int k); @Override public Iteration<Integer> successors(int v) { Iteration<Integer> iterator = new Iteration<Integer>() { private int k = 0; @Override public boolean hasNext() { while (k < _vertices[v][1].length && _vertices[v][1][k] == 0) { k++; } if (k < _vertices[v][1].length) { return true; } return false; } @Override public Integer next() { return _vertices[v][1][k++]; } private int getK() { return k; } }; return iterator; } @Override public abstract Iteration<Integer> predecessors(int v); @Override public Iteration<int[]> edges() { Iteration<int[]> iterator = new Iteration<int[]>() { private ArrNode current = _edges.head; @Override public boolean hasNext() { return current != null; } @Override public int[] next() { int[] toReturn = current.getRoot(); current = current.getNext(); return toReturn; } private ArrNode getCurrent() { return current; } }; return iterator; } @Override protected void checkMyVertex(int v) { if (!contains(v)) { throw new IllegalArgumentException("Vertex V not in graph."); } } @Override protected int edgeId(int u, int v) { return (u + 1) * v + (v - 1) * u; } /** Added Methods. */ @Override protected int[][][] getVertices() { return _vertices; } @Override protected LinkedListOfArrs getEdges() { return _edges; } /** Returns first available (empty) vertex. */ protected int getAvlVertex() { return _avlVertex; } /** If vertex i has more connections than the size of its list, this method * increases the size of the array at index i of _vertices. * Also uses amortized time and doubles size of list. * To be used right before adding a succ/pred to vertex v, if needed. * * @param a 0 if should resize pred list, 1 if succ list * @param v vertex v * * */ protected void resizeConnections(int v, int a) { int[] original = _vertices[v][a]; if (original.length >= 1) { int[] newArr = new int[original.length * 2]; boolean negOnes = _vertices[v][a][0] == -1 && _vertices[v][a][1] == -1; for (int i = 0; i < newArr.length; i++) { if (i < original.length) { newArr[i] = original[i]; } else { if (negOnes) { newArr[i] = -1; } else { newArr[i] = 0; } } } _vertices[v][a] = newArr; } else { _vertices[v][a] = new int[] {-1}; } } /** Used to resize _vertices, doubling size to get amortized time. */ protected void resizeVertices() { int[][][] newVertices = new int[_vertices.length * 2][3][]; for (int i = 0; i < newVertices.length; i++) { if (i < _vertices.length) { newVertices[i] = new int[3][]; for (int j = 0; j < newVertices[i].length; j++) { newVertices[i][j] = new int[_vertices[i][j].length]; for (int k = 0; k < newVertices[i][j].length; k++) { newVertices[i][j][k] = _vertices[i][j][k]; } } } else { newVertices[i][0] = new int[] {-1, -1}; newVertices[i][1] = new int[] {-1, -1}; newVertices[i][2] = new int[] { -1}; } } _vertices = newVertices; } /** Return the # of elements in A that aren't 0 nor -1. * @param a 1D array to be printed * @return count of nonzero/non-negative-one elements * * */ protected int arrSize(int[] a) { int count = 0; for (int i : a) { if (i != 0 && i != -1) { count++; } } return count; } /** Given a 3D array a, print out all values. * @param a 3D array to be printed. * @return String to be printed * * */ protected String printTripleArray(int[][][] a) { String result = ""; int breakCount = 0; for (int i = 0; i < a.length; i++) { result += "["; for (int j = 0; j < a[i].length; j++) { result += "["; for (int k = 0; k < a[i][j].length; k++) { result += a[i][j][k] + ", "; } result += "]"; } result += "] "; breakCount++; if (breakCount == 4) { result += "\n"; breakCount = 0; } } return result; } /** Print all edges. * @return the String to be printed * */ protected String printEdges() { return _edges.printList(); } /** I am implementing the list of edges as a linked list. This way, * if an edge gets deleted, I would not have to reassign everything after * it like I would have for an array. * The only insert method is for inserting at the end. */ protected class LinkedListOfArrs { /** Represents the head of the linked list. */ private ArrNode head; /** Keeps track of length of linked list. */ private int size; /** Constructor for this class. */ LinkedListOfArrs() { head = null; size = 0; } /** Getter method for head. * @return the ArrNode at the head position. */ private ArrNode getHead() { return head; } /** Getter method for size. * @return the size of the linked list. * */ private int getsize() { return size; } /** Getter method for size. * @return the size of the linked list. * */ protected int getSize() { return getsize(); } /** Method to set size. * @param s set the size to s. * */ protected void setSize(int s) { size = s; } /** Method to increment size by i. * @param i the amount to increase size by. * */ private void incrementSize(int i) { size += i; } /** Returns the array that is k spots from the beginning. * @param k find the ArrNode with value k. * */ protected int[] getArr(int k) { if (this != null) { if (k == 0) { return head.getRoot(); } else { ArrNode current = head.getNext(); k--; while (k > 0 && current != null) { current = current.getNext(); k--; } if (current == null) { return null; } return current.getRoot(); } } return new int[] {}; } /** Inserts a new ArrNode with value k at end of list. * @param k create ArrNode with value k and insert at end of list. * */ protected void insertAtEnd(int[] k) { ArrNode toAdd = new ArrNode(k); if (this.head == null) { this.head = toAdd; this.head.setNext(null); } else { ArrNode current = this.head; while (current != null) { if (current.getNext() == null) { current.setNext(toAdd); break; } current = current.getNext(); } } size++; } /** Find and deletes the ArrNode with value k. * @param k find the ArrNode with value k and delete it * */ protected void delete(int[] k) { if (this != null) { ArrNode current = head.getNext(); ArrNode prev = head; if (prev.getRoot() == k) { head = current; } else { while (current != null && !current.getRoot().equals(k)) { current = current.getNext(); prev = prev.getNext(); } if (current != null) { if (current.getNext() == null) { prev.setNext(null); } else { prev.setNext(current.getNext()); } } } } size--; } /** Prints out this linked list. * @return the string to be printed */ protected String printList() { String result = "<< "; ArrNode current = this.head; if (current != null) { int breakCount = 0; while (current != null) { result += printArr(current.getRoot()); breakCount++; if (breakCount == 5) { result += "\n"; breakCount = 0; } current = current.getNext(); } } result += " >>"; return result; } /** Prints out an array contained in one of the ArrNodes in this. * @param a the array to be printed * @return string to print. */ private String printArr(int[] a) { String s = "["; for (int i : a) { s += i + ", "; } s += "] "; return s; } } /** In each node of the linked list of edges is an array representing * an edge. This class is the object for that array. */ protected class ArrNode { /** Represents the array contained in the node. */ private int[] _root; /** Points to the next ArrNode. */ private ArrNode _next; /** Constructor for this class. * @param n the array that root will be set to */ ArrNode(int[] n) { _root = n; _next = null; } /** Getter method for root. * @return the root array */ private int[] getRoot() { return _root; } /** Getter method for next ArrNode. * @return the next ArrNode */ private ArrNode getNext() { return _next; } /** Setter method for root. * @param x the array that the root should be set to */ private void setRoot(int[] x) { _root = x; } /** Setter method for next ArrNode. * @param a the ArrNode that _next should be set to */ private void setNext(ArrNode a) { _next = a; } } /** Array of arrays where the index represents the vertex number * and the array at each index i contains another array such that: * inner_array[0] is a list of predecessors, * inner_array[1] = list of successors, * inner_array[2] = 1 if marked, -1 if not * Initially has space for 8 vertices, each having 2 spots for pred/succ * to begin with. -1 acts as a "no connection": * If the array at _vertices[i] = {}, it does not have any connections. * When adding a vertex to spot i (just adding, not connecting yet), * increase size of its pred & succ lists to 1, and populate with 0. * If _vertices[i] = {4, 0}, then only points to vertex 4. * NOTE: if add edge [1, 2], add 2 to 1's succs and add 1 to 2's preds * */ private int[][][] _vertices; /** Keeps track of important data of _vertices. Format: * _avlVertex = first available index (>=1) for a vertex to be added * __numVertices = number of vertices * _maxVertex = largest vertex. */ private int _avlVertex; /** Read above javadoc. */ private int _numVertices; /** Read above javadoc. */ private int _maxVertex; /** Linked list of arrays where each array within the LL is a 3-element * array of the form ['from' vertex, 'to' vertex]. weight = 1 unless * is a labeled graph. */ private LinkedListOfArrs _edges; }
21,801
0.431059
0.423819
752
28.019947
20.351194
80
false
false
0
0
0
0
0
0
0.413564
false
false
7
5b4c17bdbeec30a047401f3c8a00edb3b287c5ed
19,576,460,951,074
c6466c183b85c31edb0155c81b92d501543e3a1f
/valentine/src/main/java/com/spring/valenetin/SpringTester.java
21308986f335a1a2e77b6338956ca9ad606a0336
[]
no_license
anilyadav98/SpringService
https://github.com/anilyadav98/SpringService
e429c679f847a411e5985e196cc1ec06313a1575
5855b9755d5271a278ac8ed799995e679a832c59
refs/heads/master
2022-07-11T15:01:16.570000
2020-02-08T10:15:49
2020-02-08T10:15:49
238,916,241
0
0
null
false
2022-06-21T02:45:34
2020-02-07T12:28:44
2020-02-08T10:15:52
2022-06-21T02:45:34
12
0
0
2
Java
false
false
package com.spring.valenetin; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.valenetin.entity.ValentineEntity; import com.spring.valenetin.service.ValentineServiceImpl; public class SpringTester { public static void main(String[] args) { try { ApplicationContext container = new ClassPathXmlApplicationContext("spring.xml"); ValentineServiceImpl refOfValentineServiceImpl = container.getBean(ValentineServiceImpl.class); ValentineEntity entity = new ValentineEntity(); entity.setId(1); entity.setName("eswer"); entity.setStatus("double"); entity.setGift("ring"); entity.setAmmountSpent(420); refOfValentineServiceImpl.validateAndSave(entity); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
885
java
SpringTester.java
Java
[ { "context": "ntity();\r\n\t\t\tentity.setId(1);\r\n\t\t\tentity.setName(\"eswer\");\r\n\t\t\tentity.setStatus(\"double\");\r\n\t\t\tentity.set", "end": 656, "score": 0.9921267032623291, "start": 651, "tag": "NAME", "value": "eswer" } ]
null
[]
package com.spring.valenetin; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.valenetin.entity.ValentineEntity; import com.spring.valenetin.service.ValentineServiceImpl; public class SpringTester { public static void main(String[] args) { try { ApplicationContext container = new ClassPathXmlApplicationContext("spring.xml"); ValentineServiceImpl refOfValentineServiceImpl = container.getBean(ValentineServiceImpl.class); ValentineEntity entity = new ValentineEntity(); entity.setId(1); entity.setName("eswer"); entity.setStatus("double"); entity.setGift("ring"); entity.setAmmountSpent(420); refOfValentineServiceImpl.validateAndSave(entity); } catch (Exception e) { e.printStackTrace(); } } }
885
0.742373
0.737853
32
25.65625
26.661781
98
false
false
0
0
0
0
0
0
2.0625
false
false
7
aa6ed88b0641f6cc9a807daa89ad062956823e34
6,992,206,791,768
23d686ed5094d41af9ad2b0d93747107f147dded
/2ndEdition/oscar.alvarez/listasDia3/src/com/example/listasDia3/Main.java
c2371b655fead3264a2bc1a2c7de88ad6fe072ba
[]
no_license
rocapal/cursoAndroidURJC
https://github.com/rocapal/cursoAndroidURJC
e67565c6f6db37a77ae017d3efb599628a826e2b
2b75c5239081c1a0aff59bfb0b2f1cc9e8733bab
refs/heads/master
2021-01-13T01:47:53.116000
2013-05-25T01:04:57
2013-05-25T01:04:57
7,975,922
0
1
null
false
2013-02-07T21:36:31
2013-02-02T13:07:13
2013-02-07T21:36:30
2013-02-07T21:36:30
1,328
null
3
0
Java
null
null
package com.example.listasDia3; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.provider.SyncStateContract; import android.view.View; import android.widget.Button; public class Main extends Activity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button go_listaSimple = (Button)this.findViewById(R.id.GoListaSimple); Button go_listaCompleja = (Button)this.findViewById(R.id.GoListaCompleja); go_listaSimple.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Main.this, SimpleList.class); startActivity(intent); } }); go_listaCompleja.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Main.this, AdvancedList.class); startActivity(intent); } }); } }
UTF-8
Java
1,198
java
Main.java
Java
[]
null
[]
package com.example.listasDia3; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.provider.SyncStateContract; import android.view.View; import android.widget.Button; public class Main extends Activity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button go_listaSimple = (Button)this.findViewById(R.id.GoListaSimple); Button go_listaCompleja = (Button)this.findViewById(R.id.GoListaCompleja); go_listaSimple.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Main.this, SimpleList.class); startActivity(intent); } }); go_listaCompleja.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Main.this, AdvancedList.class); startActivity(intent); } }); } }
1,198
0.645242
0.644407
35
33.228573
23.653553
82
false
false
0
0
0
0
0
0
0.542857
false
false
7
e181f439fb49d1cb6e0cf9230d8761e978f0d002
9,869,834,871,188
5fc90c79591d982934f1d2f3528ab30a7694ef30
/Project-0/src/main/java/DAO/BankCRUD.java
9c84ad989e63cb1bb576760abf3b4f8db329a796
[]
no_license
210913-java-full-stack/preston-lee
https://github.com/210913-java-full-stack/preston-lee
75b2a05b5e25245f4d4506c781562cb1c31b3ed3
e1a56187080d1b589fe32cb330c0a10c94fffa82
refs/heads/master
2023-08-24T09:54:10.244000
2021-10-06T13:10:02
2021-10-06T13:10:02
406,127,078
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DAO; import MyArrayList.MyArrayList; import models.Account; import java.sql.SQLException; public interface BankCRUD<A> { int getAccountId() throws SQLException; MyArrayList<Account> getAccountsByUser(String username) throws SQLException; void newBankAccount(String account_type, String username) throws SQLException; boolean depositFunds(int account_id, double deposit_amount) throws SQLException; boolean accountBelongsById(int account_id, String username) throws SQLException; boolean withdrawFunds(int account_id, double withdraw_amount) throws SQLException; boolean validFundsForWithdraw(int account_id, double withdraw_amount) throws SQLException; public boolean fundsBetweenAccounts(int account1, int account2, double amount) throws SQLException; }
UTF-8
Java
812
java
BankCRUD.java
Java
[]
null
[]
package DAO; import MyArrayList.MyArrayList; import models.Account; import java.sql.SQLException; public interface BankCRUD<A> { int getAccountId() throws SQLException; MyArrayList<Account> getAccountsByUser(String username) throws SQLException; void newBankAccount(String account_type, String username) throws SQLException; boolean depositFunds(int account_id, double deposit_amount) throws SQLException; boolean accountBelongsById(int account_id, String username) throws SQLException; boolean withdrawFunds(int account_id, double withdraw_amount) throws SQLException; boolean validFundsForWithdraw(int account_id, double withdraw_amount) throws SQLException; public boolean fundsBetweenAccounts(int account1, int account2, double amount) throws SQLException; }
812
0.791872
0.789409
25
31.24
37.340893
103
false
false
0
0
0
0
0
0
0.76
false
false
7
980b6d1d78e5a5e484d008fb498bd2a5f25bc266
16,295,105,949,973
2207e58112a37e5d3b06d16fe5626c55190e078e
/engine/src/main/java/net/nicknideveloper/datasync/engine/module/base/enumerate/ConfigIdentifyEnum.java
48a312d1f7b26b1a769d8c1ff30f41de72f46560
[]
no_license
thedreambuilder/Data-Sync-Platform
https://github.com/thedreambuilder/Data-Sync-Platform
c390ddfdaa96b1ea9779ae8a8125b84371ee52f5
b2eea233a6dfe7330f842e665c3ab18da5d9a659
refs/heads/master
2016-09-11T22:44:05.888000
2016-08-02T03:39:19
2016-08-02T03:39:19
61,102,833
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.nicknideveloper.datasync.engine.module.base.enumerate; /** * [任务配置项配置识别码-枚举] * * @author Nick.Ni */ public enum ConfigIdentifyEnum { /* 数据存储相关 */ COLUMN_LIST("column_list", "字段列表"), TABLE_NAME("table_name", "主表名称"), TEMP_TABLE_NAME("temp_table_name", "副表名称"), BATCH_I_SIZE("batch_i_size", "400"), /* 粒度控制相关 */ GRADING("grading", "粒度字符串"), GRADDING_START_DATE("gradding_start_date", "粒度生效日期"), /* 动态脚本相关 */ SCRIPT_IDENTIFER("script_identifer", "脚本识别码"), OUTPUT_SCRIPT_IDENTIFERS("out_script_identifers","输出脚本识别码-可多个"), /* FTP服务相关 */ FTP_PORT("ftp_port", "ftp端口号"), FTP_USER("ftp_user", "ftp用户"), FTP_PASSWORD("ftp_password", "ftp密码"), FTP_HOST("ftp_host", "ftp主机地址"), FTP_AUTH_KEY("ftp_auth_key", "ftp授权验证key文件地址"), FTP_AUTH_PASSWORD("ftp_auth_password", "ftp授权验证key文件密码"), FTP_FILE_PATH("ftp_file_path", "ftp文件路径"), /* 文件临时存储相关 */ FILE_NAME_PATTEN("file_name_patten", "文件名称格式"), TEMP_FILE_PATH("temp_file_path", "临时文件存储路径"), /* 同步标志相关 */ LAST_SYNC_TIME("last_sync_time", "最近同步时间"); private String code; private String msg; private ConfigIdentifyEnum(String code, String msg) { this.code = code; this.msg = msg; } public String getCode() { return code; } public String getMsg() { return msg; } }
UTF-8
Java
1,656
java
ConfigIdentifyEnum.java
Java
[ { "context": "e.enumerate;\n\n/**\n * [任务配置项配置识别码-枚举]\n *\n * @author Nick.Ni\n */\npublic enum ConfigIdentifyEnum {\n\n /* 数据存储相", "end": 112, "score": 0.8812519311904907, "start": 105, "tag": "NAME", "value": "Nick.Ni" }, { "context": " FTP_USER(\"ftp_user\", \"ftp用户\"),\n FTP_PASSWORD(\"ftp_password\", \"ftp密码\"),\n FTP_HOST(\"ftp_host\", \"ftp主机地址\"),\n", "end": 702, "score": 0.8441469073295593, "start": 690, "tag": "PASSWORD", "value": "ftp_password" }, { "context": "ser\", \"ftp用户\"),\n FTP_PASSWORD(\"ftp_password\", \"ftp密码\"),\n FTP_HOST(\"ftp_host\", \"ftp主机地址\"),\n FTP_A", "end": 711, "score": 0.9188746809959412, "start": 706, "tag": "PASSWORD", "value": "ftp密码" } ]
null
[]
package net.nicknideveloper.datasync.engine.module.base.enumerate; /** * [任务配置项配置识别码-枚举] * * @author Nick.Ni */ public enum ConfigIdentifyEnum { /* 数据存储相关 */ COLUMN_LIST("column_list", "字段列表"), TABLE_NAME("table_name", "主表名称"), TEMP_TABLE_NAME("temp_table_name", "副表名称"), BATCH_I_SIZE("batch_i_size", "400"), /* 粒度控制相关 */ GRADING("grading", "粒度字符串"), GRADDING_START_DATE("gradding_start_date", "粒度生效日期"), /* 动态脚本相关 */ SCRIPT_IDENTIFER("script_identifer", "脚本识别码"), OUTPUT_SCRIPT_IDENTIFERS("out_script_identifers","输出脚本识别码-可多个"), /* FTP服务相关 */ FTP_PORT("ftp_port", "ftp端口号"), FTP_USER("ftp_user", "ftp用户"), FTP_PASSWORD("<PASSWORD>", "<PASSWORD>"), FTP_HOST("ftp_host", "ftp主机地址"), FTP_AUTH_KEY("ftp_auth_key", "ftp授权验证key文件地址"), FTP_AUTH_PASSWORD("ftp_auth_password", "ftp授权验证key文件密码"), FTP_FILE_PATH("ftp_file_path", "ftp文件路径"), /* 文件临时存储相关 */ FILE_NAME_PATTEN("file_name_patten", "文件名称格式"), TEMP_FILE_PATH("temp_file_path", "临时文件存储路径"), /* 同步标志相关 */ LAST_SYNC_TIME("last_sync_time", "最近同步时间"); private String code; private String msg; private ConfigIdentifyEnum(String code, String msg) { this.code = code; this.msg = msg; } public String getCode() { return code; } public String getMsg() { return msg; } }
1,655
0.606368
0.604197
55
24.127274
20.372044
68
false
false
0
0
0
0
0
0
0.8
false
false
7
67428f83e623ec29f784fb22537cd0fd2e60ebda
33,973,191,324,222
bd0b691a63cb3274bd8f9135496daacc78614649
/chapter_001/src/main/java/ru/job4j/calculate/package-info.java
d1cd8b2ddacc73e35cc55353384c5b46bb81a4b5
[ "Apache-2.0" ]
permissive
panyuta/job4j
https://github.com/panyuta/job4j
8a419f1f6af8f60cab1904694c75eb356af21009
59fa3fb9060cd44674f5e65fa9cf2253c725e2f9
refs/heads/master
2021-07-03T13:26:40.998000
2019-05-29T08:59:50
2019-05-29T08:59:50
185,440,563
0
0
Apache-2.0
false
2020-10-13T13:13:40
2019-05-07T16:32:47
2019-05-29T09:00:14
2020-10-13T13:13:39
97
0
0
1
Java
false
false
/** * Package for calculate task. * * @author panyuta * @version $1.0$ * @since 12.05.2019 */ package ru.job4j.calculate;
UTF-8
Java
129
java
package-info.java
Java
[ { "context": "/**\n * Package for calculate task.\n *\n * @author panyuta\n * @version $1.0$\n * @since 12.05.2019\n */\n \npack", "end": 56, "score": 0.9989764094352722, "start": 49, "tag": "USERNAME", "value": "panyuta" } ]
null
[]
/** * Package for calculate task. * * @author panyuta * @version $1.0$ * @since 12.05.2019 */ package ru.job4j.calculate;
129
0.627907
0.542636
9
13.444445
10.740485
30
false
false
0
0
0
0
0
0
0.111111
false
false
7
67aeaac9df0c2666a4c37ff8f8a1a00b3e7d8cb2
35,862,976,926,028
6de63644756dc46e772f7257e8b1131061efbb76
/src/com/msrcipts/textmessaging/TestCaseMessaging.java
0961e1fafd0b7ec2563f9bf983c826d16388e877
[]
no_license
santoshkuma/TextMessaging
https://github.com/santoshkuma/TextMessaging
32d8b1a05ae7e8d2aea1f0b8a44dd7f31d72891c
3991ed200987ac5c5a251dde1c16c07cb5785dc7
refs/heads/master
2021-05-01T17:34:55
2016-09-21T07:03:36
2016-09-21T07:03:36
68,740,817
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.msrcipts.textmessaging; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import org.apache.log4j.PropertyConfigurator; import org.openqa.selenium.By; import org.testng.annotations.Test; import io.appium.java_client.android.AndroidElement; public class TestCaseMessaging extends BaseClass { TextmessagingHelperClass helper =new TextmessagingHelperClass(); @Test(priority=1) public void VerifyHelpCode() throws InterruptedException, IOException { PropertyConfigurator.configure("Log4j.properties"); log.info("=====================================================Info=============================================="); log.info("Verifying HelpCode"); String CodeSent = "Help"; String ExpectedResponse = "Manage your account by sending the following keywords to 121 - \n" + " 1 OT: Due Amount \n" + " 2 UNB: Current Usage \n" + " 3 PAY: Payments \n" + " 4 BILL: Bill Summary \n" + " 5 BP: Current Bill Plan \n" + " 6 DATA USE: Data Usage \n" + " 7 CHECK 4G: Check 4G Compatibility \n" + " 8 GREENBILL <email id>: Start Ebill Facility \n" + " 9 EBILL <email id> <month>: One Time Ebill \n" + " 10 STOP EBILL: Stop Ebill Facility \n" + " 11 SR <SR no.>: Reference No. Status \n"; log.info("Expected Response has been captured for Verifying help code \n"); helper.OpenNewMessageWindow(); helper.EnterShortCode(); helper.EnterCode(CodeSent); helper.ClickSendButton(); helper.ReadMessage( CodeSent ,ExpectedResponse); } @Test(priority=2) public void VerifyPayments() throws IOException, InterruptedException { PropertyConfigurator.configure("Log4j.properties"); log.info("=====================================================Info=============================================="); log.info("Verifying Due Amount"); String CodeSent = "PAY"; String ExpectedResponse = "Last three payments for your airtel mobile: \n" +"1) 10-Jun-16, Rs. 1962.07\n" +"2) 30-Apr-16, Rs. 1717.21\n" +"3) 09-Apr-16, Rs. 1255.54\n"; log.info("Expected Response has been captured for Verifying Due Amount \n"); //helper.OpenNewMessageWindow(); helper.EnterCode(CodeSent); helper.ClickSendButton(); helper.ReadMessage(CodeSent, ExpectedResponse); } @Test(priority=3) public void VerifyCurrentDatausage() throws IOException, InterruptedException { PropertyConfigurator.configure("Log4j.properties"); log.info("=====================================================Info============================================== \n"); log.info("Verifying Data Usage \n"); String CodeSent = "UNB"; String ExpectedResponse = "current usage amount on your airtel mobile till 06-Aug-16 is Rs.159.00 (excludes monthly rentals)."; //helper.OpenNewMessageWindow(); log.info("Expected Response has been captured for Verifying Current Data Usage \n"); helper.EnterCode(CodeSent); helper.ClickSendButton(); helper.ReadMessage(CodeSent, ExpectedResponse); } }
UTF-8
Java
2,997
java
TestCaseMessaging.java
Java
[]
null
[]
package com.msrcipts.textmessaging; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import org.apache.log4j.PropertyConfigurator; import org.openqa.selenium.By; import org.testng.annotations.Test; import io.appium.java_client.android.AndroidElement; public class TestCaseMessaging extends BaseClass { TextmessagingHelperClass helper =new TextmessagingHelperClass(); @Test(priority=1) public void VerifyHelpCode() throws InterruptedException, IOException { PropertyConfigurator.configure("Log4j.properties"); log.info("=====================================================Info=============================================="); log.info("Verifying HelpCode"); String CodeSent = "Help"; String ExpectedResponse = "Manage your account by sending the following keywords to 121 - \n" + " 1 OT: Due Amount \n" + " 2 UNB: Current Usage \n" + " 3 PAY: Payments \n" + " 4 BILL: Bill Summary \n" + " 5 BP: Current Bill Plan \n" + " 6 DATA USE: Data Usage \n" + " 7 CHECK 4G: Check 4G Compatibility \n" + " 8 GREENBILL <email id>: Start Ebill Facility \n" + " 9 EBILL <email id> <month>: One Time Ebill \n" + " 10 STOP EBILL: Stop Ebill Facility \n" + " 11 SR <SR no.>: Reference No. Status \n"; log.info("Expected Response has been captured for Verifying help code \n"); helper.OpenNewMessageWindow(); helper.EnterShortCode(); helper.EnterCode(CodeSent); helper.ClickSendButton(); helper.ReadMessage( CodeSent ,ExpectedResponse); } @Test(priority=2) public void VerifyPayments() throws IOException, InterruptedException { PropertyConfigurator.configure("Log4j.properties"); log.info("=====================================================Info=============================================="); log.info("Verifying Due Amount"); String CodeSent = "PAY"; String ExpectedResponse = "Last three payments for your airtel mobile: \n" +"1) 10-Jun-16, Rs. 1962.07\n" +"2) 30-Apr-16, Rs. 1717.21\n" +"3) 09-Apr-16, Rs. 1255.54\n"; log.info("Expected Response has been captured for Verifying Due Amount \n"); //helper.OpenNewMessageWindow(); helper.EnterCode(CodeSent); helper.ClickSendButton(); helper.ReadMessage(CodeSent, ExpectedResponse); } @Test(priority=3) public void VerifyCurrentDatausage() throws IOException, InterruptedException { PropertyConfigurator.configure("Log4j.properties"); log.info("=====================================================Info============================================== \n"); log.info("Verifying Data Usage \n"); String CodeSent = "UNB"; String ExpectedResponse = "current usage amount on your airtel mobile till 06-Aug-16 is Rs.159.00 (excludes monthly rentals)."; //helper.OpenNewMessageWindow(); log.info("Expected Response has been captured for Verifying Current Data Usage \n"); helper.EnterCode(CodeSent); helper.ClickSendButton(); helper.ReadMessage(CodeSent, ExpectedResponse); } }
2,997
0.646313
0.623957
85
34.270588
30.618868
129
false
false
0
0
0
0
103
0.103103
1.352941
false
false
7
ea18173ebce4ab5b2f1b38e53449eb17cde009de
30,116,310,738,675
6681f7ac2cfb5596a1fcc9adf556c79810c6189e
/examples/FileSystemHandler.java
9a875a8dc9360a2d422d53fb9f1f7ad35f35757d
[ "Apache-2.0" ]
permissive
Scrumplex/Implify
https://github.com/Scrumplex/Implify
b219b6fe5c427856637955ea642673dc068c051b
d00e30dbef841010fb4d8daec71db658a6a036c5
refs/heads/master
2020-05-21T08:17:40.957000
2018-06-04T15:16:26
2018-06-04T15:16:26
84,602,966
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.scrumplex.implify; import net.scrumplex.implify.core.ImplifyServer; import net.scrumplex.implify.core.exchange.handler.FileSystemHTTPHandler; import net.scrumplex.implify.exceptions.ImplifyException; import java.io.File; import java.util.logging.Level; public class FileSystemHandler { public static void main(String[] args) { ImplifyServer implifyServer = new ImplifyServer(8080, "default"); implifyServer.setLogLevel(Level.ALL); implifyServer.setHttpHandler(new FileSystemHTTPHandler(new File("").getAbsoluteFile(), "index.html")); try { //Will not pause thread implifyServer.start(); } catch (ImplifyException e) { e.printStackTrace(); } } }
UTF-8
Java
685
java
FileSystemHandler.java
Java
[]
null
[]
package net.scrumplex.implify; import net.scrumplex.implify.core.ImplifyServer; import net.scrumplex.implify.core.exchange.handler.FileSystemHTTPHandler; import net.scrumplex.implify.exceptions.ImplifyException; import java.io.File; import java.util.logging.Level; public class FileSystemHandler { public static void main(String[] args) { ImplifyServer implifyServer = new ImplifyServer(8080, "default"); implifyServer.setLogLevel(Level.ALL); implifyServer.setHttpHandler(new FileSystemHTTPHandler(new File("").getAbsoluteFile(), "index.html")); try { //Will not pause thread implifyServer.start(); } catch (ImplifyException e) { e.printStackTrace(); } } }
685
0.770803
0.764964
24
27.541666
26.914957
104
false
false
0
0
0
0
0
0
1.5
false
false
7
41a55087da62fb987ccc65c180e2931c0e9a2cab
35,862,976,948,719
db7d6b24c35257d5b9b1299cb1965e59497d87d5
/src/controller/logoff.java
e13e762102f0c50bdb6eb5a26d9d87a43f03fd29
[]
no_license
Nigelchiang/JSP-Experiment
https://github.com/Nigelchiang/JSP-Experiment
cbda973036a4cb98f67f6871c222b001e20f1f8a
46cae8d6cb973d543e237baee4bd7e89a0d9b47b
refs/heads/master
2016-06-10T03:31:08.165000
2016-05-05T18:50:55
2016-05-05T18:50:55
57,888,164
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package controller; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by Nigel on 2016/4/19. */ public class logoff extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(false); if (session != null) { session.removeAttribute("user"); session.invalidate(); System.out.println("session destroyed"); } resp.setContentType("text/json"); resp.setCharacterEncoding("utf-8"); resp.getWriter().println("{\"success\":\"退出成功\"}"); } }
UTF-8
Java
863
java
logoff.java
Java
[ { "context": "n;\nimport java.io.IOException;\n\n/**\n * Created by Nigel on 2016/4/19.\n */\npublic class logoff extends Htt", "end": 284, "score": 0.7932804226875305, "start": 279, "tag": "USERNAME", "value": "Nigel" } ]
null
[]
package controller; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by Nigel on 2016/4/19. */ public class logoff extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(false); if (session != null) { session.removeAttribute("user"); session.invalidate(); System.out.println("session destroyed"); } resp.setContentType("text/json"); resp.setCharacterEncoding("utf-8"); resp.getWriter().println("{\"success\":\"退出成功\"}"); } }
863
0.691228
0.681871
28
29.535715
24.914829
113
false
false
0
0
0
0
0
0
0.571429
false
false
7
d885bbf384e83f1788830c92f9dffd6cd970bb7f
38,886,633,923,125
a51a32f69c32d6d878829fb5def6220452c46023
/job-admin/src/main/java/me/laiyijie/job/admin/service/impl/RuleServiceImpl.java
2b0d69fc9c4b5eed33dfc7de178a925b7e79f2f5
[]
no_license
laiyijie/job
https://github.com/laiyijie/job
aca623c79f12457c00295089d847ed0f1e477b36
cd60e6d54818819b9a64d75eb77c1f0394d2d0a1
refs/heads/master
2021-09-04T03:09:22.590000
2018-01-15T03:16:27
2018-01-15T03:16:27
112,201,963
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.laiyijie.job.admin.service.impl; import me.laiyijie.job.admin.dao.TbRuleRepository; import me.laiyijie.job.admin.dao.entity.TbRule; import me.laiyijie.job.admin.service.RuleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by laiyijie on 12/27/17. */ @Service public class RuleServiceImpl implements RuleService { @Autowired private TbRuleRepository tbRuleRepository; @Override public void deleteRule(Integer ruleId) { tbRuleRepository.delete(ruleId); } @Override public void modifyRule(TbRule rule) { tbRuleRepository.save(rule); } @Override public TbRule createRule(TbRule rule) { return tbRuleRepository.save(rule); } }
UTF-8
Java
791
java
RuleServiceImpl.java
Java
[ { "context": "ngframework.stereotype.Service;\n\n/**\n * Created by laiyijie on 12/27/17.\n */\n@Service\npublic class RuleServic", "end": 331, "score": 0.9994395971298218, "start": 323, "tag": "USERNAME", "value": "laiyijie" } ]
null
[]
package me.laiyijie.job.admin.service.impl; import me.laiyijie.job.admin.dao.TbRuleRepository; import me.laiyijie.job.admin.dao.entity.TbRule; import me.laiyijie.job.admin.service.RuleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by laiyijie on 12/27/17. */ @Service public class RuleServiceImpl implements RuleService { @Autowired private TbRuleRepository tbRuleRepository; @Override public void deleteRule(Integer ruleId) { tbRuleRepository.delete(ruleId); } @Override public void modifyRule(TbRule rule) { tbRuleRepository.save(rule); } @Override public TbRule createRule(TbRule rule) { return tbRuleRepository.save(rule); } }
791
0.738306
0.730721
30
25.366667
20.685717
62
false
false
0
0
0
0
0
0
0.333333
false
false
7
4f6336c0a21f94d49bb568a65b2e6e92c17fd486
36,232,344,128,604
f506ea97226d91da7be148a61f9cc1a680d32fdf
/ModuleWelcome/src/main/java/com/iknow/module/welcome/vm/LoadingViewModel.java
3be2733ac04d3aa2d255c4e760e6fc7343168339
[]
no_license
xiaojinzi123/IKnowAndroid
https://github.com/xiaojinzi123/IKnowAndroid
80547abe31d4a847f696d52e420843ee93beedf1
a9c934a19b6b0bb1832dbbc9802e0f6bd8ddece9
refs/heads/develop
2020-09-12T09:31:43.053000
2020-08-25T13:46:27
2020-08-25T13:48:50
222,382,593
14
2
null
false
2019-11-24T01:07:40
2019-11-18T06:54:49
2019-11-23T13:28:25
2019-11-24T01:07:38
3,802
2
0
0
Java
false
false
package com.iknow.module.welcome.vm; import android.app.Application; import androidx.annotation.NonNull; import com.iknow.module.base.vm.BaseViewModel; import java.util.concurrent.TimeUnit; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.subjects.BehaviorSubject; import io.reactivex.subjects.Subject; public class LoadingViewModel extends BaseViewModel { Subject<Long> restCountSubject = BehaviorSubject.create(); Subject<Object> countdownSubject = BehaviorSubject.create(); public LoadingViewModel(@NonNull Application application) { super(application); Disposable disposable = Observable .intervalRange(1, 3, 0, 1, TimeUnit.SECONDS) .subscribe(new Consumer<Long>() { @Override public void accept(Long value) throws Exception { restCountSubject.onNext(value); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { countdownSubject.onNext(""); countdownSubject.onComplete(); } }, new Action() { @Override public void run() throws Exception { countdownSubject.onNext(""); countdownSubject.onComplete(); } }); disposables.add(disposable); } public Observable<Long> restCountObservable() { return restCountSubject; } public Completable countdownObservable() { return countdownSubject.ignoreElements(); } }
UTF-8
Java
1,878
java
LoadingViewModel.java
Java
[]
null
[]
package com.iknow.module.welcome.vm; import android.app.Application; import androidx.annotation.NonNull; import com.iknow.module.base.vm.BaseViewModel; import java.util.concurrent.TimeUnit; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.subjects.BehaviorSubject; import io.reactivex.subjects.Subject; public class LoadingViewModel extends BaseViewModel { Subject<Long> restCountSubject = BehaviorSubject.create(); Subject<Object> countdownSubject = BehaviorSubject.create(); public LoadingViewModel(@NonNull Application application) { super(application); Disposable disposable = Observable .intervalRange(1, 3, 0, 1, TimeUnit.SECONDS) .subscribe(new Consumer<Long>() { @Override public void accept(Long value) throws Exception { restCountSubject.onNext(value); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { countdownSubject.onNext(""); countdownSubject.onComplete(); } }, new Action() { @Override public void run() throws Exception { countdownSubject.onNext(""); countdownSubject.onComplete(); } }); disposables.add(disposable); } public Observable<Long> restCountObservable() { return restCountSubject; } public Completable countdownObservable() { return countdownSubject.ignoreElements(); } }
1,878
0.605964
0.603834
61
29.786884
22.668758
78
false
false
0
0
0
0
0
0
0.491803
false
false
7
e0f1665757735e4087415aebe76e070c57d43185
36,232,344,131,264
454029d74125bb25c9cbea10a6dd9c0c7273e1b1
/api/src/main/java/com/req/TableReq.java
3dd3831045492ba4aa84f9873efa2195d0228462
[]
no_license
ChallengerXx/Tomorrow
https://github.com/ChallengerXx/Tomorrow
8b9c57f2e9c642a9c83107cb67a0a3940e0aa442
9a787f91105dc0bec41b5e05a0fd2a6fb9796541
refs/heads/master
2022-11-28T14:27:26.524000
2021-04-14T09:12:11
2021-04-14T09:12:11
120,615,409
1
0
null
false
2022-11-15T23:40:25
2018-02-07T12:58:57
2021-04-14T09:13:06
2022-11-15T23:40:22
46,968
1
0
5
Java
false
false
package com.req; import lombok.Data; @Data public class TableReq { private String table; private String machineNum; }
UTF-8
Java
128
java
TableReq.java
Java
[]
null
[]
package com.req; import lombok.Data; @Data public class TableReq { private String table; private String machineNum; }
128
0.726563
0.726563
9
13.222222
11.173161
30
false
false
0
0
0
0
0
0
0.444444
false
false
7
c5235e75bee60e1f5ffaa042ed81c9e29ddb9c3b
38,036,230,387,122
285e092741edfd4ee34b2e0cbfabdb5ff7fecca5
/src/main/java/com/search/config/BuildCacheConfig.java
f46bdae9320d584d749e9bc13c24463956f2c38c
[]
no_license
yashskullfox/RedisCache-SpringBoot
https://github.com/yashskullfox/RedisCache-SpringBoot
4b41aac30564321c2c9298212707e0855124430b
ba5418454eac74ab1b80902fa438dc099b2e98de
refs/heads/master
2021-06-28T11:42:12.605000
2021-03-06T07:25:20
2021-03-06T07:25:20
212,939,217
2
0
null
false
2019-12-28T02:51:45
2019-10-05T03:36:42
2019-12-24T02:30:58
2019-12-28T02:51:44
34
1
0
0
Java
false
false
package com.search.config; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration @EnableCaching @Profile(value = {"build"}) public class BuildCacheConfig { //This bean is Redis CacheManager for Managing different cache/Bucket. @Bean public CacheManager cacheManager(){ ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); cacheManager.setCacheNames(CacheConfig.CACHE_LIST); return cacheManager; } }
UTF-8
Java
768
java
BuildCacheConfig.java
Java
[]
null
[]
package com.search.config; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration @EnableCaching @Profile(value = {"build"}) public class BuildCacheConfig { //This bean is Redis CacheManager for Managing different cache/Bucket. @Bean public CacheManager cacheManager(){ ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); cacheManager.setCacheNames(CacheConfig.CACHE_LIST); return cacheManager; } }
768
0.802083
0.802083
21
35.57143
25.460653
81
false
false
0
0
0
0
0
0
0.47619
false
false
7
fdf4d3ab1568a9ddf4093670cfb7fb183d38761d
37,769,942,413,509
9ea72b136adf3833c2aebf4064251be3430a3b56
/newJava/src/dierji/Network/UDP/Server.java
464bcf7b58b583ee332f039585a213b90d2b8e1d
[]
no_license
wanyunhao/269
https://github.com/wanyunhao/269
5117c1c2d056a65dabe623f91603600a12eda4d4
8b748b92542ffd7ead6dc6d88973279af4e2d5de
refs/heads/master
2020-01-23T21:58:59.685000
2018-04-20T09:15:42
2018-04-20T09:15:42
74,720,846
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dierji.Network.UDP; import yh.utils.YHByteUtil; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Server { public static void main(String[] args) throws IOException { //1. 创建服务器 + 端口 DatagramSocket server = new DatagramSocket(8889); //2. 创建接收容器 byte[] content = new byte[1024]; //3. 封装成包 DatagramPacket packet = new DatagramPacket(content,content.length); //4. 接受数据 server.receive(packet); //5. 处理数据 System.out.println(YHByteUtil.getDouble(packet.getData())); server.close(); } public static double convert(byte[] data) throws IOException { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); double num = dis.readDouble(); dis.close(); return num; } }
UTF-8
Java
1,000
java
Server.java
Java
[]
null
[]
package dierji.Network.UDP; import yh.utils.YHByteUtil; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Server { public static void main(String[] args) throws IOException { //1. 创建服务器 + 端口 DatagramSocket server = new DatagramSocket(8889); //2. 创建接收容器 byte[] content = new byte[1024]; //3. 封装成包 DatagramPacket packet = new DatagramPacket(content,content.length); //4. 接受数据 server.receive(packet); //5. 处理数据 System.out.println(YHByteUtil.getDouble(packet.getData())); server.close(); } public static double convert(byte[] data) throws IOException { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); double num = dis.readDouble(); dis.close(); return num; } }
1,000
0.658947
0.645263
33
27.757576
22.627457
82
false
false
0
0
0
0
0
0
0.545455
false
false
7
9b08ea7630580e8ddaedf365415daeb006bf1dd2
35,072,702,981,881
d0bc7c4e233712e302a8a9fd32fbb519540c5154
/user-server/src/main/java/com/org/hermes/user/server/repository/entity/App.java
df73f8de780b6aa9bf754487cfaffd88caeb8a2c
[]
no_license
hermes-dxb/user
https://github.com/hermes-dxb/user
4a2893a5a0a4d3419b31f743c26633f7bd8a8ba9
e138994d8f5603b784dcc2a8c7cfea7bdf76ac1e
refs/heads/master
2020-08-30T17:22:19.089000
2019-11-04T04:40:40
2019-11-04T04:40:40
218,443,141
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.org.hermes.user.server.repository.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @Data @EqualsAndHashCode(callSuper=false) @Builder @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "app") public class App extends Audit{ @Id @Column(name = "app_id") private String appId; @Column(name = "app_secret") private String appSecret; @Column(name = "app_name") private String appName; @Column(name = "auth_db") private String authSource; @Column(name = "auth_type") private String authType; @Column(name = "redirection_url") private String redirectionUrl; @Column(name = "description") private String description; }
UTF-8
Java
926
java
App.java
Java
[]
null
[]
package com.org.hermes.user.server.repository.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @Data @EqualsAndHashCode(callSuper=false) @Builder @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "app") public class App extends Audit{ @Id @Column(name = "app_id") private String appId; @Column(name = "app_secret") private String appSecret; @Column(name = "app_name") private String appName; @Column(name = "auth_db") private String authSource; @Column(name = "auth_type") private String authType; @Column(name = "redirection_url") private String redirectionUrl; @Column(name = "description") private String description; }
926
0.737581
0.737581
37
24.027027
12.353983
53
false
false
0
0
0
0
0
0
0.459459
false
false
7
83a6f19d404f43690ca4239d6ac9fe13c031fc95
18,588,618,520,834
ff99b922512942ea049763da50c722bb0f19d1db
/core/x5agent.http/src/com/xored/x5agent/http/HttpTransport.java
b30b8acd279adc79e38e4b294cbf483431cb9468
[]
no_license
xored/x5agent
https://github.com/xored/x5agent
ca25585597c36c707b43d59cb249b13099eb30b2
99c6d0408ecf14984b5dac4669553db1127a859f
refs/heads/master
2021-01-25T04:09:10.294000
2011-08-11T14:23:24
2011-08-11T14:23:24
2,076,767
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xored.x5agent.http; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.eclipse.emf.ecore.EObject; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.xored.emfjson.Emf2Json; import com.xored.x5.DeliveryStatus; import com.xored.x5.X5FactResponse; import com.xored.x5.X5Factory; import com.xored.x5.X5Request; import com.xored.x5.X5Response; import com.xored.x5agent.core.X5Agent; import com.xored.x5agent.core.X5Transport; public class HttpTransport implements X5Transport { private String baseUrl; @Override public void initialize(Map<String, String> parameters) { this.baseUrl = parameters.get("url"); if (baseUrl == null) throw new IllegalArgumentException("URL is not specified"); } @Override public X5Response send(X5Request request) { try { Emf2Json emf2Json = new Emf2Json(); HttpClient client = new DefaultHttpClient(); String url = this.baseUrl + "/" + X5Agent.Instance.getClient() + "/facts/"; HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(emf2Json.serialize(request) .toString(), "application/json", "utf-8"); post.setEntity(entity); HttpResponse response = client.execute(post); HttpEntity responseEntity = response.getEntity(); if (responseEntity == null) { X5FactResponse factResponse = X5Factory.eINSTANCE .createX5FactResponse(); StatusLine line = response.getStatusLine(); int statusCode = line.getStatusCode(); if (statusCode == HttpStatus.SC_CREATED) { factResponse.setStatus(DeliveryStatus.ACCEPTED); } else if (statusCode >= 500 && statusCode < 600) { factResponse.setStatus(DeliveryStatus.RETRY); } else { factResponse.setStatus(DeliveryStatus.WONT_ACCEPT); } } else { String json = EntityUtils.toString(responseEntity); JsonElement parsed = new JsonParser().parse(json); if (parsed instanceof JsonObject) { EObject eObject = emf2Json.deserialize((JsonObject) parsed); if (eObject instanceof X5Response) { return (X5Response) eObject; } } } throw new RuntimeException("Unexpected format"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (ClientProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void dispose() { } }
UTF-8
Java
2,915
java
HttpTransport.java
Java
[]
null
[]
package com.xored.x5agent.http; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.eclipse.emf.ecore.EObject; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.xored.emfjson.Emf2Json; import com.xored.x5.DeliveryStatus; import com.xored.x5.X5FactResponse; import com.xored.x5.X5Factory; import com.xored.x5.X5Request; import com.xored.x5.X5Response; import com.xored.x5agent.core.X5Agent; import com.xored.x5agent.core.X5Transport; public class HttpTransport implements X5Transport { private String baseUrl; @Override public void initialize(Map<String, String> parameters) { this.baseUrl = parameters.get("url"); if (baseUrl == null) throw new IllegalArgumentException("URL is not specified"); } @Override public X5Response send(X5Request request) { try { Emf2Json emf2Json = new Emf2Json(); HttpClient client = new DefaultHttpClient(); String url = this.baseUrl + "/" + X5Agent.Instance.getClient() + "/facts/"; HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(emf2Json.serialize(request) .toString(), "application/json", "utf-8"); post.setEntity(entity); HttpResponse response = client.execute(post); HttpEntity responseEntity = response.getEntity(); if (responseEntity == null) { X5FactResponse factResponse = X5Factory.eINSTANCE .createX5FactResponse(); StatusLine line = response.getStatusLine(); int statusCode = line.getStatusCode(); if (statusCode == HttpStatus.SC_CREATED) { factResponse.setStatus(DeliveryStatus.ACCEPTED); } else if (statusCode >= 500 && statusCode < 600) { factResponse.setStatus(DeliveryStatus.RETRY); } else { factResponse.setStatus(DeliveryStatus.WONT_ACCEPT); } } else { String json = EntityUtils.toString(responseEntity); JsonElement parsed = new JsonParser().parse(json); if (parsed instanceof JsonObject) { EObject eObject = emf2Json.deserialize((JsonObject) parsed); if (eObject instanceof X5Response) { return (X5Response) eObject; } } } throw new RuntimeException("Unexpected format"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (ClientProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void dispose() { } }
2,915
0.743739
0.731389
90
31.388889
18.940664
69
false
false
0
0
0
0
0
0
2.466667
false
false
7
c11ef5e8fe54f0d86a28d1da6f9b23a8731fc31a
35,682,588,330,571
67dc6992ffa5e3f89dfc6d7f8741d33b73b66631
/driver/src/main/java/org/neo4j/driver/internal/spi/ConnectionPool.java
df30f40353d1e4ebd067e28a5f372a54a7957122
[ "MIT-0", "Apache-2.0", "MIT" ]
permissive
neo4j/neo4j-java-driver
https://github.com/neo4j/neo4j-java-driver
832dc5f9b531b9b8e3ed6fc511b3abd9c52dfe10
198adcc6c5376fe6d684dd02e709b33663fc68b1
refs/heads/5.0
2023-09-06T05:29:21.987000
2023-08-31T12:42:27
2023-08-31T12:42:27
34,007,506
338
186
Apache-2.0
false
2023-08-31T12:42:28
2015-04-15T17:08:15
2023-08-30T06:44:02
2023-08-31T12:42:27
13,684
305
149
12
Java
false
false
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.driver.internal.spi; import java.util.Set; import java.util.concurrent.CompletionStage; import org.neo4j.driver.AuthToken; import org.neo4j.driver.internal.BoltServerAddress; import org.neo4j.driver.net.ServerAddress; public interface ConnectionPool { String CONNECTION_POOL_CLOSED_ERROR_MESSAGE = "Pool closed"; CompletionStage<Connection> acquire(BoltServerAddress address, AuthToken overrideAuthToken); void retainAll(Set<BoltServerAddress> addressesToRetain); int inUseConnections(ServerAddress address); CompletionStage<Void> close(); boolean isOpen(BoltServerAddress address); }
UTF-8
Java
1,296
java
ConnectionPool.java
Java
[ { "context": "/*\n * Copyright (c) \"Neo4j\"\n * Neo4j Sweden AB [http://neo4j.com]\n *\n * This", "end": 26, "score": 0.6819847226142883, "start": 21, "tag": "USERNAME", "value": "Neo4j" } ]
null
[]
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.driver.internal.spi; import java.util.Set; import java.util.concurrent.CompletionStage; import org.neo4j.driver.AuthToken; import org.neo4j.driver.internal.BoltServerAddress; import org.neo4j.driver.net.ServerAddress; public interface ConnectionPool { String CONNECTION_POOL_CLOSED_ERROR_MESSAGE = "Pool closed"; CompletionStage<Connection> acquire(BoltServerAddress address, AuthToken overrideAuthToken); void retainAll(Set<BoltServerAddress> addressesToRetain); int inUseConnections(ServerAddress address); CompletionStage<Void> close(); boolean isOpen(BoltServerAddress address); }
1,296
0.759259
0.75
39
32.23077
27.525709
96
false
false
0
0
0
0
0
0
0.461538
false
false
7
c3465e0c3c7a573dc9c541ffa48a8565c2b97286
37,099,927,527,807
1bda698539ca1f0cf2d101f6ca0d7af594e42dce
/src/java/modelo/fachadas/CfgImagenesFacade.java
91eb19a2ee3741badd10a3b57b49f798b7c1d1b2
[]
no_license
coeisas/openmedical
https://github.com/coeisas/openmedical
7de8b1653e6af4e7f93b9b7f2c3cc037b98d2b2e
7033483bede01bca2e88832948b587c12b0fa2de
refs/heads/master
2021-01-18T21:09:04.064000
2018-05-16T00:05:45
2018-05-16T00:05:45
41,105,381
0
1
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 modelo.fachadas; import modelo.entidades.CfgImagenes; import javax.ejb.Stateless; /** * * @author santos */ @Stateless public class CfgImagenesFacade extends AbstractFacade<CfgImagenes> { public CfgImagenesFacade() { super(CfgImagenes.class); } }
UTF-8
Java
463
java
CfgImagenesFacade.java
Java
[ { "context": "es;\nimport javax.ejb.Stateless;\n\n/**\n *\n * @author santos\n */\n@Stateless\npublic class CfgImagenesFacade ext", "end": 301, "score": 0.9981205463409424, "start": 295, "tag": "USERNAME", "value": "santos" } ]
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 modelo.fachadas; import modelo.entidades.CfgImagenes; import javax.ejb.Stateless; /** * * @author santos */ @Stateless public class CfgImagenesFacade extends AbstractFacade<CfgImagenes> { public CfgImagenesFacade() { super(CfgImagenes.class); } }
463
0.730022
0.730022
22
20.045454
23.314991
79
false
false
0
0
0
0
0
0
0.318182
false
false
7
cd4d52b26ed5213fa9988d163b17ab3e43eb2573
35,923,106,493,523
009d18eb4b877ab2e653e69e766e2d86b1928757
/CodigoDeFuente/src/com/waze/view/timer/TimerView$1.java
0adb2f78162ccc3972f44c508929bd6a44ff39bf
[]
no_license
secretline/waze-security-paper
https://github.com/secretline/waze-security-paper
3a6fbaf6dfa63aca81c195d9c9ffb8ba9c827b71
eb573a23e4f2cbe4484fd2a1b1f09c31d5364fe4
refs/heads/master
2016-09-07T18:14:39.292000
2015-06-28T19:15:45
2015-06-28T19:15:45
38,207,099
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.waze.view.timer; import android.os.Handler; import android.view.View; import android.widget.TextView; import java.util.Date; // Referenced classes of package com.waze.view.timer: // TimerView, TimerCircle class this._cls0 implements Runnable { final TimerView this$0; public void run() { long l = System.currentTimeMillis(); float f = 1.0F - (float)(l - TimerView.access$0(TimerView.this).getTime()) / (1000F * (float)TimerView.access$1(TimerView.this)); if (f < 0.0F) { f = 0.0F; } int i = (int)((long)TimerView.access$1(TimerView.this) - (l - TimerView.access$0(TimerView.this).getTime()) / 1000L); if (i <= 0) { setVisibility(8); } TimerView.access$2(TimerView.this).setText((new StringBuilder()).append(i).toString()); TimerView.access$3(TimerView.this).setRatio(f); TimerView.access$3(TimerView.this).invalidate(); if (!shouldStop) { if (f > 0.0F) { TimerView.access$4(TimerView.this).postDelayed(this, 125L); return; } else { expired = true; ((View)getParent()).performClick(); return; } } else { setVisibility(8); return; } } () { this$0 = TimerView.this; super(); } }
UTF-8
Java
1,652
java
TimerView$1.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996777772903442, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.waze.view.timer; import android.os.Handler; import android.view.View; import android.widget.TextView; import java.util.Date; // Referenced classes of package com.waze.view.timer: // TimerView, TimerCircle class this._cls0 implements Runnable { final TimerView this$0; public void run() { long l = System.currentTimeMillis(); float f = 1.0F - (float)(l - TimerView.access$0(TimerView.this).getTime()) / (1000F * (float)TimerView.access$1(TimerView.this)); if (f < 0.0F) { f = 0.0F; } int i = (int)((long)TimerView.access$1(TimerView.this) - (l - TimerView.access$0(TimerView.this).getTime()) / 1000L); if (i <= 0) { setVisibility(8); } TimerView.access$2(TimerView.this).setText((new StringBuilder()).append(i).toString()); TimerView.access$3(TimerView.this).setRatio(f); TimerView.access$3(TimerView.this).invalidate(); if (!shouldStop) { if (f > 0.0F) { TimerView.access$4(TimerView.this).postDelayed(this, 125L); return; } else { expired = true; ((View)getParent()).performClick(); return; } } else { setVisibility(8); return; } } () { this$0 = TimerView.this; super(); } }
1,642
0.547821
0.523608
61
26.081966
27.802168
137
false
false
0
0
0
0
0
0
0.409836
false
false
7
e5a0aea48b790041f14261fd0d30af3c5364b71e
13,151,189,896,218
06c5b089014a201aca79db78ecaa7eacc36546d7
/src/java/main/org/tmforum/common_business_entities_domain/policy_abe/policy_structure_abe/policy_action_business_entity/PolicyAction.java
cb24313dc6f986fc562683bbda9ccfec8a225cb6
[]
no_license
yarmol/tm-sid-model
https://github.com/yarmol/tm-sid-model
e783b2e2d448825f78618a6a39dbdffe8e7b1073
979689fe571a6e67eb322e2cab7c32f46fe5157c
refs/heads/master
2021-01-18T17:01:53.612000
2017-04-06T13:15:49
2017-04-06T13:15:49
86,781,391
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Policy Action ABE * @see <a href="URL#https://www.tmforum.org/Browsable_HTML_SID_R16.5/content/_3E3F0EC000E93E1B4AD70316-content.html">Policy Action ABE</a> * @since SID_R16.5 */ package org.tmforum.common_business_entities_domain.policy_abe.policy_structure_abe.policy_action_business_entity ; /** * This is an abstract base class that represents how to form the action * clause of a PolicyRule. This consists of a single occurrence of a Poli * cyStatement, which is of the form: {variable, operator, value}Policy a * ctions have the semantics of "SET variable to value". There are two ty * pes of actions: - pass actions are invoked if the condition clause was * TRUE - fail actions are invoked if the condition clause was FALSE Inheritance tree: |- SID Models::Common Business Entities Domain::Policy ABE::Policy Framework ABE::Policy |- SID Models::Common Business Entities Domain::Root Business Entities ABE::RootEntity @since SID_R16.5 */ public abstract class PolicyAction extends Policy,RootEntity { /** * Field policyRuleBase */ protected List<PolicyRuleBase> policyRuleBase ; /** * Field policyAction */ protected List<PolicyAction> policyAction ; /** * Field policyAction1 */ protected PolicyAction policyAction1 ; /** * Field policyActionSpec */ protected PolicyActionSpec policyActionSpec ; /** * Field revenueAssuranceConsequence */ protected List<RevenueAssuranceConsequence> revenueAssuranceConsequence ; /** * Field policyRule */ protected List<PolicyRule> policyRule ; /** * Field policyAction */ protected List<PolicyAction> policyAction ; /** * Field policyAction2 */ protected PolicyAction policyAction2 ; }
UTF-8
Java
1,702
java
PolicyAction.java
Java
[]
null
[]
/** * Policy Action ABE * @see <a href="URL#https://www.tmforum.org/Browsable_HTML_SID_R16.5/content/_3E3F0EC000E93E1B4AD70316-content.html">Policy Action ABE</a> * @since SID_R16.5 */ package org.tmforum.common_business_entities_domain.policy_abe.policy_structure_abe.policy_action_business_entity ; /** * This is an abstract base class that represents how to form the action * clause of a PolicyRule. This consists of a single occurrence of a Poli * cyStatement, which is of the form: {variable, operator, value}Policy a * ctions have the semantics of "SET variable to value". There are two ty * pes of actions: - pass actions are invoked if the condition clause was * TRUE - fail actions are invoked if the condition clause was FALSE Inheritance tree: |- SID Models::Common Business Entities Domain::Policy ABE::Policy Framework ABE::Policy |- SID Models::Common Business Entities Domain::Root Business Entities ABE::RootEntity @since SID_R16.5 */ public abstract class PolicyAction extends Policy,RootEntity { /** * Field policyRuleBase */ protected List<PolicyRuleBase> policyRuleBase ; /** * Field policyAction */ protected List<PolicyAction> policyAction ; /** * Field policyAction1 */ protected PolicyAction policyAction1 ; /** * Field policyActionSpec */ protected PolicyActionSpec policyActionSpec ; /** * Field revenueAssuranceConsequence */ protected List<RevenueAssuranceConsequence> revenueAssuranceConsequence ; /** * Field policyRule */ protected List<PolicyRule> policyRule ; /** * Field policyAction */ protected List<PolicyAction> policyAction ; /** * Field policyAction2 */ protected PolicyAction policyAction2 ; }
1,702
0.744418
0.727967
88
18.352272
30.122492
139
false
false
0
0
0
0
0
0
0.170455
false
false
7
a2356554991808b5a73662f8d9db3b6bf1a79832
21,062,519,651,444
2eeb4d08e8e095bae1df6f75f02263725e1e9fb7
/android-app/app/src/main/java/com/example/ledsphereapp/SettingsPage.java
41765b3e50d0ef8ebe2f3673d2dc8e07e28d60e9
[]
no_license
luishowell/drone-ball
https://github.com/luishowell/drone-ball
a72bb4ea72f4aab7ac5ffe98b89e44038d9d88d4
d3e59153706d972d3b95241a47e0be737e4550a4
refs/heads/master
2020-04-25T07:08:56.042000
2019-05-10T16:23:59
2019-05-10T16:23:59
172,604,714
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.ledsphereapp; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import java.io.OutputStream; import java.util.Set; import java.util.ArrayList; import android.widget.Toast; import android.widget.ArrayAdapter; import android.widget.AdapterView; import android.widget.TextView; import android.content.Intent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.os.AsyncTask; import java.io.IOException; import java.util.UUID; import android.app.ProgressDialog; import android.widget.ListView; public class SettingsPage extends AppCompatActivity { EditText editImHeight; EditText editImWidth; EditText editMaxRPM; //Bluetooth helper to send command BluetoothHelper btHelper = new BluetoothHelper(this); Button btnPaired; Button btnSendTest; ListView DeviceList; private BluetoothAdapter myBluetooth = null; private Set<BluetoothDevice> pairedDevices; String address = null; private ProgressDialog progress; //BluetoothAdapter myBluetooth = null; BluetoothSocket btSocket = null; private boolean isBtConnected = false; static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings_page); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //init global variables final GlobalVariables globalVars = (GlobalVariables)getApplication(); editImWidth = (EditText) findViewById(R.id.editImWidth); editImWidth.setText(Integer.toString(globalVars.imageWidth)); editImWidth.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_NEXT) { //store the value in the relevant int value String image_width_str = v.getText().toString(); globalVars.imageWidth = Integer.parseInt(image_width_str); } return handled; } }); editImHeight = (EditText) findViewById(R.id.editImHeight); editImHeight.setText(Integer.toString(globalVars.imageHeight)); editImHeight.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_DONE) { //store the value in the relevant int value String image_height_str = v.getText().toString(); globalVars.imageHeight = Integer.parseInt(image_height_str); } return handled; } }); editMaxRPM = (EditText) findViewById(R.id.editMaxRPM); editMaxRPM.setText(Integer.toString(globalVars.maxRPM)); editMaxRPM.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_DONE) { //store the value in the relevant int String maxRPMString = v.getText().toString(); globalVars.maxRPM = Integer.parseInt(maxRPMString); } return handled; } }); //Bluetooth test stuff btnPaired = (Button)findViewById(R.id.btPaired); btnSendTest = (Button)findViewById(R.id.btnBluetoothSendTest); DeviceList = (ListView) findViewById(R.id.deviceList); //setup the bluetooth myBluetooth = BluetoothAdapter.getDefaultAdapter(); if(myBluetooth == null) { //Show a mensag. that thedevice has no bluetooth adapter Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show(); //finish apk finish(); } else { if (myBluetooth.isEnabled()) { } else { //Ask to the user turn the bluetooth on Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnBTon,1); } } //create a listener on the paired devices list btnPaired.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pairedDevicesList(); } }); //create a listener on send button btnSendTest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { byte toSend = (byte)0xFF; btHelper.sendCommandBT(toSend); } }); } private void pairedDevicesList() { pairedDevices = myBluetooth.getBondedDevices(); ArrayList list = new ArrayList(); Toast.makeText(getApplicationContext(), "pairedDeviceButtonPressed.", Toast.LENGTH_LONG).show(); if (pairedDevices.size()>0) { Toast.makeText(getApplicationContext(), "Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); for(BluetoothDevice bt : pairedDevices) { list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address } } else { Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); } final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list); DeviceList.setAdapter(adapter); DeviceList.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked } private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener() { public void onItemClick (AdapterView av, View v, int arg2, long arg3) { // Get the device MAC address, the last 17 chars in the View String info = ((TextView) v).getText().toString(); address = info.substring(info.length() - 17); new ConnectBT().execute(); //Call the class to connect } }; // fast way to call Toast private void msg(String s) { Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread { private boolean ConnectSuccess = true; //if it's here, it's almost connected @Override protected void onPreExecute() { progress = ProgressDialog.show(SettingsPage.this, "Connecting...", "Please wait!!!"); //show a progress dialog } @Override protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background { //init global variables final GlobalVariables globalVars = (GlobalVariables)getApplication(); try { if (globalVars.btSocket == null || !isBtConnected) { myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available globalVars.btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); globalVars.btSocket.connect();//start connection } } catch (IOException e) { ConnectSuccess = false;//if the try failed, you can check the exception here } return null; } @Override protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine { super.onPostExecute(result); //init global variables final GlobalVariables globalVars = (GlobalVariables)getApplication(); if (!ConnectSuccess) { msg("Connection Failed. Is it a SPP Bluetooth? Try again."); finish(); } else { msg("Connected."); isBtConnected = true; } progress.dismiss(); } } }
UTF-8
Java
9,956
java
SettingsPage.java
Java
[]
null
[]
package com.example.ledsphereapp; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import java.io.OutputStream; import java.util.Set; import java.util.ArrayList; import android.widget.Toast; import android.widget.ArrayAdapter; import android.widget.AdapterView; import android.widget.TextView; import android.content.Intent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.os.AsyncTask; import java.io.IOException; import java.util.UUID; import android.app.ProgressDialog; import android.widget.ListView; public class SettingsPage extends AppCompatActivity { EditText editImHeight; EditText editImWidth; EditText editMaxRPM; //Bluetooth helper to send command BluetoothHelper btHelper = new BluetoothHelper(this); Button btnPaired; Button btnSendTest; ListView DeviceList; private BluetoothAdapter myBluetooth = null; private Set<BluetoothDevice> pairedDevices; String address = null; private ProgressDialog progress; //BluetoothAdapter myBluetooth = null; BluetoothSocket btSocket = null; private boolean isBtConnected = false; static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings_page); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //init global variables final GlobalVariables globalVars = (GlobalVariables)getApplication(); editImWidth = (EditText) findViewById(R.id.editImWidth); editImWidth.setText(Integer.toString(globalVars.imageWidth)); editImWidth.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_NEXT) { //store the value in the relevant int value String image_width_str = v.getText().toString(); globalVars.imageWidth = Integer.parseInt(image_width_str); } return handled; } }); editImHeight = (EditText) findViewById(R.id.editImHeight); editImHeight.setText(Integer.toString(globalVars.imageHeight)); editImHeight.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_DONE) { //store the value in the relevant int value String image_height_str = v.getText().toString(); globalVars.imageHeight = Integer.parseInt(image_height_str); } return handled; } }); editMaxRPM = (EditText) findViewById(R.id.editMaxRPM); editMaxRPM.setText(Integer.toString(globalVars.maxRPM)); editMaxRPM.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_DONE) { //store the value in the relevant int String maxRPMString = v.getText().toString(); globalVars.maxRPM = Integer.parseInt(maxRPMString); } return handled; } }); //Bluetooth test stuff btnPaired = (Button)findViewById(R.id.btPaired); btnSendTest = (Button)findViewById(R.id.btnBluetoothSendTest); DeviceList = (ListView) findViewById(R.id.deviceList); //setup the bluetooth myBluetooth = BluetoothAdapter.getDefaultAdapter(); if(myBluetooth == null) { //Show a mensag. that thedevice has no bluetooth adapter Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show(); //finish apk finish(); } else { if (myBluetooth.isEnabled()) { } else { //Ask to the user turn the bluetooth on Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnBTon,1); } } //create a listener on the paired devices list btnPaired.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pairedDevicesList(); } }); //create a listener on send button btnSendTest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { byte toSend = (byte)0xFF; btHelper.sendCommandBT(toSend); } }); } private void pairedDevicesList() { pairedDevices = myBluetooth.getBondedDevices(); ArrayList list = new ArrayList(); Toast.makeText(getApplicationContext(), "pairedDeviceButtonPressed.", Toast.LENGTH_LONG).show(); if (pairedDevices.size()>0) { Toast.makeText(getApplicationContext(), "Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); for(BluetoothDevice bt : pairedDevices) { list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address } } else { Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); } final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list); DeviceList.setAdapter(adapter); DeviceList.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked } private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener() { public void onItemClick (AdapterView av, View v, int arg2, long arg3) { // Get the device MAC address, the last 17 chars in the View String info = ((TextView) v).getText().toString(); address = info.substring(info.length() - 17); new ConnectBT().execute(); //Call the class to connect } }; // fast way to call Toast private void msg(String s) { Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread { private boolean ConnectSuccess = true; //if it's here, it's almost connected @Override protected void onPreExecute() { progress = ProgressDialog.show(SettingsPage.this, "Connecting...", "Please wait!!!"); //show a progress dialog } @Override protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background { //init global variables final GlobalVariables globalVars = (GlobalVariables)getApplication(); try { if (globalVars.btSocket == null || !isBtConnected) { myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available globalVars.btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); globalVars.btSocket.connect();//start connection } } catch (IOException e) { ConnectSuccess = false;//if the try failed, you can check the exception here } return null; } @Override protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine { super.onPostExecute(result); //init global variables final GlobalVariables globalVars = (GlobalVariables)getApplication(); if (!ConnectSuccess) { msg("Connection Failed. Is it a SPP Bluetooth? Try again."); finish(); } else { msg("Connected."); isBtConnected = true; } progress.dismiss(); } } }
9,956
0.621736
0.617718
275
35.203636
31.385382
150
false
false
0
0
0
0
0
0
0.563636
false
false
7
eb653e5dcb572933f3648e3aa1b33f8dcd8d93f4
32,530,082,370,299
55cc961e666d86d050cb09fea40d08173482b710
/brewing/src/main/java/io/spring/cloud/samples/brewery/aggregating/IngredientsController.java
c83748cc39e6b40a55acd031d0fa22be34dd8212
[ "Apache-2.0" ]
permissive
spring-cloud-samples/brewery
https://github.com/spring-cloud-samples/brewery
b22f1faa40f6031126bf0618ed1fcd85079b5677
1bfca4ed62bd3d3b7a7fb6f1b70179a0154382f7
refs/heads/main
2023-08-23T10:38:29.917000
2022-11-23T16:14:13
2022-11-23T16:14:13
47,558,740
379
124
Apache-2.0
false
2022-03-10T11:09:34
2015-12-07T14:58:06
2022-03-03T12:27:22
2022-03-10T11:09:34
36,888
343
110
8
Java
false
false
package io.spring.cloud.samples.brewery.aggregating; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import io.spring.cloud.samples.brewery.common.model.Ingredients; import io.spring.cloud.samples.brewery.common.model.Order; import io.spring.cloud.samples.brewery.common.model.Version; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.concurrent.Callable; @RestController @RequestMapping(value = "/ingredients", consumes = Version.BREWING_V1, produces = MediaType.APPLICATION_JSON_VALUE) class IngredientsController { private static final Logger log = org.slf4j.LoggerFactory.getLogger(IngredientsController.class); private final IngredientsAggregator ingredientsAggregator; private final ObservationRegistry observationRegistry; @Autowired public IngredientsController(IngredientsAggregator ingredientsAggregator, ObservationRegistry observationRegistry) { this.ingredientsAggregator = ingredientsAggregator; this.observationRegistry = observationRegistry; } /** * [OBSERVABILITY] Callable - separate thread pool */ @RequestMapping(method = RequestMethod.POST) public Callable<Ingredients> distributeIngredients(@RequestBody Order order, @RequestHeader("PROCESS-ID") String processId) { log.info("Setting tags and events on an already existing span"); observationRegistry.getCurrentObservation().lowCardinalityKeyValue("beer", "stout"); observationRegistry.getCurrentObservation().event(() -> "ingredientsAggregationStarted"); log.info("Starting beer brewing process for process id [{}]", processId); return Observation.createNotStarted("inside_aggregating", observationRegistry).observe(() -> () -> ingredientsAggregator.fetchIngredients(order, processId)); } }
UTF-8
Java
1,990
java
IngredientsController.java
Java
[]
null
[]
package io.spring.cloud.samples.brewery.aggregating; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import io.spring.cloud.samples.brewery.common.model.Ingredients; import io.spring.cloud.samples.brewery.common.model.Order; import io.spring.cloud.samples.brewery.common.model.Version; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.concurrent.Callable; @RestController @RequestMapping(value = "/ingredients", consumes = Version.BREWING_V1, produces = MediaType.APPLICATION_JSON_VALUE) class IngredientsController { private static final Logger log = org.slf4j.LoggerFactory.getLogger(IngredientsController.class); private final IngredientsAggregator ingredientsAggregator; private final ObservationRegistry observationRegistry; @Autowired public IngredientsController(IngredientsAggregator ingredientsAggregator, ObservationRegistry observationRegistry) { this.ingredientsAggregator = ingredientsAggregator; this.observationRegistry = observationRegistry; } /** * [OBSERVABILITY] Callable - separate thread pool */ @RequestMapping(method = RequestMethod.POST) public Callable<Ingredients> distributeIngredients(@RequestBody Order order, @RequestHeader("PROCESS-ID") String processId) { log.info("Setting tags and events on an already existing span"); observationRegistry.getCurrentObservation().lowCardinalityKeyValue("beer", "stout"); observationRegistry.getCurrentObservation().event(() -> "ingredientsAggregationStarted"); log.info("Starting beer brewing process for process id [{}]", processId); return Observation.createNotStarted("inside_aggregating", observationRegistry).observe(() -> () -> ingredientsAggregator.fetchIngredients(order, processId)); } }
1,990
0.779397
0.777889
42
46.380951
38.796143
165
false
false
0
0
0
0
0
0
0.690476
false
false
7
b246c555a32ce2d26fc5b756fd0fb18dbeaebd02
27,419,071,284,940
ed4c9d72d80a4df9f6dbe28262e935e6abfeee70
/designPattern/proxy/dynamic/ITeacherDao.java
2fec0fa14a1b2d0d90c7725b9ee6502e58f4478a
[]
no_license
zdkswd/designPattern
https://github.com/zdkswd/designPattern
2d994d1540eab8826e5c072ba2ff8c171afde6a5
e59d73c7fb2418c5c146988d5e68668d4e4653cb
refs/heads/master
2020-07-07T12:43:42.847000
2019-08-20T11:23:25
2019-08-20T11:23:25
203,351,124
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package zdk.proxy.dynamic; public interface ITeacherDao { void teach(); void sayHello(String string); }
UTF-8
Java
113
java
ITeacherDao.java
Java
[]
null
[]
package zdk.proxy.dynamic; public interface ITeacherDao { void teach(); void sayHello(String string); }
113
0.716814
0.716814
6
17.833334
13.208794
33
false
false
0
0
0
0
0
0
0.5
false
false
7
32b13d034f334d826b86481b4516aff85c3a42d1
34,686,155,907,130
84507c69c0c215f97458fa241130453e7d9caf6d
/justice-jdk/src/main/java/com/justice/jdk/seven/SwitchString.java
8f6fdcc3365e5e75127c6c98a45d3f1aa95fbe1c
[]
no_license
justice824/justice
https://github.com/justice824/justice
d343a9fd31057b2d05a4244c1e2c087ee9a4ae27
7d63089780b6a9acb4a96e22cd4eab240a0a5545
refs/heads/master
2017-11-29T20:49:48.611000
2016-02-21T09:33:48
2016-02-21T09:33:59
37,293,577
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * 文件名:SwitchString<br/> * 版权:Copyright 2014-2015易互通科技(武汉)有限公司 All Rights Reserved.<br/> * 描述:TODO<br/> * 创建人:zhengliang@lbw001.com<br/> * 创建时间:2016/1/1110:16<br/> * 修改人:TODO 选写<br/> * 修改时间:2016/1/1110:16 选写<br/> * 修改内容:TODO 选写<br/> */ package com.justice.jdk.seven; /** * ClassName: SwitchString switch中可以使用字串<br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON(可选). <br/> * date: 2016/1/11 10:16 <br/> * * @author zhengliang@lbw001.com * @version * @since JDK 1.6 */ public class SwitchString { public static void main(String[] args) { String a = ""; switch(a) { case "test" : System.out.println("test"); case "test1" : System.out.println("test1"); break ; default : System.out.println("break"); break ; } } }
UTF-8
Java
1,010
java
SwitchString.java
Java
[ { "context": " All Rights Reserved.<br/>\n * 描述:TODO<br/>\n * 创建人:zhengliang@lbw001.com<br/>\n * 创建时间:2016/1/1110:16<br/>\n * 修改人:TODO 选写<b", "end": 138, "score": 0.9999303221702576, "start": 117, "tag": "EMAIL", "value": "zhengliang@lbw001.com" }, { "context": "r/> \n * date: 2016/1/11 10:16 <br/> \n *\n * @author zhengliang@lbw001.com \n * @version\n * @since JDK 1.6 \n */\npublic class ", "end": 475, "score": 0.9999255537986755, "start": 454, "tag": "EMAIL", "value": "zhengliang@lbw001.com" } ]
null
[]
/** * 文件名:SwitchString<br/> * 版权:Copyright 2014-2015易互通科技(武汉)有限公司 All Rights Reserved.<br/> * 描述:TODO<br/> * 创建人:<EMAIL><br/> * 创建时间:2016/1/1110:16<br/> * 修改人:TODO 选写<br/> * 修改时间:2016/1/1110:16 选写<br/> * 修改内容:TODO 选写<br/> */ package com.justice.jdk.seven; /** * ClassName: SwitchString switch中可以使用字串<br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON(可选). <br/> * date: 2016/1/11 10:16 <br/> * * @author <EMAIL> * @version * @since JDK 1.6 */ public class SwitchString { public static void main(String[] args) { String a = ""; switch(a) { case "test" : System.out.println("test"); case "test1" : System.out.println("test1"); break ; default : System.out.println("break"); break ; } } }
982
0.539823
0.483407
38
22.789474
15.497296
64
false
false
0
0
0
0
0
0
0.184211
false
false
7
c42c0fc0b1fb504ec6306e9e89e1bcba5d7d72d6
36,859,409,338,207
8f6fe920d146fa8384ea25c1587d7d2931c51ebf
/src/com/yb/tree/P94.java
51797a9d8d79415e3b01eca06a9d1d1040e5f946
[]
no_license
yangxiwen-blank/algorithms
https://github.com/yangxiwen-blank/algorithms
37680e89cb31ff97ee3289ecf7d1dc6eab237b77
8c64888ed0336b777e973e6edf5e1e8790786974
refs/heads/master
2023-01-06T18:31:14.232000
2020-11-09T02:26:59
2020-11-09T02:26:59
311,199,182
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yb.tree; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; public class P94 { List<Integer> res = new ArrayList<>(); /** * 94. 二叉树的中序遍历<br> * 给定一个二叉树,返回它的中序 遍历。 */ public List<Integer> inorderTraversal(TreeNode root) { if (root == null) return res; inorderTraversal(root.left); res.add(root.val); inorderTraversal(root.right); return res; } public List<Integer> inorderTraversalBfs(TreeNode root) { if (root == null) return res; Queue<TreeNode> queue = new ArrayDeque<>(); // queue.offer(root); while (!queue.isEmpty() || root != null) { while (root != null) { queue.offer(root); root = root.left; } root = queue.poll(); res.add(root.val); root = root.right; } return res; } }
UTF-8
Java
1,019
java
P94.java
Java
[]
null
[]
package com.yb.tree; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; public class P94 { List<Integer> res = new ArrayList<>(); /** * 94. 二叉树的中序遍历<br> * 给定一个二叉树,返回它的中序 遍历。 */ public List<Integer> inorderTraversal(TreeNode root) { if (root == null) return res; inorderTraversal(root.left); res.add(root.val); inorderTraversal(root.right); return res; } public List<Integer> inorderTraversalBfs(TreeNode root) { if (root == null) return res; Queue<TreeNode> queue = new ArrayDeque<>(); // queue.offer(root); while (!queue.isEmpty() || root != null) { while (root != null) { queue.offer(root); root = root.left; } root = queue.poll(); res.add(root.val); root = root.right; } return res; } }
1,019
0.542828
0.5387
42
22.071428
16.975323
61
false
false
0
0
0
0
0
0
0.52381
false
false
7
504a3de410617ea44764e0f942ec6eeccd34baff
16,020,228,038,980
ed4c526179ad5732a1189bbd0ce9fbc239f79bac
/src/java/com/hzih/face/recognition/domain/RegisterRequest.java
105fe8c25bd7e3d054ac12a68d3d412d48fe59b1
[]
no_license
gholdzhang/face
https://github.com/gholdzhang/face
9468ed61753837044751834b0c4441924f8107d8
15ce646c76af5a81000d8fe970ee4a411f2f1afc
refs/heads/master
2023-03-17T01:03:54.418000
2016-04-16T02:11:09
2016-04-16T02:11:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hzih.face.recognition.domain; import com.hzih.face.recognition.entity.SipXml; import com.hzih.face.recognition.utils.Configuration; /** * Created by Administrator on 15-7-24. */ public class RegisterRequest extends SipXml { private String province; private String city; private String organization; private String institution; private String place; private String address; private String ip; private int port; private double latitude; private double longitude; private String manager; private String mobile; private String telephone; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getInstitution() { return institution; } public void setInstitution(String institution) { this.institution = institution; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public String getManager() { return manager; } public void setManager(String manager) { this.manager = manager; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String toString(){ return "<?xml version=\"1.0\"?>\r\n\r\n" + "<Register>\r\n" + "<DeviceType>" + deviceType + "</DeviceType>\r\n" + "<CmdType>" + cmdType + "</CmdType>\r\n" + "<DeviceID>" + deviceId + "</DeviceID>\r\n" + "<Province>" + province + "</Province>\r\n" + "<City>" + city + "</City>\r\n" + "<Organization>" + organization + "</Organization>\r\n" + "<Institution>" + institution + "</Institution>\r\n" + "<Place>" + place + "</Place>\r\n" + "<Address>" + address + "</Address>\r\n" + "<Latitude>" + latitude + "</Latitude>\r\n" + "<Longitude>" + longitude + "</Longitude>\r\n" + "<IP>" + ip + "</IP>\r\n" + "<Port>" + port + "</Port>\r\n" + "<Manager>" + manager + "</Manager>\r\n" + "<Mobile>" + manager + "</Mobile>\r\n" + "<Telephone>" + manager + "</Telephone>\r\n" + "</Register>"; } public RegisterRequest xmlToBean(byte[] buff){ Configuration config = new Configuration(buff); return config.getRegisterRequest(); } }
UTF-8
Java
3,802
java
RegisterRequest.java
Java
[ { "context": "ecognition.utils.Configuration;\n\n/**\n * Created by Administrator on 15-7-24.\n */\npublic class RegisterRequest exte", "end": 178, "score": 0.37841081619262695, "start": 165, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.hzih.face.recognition.domain; import com.hzih.face.recognition.entity.SipXml; import com.hzih.face.recognition.utils.Configuration; /** * Created by Administrator on 15-7-24. */ public class RegisterRequest extends SipXml { private String province; private String city; private String organization; private String institution; private String place; private String address; private String ip; private int port; private double latitude; private double longitude; private String manager; private String mobile; private String telephone; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getInstitution() { return institution; } public void setInstitution(String institution) { this.institution = institution; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public String getManager() { return manager; } public void setManager(String manager) { this.manager = manager; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String toString(){ return "<?xml version=\"1.0\"?>\r\n\r\n" + "<Register>\r\n" + "<DeviceType>" + deviceType + "</DeviceType>\r\n" + "<CmdType>" + cmdType + "</CmdType>\r\n" + "<DeviceID>" + deviceId + "</DeviceID>\r\n" + "<Province>" + province + "</Province>\r\n" + "<City>" + city + "</City>\r\n" + "<Organization>" + organization + "</Organization>\r\n" + "<Institution>" + institution + "</Institution>\r\n" + "<Place>" + place + "</Place>\r\n" + "<Address>" + address + "</Address>\r\n" + "<Latitude>" + latitude + "</Latitude>\r\n" + "<Longitude>" + longitude + "</Longitude>\r\n" + "<IP>" + ip + "</IP>\r\n" + "<Port>" + port + "</Port>\r\n" + "<Manager>" + manager + "</Manager>\r\n" + "<Mobile>" + manager + "</Mobile>\r\n" + "<Telephone>" + manager + "</Telephone>\r\n" + "</Register>"; } public RegisterRequest xmlToBean(byte[] buff){ Configuration config = new Configuration(buff); return config.getRegisterRequest(); } }
3,802
0.556023
0.554182
158
23.063292
20.197971
73
false
false
0
0
0
0
0
0
0.28481
false
false
7
53f91c465e722b100fe7ea2efaf452962fa49530
18,382,460,061,466
88d2448b2a9a0039cd546b0d3fe6e1b829ba20c8
/JavaMultiThreading/src/CountDownLatchTest.java
cb8704138fc27afd674ee7af3f4d9341183275a7
[]
no_license
Shaposhnikov-Nick/JavaAdvanced
https://github.com/Shaposhnikov-Nick/JavaAdvanced
7724b7b323ee47b8a2c6729d5709efbaf898ca72
d3969aa1f9683002bcfa58ca7138c6c95ad8b0f4
refs/heads/main
2023-07-01T08:27:36.348000
2021-08-02T19:36:15
2021-08-02T19:36:15
392,072,132
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package JavaMultiThreading; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(3); //3 - указываем, сколько раз должны вызвать countDownLatch //чтобы countDownLatch.await() больше не ждал ExecutorService executorService = Executors.newFixedThreadPool(3); // задаем число потоков в пул for (int i = 0; i < 3; i++) { executorService.submit(new Processor(countDownLatch)); } executorService.shutdown(); // прекращаем прием новых заданий countDownLatch.await(); System.out.println("Latch has been opened, main thread is processing..."); } } class Processor implements Runnable { private CountDownLatch countDownLatch; Processor(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } countDownLatch.countDown(); // отсчитаем назад } }
UTF-8
Java
1,440
java
CountDownLatchTest.java
Java
[]
null
[]
package JavaMultiThreading; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(3); //3 - указываем, сколько раз должны вызвать countDownLatch //чтобы countDownLatch.await() больше не ждал ExecutorService executorService = Executors.newFixedThreadPool(3); // задаем число потоков в пул for (int i = 0; i < 3; i++) { executorService.submit(new Processor(countDownLatch)); } executorService.shutdown(); // прекращаем прием новых заданий countDownLatch.await(); System.out.println("Latch has been opened, main thread is processing..."); } } class Processor implements Runnable { private CountDownLatch countDownLatch; Processor(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } countDownLatch.countDown(); // отсчитаем назад } }
1,440
0.652108
0.645331
40
32.224998
32.111904
121
false
false
0
0
0
0
0
0
0.475
false
false
7
5c41fa4b06aa84badd247a156a4aecca95f182fd
773,094,143,324
f4e6a7f8394d6da7f697c982c5c9d6969ac8b856
/app/src/main/java/com/techart/smartsalon/data/service/executor/NetworkTimeOutException.java
a05062880ae0164f62d1f0112ce924972ed0957f
[]
no_license
AndroidProject24/SmartSalon
https://github.com/AndroidProject24/SmartSalon
2fd91f94adfa274dff260c35af8de18aa768cd8c
4cb6792154b57ac87c9b332dae450ae0023b360c
refs/heads/master
2020-06-10T02:46:54.854000
2016-12-11T17:03:18
2016-12-11T17:03:18
76,124,639
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.techart.smartsalon.data.service.executor; public class NetworkTimeOutException extends Exception { }
UTF-8
Java
114
java
NetworkTimeOutException.java
Java
[]
null
[]
package com.techart.smartsalon.data.service.executor; public class NetworkTimeOutException extends Exception { }
114
0.842105
0.842105
4
27.5
27.023138
56
false
false
0
0
0
0
0
0
0.25
false
false
7
b98bc56b580d55359688736b786d7b2980b00120
23,304,492,574,903
a535a307f445c39687790ee514cbfc0f5c34dcfa
/MatrixSearchEngine/MatrixSearchWeb/src/test/java/lut/gp/jbw/dao/ExecuteQueryTest.java
4296cd6984442e63d404f4c2cbb0ef629b9cdec5
[]
no_license
94-FreeStyle/Java
https://github.com/94-FreeStyle/Java
82cf3bfff30ce089578378c9ae387f1ed9cc9e09
3df0474596e29682a9d0866f2ef14a853156bfa0
refs/heads/master
2021-05-01T05:36:32.308000
2017-06-06T06:47:24
2017-06-06T06:47:24
79,761,968
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 lut.gp.jbw.dao; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import lut.gp.jbw.model.ReturnRecord; import org.junit.Test; /** * * @author vincent */ public class ExecuteQueryTest { /** * Test of selectRank method, of class ExecuteQuery. */ @Test public void testSelectRank() { System.out.println("selectRank"); Set<String> urls = new HashSet<>(); urls.add("www.baidu.com"); Map<String, Double> result = ExecuteQuery.selectRank(urls); for (String k : result.keySet()) { System.out.println(k + ":" + result.get(k)); } } /** * Test of selectPageCon method, of class ExecuteQuery. */ @Test public void testSelectPageCon() { System.out.println("selectPageCon"); List<String> urls = new ArrayList<>(); urls.add("www.baidu.com"); List<ReturnRecord> result = ExecuteQuery.selectPageCon(urls); for (ReturnRecord rec : result) { System.out.println(rec.toString()); } } }
UTF-8
Java
1,309
java
ExecuteQueryTest.java
Java
[ { "context": "nRecord;\nimport org.junit.Test;\n\n/**\n *\n * @author vincent\n */\npublic class ExecuteQueryTest {\n\n /**\n ", "end": 418, "score": 0.9844570159912109, "start": 411, "tag": "USERNAME", "value": "vincent" } ]
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 lut.gp.jbw.dao; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import lut.gp.jbw.model.ReturnRecord; import org.junit.Test; /** * * @author vincent */ public class ExecuteQueryTest { /** * Test of selectRank method, of class ExecuteQuery. */ @Test public void testSelectRank() { System.out.println("selectRank"); Set<String> urls = new HashSet<>(); urls.add("www.baidu.com"); Map<String, Double> result = ExecuteQuery.selectRank(urls); for (String k : result.keySet()) { System.out.println(k + ":" + result.get(k)); } } /** * Test of selectPageCon method, of class ExecuteQuery. */ @Test public void testSelectPageCon() { System.out.println("selectPageCon"); List<String> urls = new ArrayList<>(); urls.add("www.baidu.com"); List<ReturnRecord> result = ExecuteQuery.selectPageCon(urls); for (ReturnRecord rec : result) { System.out.println(rec.toString()); } } }
1,309
0.62796
0.62796
49
25.714285
21.514114
79
false
false
0
0
0
0
0
0
0.489796
false
false
7