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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7e378f4ae3f23031e720f16b7400e654b0100dbd
| 1,864,015,833,482 |
ce5b93481bc64f241794af4acbcd5959093abf03
|
/A5Tester/src/ca/NetSysLab/UDPClient/Initiator.java
|
98cc306d15677acba4affe6a7bd10f32b6c3759e
|
[] |
no_license
|
cszarapka/411-kvstore
|
https://github.com/cszarapka/411-kvstore
|
363e56709a7b8cfe204a90f477e2fd05743537e9
|
24bb67076caf8fba63419d7d5ab30310f86f6fcd
|
refs/heads/master
| 2021-01-15T10:18:35.263000 | 2015-05-03T03:53:15 | 2015-05-03T03:53:15 | 32,036,421 | 3 | 1 | null | false | 2015-05-03T03:53:15 | 2015-03-11T19:17:19 | 2015-04-27T13:09:05 | 2015-05-03T03:53:15 | 16,728 | 1 | 0 | 0 |
Java
| null | null |
package ca.NetSysLab.UDPClient;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class Initiator {
static String a = "null";
static String a2 = "null";
static String a3 = "null";
static int p = 0;
static int p2 = 0;
static int p3 = 0;
static boolean DEBUG = false;
// static methods
static ArrayList<ServerNode> buildServerNodeList(String fileName) {
ArrayList<ServerNode> serverNodes = new ArrayList<ServerNode>();
FileInputStream fin = null;
BufferedReader br = null;
try {
fin = new FileInputStream(fileName);
br = new BufferedReader(new InputStreamReader(fin));
String line = "";
while ((line = br.readLine()) != null) {
String[] tokens = line.split(":");
/*try {
if (InetAddress.getByName(tokens[0]).isReachable(5000))
{
serverNodes.add(new ServerNode(tokens[0], Integer.parseInt(tokens[1])));
}
} catch (IOException e) {
e.printStackTrace();
}*/
try {
InetAddress.getByName(tokens[0]);
serverNodes.add(new ServerNode(tokens[0], Integer.parseInt(tokens[1])));
} catch (UnknownHostException e) {
//e.printStackTrace();
System.err.println("\nFailed to reach host: " + tokens[0]);
System.err.println("Excluding from the server node list ... ");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fin.close();
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return serverNodes;
}
void executeTestsAssignmentFour() {
System.out.print("Enter address1:port1 ");
String[] sa = System.console().readLine().split(":");
a = sa[0];
p = Integer.parseInt(sa[1]);
System.out.print("Enter address2:port2 ");
String[] sa2 = System.console().readLine().split(":");
a2 = sa2[0];
p2 = Integer.parseInt(sa2[1]);
System.out.print("Enter address3:port3 ");
String[] sa3 = System.console().readLine().split(":");
a3 = sa3[0];
p3 = Integer.parseInt(sa3[1]);
System.out.println("Testing STORE A1 -------");
Tests.testStore(a, p);
System.out.println();
System.out.println("Testing STORE A2 -------");
Tests.testStore(a2, p2);
System.out.println();
System.out.println("Testing STORE A3 -------");
Tests.testStore(a3, p3);
System.out.println();
System.out.println("Testing REMOVE -------");
Tests.testRemove(a, p);
System.out.println();
System.out.println("Testing REPLACE -------");
Tests.testReplace(a, p);
System.out.println();
System.out.println("Testing LOSS REMOVE -------");
Tests.testLossRemove(a, p);
System.out.println();
System.out.println("Testing CONCURRENCY PUT -------");
Tests.testConcurrencyPut(a, p);
System.out.println();
System.out.println("Testing CROSS SERVER A1-A2 -------");
Tests.testCross(a, a2, p, p2, 0);
System.out.println();
System.out.println("Testing CROSS SERVER A1-A3 -------");
Tests.testCross(a, a3, p, p3, 0);
System.out.println();
System.out.println("Testing CROSS SERVER A2-A3 -------");
Tests.testCross(a2, a3, p2, p3, 0);
System.out.println();
System.out.println("Testing NODE FAILURE -------");
Tests.testNodeFail(a, p, a2, p2, a3, p3);
System.out.println();
System.out.println("\nDONE");
System.exit(0);
}
static void executeTestsAssignmentFive() throws IOException {
BufferedReader br;
//String smallListFileName = "";
String bigListFileName = "";
//System.out.print("Enter small node list file path: ");
//br = new BufferedReader(new InputStreamReader(System.in));
//smallListFileName = br.readLine();
System.out.print("Enter big node list file path: ");
br = new BufferedReader(new InputStreamReader(System.in));
bigListFileName = br.readLine();
//System.out.println("Enter\n A - to run test suite\n B - to run traffic generator\n C - to run load tests on the machine traffic generator is sending requests to");
//br = new BufferedReader(new InputStreamReader(System.in));
//String option = br.readLine();;
String option = "A";
//ArrayList<ServerNode> smallLsitServerNodes = buildServerNodeList(smallListFileName);
ArrayList<ServerNode> bigLsitServerNodes = buildServerNodeList(bigListFileName);
System.out.println("Done building node list ... ");
int numberOfRequestsSmall = 10;
int numberOfRequests = 20;
int numberOfClientsSmall = 20;
int numberOfClientsLarge = 50;
long durationSeconds = 180;
if (option.equalsIgnoreCase("A")) {
System.out.print("Enter Number of requests small,Number of requests large,Number of clients small,Number of clients large,Request sending duration (seconds): ");
br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(",");
numberOfRequestsSmall = Integer.parseInt(s[0]);
numberOfRequests = Integer.parseInt(s[1]);
numberOfClientsSmall = Integer.parseInt(s[2]);
numberOfClientsLarge = Integer.parseInt(s[3]);
durationSeconds = Long.parseLong(s[4]);
System.out.println("\n ... Running response time tests - medium load ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, numberOfRequestsSmall, 2222, 1); // multiple nodes / single client
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, numberOfRequests, 2222, numberOfClientsSmall); // multiple nodes / multiple clients
System.out.println("\n ... Running throughput tests - medium load ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "PUT"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "GET"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "REMOVE"); // multiple nodes / multiple clients
System.out.println("\n ... Running throughput tests - high load ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsLarge, "PUT"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsLarge, "GET"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsLarge, "REMOVE"); // multiple nodes / multiple clients
System.out.println("\n ... Running throughput test - before catastrophic node failure ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "PUT"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "GET"); // multiple nodes / multiple clients
// this one simply shuts down some of the nodes
TestsAssignmentFive.testCatastrophicFailureGracefulDegradation(bigLsitServerNodes, 20); // multiple nodes / single client
System.out.println("\n ... Running throughput test - after catastrophic node failure ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "GET"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "REMOVE"); // multiple nodes / multiple clients
} else if (option.equalsIgnoreCase("B")) {
TrafficGenerator.putRqstOnlySameNode(bigLsitServerNodes.get(0), 60); // single node / single client
} else if (option.equalsIgnoreCase("C")) {
TestsAssignmentFive.testSameNodeMultipleClients(bigLsitServerNodes.get(0), numberOfRequests, 2222, numberOfClientsSmall); // single node/ multiple clients
} else {
System.err.println("Invalid option.");
return;
}
}
public static void main(String args[]) throws IOException {
executeTestsAssignmentFive();
}
}
|
UTF-8
|
Java
| 8,890 |
java
|
Initiator.java
|
Java
|
[] | null |
[] |
package ca.NetSysLab.UDPClient;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class Initiator {
static String a = "null";
static String a2 = "null";
static String a3 = "null";
static int p = 0;
static int p2 = 0;
static int p3 = 0;
static boolean DEBUG = false;
// static methods
static ArrayList<ServerNode> buildServerNodeList(String fileName) {
ArrayList<ServerNode> serverNodes = new ArrayList<ServerNode>();
FileInputStream fin = null;
BufferedReader br = null;
try {
fin = new FileInputStream(fileName);
br = new BufferedReader(new InputStreamReader(fin));
String line = "";
while ((line = br.readLine()) != null) {
String[] tokens = line.split(":");
/*try {
if (InetAddress.getByName(tokens[0]).isReachable(5000))
{
serverNodes.add(new ServerNode(tokens[0], Integer.parseInt(tokens[1])));
}
} catch (IOException e) {
e.printStackTrace();
}*/
try {
InetAddress.getByName(tokens[0]);
serverNodes.add(new ServerNode(tokens[0], Integer.parseInt(tokens[1])));
} catch (UnknownHostException e) {
//e.printStackTrace();
System.err.println("\nFailed to reach host: " + tokens[0]);
System.err.println("Excluding from the server node list ... ");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fin.close();
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return serverNodes;
}
void executeTestsAssignmentFour() {
System.out.print("Enter address1:port1 ");
String[] sa = System.console().readLine().split(":");
a = sa[0];
p = Integer.parseInt(sa[1]);
System.out.print("Enter address2:port2 ");
String[] sa2 = System.console().readLine().split(":");
a2 = sa2[0];
p2 = Integer.parseInt(sa2[1]);
System.out.print("Enter address3:port3 ");
String[] sa3 = System.console().readLine().split(":");
a3 = sa3[0];
p3 = Integer.parseInt(sa3[1]);
System.out.println("Testing STORE A1 -------");
Tests.testStore(a, p);
System.out.println();
System.out.println("Testing STORE A2 -------");
Tests.testStore(a2, p2);
System.out.println();
System.out.println("Testing STORE A3 -------");
Tests.testStore(a3, p3);
System.out.println();
System.out.println("Testing REMOVE -------");
Tests.testRemove(a, p);
System.out.println();
System.out.println("Testing REPLACE -------");
Tests.testReplace(a, p);
System.out.println();
System.out.println("Testing LOSS REMOVE -------");
Tests.testLossRemove(a, p);
System.out.println();
System.out.println("Testing CONCURRENCY PUT -------");
Tests.testConcurrencyPut(a, p);
System.out.println();
System.out.println("Testing CROSS SERVER A1-A2 -------");
Tests.testCross(a, a2, p, p2, 0);
System.out.println();
System.out.println("Testing CROSS SERVER A1-A3 -------");
Tests.testCross(a, a3, p, p3, 0);
System.out.println();
System.out.println("Testing CROSS SERVER A2-A3 -------");
Tests.testCross(a2, a3, p2, p3, 0);
System.out.println();
System.out.println("Testing NODE FAILURE -------");
Tests.testNodeFail(a, p, a2, p2, a3, p3);
System.out.println();
System.out.println("\nDONE");
System.exit(0);
}
static void executeTestsAssignmentFive() throws IOException {
BufferedReader br;
//String smallListFileName = "";
String bigListFileName = "";
//System.out.print("Enter small node list file path: ");
//br = new BufferedReader(new InputStreamReader(System.in));
//smallListFileName = br.readLine();
System.out.print("Enter big node list file path: ");
br = new BufferedReader(new InputStreamReader(System.in));
bigListFileName = br.readLine();
//System.out.println("Enter\n A - to run test suite\n B - to run traffic generator\n C - to run load tests on the machine traffic generator is sending requests to");
//br = new BufferedReader(new InputStreamReader(System.in));
//String option = br.readLine();;
String option = "A";
//ArrayList<ServerNode> smallLsitServerNodes = buildServerNodeList(smallListFileName);
ArrayList<ServerNode> bigLsitServerNodes = buildServerNodeList(bigListFileName);
System.out.println("Done building node list ... ");
int numberOfRequestsSmall = 10;
int numberOfRequests = 20;
int numberOfClientsSmall = 20;
int numberOfClientsLarge = 50;
long durationSeconds = 180;
if (option.equalsIgnoreCase("A")) {
System.out.print("Enter Number of requests small,Number of requests large,Number of clients small,Number of clients large,Request sending duration (seconds): ");
br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(",");
numberOfRequestsSmall = Integer.parseInt(s[0]);
numberOfRequests = Integer.parseInt(s[1]);
numberOfClientsSmall = Integer.parseInt(s[2]);
numberOfClientsLarge = Integer.parseInt(s[3]);
durationSeconds = Long.parseLong(s[4]);
System.out.println("\n ... Running response time tests - medium load ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, numberOfRequestsSmall, 2222, 1); // multiple nodes / single client
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, numberOfRequests, 2222, numberOfClientsSmall); // multiple nodes / multiple clients
System.out.println("\n ... Running throughput tests - medium load ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "PUT"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "GET"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "REMOVE"); // multiple nodes / multiple clients
System.out.println("\n ... Running throughput tests - high load ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsLarge, "PUT"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsLarge, "GET"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsLarge, "REMOVE"); // multiple nodes / multiple clients
System.out.println("\n ... Running throughput test - before catastrophic node failure ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "PUT"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "GET"); // multiple nodes / multiple clients
// this one simply shuts down some of the nodes
TestsAssignmentFive.testCatastrophicFailureGracefulDegradation(bigLsitServerNodes, 20); // multiple nodes / single client
System.out.println("\n ... Running throughput test - after catastrophic node failure ...");
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "GET"); // multiple nodes / multiple clients
TestsAssignmentFive.testMultipleNodesMultipleClients(bigLsitServerNodes, durationSeconds, 2222, numberOfClientsSmall, "REMOVE"); // multiple nodes / multiple clients
} else if (option.equalsIgnoreCase("B")) {
TrafficGenerator.putRqstOnlySameNode(bigLsitServerNodes.get(0), 60); // single node / single client
} else if (option.equalsIgnoreCase("C")) {
TestsAssignmentFive.testSameNodeMultipleClients(bigLsitServerNodes.get(0), numberOfRequests, 2222, numberOfClientsSmall); // single node/ multiple clients
} else {
System.err.println("Invalid option.");
return;
}
}
public static void main(String args[]) throws IOException {
executeTestsAssignmentFive();
}
}
| 8,890 | 0.664567 | 0.648369 | 214 | 39.542057 | 41.954311 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.35514 | false | false |
7
|
b965f2804bd269a559973a8a29943d2d5dfdd960
| 30,279,519,506,131 |
85e6e61e4cc8ea2204d3a077e8e8590d1d9785e2
|
/p1/Students.java
|
f2d2b24beb913743207c1abeada92148b3c2ded7
|
[] |
no_license
|
Parthasarathi5107/JAVA
|
https://github.com/Parthasarathi5107/JAVA
|
28a350350922168adb52cdd4bac58fb9d3000d78
|
0bf0ccce71b993a27971a0f1103d440920ba3d40
|
refs/heads/main
| 2023-04-21T02:00:01.467000 | 2021-05-14T16:48:50 | 2021-05-14T16:48:50 | 352,955,754 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package p1;
import java.util.Scanner;
public class Students {
public static void main(String[] args) {
System.out.println("Enter english marks:");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
System.out.println("Enter java marks:");
int y = sc.nextInt();
System.out.println("Enter db marks:");
int z = sc.nextInt();
int TotalMarks = x+y+z;
int avg = TotalMarks/3;
System.out.println("TotalMarks = "+TotalMarks);
System.out.println("Avg Marks = "+avg);
}
}
|
UTF-8
|
Java
| 572 |
java
|
Students.java
|
Java
|
[] | null |
[] |
package p1;
import java.util.Scanner;
public class Students {
public static void main(String[] args) {
System.out.println("Enter english marks:");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
System.out.println("Enter java marks:");
int y = sc.nextInt();
System.out.println("Enter db marks:");
int z = sc.nextInt();
int TotalMarks = x+y+z;
int avg = TotalMarks/3;
System.out.println("TotalMarks = "+TotalMarks);
System.out.println("Avg Marks = "+avg);
}
}
| 572 | 0.58042 | 0.576923 | 28 | 18.428572 | 17.358465 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.607143 | false | false |
7
|
bb834417bb19c436abf5309d26a9388103da6cd8
| 11,811,160,119,626 |
6e569949e34b5e0d6067a51007055676f943a094
|
/mnb-acceptance-tests/src/test/java/uk/org/mnb/harvester/regession/frontend/VerifyTableBookingKrantiWithDeposit.java
|
0f9c4495daecd2c6cb7544683dc4329becdf2536
|
[] |
no_license
|
krayanni/mnb-acceptance-tests
|
https://github.com/krayanni/mnb-acceptance-tests
|
37fabf2cd8e7aea957e2dc0ec9d0ba0d48cfad00
|
669cc6575c817e9dd73c29d7f15168217c6bdf7f
|
refs/heads/master
| 2021-01-10T08:34:13.560000 | 2016-01-28T10:48:30 | 2016-01-28T10:48:30 | 50,575,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package uk.org.mnb.harvester.regession.frontend;
import java.awt.AWTException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import uk.org.mnb.harvester.pages.frontend.LoginPage;
import uk.org.mnb.harvester.pages.frontend.PaymentPage;
import uk.org.mnb.harvester.pages.frontend.TableBookingPage;
import uk.org.mnb.harvester.tests.AssertFactory;
import uk.org.mnb.harvester.tests.browserFactory;
public class VerifyTableBookingKrantiWithDeposit {
@Test
public void checkTableBookingKrantiWithDeposit() throws AWTException, InterruptedException
{
WebDriver driver = browserFactory.startBrowser("firefox", "https://systest.harvester.172.26.161.242.xip.io/restaurants/eastandwestmidlands/thewychwayinndroitwich/tablebooking");
TableBookingPage tablebooking = PageFactory.initElements(driver, TableBookingPage.class);
LoginPage login = PageFactory.initElements(driver, LoginPage.class);
PaymentPage payment = PageFactory.initElements(driver, PaymentPage.class);
AssertFactory Assert = PageFactory.initElements(driver, AssertFactory.class);
tablebooking.CompleteDateSectionWithEvent();
tablebooking.CompleteTimeSectionWithEvent();
tablebooking.CompleteReviewSection();
login.clickOnLoginButton();
login.loginToHarvester("krayanni@caci.co.uk", "password1234");
tablebooking.CompleteDetailsSectionWithLogin();
payment.ApprovedPayment();
// Assert.assertTrue(driver.getPageSource().contains("Thank you, "));
Assert.Confirmbooking("THANK YOU, KRANTI");
driver.quit();
}
}
|
UTF-8
|
Java
| 1,650 |
java
|
VerifyTableBookingKrantiWithDeposit.java
|
Java
|
[
{
"context": "tartBrowser(\"firefox\", \"https://systest.harvester.172.26.161.242.xip.io/restaurants/eastandwestmidlands/thewychway",
"end": 742,
"score": 0.9806313514709473,
"start": 728,
"tag": "IP_ADDRESS",
"value": "172.26.161.242"
},
{
"context": "lickOnLoginButton();\n\t \t login.loginToHarvester(\"krayanni@caci.co.uk\", \"password1234\");\n\t \t tablebooking.CompleteDeta",
"end": 1383,
"score": 0.9999328255653381,
"start": 1364,
"tag": "EMAIL",
"value": "krayanni@caci.co.uk"
},
{
"context": "\t login.loginToHarvester(\"krayanni@caci.co.uk\", \"password1234\");\n\t \t tablebooking.CompleteDetailsSectionWithLo",
"end": 1399,
"score": 0.9978069067001343,
"start": 1387,
"tag": "PASSWORD",
"value": "password1234"
}
] | null |
[] |
package uk.org.mnb.harvester.regession.frontend;
import java.awt.AWTException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import uk.org.mnb.harvester.pages.frontend.LoginPage;
import uk.org.mnb.harvester.pages.frontend.PaymentPage;
import uk.org.mnb.harvester.pages.frontend.TableBookingPage;
import uk.org.mnb.harvester.tests.AssertFactory;
import uk.org.mnb.harvester.tests.browserFactory;
public class VerifyTableBookingKrantiWithDeposit {
@Test
public void checkTableBookingKrantiWithDeposit() throws AWTException, InterruptedException
{
WebDriver driver = browserFactory.startBrowser("firefox", "https://systest.harvester.172.26.161.242.xip.io/restaurants/eastandwestmidlands/thewychwayinndroitwich/tablebooking");
TableBookingPage tablebooking = PageFactory.initElements(driver, TableBookingPage.class);
LoginPage login = PageFactory.initElements(driver, LoginPage.class);
PaymentPage payment = PageFactory.initElements(driver, PaymentPage.class);
AssertFactory Assert = PageFactory.initElements(driver, AssertFactory.class);
tablebooking.CompleteDateSectionWithEvent();
tablebooking.CompleteTimeSectionWithEvent();
tablebooking.CompleteReviewSection();
login.clickOnLoginButton();
login.loginToHarvester("<EMAIL>", "<PASSWORD>");
tablebooking.CompleteDetailsSectionWithLogin();
payment.ApprovedPayment();
// Assert.assertTrue(driver.getPageSource().contains("Thank you, "));
Assert.Confirmbooking("THANK YOU, KRANTI");
driver.quit();
}
}
| 1,636 | 0.779394 | 0.770303 | 40 | 40.25 | 36.672028 | 182 | false | false | 0 | 0 | 0 | 0 | 70 | 0.042424 | 1.725 | false | false |
7
|
83639b65c59e0accfb0d4cb3c76f01b64a295099
| 11,811,160,118,614 |
664e83c0c317c67c5c1091a1e52a815791f295bf
|
/src/leetcode/problems/MergeIntervals.java
|
0d58f082469206d348dc91f360c1b1284d619d00
|
[] |
no_license
|
arjunmishra13/learning
|
https://github.com/arjunmishra13/learning
|
9a1f21ea1a784f40cee615ac419576f3e4dea9aa
|
7d26a1e27a65fd82faddb36accb641079be0e544
|
refs/heads/master
| 2021-01-11T18:22:08.044000 | 2019-07-25T15:41:55 | 2019-07-25T15:41:55 | 69,628,015 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package leetcode.problems;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
public class MergeIntervals {
public int[][] merge(int[][] intervals) {
if (intervals == null || intervals.length == 0) {
return intervals;
}
Arrays.sort(intervals, startTime);
PriorityQueue<int[]> pq = new PriorityQueue<int[]>(endTime);
pq.add(intervals[0]);
boolean merges = false;
for (int i = 1; i < intervals.length; i++) {
int[]top = pq.peek();
if (top[1] >= intervals[i][0]) {
pq.remove();
top[1] = Math.max(top[1], intervals[i][1]);
pq.add(top);
merges = true;
} else {
pq.add(intervals[i]);
}
}
int[][]out = new int[pq.size()][2];
int i = pq.size() - 1;
while(!pq.isEmpty()) {
out[i--] = pq.remove();
}
return out;
}
Comparator<int[]>startTime = new Comparator<int[]>() {
@Override
public int compare(int[]a, int[]b) {
return Integer.compare(a[0], b[0]);
}
};
Comparator<int[]>endTime = new Comparator<int[]>() {
@Override
public int compare(int[]a, int[]b) {
return -1*Integer.compare(a[1], b[1]);
}
};
}
|
UTF-8
|
Java
| 1,212 |
java
|
MergeIntervals.java
|
Java
|
[] | null |
[] |
package leetcode.problems;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
public class MergeIntervals {
public int[][] merge(int[][] intervals) {
if (intervals == null || intervals.length == 0) {
return intervals;
}
Arrays.sort(intervals, startTime);
PriorityQueue<int[]> pq = new PriorityQueue<int[]>(endTime);
pq.add(intervals[0]);
boolean merges = false;
for (int i = 1; i < intervals.length; i++) {
int[]top = pq.peek();
if (top[1] >= intervals[i][0]) {
pq.remove();
top[1] = Math.max(top[1], intervals[i][1]);
pq.add(top);
merges = true;
} else {
pq.add(intervals[i]);
}
}
int[][]out = new int[pq.size()][2];
int i = pq.size() - 1;
while(!pq.isEmpty()) {
out[i--] = pq.remove();
}
return out;
}
Comparator<int[]>startTime = new Comparator<int[]>() {
@Override
public int compare(int[]a, int[]b) {
return Integer.compare(a[0], b[0]);
}
};
Comparator<int[]>endTime = new Comparator<int[]>() {
@Override
public int compare(int[]a, int[]b) {
return -1*Integer.compare(a[1], b[1]);
}
};
}
| 1,212 | 0.555281 | 0.542904 | 52 | 22.307692 | 17.975986 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.634615 | false | false |
7
|
0607f539e49b9c63d44cc91a602cac7d0c64c9a3
| 25,864,293,059,111 |
8e5566078326e28a3fe97cd017185877d672d0f4
|
/src/game/itens/Jogador.java
|
eb5fdc90da91469a5762c87e7c116118ed96c741
|
[] |
no_license
|
hgsaldanha/hexa
|
https://github.com/hgsaldanha/hexa
|
a4c8daf6114208d93da9296fc1792c6d27685d6a
|
c7250123c4600e2f3db92c41ee19d419af65faa8
|
refs/heads/master
| 2016-09-06T14:28:25.036000 | 2014-11-03T21:44:50 | 2014-11-03T21:44:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package game.itens;
import engine.core.Game;
import engine.core.GameController;
import engine.itens.Item;
import engine.itens.PosicaoRender;
import game.app.Hexa;
/**
*
* @author alunoruy
*/
public class Jogador extends Item {
//private int DIRECAO;
//private final int INTERVALO = 100;
PosicaoRender pr;
public Jogador(int x, int y) {
super("jogador-alemanha.gif", x, y);
addImagem("PARADO", "jogador-alemanha-parado.gif");
setDeslocamento(1);
iniciarAnimacao();
}
public Jogador(PosicaoRender pr, int p) {
super("goleiro.gif",pr,p);
//addImagem("goleiro_esquerda", "goleiro_esqueda.gif");
//addImagem("goleiro_direita", "goleiro_direita.gif");
this.pr = pr;
setDeslocamento(1);
iniciarAnimacao();
}
@Override
public void animar() {
if (!GameController.getInstance().isFimJogo()) {
moverPara(getX(), Game.ALTURA_TELA - 400, Hexa.getInstance().getVelocidadeJogador());
while (getY() < Game.ALTURA_TELA - 410) {
pausar(100);
}
chutar(new Bola(getX(),getY()+50));
changeImagem("PARADO");
}
}
public void chutar(Bola b) {
b.setJogador(this);
b.iniciarAnimacao();
}
}
|
UTF-8
|
Java
| 1,561 |
java
|
Jogador.java
|
Java
|
[
{
"context": "r;\r\nimport game.app.Hexa;\r\n\r\n\r\n/**\r\n *\r\n * @author alunoruy\r\n */\r\npublic class Jogador extends Item {\r\n //",
"end": 395,
"score": 0.9992391467094421,
"start": 387,
"tag": "USERNAME",
"value": "alunoruy"
}
] | 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 game.itens;
import engine.core.Game;
import engine.core.GameController;
import engine.itens.Item;
import engine.itens.PosicaoRender;
import game.app.Hexa;
/**
*
* @author alunoruy
*/
public class Jogador extends Item {
//private int DIRECAO;
//private final int INTERVALO = 100;
PosicaoRender pr;
public Jogador(int x, int y) {
super("jogador-alemanha.gif", x, y);
addImagem("PARADO", "jogador-alemanha-parado.gif");
setDeslocamento(1);
iniciarAnimacao();
}
public Jogador(PosicaoRender pr, int p) {
super("goleiro.gif",pr,p);
//addImagem("goleiro_esquerda", "goleiro_esqueda.gif");
//addImagem("goleiro_direita", "goleiro_direita.gif");
this.pr = pr;
setDeslocamento(1);
iniciarAnimacao();
}
@Override
public void animar() {
if (!GameController.getInstance().isFimJogo()) {
moverPara(getX(), Game.ALTURA_TELA - 400, Hexa.getInstance().getVelocidadeJogador());
while (getY() < Game.ALTURA_TELA - 410) {
pausar(100);
}
chutar(new Bola(getX(),getY()+50));
changeImagem("PARADO");
}
}
public void chutar(Bola b) {
b.setJogador(this);
b.iniciarAnimacao();
}
}
| 1,561 | 0.584241 | 0.573991 | 57 | 25.385965 | 21.719709 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.701754 | false | false |
7
|
3b447947bb72b24dfbd261640ed881a9cad7a4b6
| 33,586,644,299,726 |
18e8afd1fc11e78ea4aa7f986e11e7ece442829f
|
/TP-PDC/src/main/java/ar/edu/itba/it/pdc/proxy/filters/L33tFilter.java
|
74c68f92f31f9850c18d1b194d1edcbf3d26c026
|
[] |
no_license
|
mtsrvs/android
|
https://github.com/mtsrvs/android
|
9a7b90f8dac3b20fa94642e4c7f1e1afb736cd2f
|
c61dea911672e31a9edb257650b789554e59ab7c
|
refs/heads/master
| 2016-09-06T11:17:39.109000 | 2011-11-09T20:38:00 | 2011-11-09T20:38:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ar.edu.itba.it.pdc.proxy.filters;
public class L33tFilter {
public static String transform(String str){
StringBuilder sb = new StringBuilder();
for (int i=0; i < str.length(); i++){
char c = str.charAt(i);
switch(c){
case 'A': case 'a':
sb.append('4');
break;
case 'E': case 'e':
sb.append('3');
break;
case 'I': case 'i':
sb.append('1');
break;
case 'O': case 'o':
sb.append('0');
break;
default:
sb.append(c);
}
}
return sb.toString();
}
}
|
UTF-8
|
Java
| 527 |
java
|
L33tFilter.java
|
Java
|
[] | null |
[] |
package ar.edu.itba.it.pdc.proxy.filters;
public class L33tFilter {
public static String transform(String str){
StringBuilder sb = new StringBuilder();
for (int i=0; i < str.length(); i++){
char c = str.charAt(i);
switch(c){
case 'A': case 'a':
sb.append('4');
break;
case 'E': case 'e':
sb.append('3');
break;
case 'I': case 'i':
sb.append('1');
break;
case 'O': case 'o':
sb.append('0');
break;
default:
sb.append(c);
}
}
return sb.toString();
}
}
| 527 | 0.550285 | 0.537002 | 29 | 17.172413 | 12.448706 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.068965 | false | false |
7
|
d1f3aa83b53bba2a47411c49480895152fd1a343
| 12,841,952,259,054 |
147ca4f717452b181480c7748d181ba7e54560f4
|
/알고리즘 수업/2주차/2일/Recursion_prac.java
|
e40425610a134342fd9bc83f11ef873f35177c14
|
[] |
no_license
|
izagood/code_training_JAVA
|
https://github.com/izagood/code_training_JAVA
|
efe626cc863e497728703979be7ca60b69a04a4b
|
891b77e1329dd3a24d869f3355dba249e3bce2d6
|
refs/heads/master
| 2020-04-04T22:47:13.339000 | 2020-02-13T15:52:08 | 2020-02-13T15:52:08 | 156,335,751 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package week02.d1.ch3;
import java.util.stream.LongStream;
public class Recursion {
int RecFunc(int num){
// int sum = 0;
if(num ==1){
return 1;
}
else{
return recFuncTail(num,1);
// sum = num + RecFunc(num - 1);
}
// return sum;
}
int recFuncTail(int num, int acc){
if(num ==1){
return acc;
}
return recFuncTail(num - 1, acc + num);
}
public static void main(String[] args) {
Recursion rc = new Recursion();
System.out.println("1부터 5까지의 합은 : " + rc.RecFunc(5));
Long result = LongStream.rangeClosed(1, 5).reduce((long x, long y) -> x + y).getAsLong();
System.out.println(result);
}
}
//1부터 n 까지의 합을 구하는 예를 재귀함수를 통해 구현하여라.
//
//
//
// 예) 다음과 같이 main 을 작성할때 RecFunc(int num) 을 구함.
//
//public static void main(String[] args){
//
// System.out.println("1부터 5까지의 합은 : " + RecFunc(5));
//
// }
|
UTF-8
|
Java
| 1,097 |
java
|
Recursion_prac.java
|
Java
|
[] | null |
[] |
package week02.d1.ch3;
import java.util.stream.LongStream;
public class Recursion {
int RecFunc(int num){
// int sum = 0;
if(num ==1){
return 1;
}
else{
return recFuncTail(num,1);
// sum = num + RecFunc(num - 1);
}
// return sum;
}
int recFuncTail(int num, int acc){
if(num ==1){
return acc;
}
return recFuncTail(num - 1, acc + num);
}
public static void main(String[] args) {
Recursion rc = new Recursion();
System.out.println("1부터 5까지의 합은 : " + rc.RecFunc(5));
Long result = LongStream.rangeClosed(1, 5).reduce((long x, long y) -> x + y).getAsLong();
System.out.println(result);
}
}
//1부터 n 까지의 합을 구하는 예를 재귀함수를 통해 구현하여라.
//
//
//
// 예) 다음과 같이 main 을 작성할때 RecFunc(int num) 을 구함.
//
//public static void main(String[] args){
//
// System.out.println("1부터 5까지의 합은 : " + RecFunc(5));
//
// }
| 1,097 | 0.516616 | 0.496475 | 47 | 20.127659 | 21.398565 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.404255 | false | false |
7
|
3a25689886292a5e86decfc0cc74723d89d9d977
| 24,232,205,551,118 |
d7464a50db99d73b5dd8a68b83d6257c56734781
|
/diboot-framework/src/main/java/com/diboot/framework/service/impl/ExcelImportRecordServiceImpl.java
|
233283ce563f99662cf101b7f27aa2c78be44156
|
[
"Apache-2.0"
] |
permissive
|
panghoooooo/diboot
|
https://github.com/panghoooooo/diboot
|
bc437124d5a40cf1689a982aafbb73a18b867dd3
|
f0cfb9fbc51737cd30bada1f3254fb1a3dac306e
|
refs/heads/master
| 2020-05-29T20:17:52.974000 | 2018-11-17T08:33:15 | 2018-11-17T08:33:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.diboot.framework.service.impl;
import com.diboot.framework.model.BaseModel;
import com.diboot.framework.model.ExcelImportRecord;
import com.diboot.framework.service.ExcelImportRecordService;
import com.diboot.framework.service.mapper.BaseMapper;
import com.diboot.framework.service.mapper.ExcelImportRecordMapper;
import com.diboot.framework.utils.V;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/***
* 导入记录相关操作Service
* @author Mazc@dibo.ltd
* @version 2018-06-11
*
*/
@Service("excelImportRecordService")
public class ExcelImportRecordServiceImpl extends BaseServiceImpl implements ExcelImportRecordService {
private static final Logger logger = LoggerFactory.getLogger(ExcelImportRecordServiceImpl.class);
@Autowired
ExcelImportRecordMapper excelImportRecordMapper;
@Override
protected BaseMapper getMapper() {
return excelImportRecordMapper;
}
@Override
public <T extends BaseModel> boolean batchCreateRecords(String fileUuid, List<T> modelList) {
if(V.isEmpty(modelList)){
return true;
}
List<ExcelImportRecord> recordList = new ArrayList<>(modelList.size());
for(BaseModel model : modelList){
ExcelImportRecord record = new ExcelImportRecord();
record.setFileUuid(fileUuid);
record.setRelObjType(model.getClass().getSimpleName());
if(BaseModel.PK_TYPE.UUID.equals(record.getPkType())){
record.setRelObjUid(model.getUuid());
}
else{
record.setRelObjId(model.getId());
}
record.setCreateBy(model.getCreateBy());
record.setCreatorName(model.getCreatorName());
if(record.getCreateBy() == null){
record.setCreateBy(0L);
}
recordList.add(record);
}
// 批量创建
return batchCreateModels(recordList);
}
}
|
UTF-8
|
Java
| 1,891 |
java
|
ExcelImportRecordServiceImpl.java
|
Java
|
[
{
"context": " java.util.List;\n\n/***\n* 导入记录相关操作Service\n* @author Mazc@dibo.ltd\n* @version 2018-06-11\n*\n*/\n@Service(\"excelImportR",
"end": 630,
"score": 0.9999186396598816,
"start": 617,
"tag": "EMAIL",
"value": "Mazc@dibo.ltd"
}
] | null |
[] |
package com.diboot.framework.service.impl;
import com.diboot.framework.model.BaseModel;
import com.diboot.framework.model.ExcelImportRecord;
import com.diboot.framework.service.ExcelImportRecordService;
import com.diboot.framework.service.mapper.BaseMapper;
import com.diboot.framework.service.mapper.ExcelImportRecordMapper;
import com.diboot.framework.utils.V;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/***
* 导入记录相关操作Service
* @author <EMAIL>
* @version 2018-06-11
*
*/
@Service("excelImportRecordService")
public class ExcelImportRecordServiceImpl extends BaseServiceImpl implements ExcelImportRecordService {
private static final Logger logger = LoggerFactory.getLogger(ExcelImportRecordServiceImpl.class);
@Autowired
ExcelImportRecordMapper excelImportRecordMapper;
@Override
protected BaseMapper getMapper() {
return excelImportRecordMapper;
}
@Override
public <T extends BaseModel> boolean batchCreateRecords(String fileUuid, List<T> modelList) {
if(V.isEmpty(modelList)){
return true;
}
List<ExcelImportRecord> recordList = new ArrayList<>(modelList.size());
for(BaseModel model : modelList){
ExcelImportRecord record = new ExcelImportRecord();
record.setFileUuid(fileUuid);
record.setRelObjType(model.getClass().getSimpleName());
if(BaseModel.PK_TYPE.UUID.equals(record.getPkType())){
record.setRelObjUid(model.getUuid());
}
else{
record.setRelObjId(model.getId());
}
record.setCreateBy(model.getCreateBy());
record.setCreatorName(model.getCreatorName());
if(record.getCreateBy() == null){
record.setCreateBy(0L);
}
recordList.add(record);
}
// 批量创建
return batchCreateModels(recordList);
}
}
| 1,885 | 0.779325 | 0.773433 | 61 | 29.622952 | 25.782293 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.754098 | false | false |
7
|
f6ae7257f1ae36e5d40ebdaeca522d117eb0c92c
| 32,530,082,351,696 |
b4834e9e271fa1680b9b19198e9f7afbdfa289a0
|
/src/main/java/com/yunxi/model/aliyun/slb/instance/ListenerPort.java
|
7a99994300e30273e219a2f4f7c82f38c6d56b7b
|
[] |
no_license
|
Yunxi168/cloudmanagement
|
https://github.com/Yunxi168/cloudmanagement
|
9b4a5e9ab369524bcd6b7c3a6578ee0e43f012d2
|
cd3229b4324c50c2c7c70357ad3b87f1e1bd141a
|
refs/heads/master
| 2016-09-17T18:53:18.395000 | 2016-09-14T13:04:26 | 2016-09-14T13:04:26 | 66,326,134 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yunxi.model.aliyun.slb.instance;
import java.util.List;
public class ListenerPort {
private List<Integer> listenerPorts;
public List<Integer> getListenerPorts() {
return listenerPorts;
}
public void setListenerPorts(List<Integer> listenerPorts) {
this.listenerPorts = listenerPorts;
}
}
|
UTF-8
|
Java
| 340 |
java
|
ListenerPort.java
|
Java
|
[] | null |
[] |
package com.yunxi.model.aliyun.slb.instance;
import java.util.List;
public class ListenerPort {
private List<Integer> listenerPorts;
public List<Integer> getListenerPorts() {
return listenerPorts;
}
public void setListenerPorts(List<Integer> listenerPorts) {
this.listenerPorts = listenerPorts;
}
}
| 340 | 0.708824 | 0.708824 | 16 | 20.25 | 20.801142 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false |
7
|
26b57a7d521d0829c4df403f6a64e4045be78c68
| 24,988,119,759,376 |
392cc82ae2f1139f96d2fb0538871b80e49f9e94
|
/src/main/java/com/example/cinema/service/TicketService.java
|
2fe4a51a7533809a0610e1723e486d050bee6a29
|
[] |
no_license
|
llka/cinema-docker
|
https://github.com/llka/cinema-docker
|
9e9ac9b7d175e598a715c47d399045639b02c59b
|
c05eab45b42e39b4e544601059799111e5dab5a9
|
refs/heads/master
| 2023-06-11T23:03:02.041000 | 2021-06-22T14:10:08 | 2021-06-22T14:10:08 | 265,337,492 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.cinema.service;
import com.example.cinema.entity.Film;
import com.example.cinema.entity.Ticket;
import com.example.cinema.entity.User;
import com.example.cinema.exception.RestException;
import com.example.cinema.repository.TicketRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class TicketService {
private final UserService userService;
private final SecurityService securityService;
private final FilmService filmService;
private final TicketRepository ticketRepository;
@Transactional
public void buyTicket(Long filmId, Long ticketId) {
Film film = filmService.findFilmById(filmId);
Ticket ticket = film.getAvailableTickets().stream()
.filter(t -> t.getId().equals(ticketId))
.findFirst()
.orElseThrow(() -> new RestException("No tickets left!", HttpStatus.NOT_FOUND));
User user = securityService.getCurrentUser();
Set<Ticket> userTickets = user.getTickets();
if (userTickets == null) {
userTickets = new HashSet<>();
}
userTickets.add(ticket);
ticket.setPurchaseTime(Instant.now().atOffset(ZoneOffset.ofHours(3)).toInstant());
userService.save(user);
}
@Transactional
public void removeTicketFromCart(Long ticketId) {
Ticket ticket = ticketRepository.findById(ticketId)
.orElseThrow(() -> new RestException("Ticket not found by id: " + ticketId, HttpStatus.NOT_FOUND));
User user = securityService.getCurrentUser();
Set<Ticket> userTickets = user.getTickets();
if (userTickets != null && userTickets.contains(ticket)) {
userTickets.remove(ticket);
ticket.setPurchaseTime(null);
ticketRepository.save(ticket);
userService.save(user);
}
}
@Transactional
public void bookTicketFromCart(Long ticketId) {
Ticket ticket = ticketRepository.findById(ticketId)
.orElseThrow(() -> new RestException("Ticket not found by id: " + ticketId, HttpStatus.NOT_FOUND));
User user = securityService.getCurrentUser();
Set<Ticket> userTickets = user.getTickets();
if (userTickets != null && userTickets.contains(ticket)) {
userTickets.remove(ticket);
ticket.setBooked(true);
ticketRepository.save(ticket);
userService.save(user);
}
}
}
|
UTF-8
|
Java
| 2,723 |
java
|
TicketService.java
|
Java
|
[] | null |
[] |
package com.example.cinema.service;
import com.example.cinema.entity.Film;
import com.example.cinema.entity.Ticket;
import com.example.cinema.entity.User;
import com.example.cinema.exception.RestException;
import com.example.cinema.repository.TicketRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class TicketService {
private final UserService userService;
private final SecurityService securityService;
private final FilmService filmService;
private final TicketRepository ticketRepository;
@Transactional
public void buyTicket(Long filmId, Long ticketId) {
Film film = filmService.findFilmById(filmId);
Ticket ticket = film.getAvailableTickets().stream()
.filter(t -> t.getId().equals(ticketId))
.findFirst()
.orElseThrow(() -> new RestException("No tickets left!", HttpStatus.NOT_FOUND));
User user = securityService.getCurrentUser();
Set<Ticket> userTickets = user.getTickets();
if (userTickets == null) {
userTickets = new HashSet<>();
}
userTickets.add(ticket);
ticket.setPurchaseTime(Instant.now().atOffset(ZoneOffset.ofHours(3)).toInstant());
userService.save(user);
}
@Transactional
public void removeTicketFromCart(Long ticketId) {
Ticket ticket = ticketRepository.findById(ticketId)
.orElseThrow(() -> new RestException("Ticket not found by id: " + ticketId, HttpStatus.NOT_FOUND));
User user = securityService.getCurrentUser();
Set<Ticket> userTickets = user.getTickets();
if (userTickets != null && userTickets.contains(ticket)) {
userTickets.remove(ticket);
ticket.setPurchaseTime(null);
ticketRepository.save(ticket);
userService.save(user);
}
}
@Transactional
public void bookTicketFromCart(Long ticketId) {
Ticket ticket = ticketRepository.findById(ticketId)
.orElseThrow(() -> new RestException("Ticket not found by id: " + ticketId, HttpStatus.NOT_FOUND));
User user = securityService.getCurrentUser();
Set<Ticket> userTickets = user.getTickets();
if (userTickets != null && userTickets.contains(ticket)) {
userTickets.remove(ticket);
ticket.setBooked(true);
ticketRepository.save(ticket);
userService.save(user);
}
}
}
| 2,723 | 0.677194 | 0.676827 | 77 | 34.363636 | 26.11409 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
7
|
1883936ec6784de98749be795c3335c1c448edba
| 30,726,196,038,403 |
1c7d2d5cc03112ae3fc1351c0c544faf2132c03f
|
/com/google/android/android/common/internal/service/ServiceNotification.java
|
ab17cb930ed13ff83a11749d658aa1aa035cb2b9
|
[] |
no_license
|
RishikReddy2408/OS_Hack_1.0.1
|
https://github.com/RishikReddy2408/OS_Hack_1.0.1
|
e49eff837ae4f9a03fee9f56c5a3041a3e58dce4
|
23352a6ec7ee17e23a1f5bc0b85ae07f0c3aeeb6
|
refs/heads/master
| 2020-08-21T13:05:23.391000 | 2019-10-20T05:51:15 | 2019-10-20T05:51:15 | 216,165,741 | 6 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.google.android.android.common.internal.service;
import android.content.Context;
import android.os.Looper;
import com.google.android.android.common.aimsicd.GoogleApiClient.ConnectionCallbacks;
import com.google.android.android.common.aimsicd.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.android.common.internal.ClientSettings;
import com.google.android.gms.common.internal.service.zal;
public final class ServiceNotification
extends com.google.android.gms.common.internal.GmsClient<zal>
{
public ServiceNotification(Context paramContext, Looper paramLooper, ClientSettings paramClientSettings, GoogleApiClient.ConnectionCallbacks paramConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener paramOnConnectionFailedListener)
{
super(paramContext, paramLooper, 39, paramClientSettings, paramConnectionCallbacks, paramOnConnectionFailedListener);
}
protected final String getServiceDescriptor()
{
return "com.google.android.gms.common.internal.service.ICommonService";
}
public final String getStartServiceAction()
{
return "com.google.android.gms.common.service.START";
}
}
|
UTF-8
|
Java
| 1,156 |
java
|
ServiceNotification.java
|
Java
|
[] | null |
[] |
package com.google.android.android.common.internal.service;
import android.content.Context;
import android.os.Looper;
import com.google.android.android.common.aimsicd.GoogleApiClient.ConnectionCallbacks;
import com.google.android.android.common.aimsicd.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.android.common.internal.ClientSettings;
import com.google.android.gms.common.internal.service.zal;
public final class ServiceNotification
extends com.google.android.gms.common.internal.GmsClient<zal>
{
public ServiceNotification(Context paramContext, Looper paramLooper, ClientSettings paramClientSettings, GoogleApiClient.ConnectionCallbacks paramConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener paramOnConnectionFailedListener)
{
super(paramContext, paramLooper, 39, paramClientSettings, paramConnectionCallbacks, paramOnConnectionFailedListener);
}
protected final String getServiceDescriptor()
{
return "com.google.android.gms.common.internal.service.ICommonService";
}
public final String getStartServiceAction()
{
return "com.google.android.gms.common.service.START";
}
}
| 1,156 | 0.83045 | 0.82872 | 27 | 41.814816 | 52.316017 | 244 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703704 | false | false |
7
|
aa5fd26b4c4da621fafecb5cea8c96b93ff8354f
| 1,829,656,136,214 |
6556e49009c48695a261825a78e8381de1e21953
|
/Eksempel/src/Mainex.java
|
408e6962fdef6390871380d29a5c437f8e864160
|
[] |
no_license
|
asnestige/TDT4145-Prosjekt
|
https://github.com/asnestige/TDT4145-Prosjekt
|
167242943d21e0a193c54d8c21f5f8558a70b33c
|
329c7485d56fd7e7dbbbadb5e35b4cae1be26427
|
refs/heads/master
| 2020-04-28T04:40:55.982000 | 2019-03-20T15:49:22 | 2019-03-20T15:49:22 | 174,988,525 | 0 | 1 | null | false | 2019-03-20T15:49:23 | 2019-03-11T11:44:55 | 2019-03-20T15:48:51 | 2019-03-20T15:49:23 | 2,128 | 0 | 0 | 0 |
Java
| false | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author sveinbra
*/
public class Mainex {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
RegMaalCtrlex maalCtrl = new RegMaalCtrlex();
maalCtrl.connect();
maalCtrl.startReg(123123);
maalCtrl.regPost(0, 0, 70);
maalCtrl.regPost(1, 31, 100);
maalCtrl.regPost(2, 32, 120);
maalCtrl.regPost(3, 33, 140);
maalCtrl.regPost(4, 34, 160);
maalCtrl.regPost(5, 35, 180);
maalCtrl.regPost(6, 36, 200);
maalCtrl.regPost(7, 37, 220);
maalCtrl.regPost(8, 150, 230);
maalCtrl.regPost(9, 175, 245);
if (maalCtrl.sluttReg()) {
System.out.println("Profit!!");
}
ResultatCtrlex resultatCtrlex = new ResultatCtrlex();
resultatCtrlex.connect();
resultatCtrlex.printKlasseResultat("H50");
}
}
|
UTF-8
|
Java
| 1,085 |
java
|
Mainex.java
|
Java
|
[
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author sveinbra\n */\npublic class Mainex {\n\n /**\n * @param ",
"end": 127,
"score": 0.9994031190872192,
"start": 119,
"tag": "USERNAME",
"value": "sveinbra"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author sveinbra
*/
public class Mainex {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
RegMaalCtrlex maalCtrl = new RegMaalCtrlex();
maalCtrl.connect();
maalCtrl.startReg(123123);
maalCtrl.regPost(0, 0, 70);
maalCtrl.regPost(1, 31, 100);
maalCtrl.regPost(2, 32, 120);
maalCtrl.regPost(3, 33, 140);
maalCtrl.regPost(4, 34, 160);
maalCtrl.regPost(5, 35, 180);
maalCtrl.regPost(6, 36, 200);
maalCtrl.regPost(7, 37, 220);
maalCtrl.regPost(8, 150, 230);
maalCtrl.regPost(9, 175, 245);
if (maalCtrl.sluttReg()) {
System.out.println("Profit!!");
}
ResultatCtrlex resultatCtrlex = new ResultatCtrlex();
resultatCtrlex.connect();
resultatCtrlex.printKlasseResultat("H50");
}
}
| 1,085 | 0.567742 | 0.505069 | 45 | 23.111111 | 18.839937 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866667 | false | false |
7
|
96e51ef524e6d41a3607cf824999b663decf77e8
| 22,737,556,908,034 |
89fb6350bf9b2fc47dc3d8a8fdd54fbcacd0de7b
|
/src/main/java/org/buzheng/mybatis/pageable/PostgreSQLDialect.java
|
cb277ba5dfea9f707881211449fdb57cc42eee87
|
[] |
no_license
|
yame2009/redis_springTest_new
|
https://github.com/yame2009/redis_springTest_new
|
756382206a937408c8fd077b2fae608698f322aa
|
96c632cef7314bdb89f15a17886ef281437e67b1
|
refs/heads/master
| 2021-05-28T10:47:31.693000 | 2014-12-23T10:24:31 | 2014-12-23T10:24:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.buzheng.mybatis.pageable;
public class PostgreSQLDialect extends Dialect {
public boolean supportsLimitOffset(){
return true;
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String sql, String offsetName, int offset,
String limitName, int limit) {
StringBuffer buffer = new StringBuffer(sql.length() + 20).append(sql);
if (offset > 0) {
buffer.append(sql).append(" ");
buffer.append("limit").append(" ");
buffer.append(limitName).append(" ");
buffer.append("offset").append(" ");
buffer.append(offsetName).append(" ");
// buffer.append(" limit ? offset ?");
// setPageParameter(limitName, Integer.valueOf(limit), Integer.class);
// setPageParameter(offsetName, Integer.valueOf(offset), Integer.class);
} else {
buffer.append(sql).append(" ");
buffer.append("limit").append(" ");
buffer.append(limitName).append(" ");
// buffer.append(" limit ?");
// setPageParameter(limitName, Integer.valueOf(limit), Integer.class);
}
return buffer.toString();
}
}
|
UTF-8
|
Java
| 1,126 |
java
|
PostgreSQLDialect.java
|
Java
|
[] | null |
[] |
package org.buzheng.mybatis.pageable;
public class PostgreSQLDialect extends Dialect {
public boolean supportsLimitOffset(){
return true;
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String sql, String offsetName, int offset,
String limitName, int limit) {
StringBuffer buffer = new StringBuffer(sql.length() + 20).append(sql);
if (offset > 0) {
buffer.append(sql).append(" ");
buffer.append("limit").append(" ");
buffer.append(limitName).append(" ");
buffer.append("offset").append(" ");
buffer.append(offsetName).append(" ");
// buffer.append(" limit ? offset ?");
// setPageParameter(limitName, Integer.valueOf(limit), Integer.class);
// setPageParameter(offsetName, Integer.valueOf(offset), Integer.class);
} else {
buffer.append(sql).append(" ");
buffer.append("limit").append(" ");
buffer.append(limitName).append(" ");
// buffer.append(" limit ?");
// setPageParameter(limitName, Integer.valueOf(limit), Integer.class);
}
return buffer.toString();
}
}
| 1,126 | 0.646536 | 0.643872 | 37 | 28.432432 | 23.610054 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.513514 | false | false |
7
|
a7edf98393423978090c844c1ac261067391e599
| 2,808,908,660,107 |
41a661b13d12e0225cbff7244739908ca444d773
|
/backend/pet-owner-service/src/main/java/com/txakurrapp/petownerservice/controller/impl/OwnerController.java
|
17f237ea1f6c1fe5590f131e720b1ee0a6199395
|
[] |
no_license
|
galol130/txakurrapp
|
https://github.com/galol130/txakurrapp
|
d4bdada968723bd698c6c817185f8c6ad6a2451f
|
918a5d5245a371af24d139f45645ac532ba39609
|
refs/heads/main
| 2023-03-27T20:50:54.110000 | 2021-03-15T21:42:47 | 2021-03-15T21:42:47 | 347,792,098 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.txakurrapp.petownerservice.controller.impl;
import com.txakurrapp.petownerservice.controller.DTO.*;
import com.txakurrapp.petownerservice.controller.interfaces.IOwnerController;
import com.txakurrapp.petownerservice.model.Address;
import com.txakurrapp.petownerservice.model.Image;
import com.txakurrapp.petownerservice.service.interfaces.IOwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*", maxAge = 3600, methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
public class OwnerController implements IOwnerController {
@Autowired
private IOwnerService ownerService;
@Override
@GetMapping("/owners")
public List<OwnerGetDTO> getOwners() {
return ownerService.getAllOwners();
}
@Override
@GetMapping("/owner/{id}")
public OwnerGetDTO getOwnerById(@PathVariable(name = "id") Long id) {
return ownerService.getOwnerById(id);
}
@Override
@GetMapping("/owner/user-id/{id}")
public OwnerGetDTO getOwnerByUserId(@PathVariable(name = "id") Long id){
return ownerService.getOwnerByUserId(id);
}
@Override
@GetMapping("/owner/personal-id/{personal-id}")
public OwnerGetDTO getOwnerByPersonalId(@PathVariable(value = "personal-id") String personalId) {
return ownerService.getOwnerByPersonalId(personalId);
}
@Override
@PostMapping("/owner")
@ResponseStatus(HttpStatus.CREATED)
public OwnerGetDTO createOwner(@RequestBody OwnerPostDTO ownerPostDTO) {
return ownerService.createOwner(ownerPostDTO);
}
@Override
@PutMapping("/owner/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
public OwnerGetDTO updateOwnerBasics(@PathVariable(value = "id") Long id, @RequestBody OwnerUpdateDTO ownerUpdateDTO) {
return ownerService.updateOwnerBasics(id, ownerUpdateDTO);
}
@Override
@PutMapping("/owner/{id}/address")
@ResponseStatus(HttpStatus.ACCEPTED)
public OwnerGetDTO updateOwnerAddress(@PathVariable(value = "id") Long id, @RequestBody Address address) {
return ownerService.updateOwnerAddress(id, address);
}
@Override
@PutMapping("/owner/{id}/picture")
@ResponseStatus(HttpStatus.ACCEPTED)
public OwnerGetDTO updateOwnerPicture(@PathVariable(value = "id") Long id, @RequestBody Image image) {
return ownerService.updateOwnerPicture(id, image);
}
@Override
@PutMapping("/owner/{id}/add-pet")
public OwnerGetDTO addPet(@PathVariable(name = "id") Long id, @RequestBody PetPostDTO petPostDTO) {
return ownerService.addPet(id, petPostDTO);
}
@Override
@PutMapping("/owner/{id}/update-pet/{pet-id}")
public OwnerGetDTO updatePet(@PathVariable(name = "id") Long id, @PathVariable(name = "pet-id") Long petId, @RequestBody PetUpdateDTO petUpdateDTO) {
return ownerService.updatePet(id, petId, petUpdateDTO);
}
@Override
@PutMapping("owner/{id}/update-pet-image/{pet-id}")
public OwnerGetDTO updatePetPicture(@PathVariable(name = "id") Long id, @PathVariable(name = "pet-id") Long petId, @RequestBody Image petPicture) {
return ownerService.updatePetPicture(id, petId, petPicture);
}
@Override
@PutMapping("/owner/{id}/delete-pet/{pet-id}")
public OwnerGetDTO deletePet(@PathVariable(name = "id") Long id, @PathVariable(name = "pet-id") Long petId) {
return ownerService.deletePet(id, petId);
}
@Override
@PutMapping("/owner/{id}/add-fav/{service-id}")
public OwnerGetDTO addFav(@PathVariable(name = "id") Long id, @PathVariable(name = "service-id") Long serviceId){
return ownerService.addFav(id, serviceId);
}
@Override
@PutMapping("/owner/{id}/remove-fav/{service-id}")
public OwnerGetDTO removeFav(@PathVariable(name = "id") Long id, @PathVariable(name = "service-id") Long serviceId){
return ownerService.removeFav(id, serviceId);
}
@Override
@DeleteMapping("/owner/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteOwner(@PathVariable(value = "id") Long id) {
ownerService.deleteOwner(id);
}
}
|
UTF-8
|
Java
| 4,329 |
java
|
OwnerController.java
|
Java
|
[] | null |
[] |
package com.txakurrapp.petownerservice.controller.impl;
import com.txakurrapp.petownerservice.controller.DTO.*;
import com.txakurrapp.petownerservice.controller.interfaces.IOwnerController;
import com.txakurrapp.petownerservice.model.Address;
import com.txakurrapp.petownerservice.model.Image;
import com.txakurrapp.petownerservice.service.interfaces.IOwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*", maxAge = 3600, methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
public class OwnerController implements IOwnerController {
@Autowired
private IOwnerService ownerService;
@Override
@GetMapping("/owners")
public List<OwnerGetDTO> getOwners() {
return ownerService.getAllOwners();
}
@Override
@GetMapping("/owner/{id}")
public OwnerGetDTO getOwnerById(@PathVariable(name = "id") Long id) {
return ownerService.getOwnerById(id);
}
@Override
@GetMapping("/owner/user-id/{id}")
public OwnerGetDTO getOwnerByUserId(@PathVariable(name = "id") Long id){
return ownerService.getOwnerByUserId(id);
}
@Override
@GetMapping("/owner/personal-id/{personal-id}")
public OwnerGetDTO getOwnerByPersonalId(@PathVariable(value = "personal-id") String personalId) {
return ownerService.getOwnerByPersonalId(personalId);
}
@Override
@PostMapping("/owner")
@ResponseStatus(HttpStatus.CREATED)
public OwnerGetDTO createOwner(@RequestBody OwnerPostDTO ownerPostDTO) {
return ownerService.createOwner(ownerPostDTO);
}
@Override
@PutMapping("/owner/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
public OwnerGetDTO updateOwnerBasics(@PathVariable(value = "id") Long id, @RequestBody OwnerUpdateDTO ownerUpdateDTO) {
return ownerService.updateOwnerBasics(id, ownerUpdateDTO);
}
@Override
@PutMapping("/owner/{id}/address")
@ResponseStatus(HttpStatus.ACCEPTED)
public OwnerGetDTO updateOwnerAddress(@PathVariable(value = "id") Long id, @RequestBody Address address) {
return ownerService.updateOwnerAddress(id, address);
}
@Override
@PutMapping("/owner/{id}/picture")
@ResponseStatus(HttpStatus.ACCEPTED)
public OwnerGetDTO updateOwnerPicture(@PathVariable(value = "id") Long id, @RequestBody Image image) {
return ownerService.updateOwnerPicture(id, image);
}
@Override
@PutMapping("/owner/{id}/add-pet")
public OwnerGetDTO addPet(@PathVariable(name = "id") Long id, @RequestBody PetPostDTO petPostDTO) {
return ownerService.addPet(id, petPostDTO);
}
@Override
@PutMapping("/owner/{id}/update-pet/{pet-id}")
public OwnerGetDTO updatePet(@PathVariable(name = "id") Long id, @PathVariable(name = "pet-id") Long petId, @RequestBody PetUpdateDTO petUpdateDTO) {
return ownerService.updatePet(id, petId, petUpdateDTO);
}
@Override
@PutMapping("owner/{id}/update-pet-image/{pet-id}")
public OwnerGetDTO updatePetPicture(@PathVariable(name = "id") Long id, @PathVariable(name = "pet-id") Long petId, @RequestBody Image petPicture) {
return ownerService.updatePetPicture(id, petId, petPicture);
}
@Override
@PutMapping("/owner/{id}/delete-pet/{pet-id}")
public OwnerGetDTO deletePet(@PathVariable(name = "id") Long id, @PathVariable(name = "pet-id") Long petId) {
return ownerService.deletePet(id, petId);
}
@Override
@PutMapping("/owner/{id}/add-fav/{service-id}")
public OwnerGetDTO addFav(@PathVariable(name = "id") Long id, @PathVariable(name = "service-id") Long serviceId){
return ownerService.addFav(id, serviceId);
}
@Override
@PutMapping("/owner/{id}/remove-fav/{service-id}")
public OwnerGetDTO removeFav(@PathVariable(name = "id") Long id, @PathVariable(name = "service-id") Long serviceId){
return ownerService.removeFav(id, serviceId);
}
@Override
@DeleteMapping("/owner/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteOwner(@PathVariable(value = "id") Long id) {
ownerService.deleteOwner(id);
}
}
| 4,329 | 0.712636 | 0.711712 | 116 | 36.318966 | 36.205494 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456897 | false | false |
7
|
5cd3bd30de78100b5a19ec21f2051bd4b4db0f33
| 32,427,003,139,999 |
cfe03b525c7802b75eaad9b8d597bb03a0c406a6
|
/src/main/java/org/ruivieira/jssm/common/Structure.java
|
d73b461a60e3503bdcf9be83903163ee3c2fddf0
|
[
"Apache-2.0"
] |
permissive
|
ruivieira/jssm
|
https://github.com/ruivieira/jssm
|
c466ee72126fce6d08b4bcd9cc06cc82b1c03899
|
d29cffb9f2c64fe3ce48a712921ff5b314088cc4
|
refs/heads/master
| 2021-07-20T19:00:18.673000 | 2021-05-09T21:16:32 | 2021-05-09T21:16:32 | 124,577,901 | 0 | 0 |
Apache-2.0
| false | 2021-05-09T21:16:33 | 2018-03-09T18:23:52 | 2019-11-17T21:46:00 | 2021-05-09T21:16:32 | 81 | 0 | 0 | 2 |
Java
| false | false |
package org.ruivieira.jssm.common;
import org.apache.commons.math3.linear.RealMatrix;
import static org.ruivieira.jssm.common.MatrixUtils.blockDiagonal;
import static org.ruivieira.jssm.common.MatrixUtils.verticalCat;
public class Structure {
private RealMatrix F;
private RealMatrix G;
private RealMatrix W;
public Structure(RealMatrix F, RealMatrix G, RealMatrix W) {
this.F = F;
this.G = G;
this.W = W;
}
public Structure add(Structure another) {
final RealMatrix newF = verticalCat(this.F, another.F);
final RealMatrix newG = blockDiagonal(this.G, another.G);
final RealMatrix newW = blockDiagonal(this.W, another.W);
return new Structure(newF, newG, newW);
}
public RealMatrix getW() {
return W;
}
public RealMatrix getF() {
return F;
}
public RealMatrix getG() {
return G;
}
}
|
UTF-8
|
Java
| 928 |
java
|
Structure.java
|
Java
|
[] | null |
[] |
package org.ruivieira.jssm.common;
import org.apache.commons.math3.linear.RealMatrix;
import static org.ruivieira.jssm.common.MatrixUtils.blockDiagonal;
import static org.ruivieira.jssm.common.MatrixUtils.verticalCat;
public class Structure {
private RealMatrix F;
private RealMatrix G;
private RealMatrix W;
public Structure(RealMatrix F, RealMatrix G, RealMatrix W) {
this.F = F;
this.G = G;
this.W = W;
}
public Structure add(Structure another) {
final RealMatrix newF = verticalCat(this.F, another.F);
final RealMatrix newG = blockDiagonal(this.G, another.G);
final RealMatrix newW = blockDiagonal(this.W, another.W);
return new Structure(newF, newG, newW);
}
public RealMatrix getW() {
return W;
}
public RealMatrix getF() {
return F;
}
public RealMatrix getG() {
return G;
}
}
| 928 | 0.650862 | 0.649785 | 42 | 21.095238 | 22.569269 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
7
|
b710c96c20164dd576bfe4af87851c4dfcbe916f
| 27,565,100,131,236 |
1af641253d65c949ffe1a0a250904a47bb4fa9ab
|
/list-and-arraylist/src/com/aatish/Main.java
|
c7a084b348f8658da80378784103ff6070883a2c
|
[] |
no_license
|
Aatish810/core-java-learning
|
https://github.com/Aatish810/core-java-learning
|
b21d451c3b43250d346624392f9700d7e917f6f2
|
9a1bfaa2b56f604af73822d335df5f5bfbdaa718
|
refs/heads/master
| 2020-04-12T16:26:01.724000 | 2019-04-20T12:03:13 | 2019-04-20T12:03:13 | 162,612,262 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.aatish;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
// private static GroceryList groceryList = new GroceryList();
private static MobilePhone mobilePhone = new MobilePhone("9123456780");
public static void main(String[] args) {
// boolean quit = false;
// int choice = 0;
//
// printInstructions();
// while (!quit) {
// System.out.println("Enter your choice: ");
// choice = scanner.nextInt();
// scanner.nextLine();
//
// switch (choice) {
// case 0:
// printInstructions();
// break;
// case 1:
// groceryList.printGroceryList();
// break;
// case 2:
// addItem();
// break;
// case 3:
// modifyItem();
// break;
// case 4:
// removeItem();
// break;
// case 5:
// searchForItem();
// break;
// case 6:
// processArrayList();
// case 7:
// quit = true;
// break;
// }
// }
// Challenge Question
boolean quit = false;
startPhone();
printActions();
while(!quit) {
System.out.println("\nEnter action: (6 to show available actions)");
int action = scanner.nextInt();
scanner.nextLine();
switch (action) {
case 0:
System.out.println("\nShutting down...");
quit = true;
break;
case 1:
mobilePhone.printContacts();
break;
case 2:
addNewContact();
break;
case 3:
updateContact();
break;
case 4:
removeContact();
break;
case 5:
queryContact();
break;
case 6:
printActions();
break;
}
}
}
// public static void printInstructions() {
// System.out.println("\nPress ");
// System.out.println("\t 0 - To print choice options.");
// System.out.println("\t 1 - To print the list of grocery items.");
// System.out.println("\t 2 - To add an item to the list.");
// System.out.println("\t 3 - To modify an item in the list.");
// System.out.println("\t 4 - To remove an item from the list.");
// System.out.println("\t 5 - To search for an item in the list.");
// System.out.println("\t 6 - To quit the application.");
// }
//
// public static void addItem() {
// System.out.print("Please enter the grocery item: ");
// groceryList.addGroceryItem(scanner.nextLine());
// }
//
// public static void modifyItem() {
// System.out.print("Current item name: ");
// String itemNo = scanner.nextLine();
// System.out.print("Enter new item: ");
// String newItem = scanner.nextLine();
// groceryList.modifyGroceryItem(itemNo, newItem);
// }
//
// public static void removeItem() {
// System.out.print("Enter item name: ");
// String itemNo = scanner.nextLine();
// groceryList.removeGroceryItem(itemNo);
// }
//
// public static void searchForItem() {
// System.out.print("Item to search for: ");
// String searchItem = scanner.nextLine();
// if(groceryList.onFile(searchItem)) {
// System.out.println("Found " + searchItem);
// } else {
// System.out.println(searchItem + ", not on file.");
// }
// }
//
// public static void processArrayList() {
// ArrayList<String> newArray = new ArrayList<String>();
// newArray.addAll(groceryList.getGroceryList());
//
// ArrayList<String> nextArray = new ArrayList<String>(groceryList.getGroceryList());
//
// String[] myArray = new String[groceryList.getGroceryList().size()];
// myArray = groceryList.getGroceryList().toArray(myArray);
//
//
// }
private static void addNewContact() {
System.out.println("Enter new contact name: ");
String name = scanner.nextLine();
System.out.println("Enter phone number: ");
String phone = scanner.nextLine();
Contact newContact = Contact.createContact(name, phone);
if(mobilePhone.addNewContact(newContact)) {
System.out.println("New contact added: name = " + name + ", phone = "+ phone);
} else {
System.out.println("Cannot add, " + name + " already on file");
}
}
private static void updateContact() {
System.out.println("Enter existing contact name: ");
String name = scanner.nextLine();
Contact existingContactRecord = mobilePhone.queryContact(name);
if(existingContactRecord == null) {
System.out.println("Contact not found.");
return;
}
System.out.print("Enter new contact name: ");
String newName = scanner.nextLine();
System.out.print("Enter new contact phone number: ");
String newNumber = scanner.nextLine();
Contact newContact = Contact.createContact(newName, newNumber);
if(mobilePhone.updateContact(existingContactRecord, newContact)) {
System.out.println("Successfully updated record");
} else {
System.out.println("Error updating record.");
}
}
private static void removeContact() {
System.out.println("Enter existing contact name: ");
String name = scanner.nextLine();
Contact existingContactRecord = mobilePhone.queryContact(name);
if (existingContactRecord == null) {
System.out.println("Contact not found.");
return;
}
if(mobilePhone.removeContact(existingContactRecord)) {
System.out.println("Successfully deleted");
} else {
System.out.println("Error deleting contact");
}
}
private static void queryContact() {
System.out.println("Enter existing contact name: ");
String name = scanner.nextLine();
Contact existingContactRecord = mobilePhone.queryContact(name);
if (existingContactRecord == null) {
System.out.println("Contact not found.");
return;
}
System.out.println("Name: " + existingContactRecord.getName() + " phone number is " + existingContactRecord.getNumber());
}
private static void startPhone() {
System.out.println("Starting phone...");
}
private static void printActions() {
System.out.println("\nAvailable actions:\npress");
System.out.println("0 - to shutdown\n" +
"1 - to print contacts\n" +
"2 - to add a new contact\n" +
"3 - to update existing an existing contact\n" +
"4 - to remove an existing contact\n" +
"5 - query if an existing contact exists\n" +
"6 - to print a list of available actions.");
System.out.println("Choose your action: ");
}
}
|
UTF-8
|
Java
| 7,567 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package com.aatish;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
// private static GroceryList groceryList = new GroceryList();
private static MobilePhone mobilePhone = new MobilePhone("9123456780");
public static void main(String[] args) {
// boolean quit = false;
// int choice = 0;
//
// printInstructions();
// while (!quit) {
// System.out.println("Enter your choice: ");
// choice = scanner.nextInt();
// scanner.nextLine();
//
// switch (choice) {
// case 0:
// printInstructions();
// break;
// case 1:
// groceryList.printGroceryList();
// break;
// case 2:
// addItem();
// break;
// case 3:
// modifyItem();
// break;
// case 4:
// removeItem();
// break;
// case 5:
// searchForItem();
// break;
// case 6:
// processArrayList();
// case 7:
// quit = true;
// break;
// }
// }
// Challenge Question
boolean quit = false;
startPhone();
printActions();
while(!quit) {
System.out.println("\nEnter action: (6 to show available actions)");
int action = scanner.nextInt();
scanner.nextLine();
switch (action) {
case 0:
System.out.println("\nShutting down...");
quit = true;
break;
case 1:
mobilePhone.printContacts();
break;
case 2:
addNewContact();
break;
case 3:
updateContact();
break;
case 4:
removeContact();
break;
case 5:
queryContact();
break;
case 6:
printActions();
break;
}
}
}
// public static void printInstructions() {
// System.out.println("\nPress ");
// System.out.println("\t 0 - To print choice options.");
// System.out.println("\t 1 - To print the list of grocery items.");
// System.out.println("\t 2 - To add an item to the list.");
// System.out.println("\t 3 - To modify an item in the list.");
// System.out.println("\t 4 - To remove an item from the list.");
// System.out.println("\t 5 - To search for an item in the list.");
// System.out.println("\t 6 - To quit the application.");
// }
//
// public static void addItem() {
// System.out.print("Please enter the grocery item: ");
// groceryList.addGroceryItem(scanner.nextLine());
// }
//
// public static void modifyItem() {
// System.out.print("Current item name: ");
// String itemNo = scanner.nextLine();
// System.out.print("Enter new item: ");
// String newItem = scanner.nextLine();
// groceryList.modifyGroceryItem(itemNo, newItem);
// }
//
// public static void removeItem() {
// System.out.print("Enter item name: ");
// String itemNo = scanner.nextLine();
// groceryList.removeGroceryItem(itemNo);
// }
//
// public static void searchForItem() {
// System.out.print("Item to search for: ");
// String searchItem = scanner.nextLine();
// if(groceryList.onFile(searchItem)) {
// System.out.println("Found " + searchItem);
// } else {
// System.out.println(searchItem + ", not on file.");
// }
// }
//
// public static void processArrayList() {
// ArrayList<String> newArray = new ArrayList<String>();
// newArray.addAll(groceryList.getGroceryList());
//
// ArrayList<String> nextArray = new ArrayList<String>(groceryList.getGroceryList());
//
// String[] myArray = new String[groceryList.getGroceryList().size()];
// myArray = groceryList.getGroceryList().toArray(myArray);
//
//
// }
private static void addNewContact() {
System.out.println("Enter new contact name: ");
String name = scanner.nextLine();
System.out.println("Enter phone number: ");
String phone = scanner.nextLine();
Contact newContact = Contact.createContact(name, phone);
if(mobilePhone.addNewContact(newContact)) {
System.out.println("New contact added: name = " + name + ", phone = "+ phone);
} else {
System.out.println("Cannot add, " + name + " already on file");
}
}
private static void updateContact() {
System.out.println("Enter existing contact name: ");
String name = scanner.nextLine();
Contact existingContactRecord = mobilePhone.queryContact(name);
if(existingContactRecord == null) {
System.out.println("Contact not found.");
return;
}
System.out.print("Enter new contact name: ");
String newName = scanner.nextLine();
System.out.print("Enter new contact phone number: ");
String newNumber = scanner.nextLine();
Contact newContact = Contact.createContact(newName, newNumber);
if(mobilePhone.updateContact(existingContactRecord, newContact)) {
System.out.println("Successfully updated record");
} else {
System.out.println("Error updating record.");
}
}
private static void removeContact() {
System.out.println("Enter existing contact name: ");
String name = scanner.nextLine();
Contact existingContactRecord = mobilePhone.queryContact(name);
if (existingContactRecord == null) {
System.out.println("Contact not found.");
return;
}
if(mobilePhone.removeContact(existingContactRecord)) {
System.out.println("Successfully deleted");
} else {
System.out.println("Error deleting contact");
}
}
private static void queryContact() {
System.out.println("Enter existing contact name: ");
String name = scanner.nextLine();
Contact existingContactRecord = mobilePhone.queryContact(name);
if (existingContactRecord == null) {
System.out.println("Contact not found.");
return;
}
System.out.println("Name: " + existingContactRecord.getName() + " phone number is " + existingContactRecord.getNumber());
}
private static void startPhone() {
System.out.println("Starting phone...");
}
private static void printActions() {
System.out.println("\nAvailable actions:\npress");
System.out.println("0 - to shutdown\n" +
"1 - to print contacts\n" +
"2 - to add a new contact\n" +
"3 - to update existing an existing contact\n" +
"4 - to remove an existing contact\n" +
"5 - query if an existing contact exists\n" +
"6 - to print a list of available actions.");
System.out.println("Choose your action: ");
}
}
| 7,567 | 0.525175 | 0.519757 | 222 | 33.085587 | 23.924747 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531532 | false | false |
7
|
e5924d15e10d3d5a4b4a9eaf8e6357846a00e3a1
| 36,283,883,717,454 |
73d1f5d9188c48bb7e9b3637ff25e13e5bc5327a
|
/mongodb-connector-java/src/main/java/com/mongodb/DBTCPConnector.java
|
5add54e5e500bf4bff2ab06c042cf6ddd374537a
|
[
"Apache-2.0"
] |
permissive
|
ccdaisy/mongo-jdbc
|
https://github.com/ccdaisy/mongo-jdbc
|
603eca92bf1568f8810c25644d8ace916bb214c0
|
abe0badf1467d935f41b81aa840c2a1e1b16c39d
|
refs/heads/master
| 2021-01-15T18:08:28.335000 | 2010-09-20T11:10:55 | 2010-09-20T11:10:55 | 914,151 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// DBTCPConnector.java
/**
* Copyright (C) 2008 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.mongodb.utils.Bytes;
import com.mongodb.utils.StringUtils;
class DBTCPConnector implements DBConnector {
static Logger _logger = Logger.getLogger(Bytes.LOGGER.getName() + ".tcp");
static Logger _createLogger = Logger.getLogger(_logger.getName()
+ ".connect");
public DBTCPConnector(ServerAddress addr, MongoOptions options) throws MongoException {
this.options = options;
_checkAddress(addr);
_createLogger.info(addr.toString());
if (addr.isPaired()) {
_allHosts = new ArrayList<ServerAddress>(addr.explode());
_createLogger.info("switching to replica set mode : " + _allHosts
+ " -> " + _curAddress);
} else {
try {
_set(addr,options);
} catch (IOException e) {
throw new MongoException("can't switch address");
}
_allHosts = null;
}
}
public DBTCPConnector(Mongo m, MongoOptions options , ServerAddress... all) throws MongoException {
this(m,options, Arrays.asList(all));
}
public DBTCPConnector(Mongo m, MongoOptions options , List<ServerAddress> all)
throws MongoException {
this.options = options;
_checkAddress(all);
_allHosts = new ArrayList<ServerAddress>(all); // make a copy so it
// can't be modified
_createLogger.info(all + " -> " + _curAddress);
}
private static ServerAddress _checkAddress(ServerAddress addr) {
if (addr == null)
throw new NullPointerException("address can't be null");
return addr;
}
private static ServerAddress _checkAddress(List<ServerAddress> addrs) {
if (addrs == null)
throw new NullPointerException("addresses can't be null");
if (addrs.size() == 0)
throw new IllegalArgumentException(
"need to specify at least 1 address");
return addrs.get(0);
}
/**
* Start a "request".
*
* A "request" is a group of operations in which order matters. Examples
* include inserting a document and then performing a query which expects
* that document to have been inserted, or performing an operation and then
* using com.mongodb.Mongo.getLastError to perform error-checking on that
* operation. When a thread performs operations in a "request", all
* operations will be performed on the same socket, so they will be
* correctly ordered.
*/
public void requestStart() {
// _threadPort.get().requestStart();
}
/**
* End the current "request", if this thread is in one.
*
* By ending a request when it is safe to do so the built-in connection-
* pool is allowed to reassign requests to different sockets in order to
* more effectively balance load. See requestStart for more information.
*/
public void requestDone() {
// _threadPort.get().requestDone();
}
public void requestEnsureConnection() {
// _threadPort.get().requestEnsureConnection();
}
WriteResult _checkWriteError(String db, WriteConcern concern) throws MongoException {
CommandResult e = _port.runCommand(db, concern.getCommand());
Object foo = e.get("err");
if (foo == null)
return new WriteResult(e, concern);
int code = -1;
if (e.get("code") instanceof Number)
code = ((Number) e.get("code")).intValue();
String s = foo.toString();
if (code == 11000 || code == 11001 || s.startsWith("E11000")
|| s.startsWith("E11001"))
throw new MongoException.DuplicateKey(code, s);
throw new MongoException(code, s);
}
public WriteResult say(String namespace, OutMessage m, WriteConcern concern)
throws MongoException {
String[] names = StringUtils.splitAtFirst(namespace, ".");
try {
_port.say(m);
if (concern.callGetLastError()) {
return _checkWriteError(names[0], concern);
} else {
return new WriteResult(names[0], _port, concern);
}
} catch (IOException ioe) {
_error(ioe);
if (concern.raiseNetworkErrors())
throw new MongoException.Network("can't say something", ioe);
CommandResult res = new CommandResult();
res.put("ok", false);
res.put("$err", "NETWORK ERROR");
return new WriteResult(res, concern);
} catch (MongoException me) {
throw me;
} catch (RuntimeException re) {
throw re;
}
}
public Response call(String namespace, OutMessage m) throws MongoException {
return call(namespace, m, 2);
}
public Response call(String namespace, OutMessage m, int retries)
throws MongoException {
Response res = null;
try {
res = _port.call(m, namespace);
} catch (IOException ioe) {
String collName = StringUtils.splitAtFirst(namespace, ".")[2];
boolean shoulRetry = _error(ioe)
&& !collName.equals("$cmd") && retries > 0;
if (shoulRetry) {
return call(namespace, m, retries - 1);
}
throw new MongoException.Network("can't call something", ioe);
} catch (RuntimeException re) {
throw re;
}
ServerError err = res.getError();
if (err != null && err.isNotMasterError()) {
_pickCurrent();
if (retries <= 0) {
throw new MongoException(
"not talking to master and retries used up");
}
return call(namespace, m, retries - 1);
}
return res;
}
public ServerAddress getAddress() {
return _curAddress;
}
public List<ServerAddress> getAllAddress() {
return _allHosts;
}
public String getConnectPoint() {
return _curAddress.toString();
}
boolean _error(Throwable t) throws MongoException {
if (_allHosts != null) {
_logger.log(Level.WARNING, "replica set mode, switching master", t);
_pickCurrent();
}
return true;
}
/**
* @return next to try
*/
@SuppressWarnings("unchecked")
ServerAddress _addAllFromSet(DBObject o) {
Object foo = o.get("hosts");
if (!(foo instanceof List))
return null;
String primary = (String) o.get("primary");
ServerAddress primaryAddress = null;
synchronized (_allHosts) {
for (Object x : (List) foo) {
try {
String s = x.toString();
ServerAddress a = new ServerAddress(s);
if (!_allHosts.contains(a))
_allHosts.add(a);
if (s.equals(primary)) {
int i = _allHosts.indexOf(a);
primaryAddress = _allHosts.get(i);
}
} catch (UnknownHostException un) {
_logger.severe("unknown host [" + un + "]");
}
}
}
return primaryAddress;
}
void _pickInitial() throws MongoException {
if (_curAddress != null)
return;
// we need to just get a server to query for ismaster
_pickCurrent();
try {
_logger.info("current address beginning of _pickInitial: "
+ _curAddress);
DBObject im = isMasterCmd();
ServerAddress other = _addAllFromSet(im);
if (_isMaster(im))
return;
if (other != null) {
_set(other, this.options);
im = isMasterCmd();
_addAllFromSet(im);
if (_isMaster(im))
return;
_logger.severe("primary given was wrong: " + other
+ " going to scan");
}
synchronized (_allHosts) {
Collections.shuffle(_allHosts);
for (ServerAddress a : _allHosts) {
if (_curAddress == a)
continue;
_logger.info("remote [" + _curAddress + "] -> [" + a + "]");
_set(a, this.options);
im = isMasterCmd();
_addAllFromSet(im);
if (_isMaster(im))
return;
if (_allHosts.size() == 2)
_logger.severe("switched to: " + a
+ " but isn't master");
}
throw new MongoException("can't find master");
}
} catch (Exception e) {
_logger.log(Level.SEVERE,
"can't pick initial master, using random one", e);
}
}
private void _pickCurrent() throws MongoException {
if (_allHosts == null)
throw new MongoException(
"got master/slave issue but not in master/slave mode on the client side");
synchronized (_allHosts) {
Collections.shuffle(_allHosts);
for (int i = 0; i < _allHosts.size(); i++) {
ServerAddress a = _allHosts.get(i);
if (a == _curAddress)
continue;
if (_curAddress != null) {
_logger.info("switching from [" + _curAddress + "] to ["
+ a + "]");
}
try {
_set(a, this.options);
} catch (IOException e) {
throw new MongoException("can't switch address");
}
return;
}
}
throw new MongoException("couldn't find a new host to swtich too");
}
private boolean _set(ServerAddress addr,MongoOptions options) throws IOException {
if (_curAddress == addr)
return false;
_curAddress = addr;
this._port = new DBPort(addr._addr,options);
return true;
}
public String debugString() {
StringBuilder buf = new StringBuilder("DBTCPConnector: ");
if (_allHosts != null)
buf.append("replica set : ").append(_allHosts);
else
buf.append(_curAddress).append(" ").append(_curAddress._addr);
return buf.toString();
}
DBObject isMasterCmd() {
String namespace = "admin.$cmd";
Iterator<DBObject> i = _m._find(namespace, _isMaster, null, 0, 1, 0);
if (i == null || !i.hasNext())
throw new MongoException("no result for ismaster query?");
DBObject res = i.next();
if (i.hasNext())
throw new MongoException("what's going on");
return res;
}
boolean _isMaster(DBObject res) {
Object x = res.get("ismaster");
if (x == null)
throw new IllegalStateException("ismaster shouldn't be null: "
+ res);
if (x instanceof Boolean)
return (Boolean) x;
if (x instanceof Number)
return ((Number) x).intValue() == 1;
throw new IllegalArgumentException("invalid ismaster [" + x + "] : "
+ x.getClass().getName());
}
public void close() {
_port.close();
}
private DBPort _port;
private ServerAddress _curAddress;
private final List<ServerAddress> _allHosts;
private Mongo _m;
final MongoOptions options;
private final static DBObject _isMaster = new BasicDBObject("ismaster", 1);
}
|
UTF-8
|
Java
| 10,482 |
java
|
DBTCPConnector.java
|
Java
|
[] | null |
[] |
// DBTCPConnector.java
/**
* Copyright (C) 2008 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.mongodb.utils.Bytes;
import com.mongodb.utils.StringUtils;
class DBTCPConnector implements DBConnector {
static Logger _logger = Logger.getLogger(Bytes.LOGGER.getName() + ".tcp");
static Logger _createLogger = Logger.getLogger(_logger.getName()
+ ".connect");
public DBTCPConnector(ServerAddress addr, MongoOptions options) throws MongoException {
this.options = options;
_checkAddress(addr);
_createLogger.info(addr.toString());
if (addr.isPaired()) {
_allHosts = new ArrayList<ServerAddress>(addr.explode());
_createLogger.info("switching to replica set mode : " + _allHosts
+ " -> " + _curAddress);
} else {
try {
_set(addr,options);
} catch (IOException e) {
throw new MongoException("can't switch address");
}
_allHosts = null;
}
}
public DBTCPConnector(Mongo m, MongoOptions options , ServerAddress... all) throws MongoException {
this(m,options, Arrays.asList(all));
}
public DBTCPConnector(Mongo m, MongoOptions options , List<ServerAddress> all)
throws MongoException {
this.options = options;
_checkAddress(all);
_allHosts = new ArrayList<ServerAddress>(all); // make a copy so it
// can't be modified
_createLogger.info(all + " -> " + _curAddress);
}
private static ServerAddress _checkAddress(ServerAddress addr) {
if (addr == null)
throw new NullPointerException("address can't be null");
return addr;
}
private static ServerAddress _checkAddress(List<ServerAddress> addrs) {
if (addrs == null)
throw new NullPointerException("addresses can't be null");
if (addrs.size() == 0)
throw new IllegalArgumentException(
"need to specify at least 1 address");
return addrs.get(0);
}
/**
* Start a "request".
*
* A "request" is a group of operations in which order matters. Examples
* include inserting a document and then performing a query which expects
* that document to have been inserted, or performing an operation and then
* using com.mongodb.Mongo.getLastError to perform error-checking on that
* operation. When a thread performs operations in a "request", all
* operations will be performed on the same socket, so they will be
* correctly ordered.
*/
public void requestStart() {
// _threadPort.get().requestStart();
}
/**
* End the current "request", if this thread is in one.
*
* By ending a request when it is safe to do so the built-in connection-
* pool is allowed to reassign requests to different sockets in order to
* more effectively balance load. See requestStart for more information.
*/
public void requestDone() {
// _threadPort.get().requestDone();
}
public void requestEnsureConnection() {
// _threadPort.get().requestEnsureConnection();
}
WriteResult _checkWriteError(String db, WriteConcern concern) throws MongoException {
CommandResult e = _port.runCommand(db, concern.getCommand());
Object foo = e.get("err");
if (foo == null)
return new WriteResult(e, concern);
int code = -1;
if (e.get("code") instanceof Number)
code = ((Number) e.get("code")).intValue();
String s = foo.toString();
if (code == 11000 || code == 11001 || s.startsWith("E11000")
|| s.startsWith("E11001"))
throw new MongoException.DuplicateKey(code, s);
throw new MongoException(code, s);
}
public WriteResult say(String namespace, OutMessage m, WriteConcern concern)
throws MongoException {
String[] names = StringUtils.splitAtFirst(namespace, ".");
try {
_port.say(m);
if (concern.callGetLastError()) {
return _checkWriteError(names[0], concern);
} else {
return new WriteResult(names[0], _port, concern);
}
} catch (IOException ioe) {
_error(ioe);
if (concern.raiseNetworkErrors())
throw new MongoException.Network("can't say something", ioe);
CommandResult res = new CommandResult();
res.put("ok", false);
res.put("$err", "NETWORK ERROR");
return new WriteResult(res, concern);
} catch (MongoException me) {
throw me;
} catch (RuntimeException re) {
throw re;
}
}
public Response call(String namespace, OutMessage m) throws MongoException {
return call(namespace, m, 2);
}
public Response call(String namespace, OutMessage m, int retries)
throws MongoException {
Response res = null;
try {
res = _port.call(m, namespace);
} catch (IOException ioe) {
String collName = StringUtils.splitAtFirst(namespace, ".")[2];
boolean shoulRetry = _error(ioe)
&& !collName.equals("$cmd") && retries > 0;
if (shoulRetry) {
return call(namespace, m, retries - 1);
}
throw new MongoException.Network("can't call something", ioe);
} catch (RuntimeException re) {
throw re;
}
ServerError err = res.getError();
if (err != null && err.isNotMasterError()) {
_pickCurrent();
if (retries <= 0) {
throw new MongoException(
"not talking to master and retries used up");
}
return call(namespace, m, retries - 1);
}
return res;
}
public ServerAddress getAddress() {
return _curAddress;
}
public List<ServerAddress> getAllAddress() {
return _allHosts;
}
public String getConnectPoint() {
return _curAddress.toString();
}
boolean _error(Throwable t) throws MongoException {
if (_allHosts != null) {
_logger.log(Level.WARNING, "replica set mode, switching master", t);
_pickCurrent();
}
return true;
}
/**
* @return next to try
*/
@SuppressWarnings("unchecked")
ServerAddress _addAllFromSet(DBObject o) {
Object foo = o.get("hosts");
if (!(foo instanceof List))
return null;
String primary = (String) o.get("primary");
ServerAddress primaryAddress = null;
synchronized (_allHosts) {
for (Object x : (List) foo) {
try {
String s = x.toString();
ServerAddress a = new ServerAddress(s);
if (!_allHosts.contains(a))
_allHosts.add(a);
if (s.equals(primary)) {
int i = _allHosts.indexOf(a);
primaryAddress = _allHosts.get(i);
}
} catch (UnknownHostException un) {
_logger.severe("unknown host [" + un + "]");
}
}
}
return primaryAddress;
}
void _pickInitial() throws MongoException {
if (_curAddress != null)
return;
// we need to just get a server to query for ismaster
_pickCurrent();
try {
_logger.info("current address beginning of _pickInitial: "
+ _curAddress);
DBObject im = isMasterCmd();
ServerAddress other = _addAllFromSet(im);
if (_isMaster(im))
return;
if (other != null) {
_set(other, this.options);
im = isMasterCmd();
_addAllFromSet(im);
if (_isMaster(im))
return;
_logger.severe("primary given was wrong: " + other
+ " going to scan");
}
synchronized (_allHosts) {
Collections.shuffle(_allHosts);
for (ServerAddress a : _allHosts) {
if (_curAddress == a)
continue;
_logger.info("remote [" + _curAddress + "] -> [" + a + "]");
_set(a, this.options);
im = isMasterCmd();
_addAllFromSet(im);
if (_isMaster(im))
return;
if (_allHosts.size() == 2)
_logger.severe("switched to: " + a
+ " but isn't master");
}
throw new MongoException("can't find master");
}
} catch (Exception e) {
_logger.log(Level.SEVERE,
"can't pick initial master, using random one", e);
}
}
private void _pickCurrent() throws MongoException {
if (_allHosts == null)
throw new MongoException(
"got master/slave issue but not in master/slave mode on the client side");
synchronized (_allHosts) {
Collections.shuffle(_allHosts);
for (int i = 0; i < _allHosts.size(); i++) {
ServerAddress a = _allHosts.get(i);
if (a == _curAddress)
continue;
if (_curAddress != null) {
_logger.info("switching from [" + _curAddress + "] to ["
+ a + "]");
}
try {
_set(a, this.options);
} catch (IOException e) {
throw new MongoException("can't switch address");
}
return;
}
}
throw new MongoException("couldn't find a new host to swtich too");
}
private boolean _set(ServerAddress addr,MongoOptions options) throws IOException {
if (_curAddress == addr)
return false;
_curAddress = addr;
this._port = new DBPort(addr._addr,options);
return true;
}
public String debugString() {
StringBuilder buf = new StringBuilder("DBTCPConnector: ");
if (_allHosts != null)
buf.append("replica set : ").append(_allHosts);
else
buf.append(_curAddress).append(" ").append(_curAddress._addr);
return buf.toString();
}
DBObject isMasterCmd() {
String namespace = "admin.$cmd";
Iterator<DBObject> i = _m._find(namespace, _isMaster, null, 0, 1, 0);
if (i == null || !i.hasNext())
throw new MongoException("no result for ismaster query?");
DBObject res = i.next();
if (i.hasNext())
throw new MongoException("what's going on");
return res;
}
boolean _isMaster(DBObject res) {
Object x = res.get("ismaster");
if (x == null)
throw new IllegalStateException("ismaster shouldn't be null: "
+ res);
if (x instanceof Boolean)
return (Boolean) x;
if (x instanceof Number)
return ((Number) x).intValue() == 1;
throw new IllegalArgumentException("invalid ismaster [" + x + "] : "
+ x.getClass().getName());
}
public void close() {
_port.close();
}
private DBPort _port;
private ServerAddress _curAddress;
private final List<ServerAddress> _allHosts;
private Mongo _m;
final MongoOptions options;
private final static DBObject _isMaster = new BasicDBObject("ismaster", 1);
}
| 10,482 | 0.662087 | 0.657413 | 401 | 25.13965 | 23.231363 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.448878 | false | false |
7
|
3c597d6cc12c4d39407f1b630fbdd6b04def8e45
| 34,239,479,295,018 |
778da6dbb2eb27ace541338d0051f44353c3f924
|
/src/main/java/com/espertech/esper/core/service/ExpressionResultCacheServiceThreadlocal.java
|
8508983fdff682c3b57122eef69fe288767a67c6
|
[] |
no_license
|
jiji87432/ThreadForEsperAndBenchmark
|
https://github.com/jiji87432/ThreadForEsperAndBenchmark
|
daf7188fb142f707f9160173d48c2754e1260ec7
|
fd2fc3579b3dd4efa18e079ce80d3aee98bf7314
|
refs/heads/master
| 2021-12-12T02:15:18.810000 | 2016-12-01T12:15:01 | 2016-12-01T12:15:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* *************************************************************************************
* Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. *
* http://www.espertech.com/esper *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.core.service;
import com.espertech.esper.client.EventBean;
import java.util.Collection;
import java.util.Deque;
public class ExpressionResultCacheServiceThreadlocal implements ExpressionResultCacheService {
private ThreadLocal<ExpressionResultCacheServiceAgentInstance> threadCache = new ThreadLocal<ExpressionResultCacheServiceAgentInstance>()
{
protected synchronized ExpressionResultCacheServiceAgentInstance initialValue()
{
return new ExpressionResultCacheServiceAgentInstance();
}
};
public ExpressionResultCacheServiceThreadlocal() {
init();
}
public void destroy() {
init();
}
public void init() {
threadCache = new ThreadLocal<ExpressionResultCacheServiceAgentInstance>()
{
protected synchronized ExpressionResultCacheServiceAgentInstance initialValue()
{
return new ExpressionResultCacheServiceAgentInstance();
}
};
}
public void pushStack(ExpressionResultCacheStackEntry lambda) {
threadCache.get().pushStack(lambda);
}
public boolean popLambda() {
return threadCache.get().popLambda();
}
public Deque<ExpressionResultCacheStackEntry> getStack() {
return threadCache.get().getStack();
}
public ExpressionResultCacheEntry<EventBean, Collection<EventBean>> getPropertyColl(String propertyNameFullyQualified, EventBean reference) {
return threadCache.get().getPropertyColl(propertyNameFullyQualified, reference);
}
public void savePropertyColl(String propertyNameFullyQualified, EventBean reference, Collection<EventBean> events) {
threadCache.get().savePropertyColl(propertyNameFullyQualified, reference, events);
}
public ExpressionResultCacheEntry<EventBean[], Object> getDeclaredExpressionLastValue(Object node, EventBean[] eventsPerStream) {
return threadCache.get().getDeclaredExpressionLastValue(node, eventsPerStream);
}
public void saveDeclaredExpressionLastValue(Object node, EventBean[] eventsPerStream, Object result) {
threadCache.get().saveDeclaredExpressionLastValue(node, eventsPerStream, result);
}
public ExpressionResultCacheEntry<EventBean[], Collection<EventBean>> getDeclaredExpressionLastColl(Object node, EventBean[] eventsPerStream) {
return threadCache.get().getDeclaredExpressionLastColl(node, eventsPerStream);
}
public void saveDeclaredExpressionLastColl(Object node, EventBean[] eventsPerStream, Collection<EventBean> result) {
threadCache.get().saveDeclaredExpressionLastColl(node, eventsPerStream, result);
}
public ExpressionResultCacheEntry<Long[], Object> getEnumerationMethodLastValue(Object node) {
return threadCache.get().getEnumerationMethodLastValue(node);
}
public void saveEnumerationMethodLastValue(Object node, Object result) {
threadCache.get().saveEnumerationMethodLastValue(node, result);
}
public void pushContext(long contextNumber) {
threadCache.get().pushContext(contextNumber);
}
public void popContext() {
threadCache.get().popContext();
}
}
|
UTF-8
|
Java
| 4,042 |
java
|
ExpressionResultCacheServiceThreadlocal.java
|
Java
|
[] | null |
[] |
/*
* *************************************************************************************
* Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. *
* http://www.espertech.com/esper *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.core.service;
import com.espertech.esper.client.EventBean;
import java.util.Collection;
import java.util.Deque;
public class ExpressionResultCacheServiceThreadlocal implements ExpressionResultCacheService {
private ThreadLocal<ExpressionResultCacheServiceAgentInstance> threadCache = new ThreadLocal<ExpressionResultCacheServiceAgentInstance>()
{
protected synchronized ExpressionResultCacheServiceAgentInstance initialValue()
{
return new ExpressionResultCacheServiceAgentInstance();
}
};
public ExpressionResultCacheServiceThreadlocal() {
init();
}
public void destroy() {
init();
}
public void init() {
threadCache = new ThreadLocal<ExpressionResultCacheServiceAgentInstance>()
{
protected synchronized ExpressionResultCacheServiceAgentInstance initialValue()
{
return new ExpressionResultCacheServiceAgentInstance();
}
};
}
public void pushStack(ExpressionResultCacheStackEntry lambda) {
threadCache.get().pushStack(lambda);
}
public boolean popLambda() {
return threadCache.get().popLambda();
}
public Deque<ExpressionResultCacheStackEntry> getStack() {
return threadCache.get().getStack();
}
public ExpressionResultCacheEntry<EventBean, Collection<EventBean>> getPropertyColl(String propertyNameFullyQualified, EventBean reference) {
return threadCache.get().getPropertyColl(propertyNameFullyQualified, reference);
}
public void savePropertyColl(String propertyNameFullyQualified, EventBean reference, Collection<EventBean> events) {
threadCache.get().savePropertyColl(propertyNameFullyQualified, reference, events);
}
public ExpressionResultCacheEntry<EventBean[], Object> getDeclaredExpressionLastValue(Object node, EventBean[] eventsPerStream) {
return threadCache.get().getDeclaredExpressionLastValue(node, eventsPerStream);
}
public void saveDeclaredExpressionLastValue(Object node, EventBean[] eventsPerStream, Object result) {
threadCache.get().saveDeclaredExpressionLastValue(node, eventsPerStream, result);
}
public ExpressionResultCacheEntry<EventBean[], Collection<EventBean>> getDeclaredExpressionLastColl(Object node, EventBean[] eventsPerStream) {
return threadCache.get().getDeclaredExpressionLastColl(node, eventsPerStream);
}
public void saveDeclaredExpressionLastColl(Object node, EventBean[] eventsPerStream, Collection<EventBean> result) {
threadCache.get().saveDeclaredExpressionLastColl(node, eventsPerStream, result);
}
public ExpressionResultCacheEntry<Long[], Object> getEnumerationMethodLastValue(Object node) {
return threadCache.get().getEnumerationMethodLastValue(node);
}
public void saveEnumerationMethodLastValue(Object node, Object result) {
threadCache.get().saveEnumerationMethodLastValue(node, result);
}
public void pushContext(long contextNumber) {
threadCache.get().pushContext(contextNumber);
}
public void popContext() {
threadCache.get().popContext();
}
}
| 4,042 | 0.641514 | 0.639535 | 98 | 39.2449 | 42.557777 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489796 | false | false |
7
|
45e718d16d1841df7c2584ce89fbfe1dcc1c923f
| 6,124,623,399,431 |
0a3b337b4ec7bf9e6654dfc7bbe185e43ca60f94
|
/src/main/java/com/lti/scholarship/app/interface1/StudentInterface.java
|
a22134481c3381e3fd257acb9b1e7ae2b7454212
|
[] |
no_license
|
mdnabi/backend
|
https://github.com/mdnabi/backend
|
28e22707e0435e622eec7273a0a6e991fbb4b7d1
|
b833aa0cd02a4041e0b3c22ee15c23f5cf845dab
|
refs/heads/master
| 2020-04-22T11:11:57.436000 | 2019-02-12T14:24:42 | 2019-02-12T14:24:42 | 170,331,279 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lti.scholarship.app.interface1;
import java.util.List;
import com.lti.scholarship.app.entity.Student;
public interface StudentInterface {
public void add(Student student);
public Student fetchById(int id);
}
|
UTF-8
|
Java
| 227 |
java
|
StudentInterface.java
|
Java
|
[] | null |
[] |
package com.lti.scholarship.app.interface1;
import java.util.List;
import com.lti.scholarship.app.entity.Student;
public interface StudentInterface {
public void add(Student student);
public Student fetchById(int id);
}
| 227 | 0.788546 | 0.784141 | 11 | 19.636364 | 18.455217 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false |
7
|
b31bdb50e009f096b4169292a79ee8ef482c28db
| 15,831,249,486,799 |
55cde4185b32125c2809c0501e840a2c4982dcf2
|
/CoreStuff/src/main/java/com/fish/core/notes/BackendResponse.java
|
28199b17cd61a1f8f0c18f1048b8821770ab0442
|
[] |
no_license
|
TroyNeubauer/Notes
|
https://github.com/TroyNeubauer/Notes
|
1b80dbf6ebcf4a281ed19c86900d0e2176f99b57
|
6f87f54aed271cb35c572cd14b72599b369c9359
|
refs/heads/master
| 2020-03-22T12:15:24.850000 | 2018-07-08T16:53:08 | 2018-07-08T16:53:08 | 140,028,289 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fish.core.notes;
public final class BackendResponse {
public Object result;
public long id;
public BackendResponse(Object result, long id) {
this.result = result;
this.id = id;
}
/*
@Override
public String toString() {
return "BackendResponse{" +
"result=" + result +
", id=" + id +
'}';
}*/
}
|
UTF-8
|
Java
| 409 |
java
|
BackendResponse.java
|
Java
|
[] | null |
[] |
package com.fish.core.notes;
public final class BackendResponse {
public Object result;
public long id;
public BackendResponse(Object result, long id) {
this.result = result;
this.id = id;
}
/*
@Override
public String toString() {
return "BackendResponse{" +
"result=" + result +
", id=" + id +
'}';
}*/
}
| 409 | 0.518337 | 0.518337 | 20 | 19.450001 | 14.924727 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
7
|
f2e3716cc31a14f6787c8717cfaeefa2332d394a
| 15,831,249,487,964 |
ae5b1e117fc09145ca12961241898796c5581717
|
/SubSort/src/main/java/org/lodder/subtools/subsort/lib/control/VideoFileControlFactory.java
|
e5b9167590cc4de44ef257768d19dc560eae6cc9
|
[
"MIT"
] |
permissive
|
Denniswolt/SubTools
|
https://github.com/Denniswolt/SubTools
|
2a46b59cd7a5f4ffe119503d710639718a1463ff
|
499ec6107fe703605be451d0bc68228fdcae9f88
|
refs/heads/master
| 2021-05-08T02:05:36.299000 | 2017-10-23T05:53:08 | 2017-10-23T05:53:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.lodder.subtools.subsort.lib.control;
import java.io.File;
import org.lodder.subtools.sublibrary.Manager;
import org.lodder.subtools.sublibrary.control.ReleaseParser;
import org.lodder.subtools.sublibrary.exception.ControlFactoryException;
import org.lodder.subtools.sublibrary.exception.ReleaseParseException;
import org.lodder.subtools.sublibrary.model.MovieRelease;
import org.lodder.subtools.sublibrary.model.Release;
import org.lodder.subtools.sublibrary.model.TvRelease;
import org.lodder.subtools.sublibrary.model.VideoType;
public class VideoFileControlFactory {
private static final ReleaseParser releaseParser = new ReleaseParser();
public static VideoFileControl getController(File file, Manager manager) throws ReleaseParseException, ControlFactoryException {
Release release = releaseParser.parse(file);
if (release.getVideoType() == VideoType.EPISODE) {
return new EpisodeFileControl((TvRelease) release);
} else if (release.getVideoType() == VideoType.MOVIE) {
return new MovieFileControl((MovieRelease) release, manager);
}
throw new ControlFactoryException("Can't find controller");
}
}
|
UTF-8
|
Java
| 1,194 |
java
|
VideoFileControlFactory.java
|
Java
|
[] | null |
[] |
package org.lodder.subtools.subsort.lib.control;
import java.io.File;
import org.lodder.subtools.sublibrary.Manager;
import org.lodder.subtools.sublibrary.control.ReleaseParser;
import org.lodder.subtools.sublibrary.exception.ControlFactoryException;
import org.lodder.subtools.sublibrary.exception.ReleaseParseException;
import org.lodder.subtools.sublibrary.model.MovieRelease;
import org.lodder.subtools.sublibrary.model.Release;
import org.lodder.subtools.sublibrary.model.TvRelease;
import org.lodder.subtools.sublibrary.model.VideoType;
public class VideoFileControlFactory {
private static final ReleaseParser releaseParser = new ReleaseParser();
public static VideoFileControl getController(File file, Manager manager) throws ReleaseParseException, ControlFactoryException {
Release release = releaseParser.parse(file);
if (release.getVideoType() == VideoType.EPISODE) {
return new EpisodeFileControl((TvRelease) release);
} else if (release.getVideoType() == VideoType.MOVIE) {
return new MovieFileControl((MovieRelease) release, manager);
}
throw new ControlFactoryException("Can't find controller");
}
}
| 1,194 | 0.778057 | 0.778057 | 27 | 43.222221 | 32.058205 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
7
|
0acda5ea951ee8a13648545037ebecd7e717d194
| 26,302,379,741,019 |
c68243ef3af8bd1912936466a8a128c72ddbb7dc
|
/src/main/java/br/com/pocketpos/server/util/DatasetBuilder.java
|
cedd5074078183f5b850d3efb57ddbb7f80185ec
|
[] |
no_license
|
diogorosin/PocketPOS-Server
|
https://github.com/diogorosin/PocketPOS-Server
|
bb644225928b873d1e52c5c2dc4b512b45faa111
|
a0dae8b21530205797dbd2a2fa3bf07e4830761b
|
refs/heads/master
| 2018-11-21T06:36:43.278000 | 2018-09-30T22:52:52 | 2018-09-30T22:53:22 | 135,760,666 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.pocketpos.server.util;
import java.util.List;
import br.com.pocketpos.server.bean.DatasetBean;
import br.com.pocketpos.server.orm.Catalog;
import br.com.pocketpos.server.orm.Company;
import br.com.pocketpos.server.orm.CompanyDevice;
import br.com.pocketpos.server.orm.CompanyPaymentMethod;
import br.com.pocketpos.server.orm.CompanyReceiptMethod;
import br.com.pocketpos.server.orm.MeasureUnit;
import br.com.pocketpos.server.orm.Progeny;
import br.com.pocketpos.server.orm.SubjectSubject;
public abstract interface DatasetBuilder {
public abstract DatasetBuilder withCompany(Company company);
public abstract DatasetBuilder withDevices(List<CompanyDevice> devices);
public abstract DatasetBuilder withSubjects(List<SubjectSubject> subjects);
public abstract DatasetBuilder withMeasureUnits(List<MeasureUnit> measureUnits);
public abstract DatasetBuilder withProgenies(List<Progeny> progeny);
public abstract DatasetBuilder withCatalogs(List<Catalog> catalogs);
public abstract DatasetBuilder withReceiptMethods(List<CompanyReceiptMethod> receiptMethods);
public abstract DatasetBuilder withPaymentMethods(List<CompanyPaymentMethod> paymentMethods);
public abstract DatasetBean build();
}
|
UTF-8
|
Java
| 1,228 |
java
|
DatasetBuilder.java
|
Java
|
[] | null |
[] |
package br.com.pocketpos.server.util;
import java.util.List;
import br.com.pocketpos.server.bean.DatasetBean;
import br.com.pocketpos.server.orm.Catalog;
import br.com.pocketpos.server.orm.Company;
import br.com.pocketpos.server.orm.CompanyDevice;
import br.com.pocketpos.server.orm.CompanyPaymentMethod;
import br.com.pocketpos.server.orm.CompanyReceiptMethod;
import br.com.pocketpos.server.orm.MeasureUnit;
import br.com.pocketpos.server.orm.Progeny;
import br.com.pocketpos.server.orm.SubjectSubject;
public abstract interface DatasetBuilder {
public abstract DatasetBuilder withCompany(Company company);
public abstract DatasetBuilder withDevices(List<CompanyDevice> devices);
public abstract DatasetBuilder withSubjects(List<SubjectSubject> subjects);
public abstract DatasetBuilder withMeasureUnits(List<MeasureUnit> measureUnits);
public abstract DatasetBuilder withProgenies(List<Progeny> progeny);
public abstract DatasetBuilder withCatalogs(List<Catalog> catalogs);
public abstract DatasetBuilder withReceiptMethods(List<CompanyReceiptMethod> receiptMethods);
public abstract DatasetBuilder withPaymentMethods(List<CompanyPaymentMethod> paymentMethods);
public abstract DatasetBean build();
}
| 1,228 | 0.836319 | 0.836319 | 36 | 33.138889 | 31.360939 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.861111 | false | false |
7
|
e73f6bc45436d3ba4445b9b8be48bfc0dfe9b18b
| 34,471,407,529,540 |
5b802a8fe2f4f7c6cb5ec9c4ee60b30fca024154
|
/Interface/src/main/java/com/practice/dto/ProCityDTO.java
|
3bef23d3b03f93449e4295c8d912905f964a022c
|
[] |
no_license
|
Xushd529/Practice
|
https://github.com/Xushd529/Practice
|
099f768602058cd792e3189e4c186abdc44dccc0
|
a9832b26f80626b50d9db62ac9c3bc957a031aba
|
refs/heads/master
| 2018-08-27T18:01:49.402000 | 2018-06-03T10:41:55 | 2018-06-03T10:41:55 | 115,059,215 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.practice.dto;
import java.io.Serializable;
import java.util.List;
/**
* @author Xushd on 2018/2/23 15:30
*/
public class ProCityDTO implements Serializable{
private Long id;
private String name;
private String spell;
private String frist;
public ProCityDTO() {
}
public String getFrist() {
return frist;
}
public void setFrist(String frist) {
this.frist = frist;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpell() {
return spell;
}
public void setSpell(String spell) {
this.spell = spell;
}
}
|
UTF-8
|
Java
| 830 |
java
|
ProCityDTO.java
|
Java
|
[
{
"context": "rializable;\nimport java.util.List;\n\n/**\n * @author Xushd on 2018/2/23 15:30\n */\npublic class ProCityDTO im",
"end": 100,
"score": 0.6768547892570496,
"start": 95,
"tag": "USERNAME",
"value": "Xushd"
}
] | null |
[] |
package com.practice.dto;
import java.io.Serializable;
import java.util.List;
/**
* @author Xushd on 2018/2/23 15:30
*/
public class ProCityDTO implements Serializable{
private Long id;
private String name;
private String spell;
private String frist;
public ProCityDTO() {
}
public String getFrist() {
return frist;
}
public void setFrist(String frist) {
this.frist = frist;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpell() {
return spell;
}
public void setSpell(String spell) {
this.spell = spell;
}
}
| 830 | 0.578313 | 0.56506 | 57 | 13.561403 | 13.953579 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.263158 | false | false |
7
|
7cf377ee6947a28d1fc0eb4317cb27eac4923310
| 26,345,329,419,849 |
b3201705654d789ca15c23e0f0e93699c81dab70
|
/green/src/main/java/spring/service/ProductDeleteService.java
|
f76471e089771796c5963cab1bc480ad2687378a
|
[] |
no_license
|
hihiihiii/GreenHotel
|
https://github.com/hihiihiii/GreenHotel
|
6d0dc57fd723dfdd245aee55ecfeb4fba1a5d7fb
|
b14f15497d22b49a972d56f4e634135940d760d4
|
refs/heads/master
| 2023-06-27T22:20:52.620000 | 2021-07-21T06:17:08 | 2021-07-21T06:17:08 | 328,342,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package spring.service;
import spring.dao.ProductDao;
import spring.exception.ProductNotExistingException;
import spring.vo.Product;
public class ProductDeleteService {
private ProductDao productDao;
public ProductDeleteService(ProductDao productDao) {
this.productDao = productDao;
}
public void delete(int product_number) {
Product product = productDao.selectByProduct_number(product_number);
if(product == null) {
throw new ProductNotExistingException();
}
productDao.deleteProduct(product_number);
}
}
|
UTF-8
|
Java
| 538 |
java
|
ProductDeleteService.java
|
Java
|
[] | null |
[] |
package spring.service;
import spring.dao.ProductDao;
import spring.exception.ProductNotExistingException;
import spring.vo.Product;
public class ProductDeleteService {
private ProductDao productDao;
public ProductDeleteService(ProductDao productDao) {
this.productDao = productDao;
}
public void delete(int product_number) {
Product product = productDao.selectByProduct_number(product_number);
if(product == null) {
throw new ProductNotExistingException();
}
productDao.deleteProduct(product_number);
}
}
| 538 | 0.773234 | 0.773234 | 25 | 20.52 | 20.942053 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.32 | false | false |
10
|
31b96698b0577dcd8808160180c007066a8c5f0f
| 6,468,220,781,954 |
9cba249e558a50283ae66b2d9a5d182e375643c1
|
/src/main/java/com/ramosvji/clients/service/ClientsService.java
|
6313f2865fc906bf9cfa7cdd0be71ca685ed151a
|
[] |
no_license
|
ramosvji/mc_clients
|
https://github.com/ramosvji/mc_clients
|
74bc5ae10f31bda3e0227ece3c7f8c0d33620db9
|
fe1a17f98872d5e8ac19a43950a9df67cc371411
|
refs/heads/master
| 2020-09-22T18:13:40.756000 | 2020-03-02T05:16:56 | 2020-03-02T05:16:56 | 225,296,968 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ramosvji.clients.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.ramosvji.clients.service.dto.ClientIntDtoRequest;
import com.ramosvji.clients.service.dto.ClientIntDtoResponse;
@Service
public interface ClientsService {
public ClientIntDtoResponse save(final ClientIntDtoRequest client);
public ClientIntDtoResponse getClientByUsername(final String username);
public Page<ClientIntDtoResponse> getAll(Pageable pageable);
public void delete(final String username );
public ClientIntDtoResponse update(final ClientIntDtoRequest client, final String username);
}
|
UTF-8
|
Java
| 702 |
java
|
ClientsService.java
|
Java
|
[] | null |
[] |
package com.ramosvji.clients.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.ramosvji.clients.service.dto.ClientIntDtoRequest;
import com.ramosvji.clients.service.dto.ClientIntDtoResponse;
@Service
public interface ClientsService {
public ClientIntDtoResponse save(final ClientIntDtoRequest client);
public ClientIntDtoResponse getClientByUsername(final String username);
public Page<ClientIntDtoResponse> getAll(Pageable pageable);
public void delete(final String username );
public ClientIntDtoResponse update(final ClientIntDtoRequest client, final String username);
}
| 702 | 0.837607 | 0.837607 | 22 | 30.90909 | 29.61865 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.954545 | false | false |
10
|
70436baf8bad648e322454d7b1af8f340eaafb5a
| 12,687,333,446,293 |
d7d56477d7a52eb2bedcdf0bb79a2eb2e321bddd
|
/naver.choch92.portfolio/src/main/java/naver/choch92/board/service/SpringUserService.java
|
7ec8b598d35e320798da90b015b9264c25ca35f4
|
[] |
no_license
|
choch92/Spring
|
https://github.com/choch92/Spring
|
1d3bb8a9b8c075e0870f4ef35058f29b21d3bd1c
|
794b0a1dbad7b5815be6452edb83d121481e4bcd
|
refs/heads/master
| 2022-12-21T05:59:32.023000 | 2020-01-02T13:54:28 | 2020-01-02T13:54:28 | 224,766,736 | 0 | 0 | null | false | 2022-12-16T00:46:19 | 2019-11-29T03:02:32 | 2020-01-02T13:54:41 | 2022-12-16T00:46:18 | 25,898 | 0 | 0 | 52 |
Rich Text Format
| false | false |
package naver.choch92.board.service;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import naver.choch92.board.domain.SpringUser;
public interface SpringUserService {
// 서비스의 메소드는 파라미터를 Controller가 읽을 지 Service가 읽을 지에 따라서
// 메소드의 매개변수가 달라집니다.
// Controller가 읽으면 변환된 파라미터가 매개변수이고
// Service에서 읽고자 할 때는 HttpServletRequest입니다.
// 이메일 중복 검사를 위한 메소드
public boolean emailCheck(String email);
// 닉네임 중복 검사를 위한 메소드
public boolean nicknameCheck(HttpServletRequest request);
// 회원가입 처리를 위한 메소드
// 파라미터를 서비스에 읽기 - 파일업로드가 있어서 Multipart을 추가
public void join(MultipartHttpServletRequest request);
// 로그인 처리 메소드
public boolean login(HttpServletRequest request);
// 위도와 경도를 받아서 주소를 리턴해주는 메소드
public Map<String, Object> address(HttpServletRequest request);
// 회원정보 수정을 위한 메소드를 선언
public int update(MultipartHttpServletRequest request);
// pwcheck POST에 이메일과 비밀번호를 리턴해주는 메소드
public boolean login(SpringUser user);
// 회원탈퇴 처리를 위한 메소드를 선언
public int delete(HttpServletRequest request);
}
|
UTF-8
|
Java
| 1,555 |
java
|
SpringUserService.java
|
Java
|
[] | null |
[] |
package naver.choch92.board.service;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import naver.choch92.board.domain.SpringUser;
public interface SpringUserService {
// 서비스의 메소드는 파라미터를 Controller가 읽을 지 Service가 읽을 지에 따라서
// 메소드의 매개변수가 달라집니다.
// Controller가 읽으면 변환된 파라미터가 매개변수이고
// Service에서 읽고자 할 때는 HttpServletRequest입니다.
// 이메일 중복 검사를 위한 메소드
public boolean emailCheck(String email);
// 닉네임 중복 검사를 위한 메소드
public boolean nicknameCheck(HttpServletRequest request);
// 회원가입 처리를 위한 메소드
// 파라미터를 서비스에 읽기 - 파일업로드가 있어서 Multipart을 추가
public void join(MultipartHttpServletRequest request);
// 로그인 처리 메소드
public boolean login(HttpServletRequest request);
// 위도와 경도를 받아서 주소를 리턴해주는 메소드
public Map<String, Object> address(HttpServletRequest request);
// 회원정보 수정을 위한 메소드를 선언
public int update(MultipartHttpServletRequest request);
// pwcheck POST에 이메일과 비밀번호를 리턴해주는 메소드
public boolean login(SpringUser user);
// 회원탈퇴 처리를 위한 메소드를 선언
public int delete(HttpServletRequest request);
}
| 1,555 | 0.741485 | 0.737991 | 42 | 25.261906 | 21.908966 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.02381 | false | false |
10
|
b84ac89a1094d678d3c6c4f1724339c1764968df
| 30,769,145,754,480 |
15168174e0c7073b8dc2e39da333c9ba5ad4eda1
|
/demo/src/main/java/com/example/demo/system/service/srv/redisSrv.java
|
1b4f116a6e43e3bc0159f64cc89db64e8f3c5ad3
|
[] |
no_license
|
z944395433/demo
|
https://github.com/z944395433/demo
|
37baf61de2b4714f982b212570272bd7ce2a13d7
|
d1d82ce4cd8748865a1fd37084a7832a2d5772b7
|
refs/heads/master
| 2020-04-05T08:46:09.595000 | 2018-12-20T16:46:26 | 2018-12-20T16:46:26 | 156,728,856 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.demo.system.service.srv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
public class redisSrv {
@Autowired
RedisTemplate redisTemplate;
public void hh(){
}
}
|
UTF-8
|
Java
| 272 |
java
|
redisSrv.java
|
Java
|
[] | null |
[] |
package com.example.demo.system.service.srv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
public class redisSrv {
@Autowired
RedisTemplate redisTemplate;
public void hh(){
}
}
| 272 | 0.764706 | 0.764706 | 13 | 19.923077 | 21.634949 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false |
10
|
4d74be7c4a7fe6dabd3cc087cdc32f6131608f03
| 25,494,925,936,442 |
94ec180946876d1b2ac080aa95e369f050b43852
|
/src/java/utn/sau/hp/com/modelo/Carreras.java
|
fe0d310b2343e79165df4988e013b3545a52734d
|
[] |
no_license
|
chrgomez/syspa
|
https://github.com/chrgomez/syspa
|
6e65f7ced0cc46ee896e3e382356c88ee2f522e3
|
9d7af1d43402b137cc95b788992484eaeff6d279
|
refs/heads/master
| 2016-09-05T13:41:21.158000 | 2014-12-18T22:31:41 | 2014-12-18T22:31:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package utn.sau.hp.com.modelo;
// Generated 04/12/2014 23:31:51 by Hibernate Tools 3.6.0
import java.util.HashSet;
import java.util.Set;
/**
* Carreras generated by hbm2java
*/
public class Carreras implements java.io.Serializable {
private int id;
private String carrera;
private Set materiases = new HashSet(0);
private Set areases = new HashSet(0);
private Set ofertascarrerases = new HashSet(0);
private Set conveniosparticulareses = new HashSet(0);
public Carreras() {
}
public Carreras(int id, String carrera) {
this.id = id;
this.carrera = carrera;
}
public Carreras(int id, String carrera, Set materiases, Set areases, Set ofertascarrerases, Set conveniosparticulareses) {
this.id = id;
this.carrera = carrera;
this.materiases = materiases;
this.areases = areases;
this.ofertascarrerases = ofertascarrerases;
this.conveniosparticulareses = conveniosparticulareses;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getCarrera() {
return this.carrera;
}
public void setCarrera(String carrera) {
this.carrera = carrera;
}
public Set getMateriases() {
return this.materiases;
}
public void setMateriases(Set materiases) {
this.materiases = materiases;
}
public Set getAreases() {
return this.areases;
}
public void setAreases(Set areases) {
this.areases = areases;
}
public Set getOfertascarrerases() {
return this.ofertascarrerases;
}
public void setOfertascarrerases(Set ofertascarrerases) {
this.ofertascarrerases = ofertascarrerases;
}
public Set getConveniosparticulareses() {
return this.conveniosparticulareses;
}
public void setConveniosparticulareses(Set conveniosparticulareses) {
this.conveniosparticulareses = conveniosparticulareses;
}
}
|
UTF-8
|
Java
| 2,063 |
java
|
Carreras.java
|
Java
|
[] | null |
[] |
package utn.sau.hp.com.modelo;
// Generated 04/12/2014 23:31:51 by Hibernate Tools 3.6.0
import java.util.HashSet;
import java.util.Set;
/**
* Carreras generated by hbm2java
*/
public class Carreras implements java.io.Serializable {
private int id;
private String carrera;
private Set materiases = new HashSet(0);
private Set areases = new HashSet(0);
private Set ofertascarrerases = new HashSet(0);
private Set conveniosparticulareses = new HashSet(0);
public Carreras() {
}
public Carreras(int id, String carrera) {
this.id = id;
this.carrera = carrera;
}
public Carreras(int id, String carrera, Set materiases, Set areases, Set ofertascarrerases, Set conveniosparticulareses) {
this.id = id;
this.carrera = carrera;
this.materiases = materiases;
this.areases = areases;
this.ofertascarrerases = ofertascarrerases;
this.conveniosparticulareses = conveniosparticulareses;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getCarrera() {
return this.carrera;
}
public void setCarrera(String carrera) {
this.carrera = carrera;
}
public Set getMateriases() {
return this.materiases;
}
public void setMateriases(Set materiases) {
this.materiases = materiases;
}
public Set getAreases() {
return this.areases;
}
public void setAreases(Set areases) {
this.areases = areases;
}
public Set getOfertascarrerases() {
return this.ofertascarrerases;
}
public void setOfertascarrerases(Set ofertascarrerases) {
this.ofertascarrerases = ofertascarrerases;
}
public Set getConveniosparticulareses() {
return this.conveniosparticulareses;
}
public void setConveniosparticulareses(Set conveniosparticulareses) {
this.conveniosparticulareses = conveniosparticulareses;
}
}
| 2,063 | 0.646631 | 0.635967 | 84 | 23.511906 | 22.836111 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
10
|
b4d6826f7585abd7d92d13ff6670cbb328705f2e
| 25,546,465,526,987 |
6460ae933da7dfe24ecbed15c6435e40680ca435
|
/ingsoft-main/src/main/java/bo/ucb/edu/ingsoft/dao/AccountTypeDao.java
|
f84eae68e2528fb48832a293c14d8e33070274c2
|
[] |
no_license
|
IgnacioJaen/Proyecto
|
https://github.com/IgnacioJaen/Proyecto
|
076c50b675b41ac209d23df38d04b70e440b81e1
|
f4ec4c20a7c6f6abb06777fff4421342cf766073
|
refs/heads/master
| 2023-08-10T22:15:20.729000 | 2020-12-18T22:35:28 | 2020-12-18T22:35:28 | 287,414,586 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bo.ucb.edu.ingsoft.dao;
import bo.ucb.edu.ingsoft.dto.AccountTypeRequest;
import bo.ucb.edu.ingsoft.dto.CategoryRequest;
import bo.ucb.edu.ingsoft.dto.MessagesRequest;
import bo.ucb.edu.ingsoft.model.AccountType;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface AccountTypeDao {
//Metodos de la clase AccountTypeDao que seran utilizadas por los .xml de la
//carpeta resources/dao que utilicen como mapper esta clase
//Metodo para encontrar un tipo de cuenta y tiene un parametro de tipo accountType
public AccountType findByAccountTypeId(AccountType accountType);
//Metodo para agregar un tipo de cuenta y tiene un parametro de tipo accountType
public void accountTypeInsert(AccountType accountType);
//Metodo para actualizar un tipo de cuenta y tiene un parametro de tipo accountType
public void accountTypeUpdate(AccountType accountType);
//Metodo para eliminar un tipo de cuenta y tiene un parametro de tipo accountType
public void accountTypeDelete(AccountType accountType);
//Metodo para encontrar un tipo de cuenta y tiene un parametro de tipo accountTypeRequest
//ya que es el request para la vista del usuario de tipo cliente
public AccountTypeRequest findAccountTypeReqById(AccountTypeRequest accountTypeRequest);
public List<AccountTypeRequest> accountTypes();
public String findUserTypeById(Integer userId);
}
|
UTF-8
|
Java
| 1,444 |
java
|
AccountTypeDao.java
|
Java
|
[] | null |
[] |
package bo.ucb.edu.ingsoft.dao;
import bo.ucb.edu.ingsoft.dto.AccountTypeRequest;
import bo.ucb.edu.ingsoft.dto.CategoryRequest;
import bo.ucb.edu.ingsoft.dto.MessagesRequest;
import bo.ucb.edu.ingsoft.model.AccountType;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface AccountTypeDao {
//Metodos de la clase AccountTypeDao que seran utilizadas por los .xml de la
//carpeta resources/dao que utilicen como mapper esta clase
//Metodo para encontrar un tipo de cuenta y tiene un parametro de tipo accountType
public AccountType findByAccountTypeId(AccountType accountType);
//Metodo para agregar un tipo de cuenta y tiene un parametro de tipo accountType
public void accountTypeInsert(AccountType accountType);
//Metodo para actualizar un tipo de cuenta y tiene un parametro de tipo accountType
public void accountTypeUpdate(AccountType accountType);
//Metodo para eliminar un tipo de cuenta y tiene un parametro de tipo accountType
public void accountTypeDelete(AccountType accountType);
//Metodo para encontrar un tipo de cuenta y tiene un parametro de tipo accountTypeRequest
//ya que es el request para la vista del usuario de tipo cliente
public AccountTypeRequest findAccountTypeReqById(AccountTypeRequest accountTypeRequest);
public List<AccountTypeRequest> accountTypes();
public String findUserTypeById(Integer userId);
}
| 1,444 | 0.790166 | 0.790166 | 36 | 39.111111 | 33.183647 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false |
10
|
8c5dcac10ef9ed54c20c3a6000a74ccdb50cd382
| 13,967,233,673,128 |
886ff5ccedebd6e49681ef9a466865715ec931bc
|
/src/main/java/sobol/problems/clustering/hc/MainProgram.java
|
fe5578794af4876f50556da6049fc46cdb6bd051
|
[] |
no_license
|
RafasTavares/VisualNRP
|
https://github.com/RafasTavares/VisualNRP
|
1b24f545c9c2dcc4d4667bcb076cbb493863c69c
|
b58de341ad2ff8947fb49291f7fcee54ee5fd721
|
refs/heads/master
| 2021-05-01T16:04:41.778000 | 2015-04-20T13:48:21 | 2015-04-20T13:48:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sobol.problems.clustering.hc;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.management.modelmbean.XMLParseException;
import sobol.base.random.RandomGeneratorFactory;
import sobol.base.random.faure.FaureRandomGeneratorFactory;
import sobol.base.random.generic.AbstractRandomGeneratorFactory;
import sobol.base.random.halton.HaltonRandomGeneratorFactory;
import sobol.base.random.pseudo.PseudoRandomGeneratorFactory;
import sobol.base.random.sobol.SobolRandomGeneratorFactory;
import sobol.problems.clustering.generic.calculator.CalculadorIncrementalEVM;
import sobol.problems.clustering.generic.calculator.CalculadorIncrementalMQ;
import sobol.problems.clustering.generic.calculator.ICalculadorIncremental;
import sobol.problems.clustering.generic.model.Project;
import sobol.problems.clustering.generic.reader.CDAReader;
@SuppressWarnings("unused")
public class MainProgram
{
private static int CICLOS = 100;
private static int POPULATION_SIZE = 2000;
private static String[] instanceFilenamesReals =
{
"data\\cluster\\jodamoney 26C.odem",
"data\\cluster\\jxlsreader 27C.odem",
"data\\cluster\\seemp 31C.odem",
"data\\cluster\\apache_zip 36C.odem",
"data\\cluster\\udtjava 56C.odem",
"data\\cluster\\javaocr 59C.odem",
"data\\cluster\\pfcda_base 67C.odem",
"data\\cluster\\forms 68C.odem",
"data\\cluster\\servletapi 74C.odem",
"data\\cluster\\jscatterplot 74C.odem",
"data\\cluster\\jfluid 82C.odem",
"data\\cluster\\jxlscore 83C.odem",
"data\\cluster\\jpassword 96C.odem",
"data\\cluster\\junit 100C.odem",
"data\\cluster\\xmldom 119C.odem",
"data\\cluster\\tinytim 134C.odem",
"data\\cluster\\jkaryoscope 136C.odem",
"data\\cluster\\gae_core 140C.odem",
"data\\cluster\\javacc 154C.odem",
"data\\cluster\\javageom 172C.odem",
"data\\cluster\\jdendogram 177C.odem",
"data\\cluster\\xmlapi 184C.odem",
"data\\cluster\\jmetal 190C.odem",
"data\\cluster\\dom4j 195C.odem",
"data\\cluster\\pdf_renderer 199C.odem",
"data\\cluster\\jung_model 207C.odem",
"data\\cluster\\jconsole 220C.odem",
"data\\cluster\\jung_visualization 221C.odem",
"data\\cluster\\pfcda_swing 252C.odem",
"data\\cluster\\jpassword 269C.odem",
"data\\cluster\\jml 270C.odem",
"data\\cluster\\notepad_full 299C.odem",
/*"data\\cluster\\poormans 304C.odem",
"data\\cluster\\log4j 308C.odem",
"data\\cluster\\jtreeview 329C.odem",
"data\\cluster\\jace 340C.odem",
"data\\cluster\\javaws 378C.odem",
"data\\cluster\\res_cobol 483C.odem",
"data\\cluster\\ybase 558C.odem",
"data\\cluster\\lwjgl 569C.odem",
"data\\cluster\\apache_ant_taskdef 629C.odem",
"data\\cluster\\iTextPDF 657C.odem",
"data\\cluster\\apache_lucene_core 741C.odem",
"data\\cluster\\eclipse_jgit 912C.odem",*/
//"data\\cluster\\apache_ant 1090C.odem",
//"data\\cluster\\ylayout 1262C.odem",
//"data\\cluster\\ycomplete 2898C.odem",
""
};
private Vector<Project> readInstances(String[] filenames) throws XMLParseException
{
Vector<Project> instances = new Vector<Project>();
CDAReader reader = new CDAReader();
for (String filename : filenames)
if (filename.length() > 0)
{
Project project = reader.execute(filename);
System.out.println(project.getName() + " " + project.getClassCount());
instances.add (project);
}
return instances;
}
private void runInstance(PrintWriter out, PrintWriter details, ICalculadorIncremental calculador, String tipo, Project instance, int cycles, int popSize) throws Exception
{
for (int i = 0; i < cycles; i++)
{
int maxEvaluations = popSize * instance.getClassCount() * instance.getClassCount();
HillClimbingClustering hcc = new HillClimbingClustering(details, calculador, instance, maxEvaluations);
long initTime = System.currentTimeMillis();
details.println(tipo + " " + instance.getName() + " #" + cycles);
int[] solution = hcc.execute();
details.println();
long executionTime = (System.currentTimeMillis() - initTime);
String s = tipo + "; " + instance.getName() + " #" + i + "; " + executionTime + "; " + hcc.getFitness() + "; " + hcc.getRandomRestarts() + "; " + hcc.getRandomRestartBestFound() + "; " + hcc.printSolution(solution);
System.out.println(s);
out.println(s);
out.flush();
}
}
private void runInstanceGroupMQ(Vector<Project> instances, String randomType, AbstractRandomGeneratorFactory randomFactory) throws IOException, Exception
{
FileWriter outFile = new FileWriter("saida mq " + randomType.toLowerCase() + ".txt");
PrintWriter out = new PrintWriter(outFile);
FileWriter detailsFile = new FileWriter("saida mq " + randomType.toLowerCase() + " details.txt");
PrintWriter details = new PrintWriter(detailsFile);
for (int i = 0; i < instances.size(); i++)
{
Project projeto = instances.elementAt(i);
RandomGeneratorFactory.setRandomFactoryForPopulation(randomFactory);
ICalculadorIncremental calculador = new CalculadorIncrementalMQ(projeto, projeto.getClassCount());
runInstance(out, details, calculador, randomType, projeto, CICLOS, POPULATION_SIZE);
}
out.close();
outFile.close();
details.close();
detailsFile.close();
}
private void runInstanceGroupEVM(Vector<Project> instances, String randomType, AbstractRandomGeneratorFactory randomFactory) throws IOException, Exception
{
FileWriter outFile = new FileWriter("saida evm " + randomType.toLowerCase() + ".txt");
PrintWriter out = new PrintWriter(outFile);
FileWriter detailsFile = new FileWriter("saida evm " + randomType.toLowerCase() + " details.txt");
PrintWriter details = new PrintWriter(detailsFile);
for (int i = 0; i < instances.size(); i++)
{
Project projeto = instances.elementAt(i);
RandomGeneratorFactory.setRandomFactoryForPopulation(randomFactory);
ICalculadorIncremental calculador = new CalculadorIncrementalEVM(projeto, projeto.getClassCount());
runInstance(out, details, calculador, randomType, projeto, CICLOS, POPULATION_SIZE);
}
out.close();
outFile.close();
details.close();
detailsFile.close();
}
public static final void main(String[] args) throws Exception
{
MainProgram mp = new MainProgram();
Vector<Project> instances = new Vector<Project>();
instances.addAll(mp.readInstances(instanceFilenamesReals));
mp.runInstanceGroupMQ(instances, "SOBOL", new SobolRandomGeneratorFactory());
mp.runInstanceGroupMQ(instances, "FAURE", new FaureRandomGeneratorFactory());
mp.runInstanceGroupMQ(instances, "HALTON", new HaltonRandomGeneratorFactory());
mp.runInstanceGroupMQ(instances, "PSEUDO", new PseudoRandomGeneratorFactory());
}
}
|
UTF-8
|
Java
| 6,701 |
java
|
MainProgram.java
|
Java
|
[] | null |
[] |
package sobol.problems.clustering.hc;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.management.modelmbean.XMLParseException;
import sobol.base.random.RandomGeneratorFactory;
import sobol.base.random.faure.FaureRandomGeneratorFactory;
import sobol.base.random.generic.AbstractRandomGeneratorFactory;
import sobol.base.random.halton.HaltonRandomGeneratorFactory;
import sobol.base.random.pseudo.PseudoRandomGeneratorFactory;
import sobol.base.random.sobol.SobolRandomGeneratorFactory;
import sobol.problems.clustering.generic.calculator.CalculadorIncrementalEVM;
import sobol.problems.clustering.generic.calculator.CalculadorIncrementalMQ;
import sobol.problems.clustering.generic.calculator.ICalculadorIncremental;
import sobol.problems.clustering.generic.model.Project;
import sobol.problems.clustering.generic.reader.CDAReader;
@SuppressWarnings("unused")
public class MainProgram
{
private static int CICLOS = 100;
private static int POPULATION_SIZE = 2000;
private static String[] instanceFilenamesReals =
{
"data\\cluster\\jodamoney 26C.odem",
"data\\cluster\\jxlsreader 27C.odem",
"data\\cluster\\seemp 31C.odem",
"data\\cluster\\apache_zip 36C.odem",
"data\\cluster\\udtjava 56C.odem",
"data\\cluster\\javaocr 59C.odem",
"data\\cluster\\pfcda_base 67C.odem",
"data\\cluster\\forms 68C.odem",
"data\\cluster\\servletapi 74C.odem",
"data\\cluster\\jscatterplot 74C.odem",
"data\\cluster\\jfluid 82C.odem",
"data\\cluster\\jxlscore 83C.odem",
"data\\cluster\\jpassword 96C.odem",
"data\\cluster\\junit 100C.odem",
"data\\cluster\\xmldom 119C.odem",
"data\\cluster\\tinytim 134C.odem",
"data\\cluster\\jkaryoscope 136C.odem",
"data\\cluster\\gae_core 140C.odem",
"data\\cluster\\javacc 154C.odem",
"data\\cluster\\javageom 172C.odem",
"data\\cluster\\jdendogram 177C.odem",
"data\\cluster\\xmlapi 184C.odem",
"data\\cluster\\jmetal 190C.odem",
"data\\cluster\\dom4j 195C.odem",
"data\\cluster\\pdf_renderer 199C.odem",
"data\\cluster\\jung_model 207C.odem",
"data\\cluster\\jconsole 220C.odem",
"data\\cluster\\jung_visualization 221C.odem",
"data\\cluster\\pfcda_swing 252C.odem",
"data\\cluster\\jpassword 269C.odem",
"data\\cluster\\jml 270C.odem",
"data\\cluster\\notepad_full 299C.odem",
/*"data\\cluster\\poormans 304C.odem",
"data\\cluster\\log4j 308C.odem",
"data\\cluster\\jtreeview 329C.odem",
"data\\cluster\\jace 340C.odem",
"data\\cluster\\javaws 378C.odem",
"data\\cluster\\res_cobol 483C.odem",
"data\\cluster\\ybase 558C.odem",
"data\\cluster\\lwjgl 569C.odem",
"data\\cluster\\apache_ant_taskdef 629C.odem",
"data\\cluster\\iTextPDF 657C.odem",
"data\\cluster\\apache_lucene_core 741C.odem",
"data\\cluster\\eclipse_jgit 912C.odem",*/
//"data\\cluster\\apache_ant 1090C.odem",
//"data\\cluster\\ylayout 1262C.odem",
//"data\\cluster\\ycomplete 2898C.odem",
""
};
private Vector<Project> readInstances(String[] filenames) throws XMLParseException
{
Vector<Project> instances = new Vector<Project>();
CDAReader reader = new CDAReader();
for (String filename : filenames)
if (filename.length() > 0)
{
Project project = reader.execute(filename);
System.out.println(project.getName() + " " + project.getClassCount());
instances.add (project);
}
return instances;
}
private void runInstance(PrintWriter out, PrintWriter details, ICalculadorIncremental calculador, String tipo, Project instance, int cycles, int popSize) throws Exception
{
for (int i = 0; i < cycles; i++)
{
int maxEvaluations = popSize * instance.getClassCount() * instance.getClassCount();
HillClimbingClustering hcc = new HillClimbingClustering(details, calculador, instance, maxEvaluations);
long initTime = System.currentTimeMillis();
details.println(tipo + " " + instance.getName() + " #" + cycles);
int[] solution = hcc.execute();
details.println();
long executionTime = (System.currentTimeMillis() - initTime);
String s = tipo + "; " + instance.getName() + " #" + i + "; " + executionTime + "; " + hcc.getFitness() + "; " + hcc.getRandomRestarts() + "; " + hcc.getRandomRestartBestFound() + "; " + hcc.printSolution(solution);
System.out.println(s);
out.println(s);
out.flush();
}
}
private void runInstanceGroupMQ(Vector<Project> instances, String randomType, AbstractRandomGeneratorFactory randomFactory) throws IOException, Exception
{
FileWriter outFile = new FileWriter("saida mq " + randomType.toLowerCase() + ".txt");
PrintWriter out = new PrintWriter(outFile);
FileWriter detailsFile = new FileWriter("saida mq " + randomType.toLowerCase() + " details.txt");
PrintWriter details = new PrintWriter(detailsFile);
for (int i = 0; i < instances.size(); i++)
{
Project projeto = instances.elementAt(i);
RandomGeneratorFactory.setRandomFactoryForPopulation(randomFactory);
ICalculadorIncremental calculador = new CalculadorIncrementalMQ(projeto, projeto.getClassCount());
runInstance(out, details, calculador, randomType, projeto, CICLOS, POPULATION_SIZE);
}
out.close();
outFile.close();
details.close();
detailsFile.close();
}
private void runInstanceGroupEVM(Vector<Project> instances, String randomType, AbstractRandomGeneratorFactory randomFactory) throws IOException, Exception
{
FileWriter outFile = new FileWriter("saida evm " + randomType.toLowerCase() + ".txt");
PrintWriter out = new PrintWriter(outFile);
FileWriter detailsFile = new FileWriter("saida evm " + randomType.toLowerCase() + " details.txt");
PrintWriter details = new PrintWriter(detailsFile);
for (int i = 0; i < instances.size(); i++)
{
Project projeto = instances.elementAt(i);
RandomGeneratorFactory.setRandomFactoryForPopulation(randomFactory);
ICalculadorIncremental calculador = new CalculadorIncrementalEVM(projeto, projeto.getClassCount());
runInstance(out, details, calculador, randomType, projeto, CICLOS, POPULATION_SIZE);
}
out.close();
outFile.close();
details.close();
detailsFile.close();
}
public static final void main(String[] args) throws Exception
{
MainProgram mp = new MainProgram();
Vector<Project> instances = new Vector<Project>();
instances.addAll(mp.readInstances(instanceFilenamesReals));
mp.runInstanceGroupMQ(instances, "SOBOL", new SobolRandomGeneratorFactory());
mp.runInstanceGroupMQ(instances, "FAURE", new FaureRandomGeneratorFactory());
mp.runInstanceGroupMQ(instances, "HALTON", new HaltonRandomGeneratorFactory());
mp.runInstanceGroupMQ(instances, "PSEUDO", new PseudoRandomGeneratorFactory());
}
}
| 6,701 | 0.731831 | 0.710342 | 174 | 37.517242 | 34.099537 | 218 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.672414 | false | false |
10
|
59b4cea64d8aa3306b0d29f39401f649660f5a44
| 17,961,553,257,293 |
ec503bac061d71ceed78e4571a94740e5d492071
|
/src/main/java/com/refactor/spring/boot/configs/FilterConfig.java
|
1ff637e2efefc838591eac1e913936a2fb5ecad8
|
[] |
no_license
|
LX1993728/springboot-refactor
|
https://github.com/LX1993728/springboot-refactor
|
72732af54c4b0e2032527d6ab0a11ae569123a40
|
db93128a7067c506a4f01d2ccbf1fb2b8caf21a0
|
refs/heads/master
| 2023-08-25T07:11:50.495000 | 2021-06-21T02:33:17 | 2021-06-21T02:33:17 | 286,345,898 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.refactor.spring.boot.configs;
import com.refactor.spring.boot.filters.*;
import com.refactor.spring.boot.filters.stack.BaseFilter;
import com.refactor.spring.boot.filters.stack.FilterA;
import com.refactor.spring.boot.filters.stack.FilterB;
import com.refactor.spring.boot.filters.stack.FilterC;
import com.refactor.spring.boot.property.FilterProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
/**
* @author liuxun
* @apiNote 有关filter的相关配置
*/
@Configuration
@EnableConfigurationProperties({FilterProperty.class})
public class FilterConfig {
@Autowired
private FilterProperty filterProperty;
/**
* @apiNote filter配置方式一:通过声明Spring Bean FilterRegistrationBean对Filter进行包装
* @return
* 注意:对这种配置filter的方式,order值越小,越先进入,越后放行
*/
@Bean
public FilterRegistrationBean registerFilter1() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LogCostFilter());
registration.addUrlPatterns("/*");
registration.setName("logCostFilter-1");
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
/**
*
* @param name 设置filter的名称
* @param filter 指定的自定义filter
* @param weightOrder 保证顺序
* @return
*/
private FilterRegistrationBean wrapperFilter(String name, BaseFilter filter, int weightOrder){
FilterRegistrationBean registration = new FilterRegistrationBean();
String filterName = name == null ? filter.getClass().getSimpleName() : name;
filter.addUrlMappings(filterProperty.getPatternsByFilterName(filterName));
registration.setFilter(filter);
registration.setName(filterName);
registration.addUrlPatterns("/*");
registration.setOrder(Ordered.HIGHEST_PRECEDENCE + weightOrder);
return registration;
}
@Bean
public FilterRegistrationBean filterA() {
return wrapperFilter("filter-A", new FilterA(), 1);
}
@Bean
public FilterRegistrationBean filterB() {
return wrapperFilter("filter-B", new FilterB(), 2);
}
@Bean
public FilterRegistrationBean filterC() {
return wrapperFilter("filter-C", new FilterC(), 3);
}
}
|
UTF-8
|
Java
| 2,680 |
java
|
FilterConfig.java
|
Java
|
[
{
"context": " org.springframework.core.Ordered;\n\n/**\n * @author liuxun\n * @apiNote 有关filter的相关配置\n */\n@Configuration\n@Ena",
"end": 755,
"score": 0.9995982050895691,
"start": 749,
"tag": "USERNAME",
"value": "liuxun"
}
] | null |
[] |
package com.refactor.spring.boot.configs;
import com.refactor.spring.boot.filters.*;
import com.refactor.spring.boot.filters.stack.BaseFilter;
import com.refactor.spring.boot.filters.stack.FilterA;
import com.refactor.spring.boot.filters.stack.FilterB;
import com.refactor.spring.boot.filters.stack.FilterC;
import com.refactor.spring.boot.property.FilterProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
/**
* @author liuxun
* @apiNote 有关filter的相关配置
*/
@Configuration
@EnableConfigurationProperties({FilterProperty.class})
public class FilterConfig {
@Autowired
private FilterProperty filterProperty;
/**
* @apiNote filter配置方式一:通过声明Spring Bean FilterRegistrationBean对Filter进行包装
* @return
* 注意:对这种配置filter的方式,order值越小,越先进入,越后放行
*/
@Bean
public FilterRegistrationBean registerFilter1() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LogCostFilter());
registration.addUrlPatterns("/*");
registration.setName("logCostFilter-1");
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
/**
*
* @param name 设置filter的名称
* @param filter 指定的自定义filter
* @param weightOrder 保证顺序
* @return
*/
private FilterRegistrationBean wrapperFilter(String name, BaseFilter filter, int weightOrder){
FilterRegistrationBean registration = new FilterRegistrationBean();
String filterName = name == null ? filter.getClass().getSimpleName() : name;
filter.addUrlMappings(filterProperty.getPatternsByFilterName(filterName));
registration.setFilter(filter);
registration.setName(filterName);
registration.addUrlPatterns("/*");
registration.setOrder(Ordered.HIGHEST_PRECEDENCE + weightOrder);
return registration;
}
@Bean
public FilterRegistrationBean filterA() {
return wrapperFilter("filter-A", new FilterA(), 1);
}
@Bean
public FilterRegistrationBean filterB() {
return wrapperFilter("filter-B", new FilterB(), 2);
}
@Bean
public FilterRegistrationBean filterC() {
return wrapperFilter("filter-C", new FilterC(), 3);
}
}
| 2,680 | 0.731612 | 0.729656 | 72 | 34.5 | 26.31645 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false |
10
|
0f24bdf29aefb49aa65d1286e175c653b96bca1a
| 14,164,802,171,017 |
f7899dbae7795d2ae09a4e851a5bc9b070165d59
|
/lab2/Mini-Dictionary/src/test/java/DictionaryTest.java
|
111125528faf2395f96fc23453c385599ff087b0
|
[] |
no_license
|
OVERENSAL/dudin_oop
|
https://github.com/OVERENSAL/dudin_oop
|
76296c181f4cad526615ed55ee45aa68ace951aa
|
56d175c0b485424dced761a0b7c560092b0890ee
|
refs/heads/master
| 2021-01-05T14:26:09.982000 | 2020-07-12T11:22:42 | 2020-07-12T11:22:42 | 241,036,990 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class DictionaryTest {
public final String PATH = "D://OOP/dudin_oop/lab2/Mini-Dictionary/src/test/resources/";
Dictionary dictionaryObject = new Dictionary();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(stream);
PrintStream originalOutputStream = System.out;
@Before
public void setCustomOutputStream() {
System.setOut(out);
}
@After
public void setOriginalOutputStream() {
System.setOut(originalOutputStream);
}
@Test
public void dictionaryLoad_EmptyArgs_ShouldShowMistakeMessageAndReturnNull() {
String[] args = {};
dictionaryObject.dictionaryLoad(args);
assertEquals(dictionaryObject.MISSING_DICTIONARY + "\r\n" + dictionaryObject.USAGE_METHOD + "\r\n", stream.toString());
}
@Test
public void dictionaryLoad_NonExistFile_ShouldShowMistakeMessageAndReturnNull() {
String[] args = {PATH};
dictionaryObject.dictionaryLoad(args);
assertEquals(dictionaryObject.MISSING_DICTIONARY + "\r\n" + dictionaryObject.USAGE_METHOD + "\r\n", stream.toString());
}
@Test
public void dictionaryLoad_SomeStrings_ShouldReturnMapWithTheseStrings() {
String[] args = {PATH + "dictionarySomeString.txt"};
Map<String, String> expected = new HashMap<>();
expected.put("12", "sdf");
expected.put("sdf", "sdf");
expected.put("sef", "fds");
Map<String, String> result = dictionaryObject.dictionaryLoad(args);
assertEquals(expected, result);
}
@Test
public void dictionaryLoad_SomeStringsWithoutCouple_ShouldReturnMapWithTheseStrings() {
String[] args = {PATH + "dictionarySomeStringWithoutCouple.txt"};
Map<String, String> expected = new HashMap<>();
expected.put("sdf", "sdf");
expected.put("sef", "fds");
Map<String, String> result = dictionaryObject.dictionaryLoad(args);
assertEquals(expected, result);
}
Map<String, String> expected = new HashMap<>();
@Test
public void addWord_AddWordInDictionary_ShouldAddWord() {
ByteArrayInputStream in = new ByteArrayInputStream("4".getBytes());
System.setIn(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<String, String> result = new HashMap<>();
result.put("1", "2");
dictionaryObject.addWord(result, "3", reader);
expected.put("1", "2");
expected.put("3", "4");
assertEquals(expected, result);
}
@Test
public void addWord_Exit_ShouldShowMessage() {
ByteArrayInputStream in = new ByteArrayInputStream("".getBytes());
System.setIn(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<String, String> result = new HashMap<>();
result.put("1", "2");
dictionaryObject.addWord(result, "3", reader);
expected.put("1", "2");
assertEquals(expected, result);
assertEquals("Unknown word '3'. " + dictionaryObject.ENTER_MANUAL + "\r\n" + "Word '3' ignored." + "\r\n", stream.toString());
}
@Test
public void saveWords_SaveSomeString_ShouldSaveCorrectly() {
Map<String, String> dictionary = new HashMap<>();
dictionary.put("1", "2");
dictionary.put("2", "3");
String[] args = {PATH + "saveDictionary.txt"};
dictionaryObject.saveWords(dictionary, args);
Map<String, String> result = dictionaryObject.dictionaryLoad(args); //already tested
Map<String, String> expected = new HashMap<>();
expected.put("1", "2");
expected.put("2", "3");
assertEquals(expected, result);
}
}
|
UTF-8
|
Java
| 4,022 |
java
|
DictionaryTest.java
|
Java
|
[] | null |
[] |
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class DictionaryTest {
public final String PATH = "D://OOP/dudin_oop/lab2/Mini-Dictionary/src/test/resources/";
Dictionary dictionaryObject = new Dictionary();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(stream);
PrintStream originalOutputStream = System.out;
@Before
public void setCustomOutputStream() {
System.setOut(out);
}
@After
public void setOriginalOutputStream() {
System.setOut(originalOutputStream);
}
@Test
public void dictionaryLoad_EmptyArgs_ShouldShowMistakeMessageAndReturnNull() {
String[] args = {};
dictionaryObject.dictionaryLoad(args);
assertEquals(dictionaryObject.MISSING_DICTIONARY + "\r\n" + dictionaryObject.USAGE_METHOD + "\r\n", stream.toString());
}
@Test
public void dictionaryLoad_NonExistFile_ShouldShowMistakeMessageAndReturnNull() {
String[] args = {PATH};
dictionaryObject.dictionaryLoad(args);
assertEquals(dictionaryObject.MISSING_DICTIONARY + "\r\n" + dictionaryObject.USAGE_METHOD + "\r\n", stream.toString());
}
@Test
public void dictionaryLoad_SomeStrings_ShouldReturnMapWithTheseStrings() {
String[] args = {PATH + "dictionarySomeString.txt"};
Map<String, String> expected = new HashMap<>();
expected.put("12", "sdf");
expected.put("sdf", "sdf");
expected.put("sef", "fds");
Map<String, String> result = dictionaryObject.dictionaryLoad(args);
assertEquals(expected, result);
}
@Test
public void dictionaryLoad_SomeStringsWithoutCouple_ShouldReturnMapWithTheseStrings() {
String[] args = {PATH + "dictionarySomeStringWithoutCouple.txt"};
Map<String, String> expected = new HashMap<>();
expected.put("sdf", "sdf");
expected.put("sef", "fds");
Map<String, String> result = dictionaryObject.dictionaryLoad(args);
assertEquals(expected, result);
}
Map<String, String> expected = new HashMap<>();
@Test
public void addWord_AddWordInDictionary_ShouldAddWord() {
ByteArrayInputStream in = new ByteArrayInputStream("4".getBytes());
System.setIn(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<String, String> result = new HashMap<>();
result.put("1", "2");
dictionaryObject.addWord(result, "3", reader);
expected.put("1", "2");
expected.put("3", "4");
assertEquals(expected, result);
}
@Test
public void addWord_Exit_ShouldShowMessage() {
ByteArrayInputStream in = new ByteArrayInputStream("".getBytes());
System.setIn(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<String, String> result = new HashMap<>();
result.put("1", "2");
dictionaryObject.addWord(result, "3", reader);
expected.put("1", "2");
assertEquals(expected, result);
assertEquals("Unknown word '3'. " + dictionaryObject.ENTER_MANUAL + "\r\n" + "Word '3' ignored." + "\r\n", stream.toString());
}
@Test
public void saveWords_SaveSomeString_ShouldSaveCorrectly() {
Map<String, String> dictionary = new HashMap<>();
dictionary.put("1", "2");
dictionary.put("2", "3");
String[] args = {PATH + "saveDictionary.txt"};
dictionaryObject.saveWords(dictionary, args);
Map<String, String> result = dictionaryObject.dictionaryLoad(args); //already tested
Map<String, String> expected = new HashMap<>();
expected.put("1", "2");
expected.put("2", "3");
assertEquals(expected, result);
}
}
| 4,022 | 0.633764 | 0.6273 | 104 | 36.692307 | 30.437855 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.951923 | false | false |
10
|
f185a1a0716a23ca6eee89af55631783a24a3275
| 15,204,184,260,577 |
2f9abbdd0b02c3bc4f4b5ab2e66eff662b7b1af6
|
/app/src/main/java/com/zyp/recordyoyo/utils/PreferenceUtil.java
|
faf0b3c2811af4814766d9e93ce7f82cab837570
|
[] |
no_license
|
DjSasadvs/RecordYoYo
|
https://github.com/DjSasadvs/RecordYoYo
|
84c3ed2080dcdca2e36efd8b1e17dcb6b6c61bc3
|
59113419a4a141b8ba4607b456f119d8afa356e4
|
refs/heads/master
| 2021-05-04T09:44:00.647000 | 2017-04-11T12:10:09 | 2017-04-11T12:10:09 | 44,743,013 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zyp.recordyoyo.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
/**
* Created by zyp on 2016/12/8.
*/
public class PreferenceUtil {
private static final long ONE_DAY_INTERVAL = 24 * 60 * 60 * 1000L;
public static boolean getBoolean(Context context, String key, boolean defaultValue) {
return getPreferences(context).getBoolean(key, defaultValue);
}
public static void putBoolean(Context context, String key, boolean value) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putBoolean(key, value);
editor.commit();
}
public static int getInt(Context context, String key, int defaultValue) {
return getPreferences(context).getInt(key, defaultValue);
}
public static void putInt(Context context, String key, int value) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putInt(key, value);
editor.commit();
}
public static long getLong(Context context, String key, long defaultValue) {
return getPreferences(context).getLong(key, defaultValue);
}
public static void putLong(Context context, String key, long value) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putLong(key, value);
editor.commit();
}
public static String getString(Context context, String key, String defaultValue) {
return getPreferences(context).getString(key, defaultValue);
}
public static void putString(Context context, String key, String value) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putString(key, value);
editor.commit();
}
@SuppressLint("InlinedApi")
public static SharedPreferences getPreferences(Context context) {
if (context != null) {
if (Build.VERSION.SDK_INT >= 11) {
return context.getSharedPreferences(Constants.CONFIG_FILE_NAME, Context.MODE_MULTI_PROCESS);
} else {
return context.getSharedPreferences(Constants.CONFIG_FILE_NAME, Context.MODE_PRIVATE);
}
} else
return null;
}
public static SharedPreferences getDialogPreferences(Context context) {
return context.getSharedPreferences(Constants.DIALOG_FILE_NAME, Context.MODE_PRIVATE);
}
}
|
UTF-8
|
Java
| 2,484 |
java
|
PreferenceUtil.java
|
Java
|
[
{
"context": "ences;\nimport android.os.Build;\n\n/**\n * Created by zyp on 2016/12/8.\n */\n\npublic class PreferenceUtil {\n",
"end": 196,
"score": 0.9995052814483643,
"start": 193,
"tag": "USERNAME",
"value": "zyp"
}
] | null |
[] |
package com.zyp.recordyoyo.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
/**
* Created by zyp on 2016/12/8.
*/
public class PreferenceUtil {
private static final long ONE_DAY_INTERVAL = 24 * 60 * 60 * 1000L;
public static boolean getBoolean(Context context, String key, boolean defaultValue) {
return getPreferences(context).getBoolean(key, defaultValue);
}
public static void putBoolean(Context context, String key, boolean value) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putBoolean(key, value);
editor.commit();
}
public static int getInt(Context context, String key, int defaultValue) {
return getPreferences(context).getInt(key, defaultValue);
}
public static void putInt(Context context, String key, int value) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putInt(key, value);
editor.commit();
}
public static long getLong(Context context, String key, long defaultValue) {
return getPreferences(context).getLong(key, defaultValue);
}
public static void putLong(Context context, String key, long value) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putLong(key, value);
editor.commit();
}
public static String getString(Context context, String key, String defaultValue) {
return getPreferences(context).getString(key, defaultValue);
}
public static void putString(Context context, String key, String value) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putString(key, value);
editor.commit();
}
@SuppressLint("InlinedApi")
public static SharedPreferences getPreferences(Context context) {
if (context != null) {
if (Build.VERSION.SDK_INT >= 11) {
return context.getSharedPreferences(Constants.CONFIG_FILE_NAME, Context.MODE_MULTI_PROCESS);
} else {
return context.getSharedPreferences(Constants.CONFIG_FILE_NAME, Context.MODE_PRIVATE);
}
} else
return null;
}
public static SharedPreferences getDialogPreferences(Context context) {
return context.getSharedPreferences(Constants.DIALOG_FILE_NAME, Context.MODE_PRIVATE);
}
}
| 2,484 | 0.685185 | 0.677536 | 71 | 33.985916 | 32.363468 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.746479 | false | false |
10
|
24b78caa295fc5067ed3b9955899a195951aad8b
| 23,270,132,843,326 |
43cbaf7c55c5f5d2f531934b4a64e4eff091dcb2
|
/library/src/main/java/com/shanyuantech/TextViewBinderStrategry.java
|
2f350e2b8120d6ea9cbc946a9fb73a8f53819456
|
[] |
no_license
|
jiqimaogou/Easy-data-view-binding
|
https://github.com/jiqimaogou/Easy-data-view-binding
|
585aa55522ebbef4defbf36e3b598228ce393e0e
|
d0147331299d6514e61c1a03a7388fb182aa34a7
|
refs/heads/master
| 2015-08-22T20:28:27 | 2015-05-10T02:11:08 | 2015-05-10T02:11:08 | 33,305,747 | 3 | 1 | null | false | 2015-04-14T03:40:18 | 2015-04-02T11:40:11 | 2015-04-07T13:24:25 | 2015-04-14T03:40:18 | 276 | 0 | 1 | 0 |
Java
| null | null |
package com.shanyuantech;
import android.widget.TextView;
/**
* Created by Administrator on 2015/4/15 0015.
*/
public class TextViewBinderStrategry implements BindStrategy<CharSequence, TextView> {
@Override
public void bind(TextView view, CharSequence field) {
if (view == null) {
return;
}
view.setText(field);
}
@Override
public CharSequence collect(TextView view) {
if (view == null) {
return null;
}
return view.getText();
}
}
|
UTF-8
|
Java
| 535 |
java
|
TextViewBinderStrategry.java
|
Java
|
[] | null |
[] |
package com.shanyuantech;
import android.widget.TextView;
/**
* Created by Administrator on 2015/4/15 0015.
*/
public class TextViewBinderStrategry implements BindStrategy<CharSequence, TextView> {
@Override
public void bind(TextView view, CharSequence field) {
if (view == null) {
return;
}
view.setText(field);
}
@Override
public CharSequence collect(TextView view) {
if (view == null) {
return null;
}
return view.getText();
}
}
| 535 | 0.607477 | 0.586916 | 26 | 19.576923 | 20.879089 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false |
10
|
15ee01dd719cc3f9f4f3579d42e22b646de8b462
| 17,437,567,287,824 |
a344b30c3a43b0b72f1f6f86b670a4f96678e0a8
|
/src/main/java/nirusu/nirubot/util/tictactoe/TicTacToeGame.java
|
ea7a77a878beccfc55e6361a6f842953df29565e
|
[
"MIT"
] |
permissive
|
CDaut/nirubot
|
https://github.com/CDaut/nirubot
|
6f56bb788551595a3e88333e7796eb29ba9b2e93
|
b897c0390322a5a678a8bd168118e69021418e39
|
refs/heads/master
| 2023-05-03T16:00:09.167000 | 2021-02-01T14:11:01 | 2021-02-01T14:11:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package nirusu.nirubot.util.tictactoe;
import discord4j.common.util.Snowflake;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class TicTacToeGame {
/**
* This HashMap stores the player and the game. Stores Two instances per game.
*/
public static final Map<Snowflake, TicTacToeGame> games = new HashMap<>();
private Snowflake playerOne;
private Snowflake playerTwo;
private Snowflake playerToMove;
private TTTBoard board;
public TicTacToeGame(Snowflake playerOne, Snowflake playerTwo) {
this.playerOne = playerOne;
this.playerTwo = playerTwo;
//player one always starts
this.playerToMove = playerOne;
this.board = new TTTBoard();
}
public Snowflake getPlayerOne() {
return playerOne;
}
public Snowflake getPlayerTwo() {
return playerTwo;
}
public Snowflake getPlayerToMove() {
return playerToMove;
}
public TTTBoard getBoard() {
return board;
}
//switch the next player to move
public void advanceUser() {
if (this.playerToMove.equals(this.getPlayerOne())) {
this.playerToMove = this.playerTwo;
return;
}
if (this.playerToMove.equals(this.getPlayerTwo())) {
this.playerToMove = this.playerOne;
}
}
public Optional<Snowflake> getWinner() {
int rowCounter = 0;
int colCounter = 0;
int mainDiagonalCounter = 0;
int secondaryDiagonalCounter = 0;
//sum over rows and cols
for (int y = 0; y < TTTBoard.BOARD_SIZE; y++) {
for (int x = 0; x < TTTBoard.BOARD_SIZE; x++) {
rowCounter += this.getBoard().getArray()[y][x];
colCounter += this.getBoard().getArray()[x][y];
}
//increment diagonal counters
mainDiagonalCounter += this.getBoard().getArray()[y][y];
secondaryDiagonalCounter += this.getBoard()
.getArray()[TTTBoard.BOARD_SIZE - y - 1][TTTBoard.BOARD_SIZE - y - 1];
//check if player one won
if (rowCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_ONE
|| colCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_ONE
|| mainDiagonalCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_ONE
|| secondaryDiagonalCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_ONE) {
return Optional.of(this.playerOne);
}
//check if player two won
if (rowCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_TWO
|| colCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_TWO
|| mainDiagonalCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_TWO
|| secondaryDiagonalCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_TWO) {
return Optional.of(this.playerTwo);
}
//reset counters
rowCounter = 0;
colCounter = 0;
}
//nobody won
return Optional.empty();
}
public int evalPlayer(Snowflake player) {
if (player.equals(this.getPlayerOne())) return TTTBoard.PLAYER_ONE;
if (player.equals(this.getPlayerTwo())) return TTTBoard.PLAYER_TWO;
return TTTBoard.NOPLAYER;
}
}
|
UTF-8
|
Java
| 3,379 |
java
|
TicTacToeGame.java
|
Java
|
[] | null |
[] |
package nirusu.nirubot.util.tictactoe;
import discord4j.common.util.Snowflake;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class TicTacToeGame {
/**
* This HashMap stores the player and the game. Stores Two instances per game.
*/
public static final Map<Snowflake, TicTacToeGame> games = new HashMap<>();
private Snowflake playerOne;
private Snowflake playerTwo;
private Snowflake playerToMove;
private TTTBoard board;
public TicTacToeGame(Snowflake playerOne, Snowflake playerTwo) {
this.playerOne = playerOne;
this.playerTwo = playerTwo;
//player one always starts
this.playerToMove = playerOne;
this.board = new TTTBoard();
}
public Snowflake getPlayerOne() {
return playerOne;
}
public Snowflake getPlayerTwo() {
return playerTwo;
}
public Snowflake getPlayerToMove() {
return playerToMove;
}
public TTTBoard getBoard() {
return board;
}
//switch the next player to move
public void advanceUser() {
if (this.playerToMove.equals(this.getPlayerOne())) {
this.playerToMove = this.playerTwo;
return;
}
if (this.playerToMove.equals(this.getPlayerTwo())) {
this.playerToMove = this.playerOne;
}
}
public Optional<Snowflake> getWinner() {
int rowCounter = 0;
int colCounter = 0;
int mainDiagonalCounter = 0;
int secondaryDiagonalCounter = 0;
//sum over rows and cols
for (int y = 0; y < TTTBoard.BOARD_SIZE; y++) {
for (int x = 0; x < TTTBoard.BOARD_SIZE; x++) {
rowCounter += this.getBoard().getArray()[y][x];
colCounter += this.getBoard().getArray()[x][y];
}
//increment diagonal counters
mainDiagonalCounter += this.getBoard().getArray()[y][y];
secondaryDiagonalCounter += this.getBoard()
.getArray()[TTTBoard.BOARD_SIZE - y - 1][TTTBoard.BOARD_SIZE - y - 1];
//check if player one won
if (rowCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_ONE
|| colCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_ONE
|| mainDiagonalCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_ONE
|| secondaryDiagonalCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_ONE) {
return Optional.of(this.playerOne);
}
//check if player two won
if (rowCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_TWO
|| colCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_TWO
|| mainDiagonalCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_TWO
|| secondaryDiagonalCounter == TTTBoard.BOARD_SIZE * TTTBoard.PLAYER_TWO) {
return Optional.of(this.playerTwo);
}
//reset counters
rowCounter = 0;
colCounter = 0;
}
//nobody won
return Optional.empty();
}
public int evalPlayer(Snowflake player) {
if (player.equals(this.getPlayerOne())) return TTTBoard.PLAYER_ONE;
if (player.equals(this.getPlayerTwo())) return TTTBoard.PLAYER_TWO;
return TTTBoard.NOPLAYER;
}
}
| 3,379 | 0.593371 | 0.590115 | 103 | 31.805826 | 26.599167 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533981 | false | false |
10
|
34635dab685e1c159301475db799f0392e9a73c4
| 9,586,367,014,829 |
cfd400dc79e1cc771bc60e17e984f14ff10a7e6e
|
/workspaceLWJGL/Arc2D/src/net/stinfoservices/helias/renaud/tempest/server/Serveur.java
|
75dfb229b79bfc6931a92a4ba460d46fef9794aa
|
[] |
no_license
|
renaudhelias/MissileCommandDeluxe_workspaceLWJGL-THSF1984-2014
|
https://github.com/renaudhelias/MissileCommandDeluxe_workspaceLWJGL-THSF1984-2014
|
b8267ff6ddb63d6fdf1e3e4fadcb9a10894548eb
|
e60a6fd6bb494b386dffb4952898b5d4a276dc1d
|
refs/heads/master
| 2020-05-21T17:23:52.623000 | 2017-06-22T21:57:09 | 2017-06-22T21:57:09 | 84,638,571 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.stinfoservices.helias.renaud.tempest.server;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Serveur implements Runnable {
private final static boolean STOP_DTO = false;
private final static boolean DEBUG = false;
ServerSocket socket;
private ObjectOutputStream output;
private Socket pipe;
private Thread thread;
private boolean stop = false;
private long pollSize = 0;
private IPullMissiles pullable;
public Serveur() {
try {
socket = new ServerSocket(12321);
pipe = socket.accept();
System.out.println("hello ");
output = new ObjectOutputStream(pipe.getOutputStream());
thread = new Thread(this);
thread.start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void poll(IPullMissiles pullable) {
if (!STOP_DTO) {
this.pullable = pullable;
}
if (DEBUG) {
pollSize++;
}
}
@Override
public void run() {
try {
while (!stop ) {
kick();
Thread.sleep(100);
}
output.writeBoolean(false);
output.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private synchronized void kick() throws IOException {
if (pullable == null) return;
output.writeObject(pullable.getMissiles());
if (DEBUG) {
System.out.println("Serveur polling : "+pollSize);
pollSize = 0;
}
}
public synchronized void stop() {
stop = true;
}
}
|
UTF-8
|
Java
| 1,613 |
java
|
Serveur.java
|
Java
|
[] | null |
[] |
package net.stinfoservices.helias.renaud.tempest.server;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Serveur implements Runnable {
private final static boolean STOP_DTO = false;
private final static boolean DEBUG = false;
ServerSocket socket;
private ObjectOutputStream output;
private Socket pipe;
private Thread thread;
private boolean stop = false;
private long pollSize = 0;
private IPullMissiles pullable;
public Serveur() {
try {
socket = new ServerSocket(12321);
pipe = socket.accept();
System.out.println("hello ");
output = new ObjectOutputStream(pipe.getOutputStream());
thread = new Thread(this);
thread.start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void poll(IPullMissiles pullable) {
if (!STOP_DTO) {
this.pullable = pullable;
}
if (DEBUG) {
pollSize++;
}
}
@Override
public void run() {
try {
while (!stop ) {
kick();
Thread.sleep(100);
}
output.writeBoolean(false);
output.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private synchronized void kick() throws IOException {
if (pullable == null) return;
output.writeObject(pullable.getMissiles());
if (DEBUG) {
System.out.println("Serveur polling : "+pollSize);
pollSize = 0;
}
}
public synchronized void stop() {
stop = true;
}
}
| 1,613 | 0.689399 | 0.683199 | 76 | 20.223684 | 16.25099 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.092105 | false | false |
10
|
971cfb9bde62887374513f21d1f98476fb2676ba
| 20,581,483,303,395 |
59764e41b1542da9679e4f53b1c3ffb58a201aec
|
/commonlib/src/main/java/qa/webdriver/util/grid/GridServer.java
|
ed00d833c680aef908fbc8433ae66000ed6eb44a
|
[
"AFL-2.1",
"AFL-3.0"
] |
permissive
|
haiyun-document/WebDriverTestingTemplate
|
https://github.com/haiyun-document/WebDriverTestingTemplate
|
9fc3cc55139466307caee352f0384dc4c07c788a
|
40cd91191cd4d4085800b6597d7658a12948786b
|
refs/heads/master
| 2021-01-24T04:23:40.173000 | 2013-03-01T03:38:59 | 2013-03-01T03:39:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package qa.webdriver.util.grid;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.openqa.grid.common.GridRole;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.common.SeleniumProtocol;
import org.openqa.grid.internal.utils.GridHubConfiguration;
import org.openqa.grid.internal.utils.SelfRegisteringRemote;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* Runs a Selenium Hub Server for handling RemoteWebDriver browser
* remote control requests. Uses JSON protocol.
*/
public class GridServer {
Hub myHub = null;
SelfRegisteringRemote remoteFirefoxNode = null;
SelfRegisteringRemote remoteChromeNode = null;
/**
* Starts a default new instance of WebDriver Hub JSON server
*/
public GridServer () {
bringUpHubAndNode( "localhost", 4444, "firefox" );
}
/**
* Starts a defined new instance of WebDriver Hub JSON server
*/
public GridServer ( String hostName, int portNumber, String browserType ) {
bringUpHubAndNode( hostName, portNumber, browserType );
}
/**
* Starts a defined new instance of WebDriver Hub JSON server
*/
public GridServer ( String jsonConfigLoc ) {
bringUpHubAndNodeFromJSONConfig( jsonConfigLoc );
}
/**
* This class can be ran as a standalone server directly.
* @param none
*/
public static void main(String[] args) {
new GridServer();
}
public void bringUpHubAndNode( String hubHost, int hubPort, String browserType ) {
GridHubConfiguration gridHubConfig = new GridHubConfiguration();
gridHubConfig.setHost( hubHost );
gridHubConfig.setPort( hubPort );
myHub = new Hub( gridHubConfig );
try {
myHub.start();
} catch (Exception e) {
System.out.println("Error starting hub on port " + gridHubConfig.getPort() );
e.printStackTrace();
}
if ( browserType.equalsIgnoreCase("firefox") ) {
int ffPort = 5555;
System.out.println( "Connecting Firefox node on port " + ffPort + " to hub on port " + hubPort );
try {
remoteFirefoxNode = attachNodeToHub( DesiredCapabilities.firefox(), GridRole.NODE, ffPort, SeleniumProtocol.WebDriver );
System.out.println("maxInstances is " + remoteFirefoxNode.getConfiguration().get("maxInstances") );
} catch (Exception e) {
System.out.println("Error attaching Firefox node.");
e.printStackTrace();
}
} else if ( browserType.equalsIgnoreCase( "chrome" ) ) {
int cPort = 5556;
System.out.println( "Connecting Chrome node to hub on port " + cPort + " to hub on port " + hubPort );
DesiredCapabilities chrome = DesiredCapabilities.chrome();
chrome.setBrowserName("*googlechrome");
try {
remoteChromeNode = attachNodeToHub( chrome, GridRole.NODE, cPort, SeleniumProtocol.Selenium );
} catch (Exception e) {
System.out.println("Error attaching Chrome node.");
e.printStackTrace();
}
}
}
public void bringUpHubAndNodeFromJSONConfig( String configFile ) {
GridHubConfiguration gridHubConfig = new GridHubConfiguration();
gridHubConfig.loadFromJSON( "build/resources/test/WebDriver.json" );
myHub = new Hub( gridHubConfig );
try {
myHub.start();
} catch ( Exception e ) {
System.out.println("Error starting hub.");
e.printStackTrace();
}
DesiredCapabilities chrome = DesiredCapabilities.chrome();
chrome.setBrowserName("*googlechrome");
try {
//TODO I am not sure why we need to start 2 separate nodes here
// for each browser type. This isn't my original code.
remoteFirefoxNode = attachNodeToHub( DesiredCapabilities.firefox(), GridRole.NODE, 5555, SeleniumProtocol.WebDriver );
remoteChromeNode = attachNodeToHub( chrome, GridRole.NODE, 5556, SeleniumProtocol.Selenium );
} catch (Exception e) {
System.out.println("Error attaching node.");
e.printStackTrace();
}
}
/* Call multiple times to register more than one Node
*
*/
private SelfRegisteringRemote attachNodeToHub( DesiredCapabilities capability, GridRole role,
int nodePort, SeleniumProtocol protocol) throws Exception {
SelfRegisteringRemote node = null;
RegistrationRequest registrationRequest = new RegistrationRequest();
capability.setCapability( "seleniumProtocol", protocol );
registrationRequest.addDesiredCapability( capability );
registrationRequest.setRole(role);
registrationRequest.setConfiguration( fetchNodeConfiguration(role, nodePort, protocol) );
node = new SelfRegisteringRemote( registrationRequest );
node.startRemoteServer();
node.startRegistrationProcess();
return node;
}
private Map<String, Object> fetchNodeConfiguration(GridRole role, int portToRun, SeleniumProtocol protocol)
throws MalformedURLException {
Map<String, Object> nodeConfiguration = new HashMap<String, Object>();
nodeConfiguration.put( RegistrationRequest.AUTO_REGISTER, true );
nodeConfiguration.put( RegistrationRequest.HUB_HOST, myHub.getHost() );
nodeConfiguration.put( RegistrationRequest.HUB_PORT, myHub.getPort() );
nodeConfiguration.put( RegistrationRequest.PORT, portToRun);
URL remoteURL = new URL("http://" + myHub.getHost() + ":" + portToRun );
nodeConfiguration.put( RegistrationRequest.PROXY_CLASS, "org.openqa.grid.selenium.proxy.DefaultRemoteProxy" );
nodeConfiguration.put( RegistrationRequest.MAX_SESSION, 5 );
nodeConfiguration.put( RegistrationRequest.CLEAN_UP_CYCLE, 2000 );
nodeConfiguration.put( RegistrationRequest.REMOTE_HOST, remoteURL );
nodeConfiguration.put( RegistrationRequest.MAX_INSTANCES, 5 );
return nodeConfiguration;
}
public void shutDownNodeAndHub() {
if (remoteFirefoxNode != null) {
remoteFirefoxNode.stopRemoteServer();
System.out.println("Firefox Node shutdown");
}
if (remoteChromeNode != null) {
remoteChromeNode.stopRemoteServer();
System.out.println("Chrome Node shutdown");
}
if ( myHub != null ) {
try {
myHub.stop();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Local hub shutdown");
}
}
}
|
UTF-8
|
Java
| 6,023 |
java
|
GridServer.java
|
Java
|
[] | null |
[] |
package qa.webdriver.util.grid;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.openqa.grid.common.GridRole;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.common.SeleniumProtocol;
import org.openqa.grid.internal.utils.GridHubConfiguration;
import org.openqa.grid.internal.utils.SelfRegisteringRemote;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* Runs a Selenium Hub Server for handling RemoteWebDriver browser
* remote control requests. Uses JSON protocol.
*/
public class GridServer {
Hub myHub = null;
SelfRegisteringRemote remoteFirefoxNode = null;
SelfRegisteringRemote remoteChromeNode = null;
/**
* Starts a default new instance of WebDriver Hub JSON server
*/
public GridServer () {
bringUpHubAndNode( "localhost", 4444, "firefox" );
}
/**
* Starts a defined new instance of WebDriver Hub JSON server
*/
public GridServer ( String hostName, int portNumber, String browserType ) {
bringUpHubAndNode( hostName, portNumber, browserType );
}
/**
* Starts a defined new instance of WebDriver Hub JSON server
*/
public GridServer ( String jsonConfigLoc ) {
bringUpHubAndNodeFromJSONConfig( jsonConfigLoc );
}
/**
* This class can be ran as a standalone server directly.
* @param none
*/
public static void main(String[] args) {
new GridServer();
}
public void bringUpHubAndNode( String hubHost, int hubPort, String browserType ) {
GridHubConfiguration gridHubConfig = new GridHubConfiguration();
gridHubConfig.setHost( hubHost );
gridHubConfig.setPort( hubPort );
myHub = new Hub( gridHubConfig );
try {
myHub.start();
} catch (Exception e) {
System.out.println("Error starting hub on port " + gridHubConfig.getPort() );
e.printStackTrace();
}
if ( browserType.equalsIgnoreCase("firefox") ) {
int ffPort = 5555;
System.out.println( "Connecting Firefox node on port " + ffPort + " to hub on port " + hubPort );
try {
remoteFirefoxNode = attachNodeToHub( DesiredCapabilities.firefox(), GridRole.NODE, ffPort, SeleniumProtocol.WebDriver );
System.out.println("maxInstances is " + remoteFirefoxNode.getConfiguration().get("maxInstances") );
} catch (Exception e) {
System.out.println("Error attaching Firefox node.");
e.printStackTrace();
}
} else if ( browserType.equalsIgnoreCase( "chrome" ) ) {
int cPort = 5556;
System.out.println( "Connecting Chrome node to hub on port " + cPort + " to hub on port " + hubPort );
DesiredCapabilities chrome = DesiredCapabilities.chrome();
chrome.setBrowserName("*googlechrome");
try {
remoteChromeNode = attachNodeToHub( chrome, GridRole.NODE, cPort, SeleniumProtocol.Selenium );
} catch (Exception e) {
System.out.println("Error attaching Chrome node.");
e.printStackTrace();
}
}
}
public void bringUpHubAndNodeFromJSONConfig( String configFile ) {
GridHubConfiguration gridHubConfig = new GridHubConfiguration();
gridHubConfig.loadFromJSON( "build/resources/test/WebDriver.json" );
myHub = new Hub( gridHubConfig );
try {
myHub.start();
} catch ( Exception e ) {
System.out.println("Error starting hub.");
e.printStackTrace();
}
DesiredCapabilities chrome = DesiredCapabilities.chrome();
chrome.setBrowserName("*googlechrome");
try {
//TODO I am not sure why we need to start 2 separate nodes here
// for each browser type. This isn't my original code.
remoteFirefoxNode = attachNodeToHub( DesiredCapabilities.firefox(), GridRole.NODE, 5555, SeleniumProtocol.WebDriver );
remoteChromeNode = attachNodeToHub( chrome, GridRole.NODE, 5556, SeleniumProtocol.Selenium );
} catch (Exception e) {
System.out.println("Error attaching node.");
e.printStackTrace();
}
}
/* Call multiple times to register more than one Node
*
*/
private SelfRegisteringRemote attachNodeToHub( DesiredCapabilities capability, GridRole role,
int nodePort, SeleniumProtocol protocol) throws Exception {
SelfRegisteringRemote node = null;
RegistrationRequest registrationRequest = new RegistrationRequest();
capability.setCapability( "seleniumProtocol", protocol );
registrationRequest.addDesiredCapability( capability );
registrationRequest.setRole(role);
registrationRequest.setConfiguration( fetchNodeConfiguration(role, nodePort, protocol) );
node = new SelfRegisteringRemote( registrationRequest );
node.startRemoteServer();
node.startRegistrationProcess();
return node;
}
private Map<String, Object> fetchNodeConfiguration(GridRole role, int portToRun, SeleniumProtocol protocol)
throws MalformedURLException {
Map<String, Object> nodeConfiguration = new HashMap<String, Object>();
nodeConfiguration.put( RegistrationRequest.AUTO_REGISTER, true );
nodeConfiguration.put( RegistrationRequest.HUB_HOST, myHub.getHost() );
nodeConfiguration.put( RegistrationRequest.HUB_PORT, myHub.getPort() );
nodeConfiguration.put( RegistrationRequest.PORT, portToRun);
URL remoteURL = new URL("http://" + myHub.getHost() + ":" + portToRun );
nodeConfiguration.put( RegistrationRequest.PROXY_CLASS, "org.openqa.grid.selenium.proxy.DefaultRemoteProxy" );
nodeConfiguration.put( RegistrationRequest.MAX_SESSION, 5 );
nodeConfiguration.put( RegistrationRequest.CLEAN_UP_CYCLE, 2000 );
nodeConfiguration.put( RegistrationRequest.REMOTE_HOST, remoteURL );
nodeConfiguration.put( RegistrationRequest.MAX_INSTANCES, 5 );
return nodeConfiguration;
}
public void shutDownNodeAndHub() {
if (remoteFirefoxNode != null) {
remoteFirefoxNode.stopRemoteServer();
System.out.println("Firefox Node shutdown");
}
if (remoteChromeNode != null) {
remoteChromeNode.stopRemoteServer();
System.out.println("Chrome Node shutdown");
}
if ( myHub != null ) {
try {
myHub.stop();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Local hub shutdown");
}
}
}
| 6,023 | 0.738336 | 0.733854 | 165 | 35.503029 | 30.399487 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.509091 | false | false |
10
|
c6299e652391d73a4cb3d092bf41485bbd166fe3
| 22,153,441,313,437 |
0eb1e5599d599a9c270fc23c6a812df3bf7493c7
|
/src/main/java/tn/training/cni/controller/UserController.java
|
8d07c0806c984a830733d5f8e576307954d403b1
|
[] |
no_license
|
AbdelbassetNoomene/springboot-app
|
https://github.com/AbdelbassetNoomene/springboot-app
|
41ff3ef3004ddd44aa255e53a64aed76163f4727
|
e7726c2118d46849fcaa0f22fa5808f4f2a3e62b
|
refs/heads/master
| 2020-08-07T05:15:24.127000 | 2019-11-22T22:56:41 | 2019-11-22T22:56:41 | 213,312,191 | 0 | 0 | null | false | 2019-11-25T08:16:54 | 2019-10-07T06:38:15 | 2019-11-22T22:56:44 | 2019-11-25T08:16:53 | 32 | 0 | 0 | 0 |
Java
| false | false |
package tn.training.cni.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tn.training.cni.dto.UserDTO;
import tn.training.cni.model.User;
import tn.training.cni.service.UserService;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
UserService userService;
@GetMapping("")
List<UserDTO>getListUsers() {
return userService.getListUSers();
}
@GetMapping("/{id}")
UserDTO getUserDetails(@PathVariable long id) {
return userService.findById(id);
}
@PostMapping("")
//@PreAuthorize("hasRole('ADMIN')")
UserDTO addUser(@RequestBody User user) throws Exception{
return userService.saveUser(user);
}
@PutMapping("")
UserDTO updateUser(@RequestBody User user) throws Exception {
return userService.saveUser(user);
}
@DeleteMapping("/{id}")
void deleteUser(@PathVariable long id) {
userService.deleteUser(id);
}
}
|
UTF-8
|
Java
| 1,521 |
java
|
UserController.java
|
Java
|
[] | null |
[] |
package tn.training.cni.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tn.training.cni.dto.UserDTO;
import tn.training.cni.model.User;
import tn.training.cni.service.UserService;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
UserService userService;
@GetMapping("")
List<UserDTO>getListUsers() {
return userService.getListUSers();
}
@GetMapping("/{id}")
UserDTO getUserDetails(@PathVariable long id) {
return userService.findById(id);
}
@PostMapping("")
//@PreAuthorize("hasRole('ADMIN')")
UserDTO addUser(@RequestBody User user) throws Exception{
return userService.saveUser(user);
}
@PutMapping("")
UserDTO updateUser(@RequestBody User user) throws Exception {
return userService.saveUser(user);
}
@DeleteMapping("/{id}")
void deleteUser(@PathVariable long id) {
userService.deleteUser(id);
}
}
| 1,521 | 0.788955 | 0.788955 | 56 | 26.160715 | 22.556103 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.053571 | false | false |
10
|
b315f83ddf99c4b3bbf9c9dd23eb2aadb9fcaa64
| 21,036,749,819,105 |
eb14055be6c597843a9383fc1ec2ab71dea5e7e1
|
/src/LeetCode/201 - 250/src/PalidromLinkedList.java
|
17da320ae8a10d78e4bc1997c579295d17394545
|
[] |
no_license
|
Jessica121/Algorithms
|
https://github.com/Jessica121/Algorithms
|
f529d00298404a369ee515b88136939d285b0d06
|
10509f2ad7e5a14c615b067d0ffb338975c9ccb9
|
refs/heads/master
| 2021-01-25T14:46:24.524000 | 2019-01-28T04:35:59 | 2019-01-28T04:35:59 | 123,727,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class PalidromLinkedList {
/*
recursion: know when it is even or when it is odd.
if odd, return next when itself is the mid. else return itself.
check recursion false or true first. else return false and where it went wrong.
compare itself with the recursion, if equal, return recursion's next.
else return false. have a class wrap them.
*/
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return fast == null ? check(head, slow, true).isP : check(head, slow, false).isP;
}
private Ret check(ListNode node, ListNode mid, boolean isEven) {
if(node == mid) return new Ret((isEven ? node : node.next), true);
Ret next = check(node.next, mid, isEven);
if(!next.isP) return next;
if(node.val != next.node.val) return new Ret(node, false);
return new Ret(next.node.next, true);
}
class Ret {
boolean isP;
ListNode node;
public Ret(ListNode node, boolean isP) {
this.isP = isP;
this.node = node;
}
}
}
|
UTF-8
|
Java
| 1,239 |
java
|
PalidromLinkedList.java
|
Java
|
[] | null |
[] |
public class PalidromLinkedList {
/*
recursion: know when it is even or when it is odd.
if odd, return next when itself is the mid. else return itself.
check recursion false or true first. else return false and where it went wrong.
compare itself with the recursion, if equal, return recursion's next.
else return false. have a class wrap them.
*/
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return fast == null ? check(head, slow, true).isP : check(head, slow, false).isP;
}
private Ret check(ListNode node, ListNode mid, boolean isEven) {
if(node == mid) return new Ret((isEven ? node : node.next), true);
Ret next = check(node.next, mid, isEven);
if(!next.isP) return next;
if(node.val != next.node.val) return new Ret(node, false);
return new Ret(next.node.next, true);
}
class Ret {
boolean isP;
ListNode node;
public Ret(ListNode node, boolean isP) {
this.isP = isP;
this.node = node;
}
}
}
| 1,239 | 0.590799 | 0.590799 | 35 | 34.371429 | 25.825884 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.828571 | false | false |
10
|
6d7ca9922a05b05f1feafca8136cd62a7704df29
| 31,499,290,202,637 |
472739663acdc7aa9932abf17a2df9bd589a278e
|
/tcc-transaction-grpc/src/main/java/org/mengyun/tcctransaction/grpc/interceptor/TransactionContextServerInterceptor.java
|
0f449f44197e59264b1e67d4ce6cdb7287a80894
|
[
"Apache-2.0"
] |
permissive
|
changmingxie/tcc-transaction
|
https://github.com/changmingxie/tcc-transaction
|
85eef45895fb113b68a545024986f0668ac6522b
|
d21a3d748c477fb14a175d5d05e54ef82cf68de6
|
refs/heads/master-2.x
| 2023-08-31T21:07:17.124000 | 2023-08-16T08:44:45 | 2023-08-16T08:44:45 | 47,442,228 | 6,057 | 2,894 |
Apache-2.0
| false | 2023-08-16T08:44:46 | 2015-12-05T04:27:53 | 2023-08-16T03:45:12 | 2023-08-16T08:44:45 | 7,303 | 5,657 | 2,798 | 29 |
Java
| false | false |
package org.mengyun.tcctransaction.grpc.interceptor;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import org.mengyun.tcctransaction.api.TransactionContext;
import org.mengyun.tcctransaction.grpc.constants.TransactionContextConstants;
import org.mengyun.tcctransaction.serializer.TransactionContextSerializer;
/**
* @author Nervose.Wu
* @date 2022/6/24 16:36
*/
public class TransactionContextServerInterceptor implements ServerInterceptor {
private TransactionContextSerializer serializer = new TransactionContextSerializer();
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) {
TransactionContext transactionContext = getTransactionContext(metadata);
return new ServerListenerProxy<>(transactionContext, serverCallHandler.startCall(serverCall, metadata));
}
private TransactionContext getTransactionContext(Metadata metadata) {
byte[] transactionContextBytes = metadata.get(TransactionContextConstants.TRANSACTION_CONTEXT_HEADER_KEY);
return serializer.deserialize(transactionContextBytes);
}
}
|
UTF-8
|
Java
| 1,261 |
java
|
TransactionContextServerInterceptor.java
|
Java
|
[
{
"context": "izer.TransactionContextSerializer;\n\n/**\n * @author Nervose.Wu\n * @date 2022/6/24 16:36\n */\npublic class Transac",
"end": 411,
"score": 0.9944717884063721,
"start": 401,
"tag": "NAME",
"value": "Nervose.Wu"
}
] | null |
[] |
package org.mengyun.tcctransaction.grpc.interceptor;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import org.mengyun.tcctransaction.api.TransactionContext;
import org.mengyun.tcctransaction.grpc.constants.TransactionContextConstants;
import org.mengyun.tcctransaction.serializer.TransactionContextSerializer;
/**
* @author Nervose.Wu
* @date 2022/6/24 16:36
*/
public class TransactionContextServerInterceptor implements ServerInterceptor {
private TransactionContextSerializer serializer = new TransactionContextSerializer();
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) {
TransactionContext transactionContext = getTransactionContext(metadata);
return new ServerListenerProxy<>(transactionContext, serverCallHandler.startCall(serverCall, metadata));
}
private TransactionContext getTransactionContext(Metadata metadata) {
byte[] transactionContextBytes = metadata.get(TransactionContextConstants.TRANSACTION_CONTEXT_HEADER_KEY);
return serializer.deserialize(transactionContextBytes);
}
}
| 1,261 | 0.808089 | 0.799366 | 29 | 42.482758 | 43.289421 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false |
10
|
d17415cf12f731e1790220017b01c88cd77a041f
| 26,723,286,562,137 |
a985945fcb7c39699bd7d2cee1b873c705edd769
|
/systests/protocol-tests-amqp-0-8/src/test/java/org/apache/qpid/tests/protocol/v0_8/ChannelTest.java
|
3b069c48659ff23086ab5684a77f3729bcddf5e2
|
[
"Apache-2.0",
"GPL-2.0-only",
"CDDL-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
apache/qpid-broker-j
|
https://github.com/apache/qpid-broker-j
|
09bf66e694d8dfba74e8ee62f51b631327402d8f
|
c7b6edfade1e2c99c1b06efea51ea34f0fc4868f
|
refs/heads/main
| 2023-09-03T19:57:44.709000 | 2023-08-25T09:28:33 | 2023-08-25T09:28:33 | 88,711,981 | 64 | 52 |
Apache-2.0
| false | 2023-09-05T11:08:45 | 2017-04-19T07:00:07 | 2023-07-25T14:08:30 | 2023-09-05T11:08:44 | 147,059 | 54 | 46 | 8 |
Java
| false | false |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.tests.protocol.v0_8;
import org.junit.jupiter.api.Test;
import org.apache.qpid.server.protocol.v0_8.transport.ChannelCloseOkBody;
import org.apache.qpid.server.protocol.v0_8.transport.ChannelOpenOkBody;
import org.apache.qpid.server.protocol.v0_8.transport.ConnectionCloseBody;
import org.apache.qpid.tests.protocol.SpecificationTest;
import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
public class ChannelTest extends BrokerAdminUsingTestBase
{
@Test
@SpecificationTest(section = "1.5.2.1", description = "open a channel for use")
public void channelOpen() throws Exception
{
try (FrameTransport transport = new FrameTransport(getBrokerAdmin()).connect())
{
final Interaction interaction = transport.newInteraction();
interaction.negotiateOpen()
.channelId(1)
.channel().open().consumeResponse(ChannelOpenOkBody.class);
}
}
@Test
@SpecificationTest(section = "1.5.2.5", description = "request a channel close")
public void noFrameCanBeSentOnClosedChannel() throws Exception
{
try (FrameTransport transport = new FrameTransport(getBrokerAdmin()).connect())
{
final Interaction interaction = transport.newInteraction();
interaction.negotiateOpen()
.channelId(1)
.channel().open().consumeResponse(ChannelOpenOkBody.class)
.channel().close().consumeResponse(ChannelCloseOkBody.class)
.channel().flow(true).consumeResponse(ConnectionCloseBody.class);
}
}
}
|
UTF-8
|
Java
| 2,482 |
java
|
ChannelTest.java
|
Java
|
[] | null |
[] |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.tests.protocol.v0_8;
import org.junit.jupiter.api.Test;
import org.apache.qpid.server.protocol.v0_8.transport.ChannelCloseOkBody;
import org.apache.qpid.server.protocol.v0_8.transport.ChannelOpenOkBody;
import org.apache.qpid.server.protocol.v0_8.transport.ConnectionCloseBody;
import org.apache.qpid.tests.protocol.SpecificationTest;
import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
public class ChannelTest extends BrokerAdminUsingTestBase
{
@Test
@SpecificationTest(section = "1.5.2.1", description = "open a channel for use")
public void channelOpen() throws Exception
{
try (FrameTransport transport = new FrameTransport(getBrokerAdmin()).connect())
{
final Interaction interaction = transport.newInteraction();
interaction.negotiateOpen()
.channelId(1)
.channel().open().consumeResponse(ChannelOpenOkBody.class);
}
}
@Test
@SpecificationTest(section = "1.5.2.5", description = "request a channel close")
public void noFrameCanBeSentOnClosedChannel() throws Exception
{
try (FrameTransport transport = new FrameTransport(getBrokerAdmin()).connect())
{
final Interaction interaction = transport.newInteraction();
interaction.negotiateOpen()
.channelId(1)
.channel().open().consumeResponse(ChannelOpenOkBody.class)
.channel().close().consumeResponse(ChannelCloseOkBody.class)
.channel().flow(true).consumeResponse(ConnectionCloseBody.class);
}
}
}
| 2,482 | 0.69581 | 0.686946 | 63 | 38.396824 | 31.145098 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
10
|
cfd50f468fa539b817fa09c992315abad6f30523
| 5,196,910,483,491 |
3677d237233040c64d4b2920afb42387a341e84b
|
/Aten/MOA/code/src/org/eapp/oa/device/blo/IDeviceAllocateBiz.java
|
73e7dfc4d0fddca74239fe61c26575a881fe003a
|
[] |
no_license
|
xeonye/aten-project
|
https://github.com/xeonye/aten-project
|
0c93b5be2dca9d7c74ad63c3092270d4434e547b
|
4a0178552b2604c24da0ee40d813920f4daffdaf
|
refs/heads/master
| 2020-05-31T15:29:02.928000 | 2015-07-22T14:42:22 | 2015-07-22T14:42:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.eapp.oa.device.blo;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eapp.oa.device.dto.DevAllocateQueryParameters;
import org.eapp.oa.device.hbean.DevAllocateForm;
import org.eapp.oa.device.hbean.DevAllocateList;
import org.eapp.oa.flow.hbean.Task;
import org.eapp.util.hibernate.ListPage;
import org.eapp.oa.system.exception.OaException;
/**
* @author tim
* 调拨单
*/
public interface IDeviceAllocateBiz {
/**
* 查询调拨单列表
* @param userAccountId
* @param formStatus
* @return
*/
public List<DevAllocateForm> queryAllocateForm(String userAccountId, int formStatus);
/**
* 通过Id查询调拨单
* @param id
* @param initList
* @param initDevCfgList 是否初始化设备配置信息
* @return
*/
public DevAllocateForm getDevAllocateFormById(String id, boolean initList, boolean initDevCfgList);
/**
* 删除调拨单
* @param id
* @param accountId
* @throws OaException
*/
public void txDelDevAllocateForm(String id) throws OaException;
/**
* 待办列表
* @param userId
* @return
*/
public List<DevAllocateForm> queryDealingAllocateFrom(String userId);
/**
* 获取任务
* @param formId
* @return
*/
public List<Task> getEndedTasks(String formId) ;
/**
* 处理提交的流程任务
* @param taskInstanceId
* @param comment
* @param transitionName
* @param formId
*/
public void txDealApproveTask(String taskInstanceId, String comment, String transitionName, String formId);
/**
* 归档列表
* @param qp
* @param userAccountId
* @return
*/
public ListPage<DevAllocateForm> getArchAllocateForm(DevAllocateQueryParameters qp,
String userAccountId) ;
/**
* 验收单保存
* @param allocateId
* @param valiId
* @param deviceID
* @param valiType
* @param inDate
* @param accountID
* @param valiDate
* @param isMoney
* @param deductMoney
* @param remark
* @param valiDetailStr
*/
public void txSaveValidateForm(String allocateId, String valiId, String deviceID,
int valiType, Date inDate, String accountID,
Date valiDate, boolean isMoney, double deductMoney, String remark,
String valiDetailStr);
/**
* 启动流程
* @param devAlcForm
* @param flowKey
* @throws OaException
*/
public void txStartFlow(DevAllocateForm devAlcForm, String flowKey) throws OaException ;
/**
* 流程归档操作
* @param id
* @param inUser
* @param outUserId
* @param status
* @return
* @throws OaException
*/
public DevAllocateForm txPublishAllocateForm(String id) throws OaException;
/**
* 作废操作
* @param formId
* @throws OaException
*/
public void txCancellAllocateForm(String formId)throws OaException ;
/**
* 查询列表
* @param qp
* @return
*/
public ListPage<DevAllocateForm> getQueryAllocateForm(DevAllocateQueryParameters qp);
/**
* 管理员保存调拨单
* @param allocateForm
* @param deviceId 设备id
* @param purpose 设备用途
* @param validMainDevFlag 是否验证主设备
* @return
* @throws OaException
*/
public DevAllocateForm txSaveDevAllocateForm(DevAllocateForm allocateForm,String deviceId, boolean validMainDevFlag) throws OaException;
/**
* 获取指定设备的已归档调拨记录列表
* @param deviceID
* @return
*/
public List<DevAllocateList> getArchDevAllotListByDeviceID(String deviceID, Boolean archiveDateOrder);
/**
* 起草调拨
* @param deviceTypeCode
* @param allotType
* @param moveDate
* @param applicantID
* @param userGroupName
* @param inAccountID
* @param inGroupName
* @param reason
* @param devAllocateList
* @param isStartFlow
* @param validMainDevFlag 是否验证主设备
* @return
* @throws OaException
*/
public DevAllocateForm txSaveAsDraf(String deviceTypeCode, String allotType, Date moveDate,
String applicantID, String userGroupName, String inAccountID, String inGroupName, String reason,
Set<DevAllocateList> devAllocateList, boolean isStartFlow, boolean validMainDevFlag) throws OaException;
/**
* 草稿修改
* @param id
* @param deviceTypeCode
* @param allotType
* @param moveDate
* @param inAccountID
* @param inGroupName
* @param reason
* @param devAllocateList
* @param isStartFlow
* @param validMainDevFlag 是否验证主设备
* @return
* @throws OaException
*/
public DevAllocateForm txModifyDraftForm(String id, String deviceTypeCode, String allotType, Date moveDate,
String inAccountID, String inGroupName, String reason,
Set<DevAllocateList> devAllocateList, boolean isStartFlow, boolean validMainDevFlag) throws OaException;
/**
* 驳回到起草人修改
* @param id
* @param allotType
* @param moveDate
* @param inAccountID
* @param inGroupName
* @param reason
* @param devAllocateList
* @param validMainDevFlag 是否验证主设备
* @return
* @throws OaException
*/
public DevAllocateForm txDraftmanAmend(String id, String allotType, Date moveDate,
String inAccountID, String inGroupName, String reason,
Set<DevAllocateList> devAllocateList, boolean validMainDevFlag) throws OaException;
/**
* 设备调入 保存设备工作用途和地区
* @param map
* @throws OaException
*/
public void txSaveOrUpdateDevAllocateForm(String id,Map<String,DevAllocateList> map,Boolean valiDevFlag) throws OaException;
}
|
UTF-8
|
Java
| 5,434 |
java
|
IDeviceAllocateBiz.java
|
Java
|
[
{
"context": "pp.oa.system.exception.OaException;\n/**\n * @author tim\n *\t调拨单\n */\npublic interface IDeviceAllocateBiz {\n",
"end": 425,
"score": 0.9875779747962952,
"start": 422,
"tag": "USERNAME",
"value": "tim"
}
] | null |
[] |
package org.eapp.oa.device.blo;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eapp.oa.device.dto.DevAllocateQueryParameters;
import org.eapp.oa.device.hbean.DevAllocateForm;
import org.eapp.oa.device.hbean.DevAllocateList;
import org.eapp.oa.flow.hbean.Task;
import org.eapp.util.hibernate.ListPage;
import org.eapp.oa.system.exception.OaException;
/**
* @author tim
* 调拨单
*/
public interface IDeviceAllocateBiz {
/**
* 查询调拨单列表
* @param userAccountId
* @param formStatus
* @return
*/
public List<DevAllocateForm> queryAllocateForm(String userAccountId, int formStatus);
/**
* 通过Id查询调拨单
* @param id
* @param initList
* @param initDevCfgList 是否初始化设备配置信息
* @return
*/
public DevAllocateForm getDevAllocateFormById(String id, boolean initList, boolean initDevCfgList);
/**
* 删除调拨单
* @param id
* @param accountId
* @throws OaException
*/
public void txDelDevAllocateForm(String id) throws OaException;
/**
* 待办列表
* @param userId
* @return
*/
public List<DevAllocateForm> queryDealingAllocateFrom(String userId);
/**
* 获取任务
* @param formId
* @return
*/
public List<Task> getEndedTasks(String formId) ;
/**
* 处理提交的流程任务
* @param taskInstanceId
* @param comment
* @param transitionName
* @param formId
*/
public void txDealApproveTask(String taskInstanceId, String comment, String transitionName, String formId);
/**
* 归档列表
* @param qp
* @param userAccountId
* @return
*/
public ListPage<DevAllocateForm> getArchAllocateForm(DevAllocateQueryParameters qp,
String userAccountId) ;
/**
* 验收单保存
* @param allocateId
* @param valiId
* @param deviceID
* @param valiType
* @param inDate
* @param accountID
* @param valiDate
* @param isMoney
* @param deductMoney
* @param remark
* @param valiDetailStr
*/
public void txSaveValidateForm(String allocateId, String valiId, String deviceID,
int valiType, Date inDate, String accountID,
Date valiDate, boolean isMoney, double deductMoney, String remark,
String valiDetailStr);
/**
* 启动流程
* @param devAlcForm
* @param flowKey
* @throws OaException
*/
public void txStartFlow(DevAllocateForm devAlcForm, String flowKey) throws OaException ;
/**
* 流程归档操作
* @param id
* @param inUser
* @param outUserId
* @param status
* @return
* @throws OaException
*/
public DevAllocateForm txPublishAllocateForm(String id) throws OaException;
/**
* 作废操作
* @param formId
* @throws OaException
*/
public void txCancellAllocateForm(String formId)throws OaException ;
/**
* 查询列表
* @param qp
* @return
*/
public ListPage<DevAllocateForm> getQueryAllocateForm(DevAllocateQueryParameters qp);
/**
* 管理员保存调拨单
* @param allocateForm
* @param deviceId 设备id
* @param purpose 设备用途
* @param validMainDevFlag 是否验证主设备
* @return
* @throws OaException
*/
public DevAllocateForm txSaveDevAllocateForm(DevAllocateForm allocateForm,String deviceId, boolean validMainDevFlag) throws OaException;
/**
* 获取指定设备的已归档调拨记录列表
* @param deviceID
* @return
*/
public List<DevAllocateList> getArchDevAllotListByDeviceID(String deviceID, Boolean archiveDateOrder);
/**
* 起草调拨
* @param deviceTypeCode
* @param allotType
* @param moveDate
* @param applicantID
* @param userGroupName
* @param inAccountID
* @param inGroupName
* @param reason
* @param devAllocateList
* @param isStartFlow
* @param validMainDevFlag 是否验证主设备
* @return
* @throws OaException
*/
public DevAllocateForm txSaveAsDraf(String deviceTypeCode, String allotType, Date moveDate,
String applicantID, String userGroupName, String inAccountID, String inGroupName, String reason,
Set<DevAllocateList> devAllocateList, boolean isStartFlow, boolean validMainDevFlag) throws OaException;
/**
* 草稿修改
* @param id
* @param deviceTypeCode
* @param allotType
* @param moveDate
* @param inAccountID
* @param inGroupName
* @param reason
* @param devAllocateList
* @param isStartFlow
* @param validMainDevFlag 是否验证主设备
* @return
* @throws OaException
*/
public DevAllocateForm txModifyDraftForm(String id, String deviceTypeCode, String allotType, Date moveDate,
String inAccountID, String inGroupName, String reason,
Set<DevAllocateList> devAllocateList, boolean isStartFlow, boolean validMainDevFlag) throws OaException;
/**
* 驳回到起草人修改
* @param id
* @param allotType
* @param moveDate
* @param inAccountID
* @param inGroupName
* @param reason
* @param devAllocateList
* @param validMainDevFlag 是否验证主设备
* @return
* @throws OaException
*/
public DevAllocateForm txDraftmanAmend(String id, String allotType, Date moveDate,
String inAccountID, String inGroupName, String reason,
Set<DevAllocateList> devAllocateList, boolean validMainDevFlag) throws OaException;
/**
* 设备调入 保存设备工作用途和地区
* @param map
* @throws OaException
*/
public void txSaveOrUpdateDevAllocateForm(String id,Map<String,DevAllocateList> map,Boolean valiDevFlag) throws OaException;
}
| 5,434 | 0.724618 | 0.724618 | 211 | 23.180096 | 26.983509 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.374408 | false | false |
10
|
ec25defec0174e35c98a2ed727f5eb265a4e6593
| 28,527,172,788,995 |
e7a0353742ca0f50f8e2381f65458dff54dd4389
|
/phase2/src/GUISystem/MessageOutboxGUI.java
|
46a2a10af1a89091ace7f0449466373e2db385d9
|
[] |
no_license
|
zw123han/Conference-App
|
https://github.com/zw123han/Conference-App
|
c5ac28d55508cc7ea8e530cb654f33f2576cc967
|
a50c097a1caef310d267066371ff61bb216e878e
|
refs/heads/master
| 2023-02-15T08:38:12.582000 | 2021-01-08T23:54:20 | 2021-01-08T23:54:20 | 328,036,831 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package GUISystem;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.application.Application;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.*;
import MessagingSystem.*;
import java.util.HashMap;
/**
* GUI for the Group Message part of the Messaging System.
*
* @author Elliot
*/
public class MessageOutboxGUI extends Application{
private MessageOutboxPresenter mo;
/**
* Sets the given MessageOutboxPresenter.
*
* @param mo MessageOutboxPresenter
*/
public void setOutboxElements(MessageOutboxPresenter mo) {
this.mo = mo;
}
/**
* Sets username in MessageOutboxPresenter to that of the currently logged in user.
*
* @param username username of the current user
*/
public void setLogin(String username) {
mo.setLoggedInUser(username);
}
/**
* Runs the GUI.
*
* @param primaryStage Stage
*/
@Override
public void start(Stage primaryStage) {
//Outbox Container
VBox outboxCanvas = new VBox();
outboxCanvas.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
//Outbox Title bar
VBox outboxBar = new VBox();
outboxBar.setAlignment(Pos.TOP_CENTER);
outboxBar.setPrefSize(500, 20);
Label outboxCanvasTitle = new Label("Send Group Message");
outboxCanvasTitle.setFont(Font.loadFont(getClass().getResourceAsStream("/resources/os-bold.ttf"), 16));
outboxCanvasTitle.setTextFill(Color.WHITE);
Background outboxCanvasTitleBackground = new Background(new BackgroundFill(Color.BLACK, CornerRadii.EMPTY, Insets.EMPTY));
outboxCanvasTitle.setBackground(outboxCanvasTitleBackground);
outboxCanvasTitle.setPadding(new Insets(10, 12, 10, 12));
outboxCanvasTitle.setPrefSize(500, 20);
//Options menu
VBox optionsBar = new VBox();
optionsBar.setAlignment(Pos.TOP_CENTER);
optionsBar.setBackground(new Background(new BackgroundFill(Color.LIGHTGRAY, new CornerRadii(4), Insets.EMPTY)));
optionsBar.setPadding(new Insets(10, 12, 10, 12));
optionsBar.setPrefSize(500, 20);
Label optionsBarLabel = new Label("Send to ");
optionsBarLabel.setAlignment(Pos.CENTER_LEFT);
optionsBarLabel.setFont(Font.loadFont(getClass().getResourceAsStream("/resources/os-regular.ttf"), 12));
ComboBox dropdownMenu = new ComboBox();
HashMap<String, Long> events = mo.getAllEventInfo();
if(mo.canSendToSpeakers()){
dropdownMenu.getItems().add("All speakers");
}
for(String info : events.keySet()){
dropdownMenu.getItems().add(info);
}
// Message Text Area
HBox textFieldBar = new HBox(5);
textFieldBar.setPrefSize(500, 380);
textFieldBar.setAlignment(Pos.BOTTOM_CENTER);
textFieldBar.setPadding(new Insets(5));
// Message Box (Field)
TextArea messageBox = new TextArea("");
messageBox.setFont(Font.loadFont(getClass().getResourceAsStream("/resources/os-regular.ttf"), 12));
messageBox.setPadding(new Insets(4));
messageBox.setPrefSize(400, 380);
messageBox.setWrapText(true);
messageBox.setDisable(false);
// Send Message Button
Button sendMessage = new Button("SEND");
sendMessage.setPrefSize(50, 30);
sendMessage.setFont(Font.loadFont(getClass().getResourceAsStream("/resources/os-bold.ttf"), 10));
sendMessage.setBackground(new Background(new BackgroundFill(Color.BLACK, new CornerRadii(4), Insets.EMPTY)));
sendMessage.setTextFill(Color.WHITE);
sendMessage.setPadding(new Insets(8));
sendMessage.setDisable(false);
sendMessage.setOnAction(e -> {
Object tempChoice = dropdownMenu.getValue();
String tempMessage = messageBox.getText();
if(mo.validateMessage(tempMessage) && tempChoice != null){
messageBox.setText("");
dropdownMenu.setValue(null);
if(tempChoice.equals("All speakers")){
mo.sendToSpeakers(tempMessage);
}else {
mo.sendMessage(events.get(tempChoice.toString()), tempMessage);
}
}
});
outboxBar.getChildren().add(outboxCanvasTitle);
optionsBar.getChildren().addAll(optionsBarLabel, dropdownMenu);
textFieldBar.getChildren().addAll(messageBox, sendMessage);
outboxCanvas.getChildren().addAll(outboxBar, optionsBar, textFieldBar);
Scene scene = new Scene(outboxCanvas);
primaryStage.setTitle("Messages - Conference Simulator Phase 2");
primaryStage.setScene(scene);
primaryStage.initModality(Modality.APPLICATION_MODAL);
primaryStage.showAndWait();
}
}
|
UTF-8
|
Java
| 5,045 |
java
|
MessageOutboxGUI.java
|
Java
|
[
{
"context": "ssage part of the Messaging System.\n *\n * @author Elliot\n */\npublic class MessageOutboxGUI extends Applica",
"end": 427,
"score": 0.9995369911193848,
"start": 421,
"tag": "NAME",
"value": "Elliot"
}
] | null |
[] |
package GUISystem;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.application.Application;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.*;
import MessagingSystem.*;
import java.util.HashMap;
/**
* GUI for the Group Message part of the Messaging System.
*
* @author Elliot
*/
public class MessageOutboxGUI extends Application{
private MessageOutboxPresenter mo;
/**
* Sets the given MessageOutboxPresenter.
*
* @param mo MessageOutboxPresenter
*/
public void setOutboxElements(MessageOutboxPresenter mo) {
this.mo = mo;
}
/**
* Sets username in MessageOutboxPresenter to that of the currently logged in user.
*
* @param username username of the current user
*/
public void setLogin(String username) {
mo.setLoggedInUser(username);
}
/**
* Runs the GUI.
*
* @param primaryStage Stage
*/
@Override
public void start(Stage primaryStage) {
//Outbox Container
VBox outboxCanvas = new VBox();
outboxCanvas.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
//Outbox Title bar
VBox outboxBar = new VBox();
outboxBar.setAlignment(Pos.TOP_CENTER);
outboxBar.setPrefSize(500, 20);
Label outboxCanvasTitle = new Label("Send Group Message");
outboxCanvasTitle.setFont(Font.loadFont(getClass().getResourceAsStream("/resources/os-bold.ttf"), 16));
outboxCanvasTitle.setTextFill(Color.WHITE);
Background outboxCanvasTitleBackground = new Background(new BackgroundFill(Color.BLACK, CornerRadii.EMPTY, Insets.EMPTY));
outboxCanvasTitle.setBackground(outboxCanvasTitleBackground);
outboxCanvasTitle.setPadding(new Insets(10, 12, 10, 12));
outboxCanvasTitle.setPrefSize(500, 20);
//Options menu
VBox optionsBar = new VBox();
optionsBar.setAlignment(Pos.TOP_CENTER);
optionsBar.setBackground(new Background(new BackgroundFill(Color.LIGHTGRAY, new CornerRadii(4), Insets.EMPTY)));
optionsBar.setPadding(new Insets(10, 12, 10, 12));
optionsBar.setPrefSize(500, 20);
Label optionsBarLabel = new Label("Send to ");
optionsBarLabel.setAlignment(Pos.CENTER_LEFT);
optionsBarLabel.setFont(Font.loadFont(getClass().getResourceAsStream("/resources/os-regular.ttf"), 12));
ComboBox dropdownMenu = new ComboBox();
HashMap<String, Long> events = mo.getAllEventInfo();
if(mo.canSendToSpeakers()){
dropdownMenu.getItems().add("All speakers");
}
for(String info : events.keySet()){
dropdownMenu.getItems().add(info);
}
// Message Text Area
HBox textFieldBar = new HBox(5);
textFieldBar.setPrefSize(500, 380);
textFieldBar.setAlignment(Pos.BOTTOM_CENTER);
textFieldBar.setPadding(new Insets(5));
// Message Box (Field)
TextArea messageBox = new TextArea("");
messageBox.setFont(Font.loadFont(getClass().getResourceAsStream("/resources/os-regular.ttf"), 12));
messageBox.setPadding(new Insets(4));
messageBox.setPrefSize(400, 380);
messageBox.setWrapText(true);
messageBox.setDisable(false);
// Send Message Button
Button sendMessage = new Button("SEND");
sendMessage.setPrefSize(50, 30);
sendMessage.setFont(Font.loadFont(getClass().getResourceAsStream("/resources/os-bold.ttf"), 10));
sendMessage.setBackground(new Background(new BackgroundFill(Color.BLACK, new CornerRadii(4), Insets.EMPTY)));
sendMessage.setTextFill(Color.WHITE);
sendMessage.setPadding(new Insets(8));
sendMessage.setDisable(false);
sendMessage.setOnAction(e -> {
Object tempChoice = dropdownMenu.getValue();
String tempMessage = messageBox.getText();
if(mo.validateMessage(tempMessage) && tempChoice != null){
messageBox.setText("");
dropdownMenu.setValue(null);
if(tempChoice.equals("All speakers")){
mo.sendToSpeakers(tempMessage);
}else {
mo.sendMessage(events.get(tempChoice.toString()), tempMessage);
}
}
});
outboxBar.getChildren().add(outboxCanvasTitle);
optionsBar.getChildren().addAll(optionsBarLabel, dropdownMenu);
textFieldBar.getChildren().addAll(messageBox, sendMessage);
outboxCanvas.getChildren().addAll(outboxBar, optionsBar, textFieldBar);
Scene scene = new Scene(outboxCanvas);
primaryStage.setTitle("Messages - Conference Simulator Phase 2");
primaryStage.setScene(scene);
primaryStage.initModality(Modality.APPLICATION_MODAL);
primaryStage.showAndWait();
}
}
| 5,045 | 0.657681 | 0.645391 | 133 | 36.932331 | 29.426395 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766917 | false | false |
10
|
0fcb320ee64923e9ac77df7894b43add4c91f126
| 14,534,169,348,178 |
3c007b76a0bbed83002809303f268d983bdbfefe
|
/src/main/java/com/vieracode/payment/service/impl/PaymentServicesImpl.java
|
292646e1e35b0998caf04c543b8b42afcba23797
|
[] |
no_license
|
jviera/payment
|
https://github.com/jviera/payment
|
faa05298c3dfc237fd8186905f708c51d58420ff
|
ea59ae23995c20cc4d339933b239e4ac31f0f63d
|
refs/heads/main
| 2023-03-13T17:39:42.116000 | 2021-02-23T02:25:52 | 2021-02-23T02:25:52 | 341,400,208 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vieracode.payment.service.impl;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.vieracode.payment.common.CodeResponseEnum;
import com.vieracode.payment.exception.PaymentServiceException;
import com.vieracode.payment.model.NotificationModel;
import com.vieracode.payment.service.PaymentService;
@Service
@Qualifier("paymentServices")
public class PaymentServicesImpl implements PaymentService {
Logger logger = LoggerFactory.getLogger(PaymentService.class);
/**
* account > 0 and <999999999
*
* @param account
* @return true:ok, false:error
*/
public boolean validateAccount(int account) throws PaymentServiceException {
if (account > 0 && account < 999999999)
return true;
throw new PaymentServiceException(CodeResponseEnum.ERROR_ACCOUNT);
}
/**
* Customer not null and not Empty
* @param Customer
* @return
*/
public boolean validateCustomer(String customer) throws PaymentServiceException {
if(null != customer && !customer.trim().isEmpty())
return true;
throw new PaymentServiceException(CodeResponseEnum.ERROR_CUSTOMER);
}
/**
* Amount >= 100.00 and < 30000
* @param Amount
* @return
*/
public boolean validateAmount(float amount) throws PaymentServiceException {
if (amount >= 100 && amount < 30000)
return true;
throw new PaymentServiceException(CodeResponseEnum.ERROR_AMOUNT);
}
/**
* Simulamos el llamado al API con un sleep de 50ms
* @param notificationModel
* @return
* @throws InterruptedException
*/
public String callApi(NotificationModel notificationModel) throws InterruptedException
{
TimeUnit.MILLISECONDS.sleep(50);
logger.info("callApi Success without Async");
return "Success";
}
}
|
UTF-8
|
Java
| 1,867 |
java
|
PaymentServicesImpl.java
|
Java
|
[] | null |
[] |
package com.vieracode.payment.service.impl;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.vieracode.payment.common.CodeResponseEnum;
import com.vieracode.payment.exception.PaymentServiceException;
import com.vieracode.payment.model.NotificationModel;
import com.vieracode.payment.service.PaymentService;
@Service
@Qualifier("paymentServices")
public class PaymentServicesImpl implements PaymentService {
Logger logger = LoggerFactory.getLogger(PaymentService.class);
/**
* account > 0 and <999999999
*
* @param account
* @return true:ok, false:error
*/
public boolean validateAccount(int account) throws PaymentServiceException {
if (account > 0 && account < 999999999)
return true;
throw new PaymentServiceException(CodeResponseEnum.ERROR_ACCOUNT);
}
/**
* Customer not null and not Empty
* @param Customer
* @return
*/
public boolean validateCustomer(String customer) throws PaymentServiceException {
if(null != customer && !customer.trim().isEmpty())
return true;
throw new PaymentServiceException(CodeResponseEnum.ERROR_CUSTOMER);
}
/**
* Amount >= 100.00 and < 30000
* @param Amount
* @return
*/
public boolean validateAmount(float amount) throws PaymentServiceException {
if (amount >= 100 && amount < 30000)
return true;
throw new PaymentServiceException(CodeResponseEnum.ERROR_AMOUNT);
}
/**
* Simulamos el llamado al API con un sleep de 50ms
* @param notificationModel
* @return
* @throws InterruptedException
*/
public String callApi(NotificationModel notificationModel) throws InterruptedException
{
TimeUnit.MILLISECONDS.sleep(50);
logger.info("callApi Success without Async");
return "Success";
}
}
| 1,867 | 0.762721 | 0.739154 | 62 | 29.112904 | 25.235092 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.306452 | false | false |
10
|
9041326ff28a9cbdd346956971f9f5b69011b86a
| 2,972,117,389,604 |
e88f2e20e7233bb5a13726c2074d3c9b83ebf3fc
|
/core/src/stonering/stage/entity_menu/container/ContainerGrid.java
|
ebfe445320c16d747f915ccafb445d0178432764
|
[
"MIT"
] |
permissive
|
Sorgas/Tearfall
|
https://github.com/Sorgas/Tearfall
|
190ccfcade5b65ecc98ae57f0fa6603c3840a226
|
201c80311b9245bf52387c640d022cffab1b4463
|
refs/heads/master
| 2021-06-26T00:58:02.548000 | 2020-10-19T20:12:59 | 2020-10-19T20:12:59 | 160,510,547 | 6 | 3 |
MIT
| false | 2019-10-16T20:58:23 | 2018-12-05T11:49:38 | 2019-10-16T15:39:20 | 2019-10-16T20:58:23 | 4,293 | 3 | 2 | 0 |
Java
| false | false |
package stonering.stage.entity_menu.container;
import com.badlogic.gdx.scenes.scene2d.ui.Container;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import stonering.util.lang.StaticSkin;
/**
* Shows grid of items icons in a grid table.
*
* @author Alexander on 03.09.2019.
*/
public class ContainerGrid extends Container {
private Table mainTable;
private Table gridTable;
private Label capacityLabel;
public ContainerGrid(int capacity, int width, int heigth) {
mainTable = new Table();
mainTable.add(capacityLabel = new Label("", StaticSkin.getSkin()));
gridTable = new Table();
gridTable.defaults().size(64).space(10);
mainTable.add(gridTable);
setActor(mainTable);
}
}
|
UTF-8
|
Java
| 797 |
java
|
ContainerGrid.java
|
Java
|
[
{
"context": "grid of items icons in a grid table.\n *\n * @author Alexander on 03.09.2019.\n */\npublic class ContainerGrid ext",
"end": 312,
"score": 0.9973545074462891,
"start": 303,
"tag": "NAME",
"value": "Alexander"
}
] | null |
[] |
package stonering.stage.entity_menu.container;
import com.badlogic.gdx.scenes.scene2d.ui.Container;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import stonering.util.lang.StaticSkin;
/**
* Shows grid of items icons in a grid table.
*
* @author Alexander on 03.09.2019.
*/
public class ContainerGrid extends Container {
private Table mainTable;
private Table gridTable;
private Label capacityLabel;
public ContainerGrid(int capacity, int width, int heigth) {
mainTable = new Table();
mainTable.add(capacityLabel = new Label("", StaticSkin.getSkin()));
gridTable = new Table();
gridTable.defaults().size(64).space(10);
mainTable.add(gridTable);
setActor(mainTable);
}
}
| 797 | 0.70389 | 0.685069 | 26 | 29.653847 | 21.33423 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.653846 | false | false |
10
|
5099153c969f057160ae5e1309d922b2b8f94a64
| 8,778,913,170,384 |
dcd7fc01b2d5c461b60c038600e5867de561e73c
|
/src/model/bean/Compra.java
|
0068c06ab945a6920a3eaffa962543493676ce25
|
[] |
no_license
|
AntonioAndradeGomes/ProjetoES1
|
https://github.com/AntonioAndradeGomes/ProjetoES1
|
93b9cfa021c718ad7213241563f5b5455e6061a3
|
2143a3c29b732b056b3742f9146d78a2a9fef363
|
refs/heads/master
| 2020-03-11T11:48:26.523000 | 2018-05-18T00:25:44 | 2018-05-18T00:25:44 | 129,979,708 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package model.bean;
import java.util.ArrayList;
import java.sql.Date;
public class Compra {
private Cliente comprador;
private ArrayList<Produto> produtos;
private long codigo;
private Date data;
private double valor;
private Vendedor vendedor;
public Compra(long codigo, Date data, double valor, Vendedor vendedor)
{
// this.comprador = comprador;
this.produtos = new ArrayList<Produto>();
this.codigo = codigo;
this.data = data;
this.valor = valor;
this.vendedor = vendedor;
}
public ArrayList<Produto> getProdutos() {
return produtos;
}
public void setProdutos(ArrayList<Produto> produtos) {
this.produtos = produtos;
}
public Cliente getComprador() {
return comprador;
}
public void setComprador(Cliente comprador) {
this.comprador = comprador;
}
public long getCodigo() {
return codigo;
}
public void setCodigo(long codigo) {
this.codigo = codigo;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
public Vendedor getVendedor() {
return vendedor;
}
public void setVendedor(Vendedor vendedor) {
this.vendedor = vendedor;
}
}
|
UTF-8
|
Java
| 1,563 |
java
|
Compra.java
|
Java
|
[] | null |
[] |
package model.bean;
import java.util.ArrayList;
import java.sql.Date;
public class Compra {
private Cliente comprador;
private ArrayList<Produto> produtos;
private long codigo;
private Date data;
private double valor;
private Vendedor vendedor;
public Compra(long codigo, Date data, double valor, Vendedor vendedor)
{
// this.comprador = comprador;
this.produtos = new ArrayList<Produto>();
this.codigo = codigo;
this.data = data;
this.valor = valor;
this.vendedor = vendedor;
}
public ArrayList<Produto> getProdutos() {
return produtos;
}
public void setProdutos(ArrayList<Produto> produtos) {
this.produtos = produtos;
}
public Cliente getComprador() {
return comprador;
}
public void setComprador(Cliente comprador) {
this.comprador = comprador;
}
public long getCodigo() {
return codigo;
}
public void setCodigo(long codigo) {
this.codigo = codigo;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
public Vendedor getVendedor() {
return vendedor;
}
public void setVendedor(Vendedor vendedor) {
this.vendedor = vendedor;
}
}
| 1,563 | 0.571977 | 0.571977 | 75 | 18.84 | 17.042723 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
10
|
fce94390895b7d06adb920bdb205ade3813eea4a
| 25,503,515,850,164 |
f0c8eb22449d567e8a215e84fbe68e4e8c5a0893
|
/tapestry-ioc/src/main/java/org/apache/tapestry5/ioc/internal/services/AbtractAspectInterceptorBuilder.java
|
f4dc5606e6f8e2e86eecb76b6e4c944dcfeffd80
|
[
"Apache-2.0",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unknown-license-reference",
"MPL-1.1",
"MIT"
] |
permissive
|
apache/tapestry-5
|
https://github.com/apache/tapestry-5
|
6c8c9d5f1f28abe03f424b21b1ff96af9955f76d
|
b5bda40756c5e946901d18694a094f023ba6d2b5
|
refs/heads/master
| 2023-08-28T16:05:10.291000 | 2023-07-13T17:25:04 | 2023-07-13T17:25:04 | 4,416,959 | 89 | 103 |
Apache-2.0
| false | 2023-09-14T11:59:30 | 2012-05-23T07:00:11 | 2023-08-01T16:09:12 | 2023-09-14T11:59:29 | 42,818 | 108 | 82 | 19 |
Java
| false | false |
// Copyright 2011 The Apache Software Foundation
//
// 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.apache.tapestry5.ioc.internal.services;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.apache.tapestry5.commons.AnnotationProvider;
import org.apache.tapestry5.ioc.AnnotationAccess;
import org.apache.tapestry5.ioc.services.AspectInterceptorBuilder;
public abstract class AbtractAspectInterceptorBuilder<T> implements AspectInterceptorBuilder<T>
{
protected final AnnotationAccess annotationAccess;
public AbtractAspectInterceptorBuilder(AnnotationAccess annotationAccess)
{
this.annotationAccess = annotationAccess;
}
@Override
public AnnotationProvider getClassAnnotationProvider()
{
return annotationAccess.getClassAnnotationProvider();
}
@Override
public AnnotationProvider getMethodAnnotationProvider(String methodName, Class... parameterTypes)
{
return annotationAccess.getMethodAnnotationProvider(methodName, parameterTypes);
}
@Override
public <T extends Annotation> T getMethodAnnotation(Method method, Class<T> annotationType)
{
return getMethodAnnotationProvider(method.getName(), method.getParameterTypes()).getAnnotation(annotationType);
}
}
|
UTF-8
|
Java
| 1,810 |
java
|
AbtractAspectInterceptorBuilder.java
|
Java
|
[] | null |
[] |
// Copyright 2011 The Apache Software Foundation
//
// 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.apache.tapestry5.ioc.internal.services;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.apache.tapestry5.commons.AnnotationProvider;
import org.apache.tapestry5.ioc.AnnotationAccess;
import org.apache.tapestry5.ioc.services.AspectInterceptorBuilder;
public abstract class AbtractAspectInterceptorBuilder<T> implements AspectInterceptorBuilder<T>
{
protected final AnnotationAccess annotationAccess;
public AbtractAspectInterceptorBuilder(AnnotationAccess annotationAccess)
{
this.annotationAccess = annotationAccess;
}
@Override
public AnnotationProvider getClassAnnotationProvider()
{
return annotationAccess.getClassAnnotationProvider();
}
@Override
public AnnotationProvider getMethodAnnotationProvider(String methodName, Class... parameterTypes)
{
return annotationAccess.getMethodAnnotationProvider(methodName, parameterTypes);
}
@Override
public <T extends Annotation> T getMethodAnnotation(Method method, Class<T> annotationType)
{
return getMethodAnnotationProvider(method.getName(), method.getParameterTypes()).getAnnotation(annotationType);
}
}
| 1,810 | 0.774586 | 0.767956 | 50 | 35.200001 | 34.135025 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
10
|
0c84b71a1b43d713ada09863f09b88ae1318f096
| 3,186,865,781,437 |
05391663f13e4a3b893c0e23c393bd484a5e6078
|
/QTServer/src/mining/ClusterSet.java
|
86db68ca3deeeaf367ab4bbe8b71caa15ab0203d
|
[] |
no_license
|
claudialorusso/QT
|
https://github.com/claudialorusso/QT
|
864e0dbf31728944c14e6fd461f7a4bd6824726f
|
bef6a4bc945ad02d3b671a56ecb8e0d42a6bd035
|
refs/heads/master
| 2022-03-24T00:34:24.989000 | 2019-11-21T09:35:45 | 2019-11-21T09:35:45 | 194,099,992 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package mining;
import data.Data;
import java.io.Serializable;
import java.util.*;
/**
* Rappresenta un set di {@link Cluster}
* determinati per mezzo dell'algoritmo
* Quality Threshold.
* @author Claudia Lorusso, Angela Dileo
*/
public class ClusterSet implements Iterable<Cluster>, Serializable {
/**
* ID di serializzazione.
*/
private static final long serialVersionUID=1L;
/**
* Set di Cluster.
*/
private Set<Cluster> C = null;
/**
* Costruttore della classe ClusterSet.
*/
ClusterSet() {
C= new TreeSet<Cluster>();
}
/**
* Costruttore della classe {@link ClusterSet}
* ordinato tramite l'interfaccia {@link Comparator}.
* @param test valore booleano che permette
* di selezionare questo costruttore
* piuttosto che l'altro.
*/
ClusterSet(boolean test) {
C = new TreeSet<Cluster>(
new Comparator<Cluster>() {
/**
* Classe anonima che permette di implementare
* l'interfaccia {@link Comparator}, in modo da poter riordinare
* il {@link ClusterSet} tramite il metodo
* compare.<br>
* L'ultimo {@link Cluster} sara' quello piu' popoloso.
*/
@Override
public int compare(Cluster c1, Cluster c2) {
return c1.compareTo(c2);
}
});
}
/**
* Permette di selezionare l'ultimo {@link Cluster}
* del {@link ClusterSet}, corrispondente a quello
* piu' popoloso.
* @return ultimo {@link Cluster} nel {@link ClusterSet}, quello piu' popoloso.
*/
Cluster last() {
return ((TreeSet<Cluster>) C).last();
}
/**
* Aggiunge un {@link Cluster}
* al {@link ClusterSet}
* @param c {@link Cluster} da aggiungere al set
*/
void add(Cluster c) {
C.add(c);
}
/**
* Override del metodo toString
* di {@link Object}.
* <p>
* Restituisce una stringa
* contenente i vari centroidi dei {@link Cluster}
* contenuti nel {@link ClusterSet}.
*/
@Override
public String toString() {
String str = "";
Iterator<Cluster> cl = C.iterator();
while (cl.hasNext()) {
str += cl.next().toString() + "\n";
}
return str;
}
/**
* Restituisce una stringa
* che descriva lo stato
* di ciascun {@link Cluster} nel {@link ClusterSet}.<br>
* @param data oggetto di tipo {@link Data}
* @return str stringa che descrive lo stato
* dei {@link Cluster} nel {@link ClusterSet}.
*/
public String toString(Data data) {
int i = 0;
String str = "";
Iterator<Cluster> c = C.iterator();
while (c.hasNext()) {
str += i + ":" + c.next().toString(data) + "\n";
i++;
}
return str;
}
/**
* Override del metodo iterator.<br>
* Itera sul ClusterSet
*/
@Override
public Iterator<Cluster> iterator() {
return C.iterator();
}
}
|
UTF-8
|
Java
| 2,823 |
java
|
ClusterSet.java
|
Java
|
[
{
"context": " dell'algoritmo\r\n * Quality Threshold.\r\n * @author Claudia Lorusso, Angela Dileo\r\n */\r\npublic class ClusterSet imple",
"end": 228,
"score": 0.9998806715011597,
"start": 213,
"tag": "NAME",
"value": "Claudia Lorusso"
},
{
"context": " * Quality Threshold.\r\n * @author Claudia Lorusso, Angela Dileo\r\n */\r\npublic class ClusterSet implements Iterable",
"end": 242,
"score": 0.9998849630355835,
"start": 230,
"tag": "NAME",
"value": "Angela Dileo"
}
] | null |
[] |
package mining;
import data.Data;
import java.io.Serializable;
import java.util.*;
/**
* Rappresenta un set di {@link Cluster}
* determinati per mezzo dell'algoritmo
* Quality Threshold.
* @author <NAME>, <NAME>
*/
public class ClusterSet implements Iterable<Cluster>, Serializable {
/**
* ID di serializzazione.
*/
private static final long serialVersionUID=1L;
/**
* Set di Cluster.
*/
private Set<Cluster> C = null;
/**
* Costruttore della classe ClusterSet.
*/
ClusterSet() {
C= new TreeSet<Cluster>();
}
/**
* Costruttore della classe {@link ClusterSet}
* ordinato tramite l'interfaccia {@link Comparator}.
* @param test valore booleano che permette
* di selezionare questo costruttore
* piuttosto che l'altro.
*/
ClusterSet(boolean test) {
C = new TreeSet<Cluster>(
new Comparator<Cluster>() {
/**
* Classe anonima che permette di implementare
* l'interfaccia {@link Comparator}, in modo da poter riordinare
* il {@link ClusterSet} tramite il metodo
* compare.<br>
* L'ultimo {@link Cluster} sara' quello piu' popoloso.
*/
@Override
public int compare(Cluster c1, Cluster c2) {
return c1.compareTo(c2);
}
});
}
/**
* Permette di selezionare l'ultimo {@link Cluster}
* del {@link ClusterSet}, corrispondente a quello
* piu' popoloso.
* @return ultimo {@link Cluster} nel {@link ClusterSet}, quello piu' popoloso.
*/
Cluster last() {
return ((TreeSet<Cluster>) C).last();
}
/**
* Aggiunge un {@link Cluster}
* al {@link ClusterSet}
* @param c {@link Cluster} da aggiungere al set
*/
void add(Cluster c) {
C.add(c);
}
/**
* Override del metodo toString
* di {@link Object}.
* <p>
* Restituisce una stringa
* contenente i vari centroidi dei {@link Cluster}
* contenuti nel {@link ClusterSet}.
*/
@Override
public String toString() {
String str = "";
Iterator<Cluster> cl = C.iterator();
while (cl.hasNext()) {
str += cl.next().toString() + "\n";
}
return str;
}
/**
* Restituisce una stringa
* che descriva lo stato
* di ciascun {@link Cluster} nel {@link ClusterSet}.<br>
* @param data oggetto di tipo {@link Data}
* @return str stringa che descrive lo stato
* dei {@link Cluster} nel {@link ClusterSet}.
*/
public String toString(Data data) {
int i = 0;
String str = "";
Iterator<Cluster> c = C.iterator();
while (c.hasNext()) {
str += i + ":" + c.next().toString(data) + "\n";
i++;
}
return str;
}
/**
* Override del metodo iterator.<br>
* Itera sul ClusterSet
*/
@Override
public Iterator<Cluster> iterator() {
return C.iterator();
}
}
| 2,808 | 0.605739 | 0.603613 | 121 | 21.347107 | 18.924255 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.752066 | false | false |
10
|
b18ca1013e8b70f7530c00a22379114b6b8b8ecd
| 9,491,877,776,140 |
7ccde4e6f04cefce25af9eac3ad81731aa99e820
|
/src/main/java/com/pps/websocket/server/hander/BinaryWebSocketFrameHandler.java
|
2268b1fb4f8528830f8fe6238037f8a882accac1
|
[] |
no_license
|
pupansheng/springboot-netty-im-pps-starter
|
https://github.com/pupansheng/springboot-netty-im-pps-starter
|
f33c552004bd19a8d8fd6bbb423f45f3332088d8
|
59300b324a1283c87b84e082ae1559f79b8e668c
|
refs/heads/master
| 2023-02-10T06:49:46.079000 | 2021-01-04T07:08:06 | 2021-01-04T07:08:06 | 326,596,425 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pps.websocket.server.hander;
import com.pps.websocket.server.event.ImEvent;
import com.pps.websocket.server.event.SocketEnvent;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
/**
* @author
* @discription; 二进制处理
* @time 2020/12/17 16:00
*/
public class BinaryWebSocketFrameHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception {
SocketEnvent socketEnvent=new SocketEnvent(ctx, ImEvent.acceptBin,msg.content(),msg);
ctx.fireUserEventTriggered(socketEnvent);
}
}
|
UTF-8
|
Java
| 762 |
java
|
BinaryWebSocketFrameHandler.java
|
Java
|
[] | null |
[] |
package com.pps.websocket.server.hander;
import com.pps.websocket.server.event.ImEvent;
import com.pps.websocket.server.event.SocketEnvent;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
/**
* @author
* @discription; 二进制处理
* @time 2020/12/17 16:00
*/
public class BinaryWebSocketFrameHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception {
SocketEnvent socketEnvent=new SocketEnvent(ctx, ImEvent.acceptBin,msg.content(),msg);
ctx.fireUserEventTriggered(socketEnvent);
}
}
| 762 | 0.793883 | 0.776596 | 23 | 31.73913 | 33.452389 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false |
10
|
796cb9981d715772478dceb6472c221afad96551
| 23,055,384,467,347 |
1d5ad100235043d4053cb7ea175517b95d85c7cc
|
/app/src/main/java/com/test/demo/test/volley/VolleyActivity.java
|
f4a79d5bb3e4e90695b96b8a5df2bfc2937be005
|
[] |
no_license
|
doudou000000/TestDemo
|
https://github.com/doudou000000/TestDemo
|
b03adad56c70fa39c08cedf8d6faebfca5609b8a
|
d12d4f28954c053cc661f1463fd4086f74f48dac
|
refs/heads/master
| 2020-06-27T19:26:35.820000 | 2019-08-01T10:28:31 | 2019-08-01T10:28:31 | 200,029,488 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.test.demo.test.volley;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.test.demo.test.R;
import java.util.Map;
import okhttp3.internal.http.HttpMethod;
/**
* Created by DEV002 on 2018/5/24.
*/
public class VolleyActivity extends AppCompatActivity {
public static final String TAG = "MyTag";
private TextView textView;
private RequestQueue queue;
private static final String IMAGE_URL = "http://i9.hexunimg.cn/2013-07-05/155842064.jpg";
LruCache<String,Bitmap> mCache;
ImageView imageView;
NetworkImageView networkImageView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley);
textView = (TextView) findViewById(R.id.volley_tv);
imageView = (ImageView) findViewById(R.id.volley_img);
networkImageView = (NetworkImageView) findViewById(R.id.volley_net_img);
queue = Volley.newRequestQueue(VolleyActivity.this);
// JsonObjectRequest;
// JsonArrayRequest;
//
// ImageLoader
StringRequest request = new StringRequest(Request.Method.POST,"",null,null){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
};
// StringRequest request = new StringRequest("https://www.baidu.com/?tn=62095104_5_oem_dg", new Response.Listener<String>() {
// @Override
// public void onResponse(String s) {
// textView.setText(s);
// }
// }, new Response.ErrorListener() {
//
// @Override
// public void onErrorResponse(VolleyError volleyError) {
// Toast.makeText(VolleyActivity.this,volleyError.getMessage(),Toast.LENGTH_SHORT).show();
// }
// });
// request.setTag(TAG);
queue.add(request);
//
// //------------------------------------
// // Instantiate the cache
// Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// // Set up the network to use HttpURLConnection as the HTTP client.
// Network network = new BasicNetwork(new HurlStack());
// // Instantiate the RequestQueue with the cache and network.
// queue = new RequestQueue(cache, network);
// // Start the queue
// queue.start();
// String url ="http://www.myurl.com";
// // Formulate the request and handle the response.
// StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
// new Response.Listener<String>() {
// @Override
// public void onResponse(String response) {
// textView.setText(response);
// }
// },
// new Response.ErrorListener() {
// @Override
// public void onErrorResponse(VolleyError error) {
// textView.setText(error.toString());
// }
// });
//// Add the request to the RequestQueue.
// queue.add(stringRequest);
ImageLoader imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache() {
@Override
public Bitmap getBitmap(String url) {
mCache = new LruCache<String,Bitmap>(10 * 1024 * 1024){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url,bitmap);
}
});
// ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(imageView,R.drawable.occupancy,R.drawable.error);
//
// imageLoader.get(IMAGE_URL,imageListener);
networkImageView.setDefaultImageResId(R.drawable.occupancy);
networkImageView.setErrorImageResId(R.drawable.error);
networkImageView.setImageUrl(IMAGE_URL,imageLoader);
}
@Override
protected void onStop() {
super.onStop();
if(queue != null){
queue.cancelAll(TAG);
}
}
}
|
UTF-8
|
Java
| 5,342 |
java
|
VolleyActivity.java
|
Java
|
[
{
"context": "http3.internal.http.HttpMethod;\n\n/**\n * Created by DEV002 on 2018/5/24.\n */\n\npublic class VolleyActivity ex",
"end": 1131,
"score": 0.9992862939834595,
"start": 1125,
"tag": "USERNAME",
"value": "DEV002"
}
] | null |
[] |
package com.test.demo.test.volley;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.test.demo.test.R;
import java.util.Map;
import okhttp3.internal.http.HttpMethod;
/**
* Created by DEV002 on 2018/5/24.
*/
public class VolleyActivity extends AppCompatActivity {
public static final String TAG = "MyTag";
private TextView textView;
private RequestQueue queue;
private static final String IMAGE_URL = "http://i9.hexunimg.cn/2013-07-05/155842064.jpg";
LruCache<String,Bitmap> mCache;
ImageView imageView;
NetworkImageView networkImageView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley);
textView = (TextView) findViewById(R.id.volley_tv);
imageView = (ImageView) findViewById(R.id.volley_img);
networkImageView = (NetworkImageView) findViewById(R.id.volley_net_img);
queue = Volley.newRequestQueue(VolleyActivity.this);
// JsonObjectRequest;
// JsonArrayRequest;
//
// ImageLoader
StringRequest request = new StringRequest(Request.Method.POST,"",null,null){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
};
// StringRequest request = new StringRequest("https://www.baidu.com/?tn=62095104_5_oem_dg", new Response.Listener<String>() {
// @Override
// public void onResponse(String s) {
// textView.setText(s);
// }
// }, new Response.ErrorListener() {
//
// @Override
// public void onErrorResponse(VolleyError volleyError) {
// Toast.makeText(VolleyActivity.this,volleyError.getMessage(),Toast.LENGTH_SHORT).show();
// }
// });
// request.setTag(TAG);
queue.add(request);
//
// //------------------------------------
// // Instantiate the cache
// Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// // Set up the network to use HttpURLConnection as the HTTP client.
// Network network = new BasicNetwork(new HurlStack());
// // Instantiate the RequestQueue with the cache and network.
// queue = new RequestQueue(cache, network);
// // Start the queue
// queue.start();
// String url ="http://www.myurl.com";
// // Formulate the request and handle the response.
// StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
// new Response.Listener<String>() {
// @Override
// public void onResponse(String response) {
// textView.setText(response);
// }
// },
// new Response.ErrorListener() {
// @Override
// public void onErrorResponse(VolleyError error) {
// textView.setText(error.toString());
// }
// });
//// Add the request to the RequestQueue.
// queue.add(stringRequest);
ImageLoader imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache() {
@Override
public Bitmap getBitmap(String url) {
mCache = new LruCache<String,Bitmap>(10 * 1024 * 1024){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url,bitmap);
}
});
// ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(imageView,R.drawable.occupancy,R.drawable.error);
//
// imageLoader.get(IMAGE_URL,imageListener);
networkImageView.setDefaultImageResId(R.drawable.occupancy);
networkImageView.setErrorImageResId(R.drawable.error);
networkImageView.setImageUrl(IMAGE_URL,imageLoader);
}
@Override
protected void onStop() {
super.onStop();
if(queue != null){
queue.cancelAll(TAG);
}
}
}
| 5,342 | 0.625983 | 0.615125 | 154 | 33.688313 | 26.907373 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.61039 | false | false |
10
|
44a0a168410977d303f49a22e67346426ad0ec63
| 23,278,722,775,344 |
4df0d8de65d27a69c296718bfaa75271e7d9c94f
|
/src/main/java/com/qinjiangbo/gen/model/RepStuKey.java
|
c1da55836165bf5fd979ed72aed5395aa65254c4
|
[] |
no_license
|
QinJiangbo/SpringMVC
|
https://github.com/QinJiangbo/SpringMVC
|
9775f300e77f7f6db120ab5e901d06d164fbd0c0
|
df87a16fa2eea6c91a840e0f349b488d9f27e82d
|
refs/heads/master
| 2021-01-17T01:06:27.039000 | 2018-01-04T13:40:18 | 2018-01-04T13:40:18 | 65,295,582 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.qinjiangbo.gen.model;
import java.io.Serializable;
public class RepStuKey implements Serializable {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column rep_stu.user_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
private Long userId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column rep_stu.attr_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
private Long attrId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table rep_stu
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rep_stu.user_id
*
* @return the value of rep_stu.user_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
public Long getUserId() {
return userId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rep_stu.user_id
*
* @param userId the value for rep_stu.user_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
public void setUserId(Long userId) {
this.userId = userId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rep_stu.attr_id
*
* @return the value of rep_stu.attr_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
public Long getAttrId() {
return attrId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rep_stu.attr_id
*
* @param attrId the value for rep_stu.attr_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
public void setAttrId(Long attrId) {
this.attrId = attrId;
}
}
|
UTF-8
|
Java
| 2,103 |
java
|
RepStuKey.java
|
Java
|
[] | null |
[] |
package com.qinjiangbo.gen.model;
import java.io.Serializable;
public class RepStuKey implements Serializable {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column rep_stu.user_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
private Long userId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column rep_stu.attr_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
private Long attrId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table rep_stu
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rep_stu.user_id
*
* @return the value of rep_stu.user_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
public Long getUserId() {
return userId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rep_stu.user_id
*
* @param userId the value for rep_stu.user_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
public void setUserId(Long userId) {
this.userId = userId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rep_stu.attr_id
*
* @return the value of rep_stu.attr_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
public Long getAttrId() {
return attrId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rep_stu.attr_id
*
* @param attrId the value for rep_stu.attr_id
*
* @mbggenerated Tue Jun 21 00:00:04 CST 2016
*/
public void setAttrId(Long attrId) {
this.attrId = attrId;
}
}
| 2,103 | 0.625773 | 0.585354 | 77 | 26.324675 | 23.722115 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.116883 | false | false |
10
|
28d77eabce4c98dbdbe32ff24ca732e3dd5c794c
| 8,881,992,397,584 |
3b390524a224db83e037fe696fd77b15dc84c75b
|
/src/main/java/com/vics/backendapirest/dao/IProductDao.java
|
041c123d157d9c8d7743dd34a39328d034774bd3
|
[] |
no_license
|
victoriaacuna/ClientesApp-Backend
|
https://github.com/victoriaacuna/ClientesApp-Backend
|
589c19ea198c6afce5c7b20eb80cf712be07f907
|
18de705833fbc5389005c3273e32c571a9a4e8a0
|
refs/heads/master
| 2022-12-11T05:03:17.866000 | 2020-09-18T01:14:16 | 2020-09-18T01:14:16 | 296,474,404 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vics.backendapirest.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.vics.backendapirest.entity.Product;
public interface IProductDao extends CrudRepository<Product, Long>{
// @Query("SELECT p FROM product WHERE p.name LIKE %?1%")
// public List<Product> filterByName(String name);
// Esto es un método que gracias a Spring, el Containing hace lo mismo que el método
// anterior. Con el IgnoreCase ignora si es mayúscula o minúscula.
// Esto se puede buscar en las proyectos de Spring, en Spring Data, en Learn,
// en la última versión estable, en Query Creation.
public List<Product> findByNameContainingIgnoreCase(String name);
}
|
UTF-8
|
Java
| 765 |
java
|
IProductDao.java
|
Java
|
[] | null |
[] |
package com.vics.backendapirest.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.vics.backendapirest.entity.Product;
public interface IProductDao extends CrudRepository<Product, Long>{
// @Query("SELECT p FROM product WHERE p.name LIKE %?1%")
// public List<Product> filterByName(String name);
// Esto es un método que gracias a Spring, el Containing hace lo mismo que el método
// anterior. Con el IgnoreCase ignora si es mayúscula o minúscula.
// Esto se puede buscar en las proyectos de Spring, en Spring Data, en Learn,
// en la última versión estable, en Query Creation.
public List<Product> findByNameContainingIgnoreCase(String name);
}
| 765 | 0.781291 | 0.779974 | 20 | 36.950001 | 29.8839 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.05 | false | false |
10
|
f5680302fca85f8c7c53b60f3bb19e79e1667734
| 8,881,992,401,290 |
53300782408e1fa44422acb774c046711e39f5a2
|
/tcp/TCPCliente.java
|
8d48e0cb14b837106f7142daf7c3aafaac8ab5a1
|
[] |
no_license
|
Dairon-Juraski/Uenp
|
https://github.com/Dairon-Juraski/Uenp
|
9d033f38531ec71be9851e539b954e8d9fcbdccc
|
8be2e34ed6d4497e865de2064657a36ddcb4848a
|
refs/heads/master
| 2023-07-13T23:30:20.152000 | 2021-08-09T03:08:33 | 2021-08-09T03:08:33 | 290,496,620 | 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 tcp;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
/**
*
* @author Juraski
*/
public class TCPCliente {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
String mensagem = "";
String servidor = "localhost";
int porta = 8080;
Scanner ler = new Scanner(System.in);
//Configura o socket de conexão TCP
Socket conexao = new Socket(servidor, porta);
System.out.println("Conectado ao servidor " +
servidor + ", na porta: " + porta + "\n");
//Objeto saída enviará a mensagem ao do servidor
ObjectOutputStream saida = new ObjectOutputStream(conexao.getOutputStream());
//Objeto entrada receberá a mensagem do servidor
ObjectInputStream entrada = new ObjectInputStream(conexao.getInputStream());
System.out.println("Digite a opção desejada:");
System.out.println("1 - Menu");
System.out.println("2 - Listar pedidos");
System.out.println("4 - Sair\n");
do {
//Mensagem de saida
System.out.print("Mensagem..: ");
mensagem = ler.nextLine();
saida.writeObject(mensagem);
//Envia a mensagem
saida.flush();
if (mensagem.equals("4")){
break;
}
//lendo a mensagem enviada pelo servidor
mensagem = (String) entrada.readObject();
System.out.println("Servidor>>\n"+mensagem);
} while (true);
//Fechando as conexões
saida.close();
entrada.close();
conexao.close();
} catch (Exception e) {
System.err.println("erro: " + e.toString());
}
}
}
|
UTF-8
|
Java
| 2,325 |
java
|
TCPCliente.java
|
Java
|
[
{
"context": "\r\nimport java.util.Scanner;\r\n\r\n/**\r\n *\r\n * @author Juraski\r\n */\r\npublic class TCPCliente {\r\n\r\n /**\r\n * ",
"end": 358,
"score": 0.9256332516670227,
"start": 351,
"tag": "NAME",
"value": "Juraski"
}
] | 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 tcp;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
/**
*
* @author Juraski
*/
public class TCPCliente {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
String mensagem = "";
String servidor = "localhost";
int porta = 8080;
Scanner ler = new Scanner(System.in);
//Configura o socket de conexão TCP
Socket conexao = new Socket(servidor, porta);
System.out.println("Conectado ao servidor " +
servidor + ", na porta: " + porta + "\n");
//Objeto saída enviará a mensagem ao do servidor
ObjectOutputStream saida = new ObjectOutputStream(conexao.getOutputStream());
//Objeto entrada receberá a mensagem do servidor
ObjectInputStream entrada = new ObjectInputStream(conexao.getInputStream());
System.out.println("Digite a opção desejada:");
System.out.println("1 - Menu");
System.out.println("2 - Listar pedidos");
System.out.println("4 - Sair\n");
do {
//Mensagem de saida
System.out.print("Mensagem..: ");
mensagem = ler.nextLine();
saida.writeObject(mensagem);
//Envia a mensagem
saida.flush();
if (mensagem.equals("4")){
break;
}
//lendo a mensagem enviada pelo servidor
mensagem = (String) entrada.readObject();
System.out.println("Servidor>>\n"+mensagem);
} while (true);
//Fechando as conexões
saida.close();
entrada.close();
conexao.close();
} catch (Exception e) {
System.err.println("erro: " + e.toString());
}
}
}
| 2,325 | 0.513374 | 0.509922 | 72 | 30.194445 | 23.644732 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.472222 | false | false |
10
|
035db61f06f8404ae66eea6901909eb96807c279
| 29,240,137,374,677 |
e33134036c047782277aef6408a1fe47437772f1
|
/src/tests/p2p/Peer2Test.java
|
29379b2b869fb6971c50d9472163a153a565731e
|
[] |
no_license
|
gregcarlin/ODRA-with-Enums
|
https://github.com/gregcarlin/ODRA-with-Enums
|
3c7419c8d5adda13d4969acf9058fbd54a667b59
|
e8c077acff0b851103f3e439c42effdf957bd67a
|
refs/heads/master
| 2021-05-27T05:08:31.350000 | 2014-09-13T01:43:12 | 2014-09-13T01:43:12 | 17,455,848 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tests.p2p;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import odra.cli.CLI;
import odra.cli.batch.BatchException;
import odra.db.Database;
import odra.db.DatabaseException;
import odra.db.OID;
import odra.db.objects.data.DBLink;
import odra.db.objects.data.DBModule;
import odra.dbinstance.DBInstance;
import odra.store.DefaultStore;
import odra.store.memorymanagement.RevSeqFitMemManager;
import odra.store.persistence.DataFileHeap;
import odra.store.sbastore.ObjectManager;
import odra.system.config.ConfigServer;
import odra.virtualnetwork.CMUHandlerImpl;
import odra.virtualnetwork.RemoteP2PStore;
import odra.virtualnetwork.RequestHandlerImpl;
import odra.virtualnetwork.api.TransportPeer;
import odra.virtualnetwork.facade.Config;
import odra.virtualnetwork.cmu.CMUnit;
import odra.virtualnetwork.pu.ClientUnit;
/**
*Startuje bazę danych i tworzy w niej DBPeer (analog DBLink)
*za pomocą tego obiektu dokonuje remoteBind i deref
*/
public class Peer2Test {
private ObjectManager manager;
private static DefaultStore store;
private Database db;
private DBInstance instance;
private DBModule gridmodule;
//private OID xoid;
private void createDatabase() throws Exception {
DataFileHeap fileHeap;
RevSeqFitMemManager allocator;
fileHeap = new DataFileHeap("/tmp/test_pu2.dbf");
fileHeap.format(1024 * 1024 * 20);
fileHeap.open();
allocator = new RevSeqFitMemManager(fileHeap);
allocator.initialize();
manager = new ObjectManager(allocator);
manager.initialize(100);
store = new DefaultStore(manager);
store.initialize();
// prepare the database
Database.initialize(store);
Database.open(store);
instance = new DBInstance();
instance.startup();
DBModule sysmod = Database.getSystemModule();
DBModule mod = Database.getModuleByName("admin");
//mod.createMetaVariable("x", 1, 1, "integer", 0);
//mod.createIntegerObject("x", mod.getDatabaseEntry(), 27);
gridmodule = new DBModule(mod.createSubmodule("grid", 0));
/*
mod = p2pmodremote;
p2pmodremote.createMetaVariable("x", 1, 1, "integer", 0);
p2pmodremote.createIntegerObject("x", mod.getDatabaseEntry(), 27);
p2pmodremote.createMetaVariable("str", 1, 1, "string", 0);
p2pmodremote.createStringObject("str", mod.getDatabaseEntry(), "string !!", 30);
p2pmodremote.createMetaVariable("y", 1, 1, "real", 0);
p2pmodremote.createDoubleObject("y", mod.getDatabaseEntry(),12.5);
p2pmodremote.createMetaVariable("b", 1, 1, "boolean", 0);
p2pmodremote.createBooleanObject("b", mod.getDatabaseEntry(), false);
//mod.createMetaVariable("com", 1, 1, "complex", 0);
OID complex = mod.createComplexObject("com", mod.getDatabaseEntry(), 0);
mod.createStringObject("nazwa", complex, "jakas nazwa", 0);
mod.createIntegerObject("numer", complex, 12);
OID empagg = mod.createAggregateObject("emp", mod.getDatabaseEntry(), 0);
for (int i = 0; i < 5; i++) {
OID e1 = mod.createComplexObject("emp", empagg, 0);
mod.createStringObject("first", e1, "x", 0);
OID a1 = mod.createComplexObject("address", e1, 0);
mod.createStringObject("street", a1, "krotka", 0);
mod.createStringObject("town", a1, "warszawa", 0);
OID e2 = mod.createComplexObject("emp", empagg, 0);
mod.createStringObject("first", e2, "x", 0);
OID a2 = mod.createComplexObject("address", e2, 0);
mod.createStringObject("street", a2, "krotka", 0);
mod.createStringObject("town", a2, "warszawa", 0);
OID e3 = mod.createComplexObject("emp", empagg, 0);
mod.createStringObject("first", e3, "x", 0);
OID a3 = mod.createComplexObject("address", e3, 0);
mod.createStringObject("street", a3, "krotka", 0);
mod.createStringObject("town", a3, "warszawa", 0);
}
*/
System.out.println("Database created");
}
public static void main(String[] args){
//local testing port conflict fix
odra.virtualnetwork.facade.Config.jxtaTransportPortStart = 9801;
odra.virtualnetwork.facade.Config.jxtaTransportPortEnd = 9899;
odra.virtualnetwork.facade.Config.peerPort = 9551;
odra.virtualnetwork.facade.Config.peerType =odra.virtualnetwork.facade.Config.PEER_TYPE.PEER_ENDPOINT;
ConfigServer.LSNR_PORT = 1521;
ConfigServer.WS_SERVER_PORT = 8889;
ConfigServer.TYPECHECKING = true;
odra.virtualnetwork.facade.Config.repoIdentity = "peer2test";
odra.virtualnetwork.facade.Config.platformHome = URI.create("file:///tmp/odra_pu2");
Peer2Test test = new Peer2Test();
try {
test.createDatabase();
} catch (Exception e1) {
e1.printStackTrace();
}
CLI cli = new CLI();
try {
cli.execBatch(new String[] {"res/p2p/pu2.cli"});
cli.begin();
} catch (BatchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 4,807 |
java
|
Peer2Test.java
|
Java
|
[
{
"context": "odra.virtualnetwork.facade.Config.repoIdentity = \"peer2test\";\n\t\todra.virtualnetwork.facade.Config.platformHom",
"end": 4368,
"score": 0.9926773905754089,
"start": 4359,
"tag": "USERNAME",
"value": "peer2test"
}
] | null |
[] |
package tests.p2p;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import odra.cli.CLI;
import odra.cli.batch.BatchException;
import odra.db.Database;
import odra.db.DatabaseException;
import odra.db.OID;
import odra.db.objects.data.DBLink;
import odra.db.objects.data.DBModule;
import odra.dbinstance.DBInstance;
import odra.store.DefaultStore;
import odra.store.memorymanagement.RevSeqFitMemManager;
import odra.store.persistence.DataFileHeap;
import odra.store.sbastore.ObjectManager;
import odra.system.config.ConfigServer;
import odra.virtualnetwork.CMUHandlerImpl;
import odra.virtualnetwork.RemoteP2PStore;
import odra.virtualnetwork.RequestHandlerImpl;
import odra.virtualnetwork.api.TransportPeer;
import odra.virtualnetwork.facade.Config;
import odra.virtualnetwork.cmu.CMUnit;
import odra.virtualnetwork.pu.ClientUnit;
/**
*Startuje bazę danych i tworzy w niej DBPeer (analog DBLink)
*za pomocą tego obiektu dokonuje remoteBind i deref
*/
public class Peer2Test {
private ObjectManager manager;
private static DefaultStore store;
private Database db;
private DBInstance instance;
private DBModule gridmodule;
//private OID xoid;
private void createDatabase() throws Exception {
DataFileHeap fileHeap;
RevSeqFitMemManager allocator;
fileHeap = new DataFileHeap("/tmp/test_pu2.dbf");
fileHeap.format(1024 * 1024 * 20);
fileHeap.open();
allocator = new RevSeqFitMemManager(fileHeap);
allocator.initialize();
manager = new ObjectManager(allocator);
manager.initialize(100);
store = new DefaultStore(manager);
store.initialize();
// prepare the database
Database.initialize(store);
Database.open(store);
instance = new DBInstance();
instance.startup();
DBModule sysmod = Database.getSystemModule();
DBModule mod = Database.getModuleByName("admin");
//mod.createMetaVariable("x", 1, 1, "integer", 0);
//mod.createIntegerObject("x", mod.getDatabaseEntry(), 27);
gridmodule = new DBModule(mod.createSubmodule("grid", 0));
/*
mod = p2pmodremote;
p2pmodremote.createMetaVariable("x", 1, 1, "integer", 0);
p2pmodremote.createIntegerObject("x", mod.getDatabaseEntry(), 27);
p2pmodremote.createMetaVariable("str", 1, 1, "string", 0);
p2pmodremote.createStringObject("str", mod.getDatabaseEntry(), "string !!", 30);
p2pmodremote.createMetaVariable("y", 1, 1, "real", 0);
p2pmodremote.createDoubleObject("y", mod.getDatabaseEntry(),12.5);
p2pmodremote.createMetaVariable("b", 1, 1, "boolean", 0);
p2pmodremote.createBooleanObject("b", mod.getDatabaseEntry(), false);
//mod.createMetaVariable("com", 1, 1, "complex", 0);
OID complex = mod.createComplexObject("com", mod.getDatabaseEntry(), 0);
mod.createStringObject("nazwa", complex, "jakas nazwa", 0);
mod.createIntegerObject("numer", complex, 12);
OID empagg = mod.createAggregateObject("emp", mod.getDatabaseEntry(), 0);
for (int i = 0; i < 5; i++) {
OID e1 = mod.createComplexObject("emp", empagg, 0);
mod.createStringObject("first", e1, "x", 0);
OID a1 = mod.createComplexObject("address", e1, 0);
mod.createStringObject("street", a1, "krotka", 0);
mod.createStringObject("town", a1, "warszawa", 0);
OID e2 = mod.createComplexObject("emp", empagg, 0);
mod.createStringObject("first", e2, "x", 0);
OID a2 = mod.createComplexObject("address", e2, 0);
mod.createStringObject("street", a2, "krotka", 0);
mod.createStringObject("town", a2, "warszawa", 0);
OID e3 = mod.createComplexObject("emp", empagg, 0);
mod.createStringObject("first", e3, "x", 0);
OID a3 = mod.createComplexObject("address", e3, 0);
mod.createStringObject("street", a3, "krotka", 0);
mod.createStringObject("town", a3, "warszawa", 0);
}
*/
System.out.println("Database created");
}
public static void main(String[] args){
//local testing port conflict fix
odra.virtualnetwork.facade.Config.jxtaTransportPortStart = 9801;
odra.virtualnetwork.facade.Config.jxtaTransportPortEnd = 9899;
odra.virtualnetwork.facade.Config.peerPort = 9551;
odra.virtualnetwork.facade.Config.peerType =odra.virtualnetwork.facade.Config.PEER_TYPE.PEER_ENDPOINT;
ConfigServer.LSNR_PORT = 1521;
ConfigServer.WS_SERVER_PORT = 8889;
ConfigServer.TYPECHECKING = true;
odra.virtualnetwork.facade.Config.repoIdentity = "peer2test";
odra.virtualnetwork.facade.Config.platformHome = URI.create("file:///tmp/odra_pu2");
Peer2Test test = new Peer2Test();
try {
test.createDatabase();
} catch (Exception e1) {
e1.printStackTrace();
}
CLI cli = new CLI();
try {
cli.execBatch(new String[] {"res/p2p/pu2.cli"});
cli.begin();
} catch (BatchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 4,807 | 0.723621 | 0.698231 | 155 | 30 | 23.377684 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.587097 | false | false |
10
|
4f53d0b400c7fbf51565f8a2eee75bcfc29dfe86
| 29,240,137,376,032 |
5b9fa8563ae0453613b68a800b27eb7e76f6d5aa
|
/Documents/Flor/UTN/semestre2/laboratorioII/Java/Testing/Ej_Listados_0/test/ej_listados_0/ListadoTest.java
|
ba1725390067bb201df210379189b11563a69345
|
[] |
no_license
|
sp2020jarvan3/TestingLabII
|
https://github.com/sp2020jarvan3/TestingLabII
|
d13418b2fdd3e15f470609c8a2d487d550048b99
|
2655214e03a0f9858af945ead6b8c2639106569d
|
refs/heads/master
| 2022-01-14T17:31:15.236000 | 2019-05-06T22:06:59 | 2019-05-06T22:06:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ej_listados_0;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author flocy
*/
public class ListadoTest {
public ListadoTest() {
}
/**
* Test of agregarUnaPersona method, of class Listado.
*/
@Test
public void testAgregarUnaPersona() {
System.out.println("agregarUnaPersona");
Persona per = new Persona("Laura", 'F', "39457821");
int n = 0;
Listado instance = new Listado(5);
int expResult = n+1;
int result = instance.agregarUnaPersona(per, n);
assertEquals(expResult, result);
}
/**
* Test of muestraNombres method, of class Listado.
*/
@Test
public void testMuestraNombres() {
System.out.println("muestraNombres");
Listado instance = new Listado(5);
Persona per = new Persona("Pedro", 'M', "12345678");
instance.agregarUnaPersona(per, 0);
instance.agregarUnaPersona(per, 1);
instance.agregarUnaPersona(per, 2);
instance.agregarUnaPersona(per, 3);
instance.agregarUnaPersona(per, 4);
for (int i = 0; i < 5; i++) {
assertEquals(per, instance.p[i]);
}
}
}
|
UTF-8
|
Java
| 1,566 |
java
|
ListadoTest.java
|
Java
|
[
{
"context": " static org.junit.Assert.*;\r\n\r\n/**\r\n *\r\n * @author flocy\r\n */\r\npublic class ListadoTest {\r\n \r\n publi",
"end": 414,
"score": 0.9996676445007324,
"start": 409,
"tag": "USERNAME",
"value": "flocy"
},
{
"context": "UnaPersona\");\r\n Persona per = new Persona(\"Laura\", 'F', \"39457821\");\r\n int n = 0;\r\n ",
"end": 714,
"score": 0.999814510345459,
"start": 709,
"tag": "NAME",
"value": "Laura"
},
{
"context": "a\");\r\n Persona per = new Persona(\"Laura\", 'F', \"39457821\");\r\n int n = 0;\r\n Lista",
"end": 719,
"score": 0.582198977470398,
"start": 718,
"tag": "NAME",
"value": "F"
},
{
"context": "w Listado(5);\r\n Persona per = new Persona(\"Pedro\", 'M', \"12345678\");\r\n instance.agregarUnaP",
"end": 1196,
"score": 0.9997738599777222,
"start": 1191,
"tag": "NAME",
"value": "Pedro"
},
{
"context": "(5);\r\n Persona per = new Persona(\"Pedro\", 'M', \"12345678\");\r\n instance.agregarUnaPerson",
"end": 1201,
"score": 0.5525964498519897,
"start": 1200,
"tag": "NAME",
"value": "M"
}
] | 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 ej_listados_0;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author flocy
*/
public class ListadoTest {
public ListadoTest() {
}
/**
* Test of agregarUnaPersona method, of class Listado.
*/
@Test
public void testAgregarUnaPersona() {
System.out.println("agregarUnaPersona");
Persona per = new Persona("Laura", 'F', "39457821");
int n = 0;
Listado instance = new Listado(5);
int expResult = n+1;
int result = instance.agregarUnaPersona(per, n);
assertEquals(expResult, result);
}
/**
* Test of muestraNombres method, of class Listado.
*/
@Test
public void testMuestraNombres() {
System.out.println("muestraNombres");
Listado instance = new Listado(5);
Persona per = new Persona("Pedro", 'M', "12345678");
instance.agregarUnaPersona(per, 0);
instance.agregarUnaPersona(per, 1);
instance.agregarUnaPersona(per, 2);
instance.agregarUnaPersona(per, 3);
instance.agregarUnaPersona(per, 4);
for (int i = 0; i < 5; i++) {
assertEquals(per, instance.p[i]);
}
}
}
| 1,566 | 0.597063 | 0.579183 | 57 | 25.473684 | 20.57004 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736842 | false | false |
10
|
374a0c7289e08e95474c79bc8c556ca73bf908f3
| 1,391,569,411,091 |
0efd3a6592e8d4132d56322d4fce05829c14ade1
|
/org/apache/poi/hssf/record/aggregates/ChartSubstreamRecordAggregate.java
|
2dcb7cb48e08a738f6f26ed941d450e4ff5564aa
|
[
"Apache-2.0"
] |
permissive
|
hkust1516csefyp43/previously-ehr
|
https://github.com/hkust1516csefyp43/previously-ehr
|
0e44cdaef9ca1535418add540ebc926477c77529
|
b1058f388ba40d4aa160c6805218ff9069367dcf
|
refs/heads/master
| 2015-09-25T06:50:20.977000 | 2015-07-26T16:28:48 | 2015-07-26T16:28:48 | 39,731,556 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/* */ package org.apache.poi.hssf.record.aggregates;
/* */
/* */ import java.util.ArrayList;
/* */ import java.util.List;
/* */ import org.apache.poi.hssf.model.RecordStream;
/* */ import org.apache.poi.hssf.record.BOFRecord;
/* */ import org.apache.poi.hssf.record.EOFRecord;
/* */ import org.apache.poi.hssf.record.HeaderFooterRecord;
/* */ import org.apache.poi.hssf.record.Record;
/* */ import org.apache.poi.hssf.record.RecordBase;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public final class ChartSubstreamRecordAggregate
/* */ extends RecordAggregate
/* */ {
/* */ private final BOFRecord _bofRec;
/* */ private final List<RecordBase> _recs;
/* */ private PageSettingsBlock _psBlock;
/* */
/* */ public ChartSubstreamRecordAggregate(RecordStream rs)
/* */ {
/* 42 */ this._bofRec = ((BOFRecord)rs.getNext());
/* 43 */ List<RecordBase> temp = new ArrayList();
/* 44 */ while (rs.peekNextClass() != EOFRecord.class) {
/* 45 */ if (PageSettingsBlock.isComponentRecord(rs.peekNextSid())) {
/* 46 */ if (this._psBlock != null) {
/* 47 */ if (rs.peekNextSid() == 2204)
/* */ {
/* 49 */ this._psBlock.addLateHeaderFooter((HeaderFooterRecord)rs.getNext());
/* */ }
/* */ else {
/* 52 */ throw new IllegalStateException("Found more than one PageSettingsBlock in chart sub-stream");
/* */ }
/* */ } else {
/* 55 */ this._psBlock = new PageSettingsBlock(rs);
/* 56 */ temp.add(this._psBlock);
/* */ }
/* */ } else
/* 59 */ temp.add(rs.getNext());
/* */ }
/* 61 */ this._recs = temp;
/* 62 */ Record eof = rs.getNext();
/* 63 */ if (!(eof instanceof EOFRecord)) {
/* 64 */ throw new IllegalStateException("Bad chart EOF");
/* */ }
/* */ }
/* */
/* */ public void visitContainedRecords(RecordAggregate.RecordVisitor rv) {
/* 69 */ if (this._recs.isEmpty()) {
/* 70 */ return;
/* */ }
/* 72 */ rv.visitRecord(this._bofRec);
/* 73 */ for (int i = 0; i < this._recs.size(); i++) {
/* 74 */ RecordBase rb = (RecordBase)this._recs.get(i);
/* 75 */ if ((rb instanceof RecordAggregate)) {
/* 76 */ ((RecordAggregate)rb).visitContainedRecords(rv);
/* */ } else {
/* 78 */ rv.visitRecord((Record)rb);
/* */ }
/* */ }
/* 81 */ rv.visitRecord(EOFRecord.instance);
/* */ }
/* */ }
/* Location: C:\Users\Louis\Desktop\previously-ehr\Sight201507251711.jar!\org\apache\poi\hssf\record\aggregates\ChartSubstreamRecordAggregate.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
UTF-8
|
Java
| 2,962 |
java
|
ChartSubstreamRecordAggregate.java
|
Java
|
[
{
"context": "}\n/* */ }\n\n\n/* Location: C:\\Users\\Louis\\Desktop\\previously-ehr\\Sight201507251711.jar!\\org",
"end": 2771,
"score": 0.7033553123474121,
"start": 2766,
"tag": "USERNAME",
"value": "Louis"
}
] | null |
[] |
/* */ package org.apache.poi.hssf.record.aggregates;
/* */
/* */ import java.util.ArrayList;
/* */ import java.util.List;
/* */ import org.apache.poi.hssf.model.RecordStream;
/* */ import org.apache.poi.hssf.record.BOFRecord;
/* */ import org.apache.poi.hssf.record.EOFRecord;
/* */ import org.apache.poi.hssf.record.HeaderFooterRecord;
/* */ import org.apache.poi.hssf.record.Record;
/* */ import org.apache.poi.hssf.record.RecordBase;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public final class ChartSubstreamRecordAggregate
/* */ extends RecordAggregate
/* */ {
/* */ private final BOFRecord _bofRec;
/* */ private final List<RecordBase> _recs;
/* */ private PageSettingsBlock _psBlock;
/* */
/* */ public ChartSubstreamRecordAggregate(RecordStream rs)
/* */ {
/* 42 */ this._bofRec = ((BOFRecord)rs.getNext());
/* 43 */ List<RecordBase> temp = new ArrayList();
/* 44 */ while (rs.peekNextClass() != EOFRecord.class) {
/* 45 */ if (PageSettingsBlock.isComponentRecord(rs.peekNextSid())) {
/* 46 */ if (this._psBlock != null) {
/* 47 */ if (rs.peekNextSid() == 2204)
/* */ {
/* 49 */ this._psBlock.addLateHeaderFooter((HeaderFooterRecord)rs.getNext());
/* */ }
/* */ else {
/* 52 */ throw new IllegalStateException("Found more than one PageSettingsBlock in chart sub-stream");
/* */ }
/* */ } else {
/* 55 */ this._psBlock = new PageSettingsBlock(rs);
/* 56 */ temp.add(this._psBlock);
/* */ }
/* */ } else
/* 59 */ temp.add(rs.getNext());
/* */ }
/* 61 */ this._recs = temp;
/* 62 */ Record eof = rs.getNext();
/* 63 */ if (!(eof instanceof EOFRecord)) {
/* 64 */ throw new IllegalStateException("Bad chart EOF");
/* */ }
/* */ }
/* */
/* */ public void visitContainedRecords(RecordAggregate.RecordVisitor rv) {
/* 69 */ if (this._recs.isEmpty()) {
/* 70 */ return;
/* */ }
/* 72 */ rv.visitRecord(this._bofRec);
/* 73 */ for (int i = 0; i < this._recs.size(); i++) {
/* 74 */ RecordBase rb = (RecordBase)this._recs.get(i);
/* 75 */ if ((rb instanceof RecordAggregate)) {
/* 76 */ ((RecordAggregate)rb).visitContainedRecords(rv);
/* */ } else {
/* 78 */ rv.visitRecord((Record)rb);
/* */ }
/* */ }
/* 81 */ rv.visitRecord(EOFRecord.instance);
/* */ }
/* */ }
/* Location: C:\Users\Louis\Desktop\previously-ehr\Sight201507251711.jar!\org\apache\poi\hssf\record\aggregates\ChartSubstreamRecordAggregate.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 2,962 | 0.506077 | 0.481769 | 89 | 32.292133 | 27.056828 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.337079 | false | false |
10
|
6ff7e05f0a921965b8ff0b54682db6fbc085f9da
| 23,295,902,670,117 |
9b585e5702aafb7d6352ab11e8f62b1aea6674b4
|
/src/main/java/es/upm/miw/repositories/ArticleRepository.java
|
1d892a0598a5db8de7e2cf86c07a09ff46ebe244
|
[] |
no_license
|
tfm-microservicios/articleUniqueDBMicroserviceTFM
|
https://github.com/tfm-microservicios/articleUniqueDBMicroserviceTFM
|
6d28015616975635f2bfae19d642b893060ef074
|
9d9ca93270a5aa44bf332a02746968c2cc04f638
|
refs/heads/master
| 2020-06-03T04:09:15.226000 | 2019-06-18T12:42:06 | 2019-06-18T12:42:06 | 191,432,336 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package es.upm.miw.repositories;
import es.upm.miw.documents.Article;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ArticleRepository extends MongoRepository<Article, String> {
}
|
UTF-8
|
Java
| 221 |
java
|
ArticleRepository.java
|
Java
|
[] | null |
[] |
package es.upm.miw.repositories;
import es.upm.miw.documents.Article;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ArticleRepository extends MongoRepository<Article, String> {
}
| 221 | 0.832579 | 0.832579 | 8 | 26.625 | 29.723465 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
10
|
53b9df3060e31dafb185d0ea917d2fedf679e4fb
| 10,136,122,857,752 |
034e0d9ce5a00dab7f8119fd02d52a1458eefa40
|
/lab03/wej01/src/main/java/daniel/filmy/Film.java
|
29af0407bb80e879bd1de28c2464865b1d038a71
|
[] |
no_license
|
Pariston/Testowanie-Automatyczne
|
https://github.com/Pariston/Testowanie-Automatyczne
|
c64af1db5e029cc305c6900c4eee8cada6144f36
|
339967936b93311e9ea11bcc8a824a71ae260cd2
|
refs/heads/master
| 2021-01-21T04:31:01.957000 | 2016-06-20T08:26:35 | 2016-06-20T08:26:35 | 52,866,720 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package daniel.filmy;
import java.util.ArrayList;
import java.util.List;
public class Film {
public String tytul;
public String opis;
public int rokProdukcji;
//public List<film> filmy = new ArrayList();
public Film(String Tytul, String Opis, int RokProdukcji) {
this.tytul = Tytul;
this.opis = Opis;
this.rokProdukcji = RokProdukcji;
}
}
|
UTF-8
|
Java
| 355 |
java
|
Film.java
|
Java
|
[] | null |
[] |
package daniel.filmy;
import java.util.ArrayList;
import java.util.List;
public class Film {
public String tytul;
public String opis;
public int rokProdukcji;
//public List<film> filmy = new ArrayList();
public Film(String Tytul, String Opis, int RokProdukcji) {
this.tytul = Tytul;
this.opis = Opis;
this.rokProdukcji = RokProdukcji;
}
}
| 355 | 0.729577 | 0.729577 | 17 | 19.882353 | 15.903689 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.470588 | false | false |
10
|
78b42853b0c384c25cd42751841e2a3e94985da4
| 31,756,988,204,452 |
4a9dff8ea8b07d85ed62c0389fa97c8c07d2fede
|
/mini-security-browser/src/main/java/com/yicj/security/browser/validate/code/impl/SessionValidateCodeRepository.java
|
810d1668cfc680e5f833c2403977d8fcff52fd96
|
[] |
no_license
|
yichengjie/spring-security-study4
|
https://github.com/yichengjie/spring-security-study4
|
6fdc7f648b20532217c17909d7474e18f9de1f7d
|
94d44c2efe1f23a49f6fb8fd92a855dd6696808a
|
refs/heads/master
| 2022-12-10T21:31:34.120000 | 2020-09-10T12:19:28 | 2020-09-10T12:19:28 | 291,486,020 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yicj.security.browser.validate.code.impl;
import com.yicj.security.browser.session.support.HttpSessionSessionStrategy;
import com.yicj.security.browser.session.support.SessionStrategy;
import com.yicj.security.core.validate.model.ValidateCode;
import com.yicj.security.core.validate.code.ValidateCodeRepository;
import com.yicj.security.core.validate.model.ValidateCodeType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
/**
* ClassName: SessionValidateCodeRepository
* Description: TODO(描述)
* Date: 2020/8/31 15:17
*
* @author yicj(626659321 @ qq.com)
* 修改记录
* @version 产品版本信息 yyyy-mm-dd 姓名(邮箱) 修改信息
*/
@Component
public class SessionValidateCodeRepository implements ValidateCodeRepository {
/**
* 验证码放入session时的前缀
*/
String SESSION_KEY_PREFIX = "SESSION_KEY_FOR_CODE_";
/**
* 操作session的工具类
*/
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType validateCodeType) {
sessionStrategy.setAttribute(request, getSessionKey(request, validateCodeType), code);
}
/**
* 构建验证码放入session时的key
*
* @param request
* @return
*/
private String getSessionKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
return SESSION_KEY_PREFIX + validateCodeType.toString().toUpperCase();
}
@Override
public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {
return (ValidateCode) sessionStrategy.getAttribute(request, getSessionKey(request, validateCodeType));
}
@Override
public void remove(ServletWebRequest request, ValidateCodeType codeType) {
sessionStrategy.removeAttribute(request, getSessionKey(request, codeType));
}
}
|
UTF-8
|
Java
| 2,050 |
java
|
SessionValidateCodeRepository.java
|
Java
|
[
{
"context": "TODO(描述)\r\n * Date: 2020/8/31 15:17\r\n *\r\n * @author yicj(626659321 @ qq.com)\r\n * 修改记录\r\n * @version 产品版本信息 ",
"end": 635,
"score": 0.9995443224906921,
"start": 631,
"tag": "USERNAME",
"value": "yicj"
}
] | null |
[] |
package com.yicj.security.browser.validate.code.impl;
import com.yicj.security.browser.session.support.HttpSessionSessionStrategy;
import com.yicj.security.browser.session.support.SessionStrategy;
import com.yicj.security.core.validate.model.ValidateCode;
import com.yicj.security.core.validate.code.ValidateCodeRepository;
import com.yicj.security.core.validate.model.ValidateCodeType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
/**
* ClassName: SessionValidateCodeRepository
* Description: TODO(描述)
* Date: 2020/8/31 15:17
*
* @author yicj(626659321 @ qq.com)
* 修改记录
* @version 产品版本信息 yyyy-mm-dd 姓名(邮箱) 修改信息
*/
@Component
public class SessionValidateCodeRepository implements ValidateCodeRepository {
/**
* 验证码放入session时的前缀
*/
String SESSION_KEY_PREFIX = "SESSION_KEY_FOR_CODE_";
/**
* 操作session的工具类
*/
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType validateCodeType) {
sessionStrategy.setAttribute(request, getSessionKey(request, validateCodeType), code);
}
/**
* 构建验证码放入session时的key
*
* @param request
* @return
*/
private String getSessionKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
return SESSION_KEY_PREFIX + validateCodeType.toString().toUpperCase();
}
@Override
public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {
return (ValidateCode) sessionStrategy.getAttribute(request, getSessionKey(request, validateCodeType));
}
@Override
public void remove(ServletWebRequest request, ValidateCodeType codeType) {
sessionStrategy.removeAttribute(request, getSessionKey(request, codeType));
}
}
| 2,050 | 0.728848 | 0.718654 | 60 | 30.733334 | 33.461853 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433333 | false | false |
10
|
fb37dce6b56d58dbf292750b30d9e5b14c6941d6
| 2,156,073,634,889 |
b39dcfd86528c538843b5cc299562e12bb6163a2
|
/src/test/java/org/ligson/designmode/behavior/strategy/Minus.java
|
b128070b7c0fc5934c7214cc70da647cb3f837a4
|
[] |
no_license
|
nguyenanh1997/demo
|
https://github.com/nguyenanh1997/demo
|
690ba53c33317094245d18a64f63349841e4afe9
|
725036dc51a2f9eaa2dd20b8cb9a2533e9c82434
|
refs/heads/master
| 2021-04-08T15:15:15.427000 | 2015-03-30T05:55:52 | 2015-03-30T05:55:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.ligson.designmode.behavior.strategy;
/**
* @author liuzhongbing
* 减法计算类
*/
public class Minus extends AbstractCalculator implements ICalculator {
public int calculate(String expression) {
int arrayInt[] = split(expression, "-");
return arrayInt[0] - arrayInt[1];
}
}
|
UTF-8
|
Java
| 311 |
java
|
Minus.java
|
Java
|
[
{
"context": "n.designmode.behavior.strategy;\r\n\r\n/**\r\n * @author liuzhongbing\r\n * 减法计算类\r\n */\r\npublic class Minus extends Abstra",
"end": 80,
"score": 0.9919326901435852,
"start": 68,
"tag": "USERNAME",
"value": "liuzhongbing"
}
] | null |
[] |
package org.ligson.designmode.behavior.strategy;
/**
* @author liuzhongbing
* 减法计算类
*/
public class Minus extends AbstractCalculator implements ICalculator {
public int calculate(String expression) {
int arrayInt[] = split(expression, "-");
return arrayInt[0] - arrayInt[1];
}
}
| 311 | 0.700997 | 0.694352 | 12 | 23.083334 | 22.691622 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false |
10
|
ce6f5606c01373a6736c97a522980a920ffd2aa8
| 2,156,073,634,083 |
7e008363a58ba12d9e31f98604047dfa7763642b
|
/src/main/java/workerapp/task/impl/StopTask.java
|
a6ec6949e2eb5d6dd4d38b9c6f6c5b172fbce99a
|
[] |
no_license
|
amozh/common-worker
|
https://github.com/amozh/common-worker
|
32f5be7ff8e6e4710d65d5eaa901a25b423825c0
|
155411a8e180b1085624db5b22a0df37508ef218
|
refs/heads/master
| 2021-05-29T23:53:48.412000 | 2015-10-08T19:55:14 | 2015-10-08T19:55:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package workerapp.task.impl;
import org.springframework.beans.factory.annotation.Autowired;
import workerapp.ApplicationManager;
import workerapp.message.HttpTaskMessage;
import workerapp.task.Task;
import workerapp.task.WorkResult;
/**
* Created by Andrii Mozharovskyi on 29.09.2015.
*/
public class StopTask extends Task {
@Autowired
ApplicationManager applicationManager;
@Override
public WorkResult process() {
System.out.println("Stop task");
applicationManager.interrupt();
return new WorkResult(new HttpTaskMessage()); //TODO: implement real work result for stop task
}
}
|
UTF-8
|
Java
| 628 |
java
|
StopTask.java
|
Java
|
[
{
"context": "port workerapp.task.WorkResult;\n\n/**\n * Created by Andrii Mozharovskyi on 29.09.2015.\n */\npublic class StopTask extends ",
"end": 272,
"score": 0.9998767375946045,
"start": 253,
"tag": "NAME",
"value": "Andrii Mozharovskyi"
}
] | null |
[] |
package workerapp.task.impl;
import org.springframework.beans.factory.annotation.Autowired;
import workerapp.ApplicationManager;
import workerapp.message.HttpTaskMessage;
import workerapp.task.Task;
import workerapp.task.WorkResult;
/**
* Created by <NAME> on 29.09.2015.
*/
public class StopTask extends Task {
@Autowired
ApplicationManager applicationManager;
@Override
public WorkResult process() {
System.out.println("Stop task");
applicationManager.interrupt();
return new WorkResult(new HttpTaskMessage()); //TODO: implement real work result for stop task
}
}
| 615 | 0.748408 | 0.735669 | 22 | 27.545454 | 24.418188 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
10
|
9ad6f47d503fe45cf2601824c19d67518a3a5553
| 2,662,879,786,260 |
0ceca1b56ae65ca3819f0213b936de5e7150417e
|
/SFResourceAllocator/src/com/saiglobal/sf/allocator/processor/MIP3RetailProcessor.java
|
0731234e6e22a491dcfb40533c1d2460fdf387f2
|
[] |
no_license
|
LucaContri/dataanalysis
|
https://github.com/LucaContri/dataanalysis
|
a2351c9f000e8ef8ed26fd9b1061868267518ce8
|
9a0b4dc2b8164b41aa0db18d4c1222b0e64fa2a7
|
refs/heads/master
| 2021-01-23T04:39:05.946000 | 2018-01-03T10:10:50 | 2018-01-03T10:10:50 | 92,932,412 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.saiglobal.sf.allocator.processor;
/*
* MIP2Processon + Milk Runs
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.google.ortools.linearsolver.MPConstraint;
import com.google.ortools.linearsolver.MPObjective;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
import com.google.ortools.linearsolver.MPSolver.ResultStatus;
import com.saiglobal.sf.allocator.data.DbHelper;
import com.saiglobal.sf.allocator.rules.ProcessorRule;
import com.saiglobal.sf.core.model.Competency;
import com.saiglobal.sf.core.model.CompetencyType;
import com.saiglobal.sf.core.model.Location;
import com.saiglobal.sf.core.model.Resource;
import com.saiglobal.sf.core.model.ResourceCalendar;
import com.saiglobal.sf.core.model.ResourceEvent;
import com.saiglobal.sf.core.model.ResourceEventType;
import com.saiglobal.sf.core.model.Schedule;
import com.saiglobal.sf.core.model.ScheduleParameters;
import com.saiglobal.sf.core.model.ScheduleStatus;
import com.saiglobal.sf.core.model.ScheduleType;
import com.saiglobal.sf.core.model.SfResourceType;
import com.saiglobal.sf.core.model.TravelCostCalculationType;
import com.saiglobal.sf.core.model.WorkItem;
import com.saiglobal.sf.core.utility.Utility;
public class MIP3RetailProcessor implements Processor {
static {
// OR Tools
// https://github.com/google/or-tools/releases/download/v5.1/or-tools_flatzinc_VisualStudio2015-64bit_v5.1.4045.zip
// https://developers.google.com/optimization/
System.loadLibrary("jniortools");
}
protected DbHelper db;
protected ScheduleParameters parameters;
protected List<WorkItem> workItemList;
protected List<Resource> resources;
protected Logger logger = Logger.getLogger(AbstractProcessor.class);
final double infinity = Double.MAX_VALUE;
final Locale currentLocale = Locale.getDefault();
final NumberFormat percentFormatter = NumberFormat.getPercentInstance(currentLocale);
final NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
final long maxExecTime = 3000000; // 50 minutes
final int cost_of_not_performing = 50000;
final int no_of_closest_auditors = 5;
int timeSlothours = 1;
int startHourBusinessDay = 8;
int endHourBusinessDay = 18;
int no_of_time_slots_day = Math.floorDiv(endHourBusinessDay-startHourBusinessDay, timeSlothours);
List<WorkItem> workItemListBatch = null;
String solverType = null;
String period = null;
int num_audits = 0;
int num_auditors = 0;
int num_time_slots = 0;
double[][][] costs = null;
double[] resource_capacity = null;
int[][] resource_availability = null;
double[][][] audit_duration = null;
TravelCostCalculationType travelCostCalculationType = TravelCostCalculationType.EMPIRICAL_UK;
public MIP3RetailProcessor(DbHelper db, ScheduleParameters parameters) throws Exception {
this.db = db;
this.parameters = parameters;
this.init();
}
@Override
public void execute() throws Exception {
// Sort workItems
Utility.startTimeCounter("MIP3Processor.execute");
workItemList = sortWorkItems(workItemList);
saveBatchDetails(this.parameters);
// Break processing in sub-groups based on period
List<String> periods = parameters.getPeriodsWorkingDays().keySet().stream().sorted().collect(Collectors.toList());
for (String local_period : periods) {
period = local_period;
logger.info("Start processing batch " + period + ". Time: " + System.currentTimeMillis());
workItemListBatch = workItemList.stream().filter(wi -> Utility.getPeriodformatter().format(wi.getTargetDate()).equalsIgnoreCase(period) && wi.isPrimary()).collect(Collectors.toList());
List<Schedule> schedule = scheduleBatch();
logger.info("Saving schedule for batch " + period + ". Time: " + System.currentTimeMillis());
saveSchedule(schedule);
}
updateBatchDetails(this.parameters);
Utility.stopTimeCounter("MIP3Processor.execute");
Utility.logAllProcessingTime();
Utility.logAllEventCounter();
}
@Override
public List<ProcessorRule> getRules() {
return null;
}
@Override
public int getBatchSize() {
return 0;
}
protected Logger initLogger() {
return Logger.getLogger(MIP3RetailProcessor.class);
}
protected List<WorkItem> sortWorkItems(List<WorkItem> workItemList) {
// Sort WI by target date
Utility.startTimeCounter("MIPProcessor.sortWorkItems");
Comparator<WorkItem> byDate = (wi1, wi2) -> Long.compare(
wi1.getTargetDate().getTime(), wi2.getTargetDate().getTime());
workItemList = workItemList.stream().sorted(byDate).collect(Collectors.toList());
Utility.stopTimeCounter("MIPProcessor.sortWorkItems");
return workItemList;
}
private static MPSolver createSolver (String solverType) {
try {
return new MPSolver("IntegerProgrammingExample", MPSolver.OptimizationProblemType.valueOf(solverType));
} catch (java.lang.IllegalArgumentException e) {
return null;
}
}
private double calculateSolutionCost(HashMap<String, MPVariable> x, TravelCostCalculationType travelCostCalculationType) throws Exception {
double totalCost = 0;
// The value of each variable in the solution.
for (String key : x.keySet()) {
if(x.get(key).solutionValue()>0) {
Index idx = new Index(key);
if(idx.getAuditor()<resources.size()) {
logger.debug(resources.get(idx.getAuditor()).getName() + " assigned to audit " + workItemListBatch.get(idx.getAudit()).getName() + " to be performed on: " + Utility.getActivitydateformatter().format(getTimeFromSlot(idx.getTimeSlot(), period).getTime()) + (idx.getAudit()==idx.getPreviousAudit()?"":(" as part of a milk run following audit" + workItemListBatch.get(idx.getPreviousAudit()).getName())));
totalCost += Utility.calculateAuditCost(resources.get(idx.getAuditor()), workItemListBatch.get(idx.getAudit()), workItemListBatch.get(idx.getPreviousAudit()), travelCostCalculationType, db, (idx.getPreviousAudit()!=idx.getAudit() || getFollowingAuditInMilkRun(idx, x)==null), idx.getPreviousAudit()==idx.getAudit(),getFollowingAuditInMilkRun(idx, x)==null);
} else {
logger.debug("Audit " + workItemListBatch.get(idx.getAudit()).getName() + " unallocated");
totalCost += workItemListBatch.get(idx.getAudit()).getCostOfNotAllocating();
}
}
}
return totalCost;
}
private SolverResult solve(boolean[][][][] constraints) throws Exception {
logger.debug("Start solve(int[][][][] constraints)");
boolean timeConstrained = true;
if(constraints[0][0][0].length==1)
timeConstrained = false;
// Instantiate a mixed-integer solver
MPSolver solver = createSolver(solverType);
if (solver == null) {
logger.error("Could not create solver " + solverType);
return null;
}
// Variables
logger.debug("MPVariable[constraints.length][constraints[0].length][constraints[0][0].length][constraints[0][0][0].length = " + constraints.length * constraints[0].length * constraints[0][0].length *constraints[0][0][0].length);
HashMap<String, MPVariable> x = new HashMap<String, MPVariable>();
for (int i = 0; i < constraints.length; i++) {
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t])
x.put(i+","+j+","+jp+","+t, solver.makeIntVar(0, 1, "x["+i+","+j+","+jp+","+t+"]"));
}
}
}
}
// Constraints
// The total duration of the tasks each worker takes on in a month is at most his/her capacity in the month.
for (int i = 0; i < constraints.length-1; i++) {
MPConstraint ct1 = solver.makeConstraint(0, resource_capacity[i]);
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t]) {
ct1.setCoefficient(x.get(i+","+j+","+jp+","+t), audit_duration[i][j][jp]);
if(parameters.isMilkRuns() && j!=jp) {
// If auditor i* performs audit j* preceded by audit jp*(!=j) at time t*, then auditor i* has to perform audit jp* at time (t*-audit_duration[i][jp][jp2])
MPConstraint ct2 = solver.makeConstraint(0, 1);
ct2.setCoefficient(x.get(i+","+j+","+jp+","+t), -1);
for (int jp2 = 0; jp2 < constraints[i][jp].length; jp2++) {
//for (int t2 = 0; t2 < constraints[i][jp][jp2].length; t2++) {
if (((t-(int)Math.ceil(audit_duration[i][jp][jp2]/timeSlothours)>=0)
//&& (t2 == t-(int)Math.ceil(audit_duration[i][jp][jp2]/timeSlothours))
)
|| !timeConstrained)
ct2.setCoefficient(x.get(i+","+jp+","+jp2+","+(timeConstrained?(t-(int)Math.ceil(audit_duration[i][jp][jp2]/timeSlothours)):0)), 1);
//else
//ct2.setCoefficient(x.get(i+","+jp+","+jp2+","+t2), 0);
//}
}
}
}
}
}
}
}
if(timeConstrained) {
// The duration of each task each worker takes is at most his/her availability at the time it is taken
for (int i = 0; i < constraints.length-1; i++) {
for (int t = 0; t < constraints[i][0][0].length; t++) {
MPConstraint ct = solver.makeConstraint(0, resource_availability[i][t]*timeSlothours);
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
if (constraints[i][j][jp][t])
ct.setCoefficient(x.get(i+","+j+","+jp+","+t), audit_duration[i][j][jp]);
}
}
}
}
// No overlapping jobs
for (int i = 0; i < constraints.length-1; i++) {
// For each auditor
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t]) {
// For each audit j preceded by audit jp starting at time t ...
int audit_duration_timeslots = (int) Math.ceil(audit_duration[i][j][jp]/timeSlothours);
// ... there are no other audit j2 starting at t+s; for each 0 < s < audit_duration_timeslots
for (int s = 0; s < audit_duration_timeslots; s++) {
MPConstraint ct = solver.makeConstraint(0, 1);
ct.setCoefficient(x.get(i+","+j+","+jp+","+t), 1);
if (t+s<num_time_slots) {
for (int j2 = 0; j2 < constraints[i].length; j2++) {
for (int jp2 = 0; jp2 < constraints[i][j2].length; jp2++) {
if(j2!=j && constraints[i][j2][jp2][t+s]) {
ct.setCoefficient(x.get(i+","+j2+","+jp2+","+(t+s)), 1);
}
}
}
}
}
}
}
}
}
}
}
// Each task is assigned to one worker in one time slot only and preceded by one audit only.
for (int j = 0; j < constraints[0].length; j++) {
MPConstraint ct = solver.makeConstraint(1, 1);
for (int i = 0; i < constraints.length; i++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t])
ct.setCoefficient(x.get(i+","+j+","+jp+","+t), 1);
}
}
}
}
// Objective: Minimise total cost
MPObjective objective = solver.objective();
for (int i = 0; i < constraints.length; i++) {
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t])
objective.setCoefficient(x.get(i+","+j+","+jp+","+t), costs[i][j][jp]);
}
}
}
}
logger.info("No audits:" + workItemListBatch.size());
logger.info("No auditors:" + resources.size());
logger.info("No. variables: " + solver.numVariables());
logger.info("No. constraints: " + solver.numConstraints());
//solver.enableOutput();
solver.setTimeLimit(maxExecTime);
ResultStatus resultStatus = solver.solve();
// Verify that the solution satisfies all constraints (when using solvers
// others than GLOP_LINEAR_PROGRAMMING, this is highly recommended!).
if (!solver.verifySolution(/*tolerance=*/1e-7, /*logErrors=*/true)) {
logger.error("The solution returned by the solver violated the problem constraints by at least 1e-7");
throw new Exception("The solution returned by the solver violated the problem constraints by at least 1e-7");
}
logger.info("Problem solved in " + solver.wallTime() + " milliseconds");
logger.info("No. interations : " + solver.iterations());
logger.info("Problem solved in " + solver.nodes() + " branch-and-bound nodes");
logger.info("Optimal objective value = " + currencyFormatter.format(solver.objective().value()));
logger.info("Total cost: " + currencyFormatter.format(calculateSolutionCost(x, travelCostCalculationType)));
SolverResult sr = new SolverResult();
sr.setSolver(solver);
sr.setResultStatus(resultStatus);
sr.setVariables(x);
logger.debug("Finished solve(int[][][][] constraints)");
return sr;
}
private void initBatchVariables() throws Exception {
logger.debug("Start initBatchVariables()");
// SCIP_MIXED_INTEGER_PROGRAMMING - (http://scip.zib.de/)
// GLPK_MIXED_INTEGER_PROGRAMMING - (https://www.gnu.org/software/glpk/)
// CBC_MIXED_INTEGER_PROGRAMMING - (https://projects.coin-or.org/Cbc)
solverType = "CBC_MIXED_INTEGER_PROGRAMMING";
costs = getCostMatrix();
// Maximum total of task sizes for any worker
num_audits = workItemListBatch.size();
num_auditors = resources.size()+1; // Add a fake auditor to assign impossible tasks
num_time_slots = getPeriodSlots(period);
resource_capacity = getResourceCapacityMatrix();
resource_availability = getResourceAvailailityMatrix();
audit_duration = getAuditDurationMatrix();
logger.debug("Finished initBatchVariables()");
}
private boolean[][][][] presolve() {
/*
* Presolving. The purpose of presolving, which takes place
* before the tree search is started, is to reduces
* the size of the model by removing irrelevant information
* such as redundant constraints or fixed variables.
*/
logger.debug("Start presolve()");
boolean[][][][] constraints = new boolean[num_auditors][num_audits][num_audits][num_time_slots];
for (int i = 0; i < num_auditors; i++) {
for (int j = 0; j < num_audits; j++) {
for (int jp = 0; jp < num_audits; jp++) {
for (int t = 0; t < num_time_slots; t++) {
// Default
constraints[i][j][jp][t] = true;
// If this is the fake auditor we allow only scheduling of no milk runs (j!=jp) at time zero (t=0)
if(i==num_auditors-1) {
if(j!=jp || t>0)
constraints[i][j][jp][t] = false;
else
constraints[i][j][jp][t] = true;
continue;
}
/*
boolean heuristicExcludeAsNotGoodCandidateForMilkRun = false;
heuristicIf:
if(parameters.isMilkRuns()) {
double distanceJToJp = Double.MAX_VALUE;
double distanceHomeToJ = Double.MAX_VALUE;
double distanceHomeToJp = Double.MAX_VALUE;
try {
distanceJToJp = Utility.calculateDistanceKm(workItemListBatch.get(j).getClientSite(), workItemListBatch.get(jp).getClientSite(), db);
} catch (Exception e) {
//Ignore. Use default
}
try {
distanceHomeToJp = Utility.calculateDistanceKm(resources.get(i).getHome(), workItemListBatch.get(jp).getClientSite(), db);
} catch (Exception e) {
//Ignore. Use default
}
if(distanceJToJp>=distanceHomeToJp) {
heuristicExcludeAsNotGoodCandidateForMilkRun = true;
break heuristicIf;
}
try {
distanceHomeToJ = Utility.calculateDistanceKm(resources.get(i).getHome(), workItemListBatch.get(j).getClientSite(), db);
} catch (Exception e) {
//Ignore. Use default
}
double travelTimeJToJ = Utility.calculateTravelTimeHrsRetail(distanceJToJp, false);
if (travelTimeJToJ>0) {
// If travel time between the audits cannot be done within normal daily duties
heuristicExcludeAsNotGoodCandidateForMilkRun = true;
break heuristicIf;
}
double travelTimeHomeToJ = Utility.calculateTravelTimeHrsRetail(distanceHomeToJ, false);
if (travelTimeHomeToJ==0) {
// If travel time between auditor and audit is 0 (i.e. done within normal duty), the audit cannot be part of a milk run for this auditor at any time
heuristicExcludeAsNotGoodCandidateForMilkRun = true;
}
}
if (heuristicExcludeAsNotGoodCandidateForMilkRun) {
// Excludes auditors/audit combinations not a good candidate for milk run
constraints[i][j][jp][t] = false;
continue;
}
*/
double jpMinDuration = Arrays.stream(audit_duration[i][jp]).min().orElse(0);
if (i<num_auditors-1
&& (
((t - (int) Math.ceil(jpMinDuration)/timeSlothours<0) && j!=jp)
|| (resource_availability[i][t]<Math.ceil(audit_duration[i][j][jp]/timeSlothours))
|| ((t - (int) Math.ceil(jpMinDuration))>=0 && (resource_availability[i][t - (int) Math.ceil(jpMinDuration)/timeSlothours]<Math.ceil(jpMinDuration/timeSlothours))) && j!=jp)) {
// Exclude not available dates either for audit j starting at t or preceding audit jp starting at (t - (int) Math.ceil(jpMinDuration)/timeSlothours)
constraints[i][j][jp][t] = false;
continue;
}
// If not doing milk runs excludes all j!=jp
if(!parameters.isMilkRuns() && j!=jp) {
constraints[i][j][jp][t] = false;
continue;
}
}
}
}
}
// TODO: Exclude assignments which will lead to auditor being away for longer than X days
logger.debug("Finshed presolve()");
return constraints;
}
private boolean orArray(boolean[] a) {
for (boolean b : a) {
if(b)
return true;
}
return false;
}
protected List<Schedule> scheduleBatch() throws Exception {
initBatchVariables();
boolean[][][][] constraints = presolve();
// Solve relaxed problem excluding time slots constraints to find a lower bound (LB)
logger.debug("Start relaxedConstraints");
boolean[][][][] relaxedConstraints = new boolean[constraints.length][constraints[0].length][constraints[0][0].length][1];
for (int i = 0; i < relaxedConstraints.length; i++) {
for (int j = 0; j < relaxedConstraints[i].length; j++) {
for (int jp = 0; jp < relaxedConstraints[i][j].length; jp++) {
if (orArray(constraints[i][j][jp]))
relaxedConstraints[i][j][jp][0] = true;
else
relaxedConstraints[i][j][jp][0] = false;
}
}
}
logger.debug("Finished relaxedConstraints");
SolverResult srRelaxed = solve(relaxedConstraints);
ResultStatus resultStatusRelaxed = srRelaxed.getResultStatus();
HashMap<String, MPVariable> xRelaxed = srRelaxed.getVariables();
double lowerBound = -1;
// Check that the problem has an optimal solution.
if (resultStatusRelaxed != MPSolver.ResultStatus.OPTIMAL) {
logger.error("Could not find an optimal solution to the relaxed problem in the time limit of " + maxExecTime/1000/60 + " minutes");
} else {
lowerBound = srRelaxed.getSolver().objective().value();
logger.info("Found LB of cost: " + currencyFormatter.format(lowerBound) + " (" + currencyFormatter.format(calculateSolutionCost(xRelaxed, travelCostCalculationType)) +")");
}
SolverResult sr = null;
ResultStatus resultStatus = null;
HashMap<String, MPVariable> x = null;
double obj = Double.MAX_VALUE;
// Solve full problem
sr = solve(constraints);
resultStatus = sr.getResultStatus();
obj = sr.getSolver().objective().value();
if (resultStatus.equals(MPSolver.ResultStatus.OPTIMAL)) {
x = sr.getVariables();
logger.info("Found optimal Solution with objective value of " + currencyFormatter.format(obj) + " (" + currencyFormatter.format(calculateSolutionCost(x, travelCostCalculationType)) +")");
}
if (resultStatus.equals(MPSolver.ResultStatus.FEASIBLE)) {
x = sr.getVariables();
if(lowerBound>0)
logger.info("Found feasable solution with objective value of " + currencyFormatter.format(obj) + " vs lower bound of " + currencyFormatter.format(lowerBound) + " (+" + percentFormatter.format((obj-lowerBound)/lowerBound) + ")");
else
logger.info("Found feasable solution with objective value of " + currencyFormatter.format(obj));
}
// Move unallocated to next month within target.
Calendar auxStart = Calendar.getInstance();
Calendar auxEnd = Calendar.getInstance();
for (WorkItem wi : getUnallocated(x)) {
WorkItem wil = getWorkItemFromList(wi.getId());
auxStart.setTimeInMillis(wil.getTargetDate().getTime());
auxEnd.setTimeInMillis(wil.getEndAuditWindow().getTime());
auxStart.add(Calendar.MONTH, 1);
if (auxStart.before(auxEnd)) {
logger.debug("Moving unallocated audit " + wil.getName() + " from " + Utility.getPeriodformatter().format(wil.getTargetDate()) + " to " + Utility.getPeriodformatter().format(auxStart.getTime()));
wil.setTargetDate(new Date(auxStart.getTimeInMillis()));
wil.setCostOfNotAllocating(wil.getCostOfNotAllocating()+cost_of_not_performing);
wil.setLog(false);
} else {
wil.setLog(true);
wil.setComment("Not allocated due to missing availability");
logger.debug("Cannot allocate audit " + wil.getName() + " and cannot move to next period (" + Utility.getPeriodformatter().format(auxStart.getTime()) + ") as it is outside the audit window end date (" + Utility.getPeriodformatter().format(wil.getEndAuditWindow()) + ")");
}
}
return populateSchedule(x);
}
private WorkItem getWorkItemFromList(String workItemId) {
if (workItemId == null)
return null;
for (WorkItem wi : workItemList) {
if (wi.getId().equalsIgnoreCase(workItemId))
return wi;
}
return null;
}
private List<WorkItem> getUnallocated(HashMap<String, MPVariable> x) {
List<WorkItem> unallocated = new ArrayList<WorkItem>();
if (x == null)
return unallocated;
auditloop:
for (int j = 0; j < num_audits; j++) {
for (int jp = 0; jp < num_audits; jp++) {
for (int t = 0; t < num_time_slots; t++) {
Index idx = new Index(num_auditors-1, j, jp, t);
if(x.containsKey(idx.toKey()) && x.get(idx.toKey()).solutionValue()>0) {
unallocated.add(workItemListBatch.get(j));
continue auditloop;
}
}
}
}
return unallocated;
}
@SuppressWarnings("unused")
private List<Integer> getClosestAuditors(int j) {
Comparator<Resource> byDistance = (r1, r2) -> Double.compare(
Utility.calculateDistanceKm(
r1.getHome().getLatitude(), r1.getHome().getLongitude(),
workItemListBatch.get(j).getClientSite().getLatitude(), workItemListBatch.get(j).getClientSite().getLongitude()),
Utility.calculateDistanceKm(
r2.getHome().getLatitude(), r2.getHome().getLongitude(),
workItemListBatch.get(j).getClientSite().getLatitude(), workItemListBatch.get(j).getClientSite().getLongitude()));
int[] closestAuditors =
resources.stream()
.filter(r -> r.canPerform(workItemListBatch.get(j)))
.sorted(byDistance)
.limit(no_of_closest_auditors)
.mapToInt(r -> getResourceIndex(r))
.toArray();
List<Integer> closestAuditorsList = new ArrayList<Integer>();
for (int i = 0; i < closestAuditors.length; i++) {
closestAuditorsList.add(closestAuditors[i]);
}
return closestAuditorsList;
}
private int getResourceIndex(Resource resource) {
for (int i = 0; i < resources.size(); i++) {
if (resources.get(i).getId().equals(resource.getId()))
return i;
}
return -1;
}
@SuppressWarnings("unused")
private int[] getNumAuditsByPeriod(List<WorkItem> workItemList) {
// Return an array of x elements where x is the no. of periods and each element contains a pointer to the first audit in the period
List<Integer> aux = new ArrayList<Integer>();
// Work Items are already sorted by start date
String currentPeriod = Utility.getPeriodformatter().format(workItemList.get(0).getStartDate());
aux.add(0);
for (int i = 0; i < workItemList.size(); i++) {
if (!Utility.getPeriodformatter().format(workItemList.get(i).getStartDate()).equalsIgnoreCase(currentPeriod)) {
currentPeriod = Utility.getPeriodformatter().format(workItemList.get(i).getStartDate());
aux.add(i);
}
}
aux.add(workItemList.size());
int[] retValue = new int[aux.size()];
for (int i = 0; i < aux.size(); i++) {
retValue[i] = aux.get(i).intValue();
}
return retValue;
}
private double[][][] getAuditDurationMatrix() {
double[][][] auditDurations = new double[resources.size()+1][workItemListBatch.size()][workItemListBatch.size()];
for (int i = 0; i <= resources.size(); i++) {
for (int j = 0; j < workItemListBatch.size(); j++) {
for (int jp = 0; jp < workItemListBatch.size(); jp++) {
double distance = 0;
if (!workItemListBatch.get(j).getServiceDeliveryType().equalsIgnoreCase("Off Site")) {
try {
if(j==jp) {
distance = Utility.calculateDistanceKm(workItemListBatch.get(j).getClientSite(), resources.get(i).getHome(), db);
} else {
distance = Utility.calculateDistanceKm(workItemListBatch.get(jp).getClientSite(), workItemListBatch.get(j).getClientSite(), db);
}
} catch (Exception e) {
// Assume infinite distance
distance = Double.MAX_VALUE;
}
}
auditDurations[i][j][jp] =
workItemListBatch.get(j).getRequiredDuration()
+ workItemListBatch.get(j).getLinkedWorkItems().stream().mapToInt(wi -> (int) Math.ceil(wi.getRequiredDuration())).sum()
+ Math.round(Utility.calculateTravelTimeHrsRetail(distance, false));
}
}
}
return auditDurations;
}
private int[][] getResourceAvailailityMatrix() throws ParseException {
/* Returns a 2-dimensional array
* For each resource
* For each time slot
* -> no. of consecutive slots available.
*/
int[][] resourceAvailability = new int[resources.size()+1][getPeriodSlots(period)];
for(int t = 0; t < resourceAvailability[0].length; t++) {
// For each time slot
for (int i = 0; i < resourceAvailability.length-1; i++) {
// For each resource
// TODO: Commenting for testing purpose only. Remove in final version
Calendar date = getTimeFromSlot(t, period);
/*
Calendar tomorrow = Calendar.getInstance();
tomorrow.add(Calendar.DATE, 1);
if (date.before(tomorrow)) {
// Can't schedule in the past !!!
resourceAvailability[i][t] = 0;
} else {
*/
//logger.info("Time slot " + t + " = " + Utility.getMysqldateformat().format(date.getTime()));
Calendar firstWeekend = Calendar.getInstance();
firstWeekend.setTime(date.getTime());
firstWeekend.add(Calendar.DAY_OF_MONTH, Math.max(6-(date.get(Calendar.DAY_OF_WEEK)==1?7:date.get(Calendar.DAY_OF_WEEK)-1),0));
firstWeekend.set(Calendar.HOUR_OF_DAY, startHourBusinessDay);
//logger.info("First weekend = " + Utility.getMysqldateformat().format(firstWeekend.getTime()));
Calendar firstEventAfterDate = Calendar.getInstance();
firstEventAfterDate.setTime(resources.get(i).getCalender().getEvents().stream()
.filter(e -> e.getEndDateTime().getTime()>date.getTimeInMillis())
.map(e -> e.getStartDateTime()).min(Date::compareTo).orElse(firstWeekend.getTime()));
//logger.info("First event after date= " + Utility.getMysqldateformat().format(firstEventAfterDate.getTime()));
if (firstWeekend.before(firstEventAfterDate))
firstEventAfterDate.setTime(firstWeekend.getTime());
resourceAvailability[i][t] = 0;
date.add(Calendar.HOUR_OF_DAY, timeSlothours);
while (date.before(firstEventAfterDate)) {
//logger.info("Time slot " + t + " = " + Utility.getMysqldateformat().format(date.getTime()));
if(date.get(Calendar.HOUR_OF_DAY)-timeSlothours>=startHourBusinessDay && date.get(Calendar.HOUR_OF_DAY)<=endHourBusinessDay)
resourceAvailability[i][t]++;
date.add(Calendar.HOUR_OF_DAY, timeSlothours);
//}
//logger.info("Slot available at date = " + resourceAvailability[i][t]);
}
}
resourceAvailability[resourceAvailability.length-1][t] = Integer.MAX_VALUE;
}
return resourceAvailability;
}
private double[] getResourceCapacityMatrix() {
HashMap<String, Integer> periodWorkingDays = parameters.getPeriodsWorkingDays();
double[] resourceCapacity = new double[resources.size()+1];
for (int i = 0; i < resourceCapacity.length-1; i++) {
// For each resource
double bopDays = (double) (Math.ceil(resources.get(i).getCalender().getEvents().stream().filter(e -> e.getPeriod().equalsIgnoreCase(period.toString()) && e.getType().equals(ResourceEventType.SF_BOP)).mapToDouble(ResourceEvent::getDurationWorkingDays).sum() * 2) / 2);
double auditDays = (double) (Math.ceil(resources.get(i).getCalender().getEvents().stream().filter(e -> e.getPeriod().equalsIgnoreCase(period.toString()) && (e.getType().equals(ResourceEventType.ALLOCATOR_WIR)||e.getType().equals(ResourceEventType.SF_WIR)||e.getType().equals(ResourceEventType.ALLOCATOR_TRAVEL))).mapToDouble(ResourceEvent::getDurationWorkingDays).sum() * 2) / 2);
resourceCapacity[i] = Math.max(((periodWorkingDays.get(period) - bopDays)*resources.get(i).getCapacity()/100 - auditDays)*8,0);
}
resourceCapacity[resourceCapacity.length-1] = infinity;
return resourceCapacity;
}
private Calendar getTimeFromSlot(int slotNo, String period) throws ParseException {
Calendar periodC = Calendar.getInstance();
periodC.setTime(Utility.getPeriodformatter().parse(period));
return getTimeFromSlot(slotNo, periodC);
}
private Calendar getTimeFromSlot(int slotNo, Calendar period) {
Calendar date = Calendar.getInstance();
date.setTime(period.getTime());
date.add(Calendar.DAY_OF_MONTH, slotNo/no_of_time_slots_day);
date.set(Calendar.HOUR_OF_DAY, startHourBusinessDay + (slotNo%no_of_time_slots_day)*timeSlothours);
return date;
}
private int getSlotFromTime(Calendar date) throws ParseException {
Calendar start = Calendar.getInstance();
start.setTime(Utility.getPeriodformatter().parse(period));
int daysFromStart = (int) Math.floor((date.getTimeInMillis()-start.getTimeInMillis())/1000/60/60/24);
return (daysFromStart)*no_of_time_slots_day
+ Math.max(date.get(Calendar.HOUR_OF_DAY)-startHourBusinessDay,0)/timeSlothours;
}
private int getSlotFromTime(Date date) throws ParseException {
Calendar aux = Calendar.getInstance();
aux.setTime(date);
return getSlotFromTime(aux);
}
private int getPeriodSlots(Calendar period) {
/* 1 Slot = 1/2 Day
* i.e. Period January 2017
* slot 0 = 1/1/17 am
* slot 1 = 1/1/17 pm
* slot 2 = 2/1/17 am
* ...
* slot 61 = 31/1/17 pm
*/
int no_of_slots = period.getMaximum(Calendar.DAY_OF_MONTH)*no_of_time_slots_day;
return no_of_slots;
}
private int getPeriodSlots(Date period) {
Calendar periodC = Calendar.getInstance();
periodC.setTime(period);
return getPeriodSlots(periodC);
}
private int getPeriodSlots(String period) throws ParseException {
Date periodD = Utility.getPeriodformatter().parse(period);
return getPeriodSlots(periodD);
}
private double[][][] getCostMatrix() throws Exception {
double[][][] costs = new double[resources.size()+1][workItemListBatch.size()][workItemListBatch.size()];
for (int j = 0; j < workItemListBatch.size(); j++) {
for (int jp = 0; jp < workItemListBatch.size(); jp++) {
for (int i = 0; i < resources.size(); i++) {
// At this point I do not know if the audit is the last in the milk run. However, if we minimise the one way travel cost, we minimise the return travel cost.
costs[i][j][jp] = Utility.calculateAuditCost(resources.get(i), workItemListBatch.get(j), workItemListBatch.get(j),travelCostCalculationType, db, true, jp==j, false);
}
// Cost of not performing the audit
costs[resources.size()][j][jp] = workItemListBatch.get(j).getCostOfNotAllocating();
}
}
return costs;
}
private Index getPreviousAuditInMilkRun(Index idx, HashMap<String, MPVariable> solution) {
if (idx.getAudit()==idx.getPreviousAudit())
return idx;
for (int jp=0; jp<num_audits; jp++)
for (int t=0;t<num_time_slots; t++)
if(solution.containsKey(idx.getKey(idx.getAuditor(), idx.getPreviousAudit(), jp, t)) && solution.get(idx.getKey(idx.getAuditor(), idx.getPreviousAudit(), jp, t)).solutionValue()>0)
return new Index(idx.getAuditor(), idx.getPreviousAudit(), jp, t);
return null;
}
private Index getFollowingAuditInMilkRun(Index idx, HashMap<String, MPVariable> solution) {
for (int jp=0; jp<num_audits; jp++) {
for (int t=0;t<num_time_slots; t++) {
if(solution.containsKey(idx.getKey(idx.getAuditor(), jp, idx.getAudit(), t)) && solution.get(idx.getKey(idx.getAuditor(), jp, idx.getAudit(), t)).solutionValue()>0 )
return new Index(idx.getAuditor(), jp, idx.getAudit(), t);
}
}
return null; // Last Audit in milk run
}
private Index getFirstAuditInMilkRun(Index idx, HashMap<String, MPVariable> solution) {
Index previousAudit = getPreviousAuditInMilkRun(idx, solution);
if(previousAudit.getAudit() == idx.getAudit())
return idx;
else
return getPreviousAuditInMilkRun(previousAudit, solution);
}
private String getMilkRunId(Index idx, HashMap<String, MPVariable> solution) {
return workItemListBatch.get(getFirstAuditInMilkRun(idx, solution).getAudit()).getId();
}
private String getMilkRunId(String key, HashMap<String, MPVariable> solution) {
return getMilkRunId(new Index(key), solution);
}
private List<Schedule> populateSchedule(HashMap<String, MPVariable> x) throws Exception {
List<Schedule> returnSchedule = new ArrayList<Schedule>();
if(x == null)
return returnSchedule;
// The value of each variable in the solution.
for (String key :x.keySet()) {
if (x.get(key).solutionValue()>0) {
Index idx = new Index(key);
// Initialise Schedule
List<Schedule> schedules = Schedule.getSchedules(workItemListBatch.get(idx.getAudit()));
if (idx.getAuditor()<num_auditors-1) {
// Assigned to actual resource. I.e. Allocated
workItemListBatch.get(idx.getAudit()).setLog(true);
for (Schedule schedule : schedules) {
schedule.setResourceId(resources.get(idx.getAuditor()).getId());
schedule.setResourceName(resources.get(idx.getAuditor()).getName());
schedule.setResourceType(resources.get(idx.getAuditor()).getType());
schedule.setStatus(ScheduleStatus.ALLOCATED);
schedule.setWorkItemGroup(getMilkRunId(key,x));
schedule.setTotalCost(Utility.calculateAuditCost(resources.get(idx.getAuditor()), workItemListBatch.get(idx.getAudit()), workItemListBatch.get(idx.getPreviousAudit()), travelCostCalculationType, db, (idx.getAudit()!=idx.getPreviousAudit() || getFollowingAuditInMilkRun(idx, x)!=null), idx.getAudit()==idx.getPreviousAudit(), getFollowingAuditInMilkRun(idx, x)!=null));
if (workItemListBatch.get(idx.getAudit()).getServiceDeliveryType().equalsIgnoreCase("Off Site"))
schedule.setDistanceKm(0);
else
if (idx.getAudit()==idx.getPreviousAudit())
schedule.setDistanceKm(Utility.calculateDistanceKm(workItemListBatch.get(idx.getAudit()).getClientSite(), resources.get(idx.getAuditor()).getHome(), db));
else
schedule.setDistanceKm(Utility.calculateDistanceKm(workItemListBatch.get(idx.getPreviousAudit()).getClientSite(), workItemListBatch.get(idx.getAudit()).getClientSite(), db));
schedule.setTravelDuration(Math.round(Utility.calculateTravelTimeHrsRetail(schedule.getDistanceKm(), false)));
}
Schedule travelling = new Schedule(workItemListBatch.get(idx.getAudit()));
travelling.setType(ScheduleType.TRAVEL);
travelling.setDistanceKm(schedules.get(0).getDistanceKm());
travelling.setResourceId(schedules.get(0).getResourceId());
travelling.setResourceName(schedules.get(0).getResourceName());
travelling.setResourceType(schedules.get(0).getResourceType());
travelling.setTravelDuration(schedules.get(0).getTravelDuration());
travelling.setDuration(schedules.get(0).getTravelDuration());
travelling.setStatus(ScheduleStatus.ALLOCATED);
if (idx.getAudit()==idx.getPreviousAudit())
travelling.setNotes("Travel from " + resources.get(idx.getAuditor()).getHome().getCity() + " (" + resources.get(idx.getAuditor()).getHome().getPostCode() + ")" +" to " + workItemListBatch.get(idx.getAudit()).getClientSite().getCity() + " (" + workItemListBatch.get(idx.getAudit()).getClientSite().getPostCode() + ")");
else
travelling.setNotes("Travel from " + workItemListBatch.get(idx.getPreviousAudit()).getClientSite().getCity() + " (" + workItemListBatch.get(idx.getPreviousAudit()).getClientSite().getPostCode() + ")" +" to " + workItemListBatch.get(idx.getAudit()).getClientSite().getCity() + " (" + workItemListBatch.get(idx.getAudit()).getClientSite().getPostCode() + ")");
//postProcessTravel(returnSchedule, travelling);
Schedule travellingReturn = new Schedule(workItemListBatch.get(idx.getAudit()));
travellingReturn.setType(ScheduleType.TRAVEL);
travellingReturn.setResourceId(schedules.get(0).getResourceId());
travellingReturn.setResourceName(schedules.get(0).getResourceName());
travellingReturn.setResourceType(schedules.get(0).getResourceType());
travellingReturn.setStatus(ScheduleStatus.ALLOCATED);
if (getFollowingAuditInMilkRun(idx, x) == null) {
// This is the last audit in the milk run. Add travel return home.
travellingReturn.setDistanceKm(Utility.calculateDistanceKm(workItemListBatch.get(idx.getAudit()).getClientSite(), resources.get(idx.getAuditor()).getHome(), db));
travellingReturn.setTravelDuration(Math.round(Utility.calculateTravelTimeHrsRetail(travellingReturn.getDistanceKm(), false)));
travellingReturn.setDuration(travellingReturn.getTravelDuration());
} else {
travellingReturn.setDistanceKm(0);
travellingReturn.setTravelDuration(0);
travellingReturn.setDuration(0);
}
//postProcessTravel(returnSchedule, travellingReturn);
// Set Start and End Dates for events
int slotPointer = idx.getTimeSlot();
travelling.setStartDate(getTimeFromSlot(slotPointer, period).getTime());
slotPointer += (int) Math.ceil(travelling.getTravelDuration()/timeSlothours);
travelling.setEndDate(getTimeFromSlot(slotPointer, period).getTime());
for (Schedule schedule : schedules) {
schedule.setStartDate(getTimeFromSlot(slotPointer, period).getTime());
slotPointer += (int) Math.ceil(schedule.getWorkItemDuration()/timeSlothours);
schedule.setEndDate(getTimeFromSlot(slotPointer, period).getTime());
}
travellingReturn.setStartDate(getTimeFromSlot(slotPointer, period).getTime());
slotPointer += (int) Math.ceil(travelling.getTravelDuration()/timeSlothours);
travellingReturn.setEndDate(getTimeFromSlot(slotPointer, period).getTime());
// Book resource for audit - One event for each time slot
Resource resource = resources.get(idx.getAuditor());
slotPointer = idx.getTimeSlot() + (int) Math.ceil(travelling.getTravelDuration()/timeSlothours);;
for (Schedule schedule : schedules) {
for (int t1 = 0; t1 < (int) Math.ceil(schedule.getWorkItemDuration()/timeSlothours); t1++) {
ResourceEvent eventToBook = new ResourceEvent();
eventToBook.setType(ResourceEventType.ALLOCATOR_WIR);
eventToBook.setStartDateTime(getTimeFromSlot(slotPointer, period).getTime());
slotPointer++;
eventToBook.setEndDateTime(getTimeFromSlot(slotPointer, period).getTime());
resource.bookFor(eventToBook);
}
}
// Book resource for travel
ResourceEvent travelToBook = new ResourceEvent();
travelToBook.setType(ResourceEventType.ALLOCATOR_TRAVEL);
travelToBook.setStartDateTime(travelling.getStartDate());
travelToBook.setEndDateTime(travelling.getEndDate());
resource.bookFor(travelToBook);
ResourceEvent travelToBookReturn = new ResourceEvent();
travelToBookReturn.setType(ResourceEventType.ALLOCATOR_TRAVEL);
travelToBookReturn.setStartDateTime(travellingReturn.getStartDate());
travelToBookReturn.setEndDateTime(travellingReturn.getEndDate());
resource.bookFor(travelToBookReturn);
// Add to return schedule
if(travelling.getDuration()>0)
returnSchedule.add(travelling);
if(travellingReturn.getDuration()>0)
returnSchedule.add(travellingReturn);
} else {
final int j1 = idx.getAudit();
schedules.stream().forEach(s -> s.setNotes(workItemListBatch.get(j1).getComment()));
schedules.stream().forEach(s -> s.setTotalCost(workItemListBatch.get(j1).getCostOfNotAllocating()));
}
// Add unallocated only if needs to be logged. Unallocated audits moved to next period are not logged to avoid duplications
if(workItemListBatch.get(idx.getAudit()).isLog()) {
returnSchedule.addAll(schedules);
}
}
}
return scheduleToEvents(returnSchedule);
}
private List<Schedule> scheduleToEvents(List<Schedule> schedules) throws ParseException {
List<Schedule> events = new ArrayList<Schedule>();
for (Schedule schedule : schedules) {
if (schedule.getStatus().equals(ScheduleStatus.NOT_ALLOCATED)) {
events.add(schedule);
} else {
for(int t = getSlotFromTime(schedule.getStartDate()); t < getSlotFromTime(schedule.getStartDate()) + (int) Math.ceil(schedule.getDuration()/timeSlothours); t++) {
Schedule event = new Schedule(schedule);
event.setStartDate(new Date(getTimeFromSlot(t, period).getTimeInMillis()));
event.setEndDate(new Date(getTimeFromSlot(t, period).getTimeInMillis()+timeSlothours*60*60*1000));
event.setDuration(timeSlothours);
events.add(event);
}
}
}
return events;
}
class Index {
private int auditor, audit, previousAudit, timeSlot;
public Index(int auditor, int audit, int previousAudit, int timeSlot) {
super();
this.auditor = auditor;
this.audit = audit;
this.previousAudit = previousAudit;
this.timeSlot = timeSlot;
}
public Index(String key) {
super();
String[] idx = key.split(",");
this.auditor = Integer.parseInt(idx[0]);
this.audit = Integer.parseInt(idx[1]);
this.previousAudit = Integer.parseInt(idx[2]);
this.timeSlot = Integer.parseInt(idx[3]);
}
public int getAuditor() {
return auditor;
}
public void setAuditor(int auditor) {
this.auditor = auditor;
}
public int getAudit() {
return audit;
}
public void setAudit(int audit) {
this.audit = audit;
}
public int getPreviousAudit() {
return previousAudit;
}
public void setPreviousAudit(int previousAudit) {
this.previousAudit = previousAudit;
}
public int getTimeSlot() {
return timeSlot;
}
public String getKey(int i, int j, int js, int t) {
return i + "," + j + "," + js + "," + t;
}
public String toKey() {
return getKey(getAuditor(), getAudit(), getPreviousAudit(), getTimeSlot());
}
public void setTimeSlot(int timeSlot) {
this.timeSlot = timeSlot;
}
}
class SolverResult {
private ResultStatus resultStatus = null;
private HashMap<String, MPVariable> variables = null;
private MPSolver solver = null;
public ResultStatus getResultStatus() {
return resultStatus;
}
public void setResultStatus(ResultStatus resultStatus) {
this.resultStatus = resultStatus;
}
public HashMap<String, MPVariable> getVariables() {
return variables;
}
public void setVariables(HashMap<String, MPVariable> variables) {
this.variables = variables;
}
public MPSolver getSolver() {
return solver;
}
public void setSolver(MPSolver solver) {
this.solver = solver;
}
}
protected void postProcessWorkItemList() {
final Calendar start = Calendar.getInstance();
start.setTime(parameters.getStartDate());
final Calendar end = Calendar.getInstance();
end.setTime(parameters.getEndDate());
if(parameters.getBoltOnStandards() != null) {
for (WorkItem wi : workItemList) {
if (parameters.getBoltOnStandards().contains(wi.getPrimaryStandard().getCompetencyName())) {
logger.debug("Found Bolt-On audit " + wi.getName() + " (" + wi.getPrimaryStandard().getCompetencyName() + ")");
wi.setPrimary(false);
// Find primary wi and add the bolt-on to it
WorkItem primaryWi = workItemList.stream().filter(wi2 ->
wi2.getClientSite().getFullAddress().equalsIgnoreCase(wi.getClientSite().getFullAddress()) &&
//Utility.getPeriodformatter().format(wi2.getTargetDate()).equalsIgnoreCase(Utility.getPeriodformatter().format(wi.getTargetDate())) &&
!wi2.getId().equals(wi.getId()))
.findFirst()
.orElse(null);
if (primaryWi != null) {
primaryWi.getLinkedWorkItems().add(wi);
logger.debug("Added Bolt-On audit " + wi.getName() + " (" + Utility.getActivitydateformatter().format(wi.getTargetDate()) + ") to " + primaryWi.getName() + " (" + Utility.getActivitydateformatter().format(primaryWi.getTargetDate()) + ")");
} else {
logger.debug("Could not add Bolt-On audit " + wi.getName() + " (" + Utility.getActivitydateformatter().format(wi.getTargetDate()) + ") to any other audit in scope.");
}
}
}
}
Calendar auxStart = Calendar.getInstance();
Calendar auxEnd = Calendar.getInstance();
for (WorkItem wi : workItemList) {
// Default Audit Window = Target Month
auxStart.setTime(wi.getTargetDate());
auxEnd.setTime(wi.getTargetDate());
auxStart.set(Calendar.DAY_OF_MONTH, 1);
auxEnd.set(Calendar.DAY_OF_MONTH, auxEnd.getActualMaximum(Calendar.DAY_OF_MONTH));
// Custom audit windows
// Audit Window outside period - override
if (auxStart.before(start))
auxStart.set(Calendar.MONTH,start.get(Calendar.MONTH));
if (auxEnd.before(start))
auxEnd.set(Calendar.MONTH,start.get(Calendar.MONTH));
if (auxStart.after(end))
auxStart.set(Calendar.MONTH,end.get(Calendar.MONTH));
if (auxEnd.after(end))
auxEnd.set(Calendar.MONTH,end.get(Calendar.MONTH));
wi.setTargetDate(new Date(auxStart.getTimeInMillis()));
wi.setStartAuditWindow(new Date(auxStart.getTimeInMillis()));
wi.setEndAuditWindow(new Date(auxEnd.getTimeInMillis()));
wi.setCostOfNotAllocating(cost_of_not_performing);
}
}
public void init() throws Exception {
// Init logger
logger = this.initLogger();
Utility.startTimeCounter("MIP3RetailProcessor.init");
// Init tables
this.db.executeStatement(this.db.getCreateScheduleTableSql());
this.db.executeStatement(this.db.getCreateScheduleBatchTableSql());
if (parameters.getBatchId() == null)
this.parameters.setBatchId(getNewBatchId());
this.parameters.setSubBatchId(getLastSubBatchId()+1);
// Init WorkItems and Resources
resources = getResourceBatch(parameters);
for (Resource r : resources) {
logger.debug(r.toCsv());
}
workItemList = getWorkItemBatch(parameters);
if (parameters.includePipeline()) {
List<WorkItem> pipelineWI = getPipelineWorkItems();
for (WorkItem workItem : pipelineWI) {
workItemList.add(workItem);
}
}
postProcessWorkItemList();
Utility.stopTimeCounter("MIP3RetailProcessor.init");
}
private List<WorkItem> getWorkItemBatch(ScheduleParameters parameters2) throws Exception {
List<WorkItem> retValue = new ArrayList<WorkItem>();
String query = "select a.Id, a.client_name as 'clientName', s.address as 'clientAddress', geo.Latitude as 'clientLatitude', geo.Longitude as 'clientLongitude', a.date as 'auditDate', a.audit_definition, a.call_time, a.audit_definition "
+ "from retail.audits a "
+ "inner join retail.sites s on a.site_id = s.Id "
+ "left join salesforce.saig_geocode_cache geo on s.address = geo.Address "
+ "where "
+ "a.auditor_name in ('" + StringUtils.join(parameters2.getResourceNames(), "','") + "') "
+ "and a.date between '" + Utility.getActivitydateformatter().format(parameters2.getStartDate()) + "' and '" + Utility.getActivitydateformatter().format(parameters2.getEndDate()) + "';";
ResultSet rs = db.executeSelect(query, -1);
while (rs.next()) {
WorkItem wi = new WorkItem();
wi.setName(rs.getString("id"));
wi.setId(rs.getString("id"));
Location clientSite = new Location();
clientSite.setName(rs.getString("clientName"));
clientSite.setAddress_1(rs.getString("clientAddress"));
clientSite.setLatitude(rs.getDouble("clientLatitude"));
clientSite.setLongitude(rs.getDouble("clientLongitude"));
wi.setClientSite(clientSite);
Calendar aux = Calendar.getInstance();
aux.setTime(Utility.getMysqldateformat().parse(rs.getString("auditDate")));
aux.set(Calendar.DATE, 1);
wi.setTargetDate(aux.getTime());
wi.setRequiredDuration(rs.getDouble("call_time")/60);
wi.setServiceDeliveryType("On Site");
List<Competency> competencies = new ArrayList<Competency>();
competencies.add(new Competency(rs.getString("audit_definition"), rs.getString("audit_definition"), CompetencyType.PRIMARYSTANDARD, ""));
wi.setRequiredCompetencies(competencies);
retValue.add(wi);
}
return retValue;
}
private List<Resource> getResourceBatch(ScheduleParameters parameters2) throws Exception {
List<Resource> retValue = new ArrayList<Resource>();
String query = "select r.*, "
+ "geo.Latitude, "
+ "geo.Longitude "
+ "from retail.auditors r "
+ "left join salesforce.saig_geocode_cache geo on r.`home_address` = geo.Address "
+ "where r.name in ('" + StringUtils.join(parameters2.getResourceNames(), "','") + "');";
ResultSet rs = db.executeSelect(query, -1);
while (rs.next()) {
Resource r = new Resource();
r.setName(rs.getString("name"));
r.setId(rs.getString("id"));
r.setHome(new Location(rs.getString("home_address"), rs.getString("home_address"), "", "", "", rs.getString("country"), "", "", rs.getDouble("latitude"), rs.getDouble("longitude")));
r.setCapacity(100);
r.setType(SfResourceType.Employee);
r.setHourlyRate(0.0);
r.setCalendar(new ResourceCalendar(r, parameters2.getCalendarStartDate(), parameters2.getCalendarEndDate()));
r.getCalender().setEvents(new ArrayList<ResourceEvent>());
retValue.add(r);
}
return retValue;
}
private int getLastSubBatchId() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
String query = "SELECT MAX(SubBatchId) FROM " + this.db.getScheduleBatchTableName() + " WHERE BatchId='" + this.getBatchId() + "'";
return db.executeScalarInt(query);
}
protected void saveSchedule(List<Schedule> scheduleList) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
// Early exit
if(scheduleList == null || scheduleList.size()==0)
return;
String insert = "INSERT INTO " + this.db.getScheduleTableName() +
" (`BatchId`, `SubBatchId`, `WorkItemId`, `WorkItemName`, `WorkItemSource`, `WorkItemCountry`, `WorkItemState`, `WorkItemTimeZone`, `ResourceId`, `ResourceName`, `ResourceType`, `StartDate`, `EndDate`, `Duration`, `TravelDuration`, `Status`, `Type`, `PrimaryStandard`, `Competencies`, `Comment`, `Distance`, `Notes`, `WorkItemGroup`, `TotalCost`) VALUES ";
for (Schedule schedule : scheduleList) {
insert += " \n('" + getBatchId() + "', " + getSubBatchId() + ", " + schedule.toSqlString() + ") ,";
}
this.db.executeStatement(Utility.removeLastChar(insert));
}
protected void saveBatchDetails(ScheduleParameters parameters) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
String insert = "INSERT INTO " + this.db.getScheduleBatchTableName() +
" (`BatchId`, `SubBatchId`, `RevenueOwnership`, `SchedulingOwnership`, `ReportingBusinessUnits`, `AuditCountries`, `ResourceCountries`, `ScoreContractorPenalties`,`ScoreAvailabilityDayReward`,`ScoreDistanceKmPenalty`,`ScoreCapabilityAuditPenalty`, `WorkItemStatuses`, `ResourceTypes`, `StartDate`, `EndDate`, `Comment`, `completed`, `created`) " +
"VALUES (" + parameters.toSqlString() + ", 0, utc_timestamp())";
this.db.executeStatement(insert);
}
protected void updateBatchDetails(ScheduleParameters parameters) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
String update = "UPDATE " + this.db.getScheduleBatchTableName() + " SET lastModified=utc_timestamp(), completed = 1 WHERE BatchId = '" + parameters.getBatchId() + "' AND SubBatchId = " + parameters.getSubBatchId();
this.db.executeStatement(update);
}
protected List<WorkItem> getPipelineWorkItems() {
return new ArrayList<WorkItem>();
};
protected List<Resource> sortResources(List<Resource> resourceList) {
return resourceList;
};
protected String getNewBatchId() {
return UUID.randomUUID().toString();
}
public String getBatchId() {
return this.parameters.getBatchId();
}
public int getSubBatchId() {
return this.parameters.getSubBatchId();
}
@Override
public void setDbHelper(DbHelper db) {
this.db = db;
}
@Override
public void setParameters(ScheduleParameters sp) {
this.parameters = sp;
}
}
|
UTF-8
|
Java
| 53,966 |
java
|
MIP3RetailProcessor.java
|
Java
|
[] | null |
[] |
package com.saiglobal.sf.allocator.processor;
/*
* MIP2Processon + Milk Runs
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.google.ortools.linearsolver.MPConstraint;
import com.google.ortools.linearsolver.MPObjective;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
import com.google.ortools.linearsolver.MPSolver.ResultStatus;
import com.saiglobal.sf.allocator.data.DbHelper;
import com.saiglobal.sf.allocator.rules.ProcessorRule;
import com.saiglobal.sf.core.model.Competency;
import com.saiglobal.sf.core.model.CompetencyType;
import com.saiglobal.sf.core.model.Location;
import com.saiglobal.sf.core.model.Resource;
import com.saiglobal.sf.core.model.ResourceCalendar;
import com.saiglobal.sf.core.model.ResourceEvent;
import com.saiglobal.sf.core.model.ResourceEventType;
import com.saiglobal.sf.core.model.Schedule;
import com.saiglobal.sf.core.model.ScheduleParameters;
import com.saiglobal.sf.core.model.ScheduleStatus;
import com.saiglobal.sf.core.model.ScheduleType;
import com.saiglobal.sf.core.model.SfResourceType;
import com.saiglobal.sf.core.model.TravelCostCalculationType;
import com.saiglobal.sf.core.model.WorkItem;
import com.saiglobal.sf.core.utility.Utility;
public class MIP3RetailProcessor implements Processor {
static {
// OR Tools
// https://github.com/google/or-tools/releases/download/v5.1/or-tools_flatzinc_VisualStudio2015-64bit_v5.1.4045.zip
// https://developers.google.com/optimization/
System.loadLibrary("jniortools");
}
protected DbHelper db;
protected ScheduleParameters parameters;
protected List<WorkItem> workItemList;
protected List<Resource> resources;
protected Logger logger = Logger.getLogger(AbstractProcessor.class);
final double infinity = Double.MAX_VALUE;
final Locale currentLocale = Locale.getDefault();
final NumberFormat percentFormatter = NumberFormat.getPercentInstance(currentLocale);
final NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
final long maxExecTime = 3000000; // 50 minutes
final int cost_of_not_performing = 50000;
final int no_of_closest_auditors = 5;
int timeSlothours = 1;
int startHourBusinessDay = 8;
int endHourBusinessDay = 18;
int no_of_time_slots_day = Math.floorDiv(endHourBusinessDay-startHourBusinessDay, timeSlothours);
List<WorkItem> workItemListBatch = null;
String solverType = null;
String period = null;
int num_audits = 0;
int num_auditors = 0;
int num_time_slots = 0;
double[][][] costs = null;
double[] resource_capacity = null;
int[][] resource_availability = null;
double[][][] audit_duration = null;
TravelCostCalculationType travelCostCalculationType = TravelCostCalculationType.EMPIRICAL_UK;
public MIP3RetailProcessor(DbHelper db, ScheduleParameters parameters) throws Exception {
this.db = db;
this.parameters = parameters;
this.init();
}
@Override
public void execute() throws Exception {
// Sort workItems
Utility.startTimeCounter("MIP3Processor.execute");
workItemList = sortWorkItems(workItemList);
saveBatchDetails(this.parameters);
// Break processing in sub-groups based on period
List<String> periods = parameters.getPeriodsWorkingDays().keySet().stream().sorted().collect(Collectors.toList());
for (String local_period : periods) {
period = local_period;
logger.info("Start processing batch " + period + ". Time: " + System.currentTimeMillis());
workItemListBatch = workItemList.stream().filter(wi -> Utility.getPeriodformatter().format(wi.getTargetDate()).equalsIgnoreCase(period) && wi.isPrimary()).collect(Collectors.toList());
List<Schedule> schedule = scheduleBatch();
logger.info("Saving schedule for batch " + period + ". Time: " + System.currentTimeMillis());
saveSchedule(schedule);
}
updateBatchDetails(this.parameters);
Utility.stopTimeCounter("MIP3Processor.execute");
Utility.logAllProcessingTime();
Utility.logAllEventCounter();
}
@Override
public List<ProcessorRule> getRules() {
return null;
}
@Override
public int getBatchSize() {
return 0;
}
protected Logger initLogger() {
return Logger.getLogger(MIP3RetailProcessor.class);
}
protected List<WorkItem> sortWorkItems(List<WorkItem> workItemList) {
// Sort WI by target date
Utility.startTimeCounter("MIPProcessor.sortWorkItems");
Comparator<WorkItem> byDate = (wi1, wi2) -> Long.compare(
wi1.getTargetDate().getTime(), wi2.getTargetDate().getTime());
workItemList = workItemList.stream().sorted(byDate).collect(Collectors.toList());
Utility.stopTimeCounter("MIPProcessor.sortWorkItems");
return workItemList;
}
private static MPSolver createSolver (String solverType) {
try {
return new MPSolver("IntegerProgrammingExample", MPSolver.OptimizationProblemType.valueOf(solverType));
} catch (java.lang.IllegalArgumentException e) {
return null;
}
}
private double calculateSolutionCost(HashMap<String, MPVariable> x, TravelCostCalculationType travelCostCalculationType) throws Exception {
double totalCost = 0;
// The value of each variable in the solution.
for (String key : x.keySet()) {
if(x.get(key).solutionValue()>0) {
Index idx = new Index(key);
if(idx.getAuditor()<resources.size()) {
logger.debug(resources.get(idx.getAuditor()).getName() + " assigned to audit " + workItemListBatch.get(idx.getAudit()).getName() + " to be performed on: " + Utility.getActivitydateformatter().format(getTimeFromSlot(idx.getTimeSlot(), period).getTime()) + (idx.getAudit()==idx.getPreviousAudit()?"":(" as part of a milk run following audit" + workItemListBatch.get(idx.getPreviousAudit()).getName())));
totalCost += Utility.calculateAuditCost(resources.get(idx.getAuditor()), workItemListBatch.get(idx.getAudit()), workItemListBatch.get(idx.getPreviousAudit()), travelCostCalculationType, db, (idx.getPreviousAudit()!=idx.getAudit() || getFollowingAuditInMilkRun(idx, x)==null), idx.getPreviousAudit()==idx.getAudit(),getFollowingAuditInMilkRun(idx, x)==null);
} else {
logger.debug("Audit " + workItemListBatch.get(idx.getAudit()).getName() + " unallocated");
totalCost += workItemListBatch.get(idx.getAudit()).getCostOfNotAllocating();
}
}
}
return totalCost;
}
private SolverResult solve(boolean[][][][] constraints) throws Exception {
logger.debug("Start solve(int[][][][] constraints)");
boolean timeConstrained = true;
if(constraints[0][0][0].length==1)
timeConstrained = false;
// Instantiate a mixed-integer solver
MPSolver solver = createSolver(solverType);
if (solver == null) {
logger.error("Could not create solver " + solverType);
return null;
}
// Variables
logger.debug("MPVariable[constraints.length][constraints[0].length][constraints[0][0].length][constraints[0][0][0].length = " + constraints.length * constraints[0].length * constraints[0][0].length *constraints[0][0][0].length);
HashMap<String, MPVariable> x = new HashMap<String, MPVariable>();
for (int i = 0; i < constraints.length; i++) {
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t])
x.put(i+","+j+","+jp+","+t, solver.makeIntVar(0, 1, "x["+i+","+j+","+jp+","+t+"]"));
}
}
}
}
// Constraints
// The total duration of the tasks each worker takes on in a month is at most his/her capacity in the month.
for (int i = 0; i < constraints.length-1; i++) {
MPConstraint ct1 = solver.makeConstraint(0, resource_capacity[i]);
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t]) {
ct1.setCoefficient(x.get(i+","+j+","+jp+","+t), audit_duration[i][j][jp]);
if(parameters.isMilkRuns() && j!=jp) {
// If auditor i* performs audit j* preceded by audit jp*(!=j) at time t*, then auditor i* has to perform audit jp* at time (t*-audit_duration[i][jp][jp2])
MPConstraint ct2 = solver.makeConstraint(0, 1);
ct2.setCoefficient(x.get(i+","+j+","+jp+","+t), -1);
for (int jp2 = 0; jp2 < constraints[i][jp].length; jp2++) {
//for (int t2 = 0; t2 < constraints[i][jp][jp2].length; t2++) {
if (((t-(int)Math.ceil(audit_duration[i][jp][jp2]/timeSlothours)>=0)
//&& (t2 == t-(int)Math.ceil(audit_duration[i][jp][jp2]/timeSlothours))
)
|| !timeConstrained)
ct2.setCoefficient(x.get(i+","+jp+","+jp2+","+(timeConstrained?(t-(int)Math.ceil(audit_duration[i][jp][jp2]/timeSlothours)):0)), 1);
//else
//ct2.setCoefficient(x.get(i+","+jp+","+jp2+","+t2), 0);
//}
}
}
}
}
}
}
}
if(timeConstrained) {
// The duration of each task each worker takes is at most his/her availability at the time it is taken
for (int i = 0; i < constraints.length-1; i++) {
for (int t = 0; t < constraints[i][0][0].length; t++) {
MPConstraint ct = solver.makeConstraint(0, resource_availability[i][t]*timeSlothours);
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
if (constraints[i][j][jp][t])
ct.setCoefficient(x.get(i+","+j+","+jp+","+t), audit_duration[i][j][jp]);
}
}
}
}
// No overlapping jobs
for (int i = 0; i < constraints.length-1; i++) {
// For each auditor
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t]) {
// For each audit j preceded by audit jp starting at time t ...
int audit_duration_timeslots = (int) Math.ceil(audit_duration[i][j][jp]/timeSlothours);
// ... there are no other audit j2 starting at t+s; for each 0 < s < audit_duration_timeslots
for (int s = 0; s < audit_duration_timeslots; s++) {
MPConstraint ct = solver.makeConstraint(0, 1);
ct.setCoefficient(x.get(i+","+j+","+jp+","+t), 1);
if (t+s<num_time_slots) {
for (int j2 = 0; j2 < constraints[i].length; j2++) {
for (int jp2 = 0; jp2 < constraints[i][j2].length; jp2++) {
if(j2!=j && constraints[i][j2][jp2][t+s]) {
ct.setCoefficient(x.get(i+","+j2+","+jp2+","+(t+s)), 1);
}
}
}
}
}
}
}
}
}
}
}
// Each task is assigned to one worker in one time slot only and preceded by one audit only.
for (int j = 0; j < constraints[0].length; j++) {
MPConstraint ct = solver.makeConstraint(1, 1);
for (int i = 0; i < constraints.length; i++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t])
ct.setCoefficient(x.get(i+","+j+","+jp+","+t), 1);
}
}
}
}
// Objective: Minimise total cost
MPObjective objective = solver.objective();
for (int i = 0; i < constraints.length; i++) {
for (int j = 0; j < constraints[i].length; j++) {
for (int jp = 0; jp < constraints[i][j].length; jp++) {
for (int t = 0; t < constraints[i][j][jp].length; t++) {
if (constraints[i][j][jp][t])
objective.setCoefficient(x.get(i+","+j+","+jp+","+t), costs[i][j][jp]);
}
}
}
}
logger.info("No audits:" + workItemListBatch.size());
logger.info("No auditors:" + resources.size());
logger.info("No. variables: " + solver.numVariables());
logger.info("No. constraints: " + solver.numConstraints());
//solver.enableOutput();
solver.setTimeLimit(maxExecTime);
ResultStatus resultStatus = solver.solve();
// Verify that the solution satisfies all constraints (when using solvers
// others than GLOP_LINEAR_PROGRAMMING, this is highly recommended!).
if (!solver.verifySolution(/*tolerance=*/1e-7, /*logErrors=*/true)) {
logger.error("The solution returned by the solver violated the problem constraints by at least 1e-7");
throw new Exception("The solution returned by the solver violated the problem constraints by at least 1e-7");
}
logger.info("Problem solved in " + solver.wallTime() + " milliseconds");
logger.info("No. interations : " + solver.iterations());
logger.info("Problem solved in " + solver.nodes() + " branch-and-bound nodes");
logger.info("Optimal objective value = " + currencyFormatter.format(solver.objective().value()));
logger.info("Total cost: " + currencyFormatter.format(calculateSolutionCost(x, travelCostCalculationType)));
SolverResult sr = new SolverResult();
sr.setSolver(solver);
sr.setResultStatus(resultStatus);
sr.setVariables(x);
logger.debug("Finished solve(int[][][][] constraints)");
return sr;
}
private void initBatchVariables() throws Exception {
logger.debug("Start initBatchVariables()");
// SCIP_MIXED_INTEGER_PROGRAMMING - (http://scip.zib.de/)
// GLPK_MIXED_INTEGER_PROGRAMMING - (https://www.gnu.org/software/glpk/)
// CBC_MIXED_INTEGER_PROGRAMMING - (https://projects.coin-or.org/Cbc)
solverType = "CBC_MIXED_INTEGER_PROGRAMMING";
costs = getCostMatrix();
// Maximum total of task sizes for any worker
num_audits = workItemListBatch.size();
num_auditors = resources.size()+1; // Add a fake auditor to assign impossible tasks
num_time_slots = getPeriodSlots(period);
resource_capacity = getResourceCapacityMatrix();
resource_availability = getResourceAvailailityMatrix();
audit_duration = getAuditDurationMatrix();
logger.debug("Finished initBatchVariables()");
}
private boolean[][][][] presolve() {
/*
* Presolving. The purpose of presolving, which takes place
* before the tree search is started, is to reduces
* the size of the model by removing irrelevant information
* such as redundant constraints or fixed variables.
*/
logger.debug("Start presolve()");
boolean[][][][] constraints = new boolean[num_auditors][num_audits][num_audits][num_time_slots];
for (int i = 0; i < num_auditors; i++) {
for (int j = 0; j < num_audits; j++) {
for (int jp = 0; jp < num_audits; jp++) {
for (int t = 0; t < num_time_slots; t++) {
// Default
constraints[i][j][jp][t] = true;
// If this is the fake auditor we allow only scheduling of no milk runs (j!=jp) at time zero (t=0)
if(i==num_auditors-1) {
if(j!=jp || t>0)
constraints[i][j][jp][t] = false;
else
constraints[i][j][jp][t] = true;
continue;
}
/*
boolean heuristicExcludeAsNotGoodCandidateForMilkRun = false;
heuristicIf:
if(parameters.isMilkRuns()) {
double distanceJToJp = Double.MAX_VALUE;
double distanceHomeToJ = Double.MAX_VALUE;
double distanceHomeToJp = Double.MAX_VALUE;
try {
distanceJToJp = Utility.calculateDistanceKm(workItemListBatch.get(j).getClientSite(), workItemListBatch.get(jp).getClientSite(), db);
} catch (Exception e) {
//Ignore. Use default
}
try {
distanceHomeToJp = Utility.calculateDistanceKm(resources.get(i).getHome(), workItemListBatch.get(jp).getClientSite(), db);
} catch (Exception e) {
//Ignore. Use default
}
if(distanceJToJp>=distanceHomeToJp) {
heuristicExcludeAsNotGoodCandidateForMilkRun = true;
break heuristicIf;
}
try {
distanceHomeToJ = Utility.calculateDistanceKm(resources.get(i).getHome(), workItemListBatch.get(j).getClientSite(), db);
} catch (Exception e) {
//Ignore. Use default
}
double travelTimeJToJ = Utility.calculateTravelTimeHrsRetail(distanceJToJp, false);
if (travelTimeJToJ>0) {
// If travel time between the audits cannot be done within normal daily duties
heuristicExcludeAsNotGoodCandidateForMilkRun = true;
break heuristicIf;
}
double travelTimeHomeToJ = Utility.calculateTravelTimeHrsRetail(distanceHomeToJ, false);
if (travelTimeHomeToJ==0) {
// If travel time between auditor and audit is 0 (i.e. done within normal duty), the audit cannot be part of a milk run for this auditor at any time
heuristicExcludeAsNotGoodCandidateForMilkRun = true;
}
}
if (heuristicExcludeAsNotGoodCandidateForMilkRun) {
// Excludes auditors/audit combinations not a good candidate for milk run
constraints[i][j][jp][t] = false;
continue;
}
*/
double jpMinDuration = Arrays.stream(audit_duration[i][jp]).min().orElse(0);
if (i<num_auditors-1
&& (
((t - (int) Math.ceil(jpMinDuration)/timeSlothours<0) && j!=jp)
|| (resource_availability[i][t]<Math.ceil(audit_duration[i][j][jp]/timeSlothours))
|| ((t - (int) Math.ceil(jpMinDuration))>=0 && (resource_availability[i][t - (int) Math.ceil(jpMinDuration)/timeSlothours]<Math.ceil(jpMinDuration/timeSlothours))) && j!=jp)) {
// Exclude not available dates either for audit j starting at t or preceding audit jp starting at (t - (int) Math.ceil(jpMinDuration)/timeSlothours)
constraints[i][j][jp][t] = false;
continue;
}
// If not doing milk runs excludes all j!=jp
if(!parameters.isMilkRuns() && j!=jp) {
constraints[i][j][jp][t] = false;
continue;
}
}
}
}
}
// TODO: Exclude assignments which will lead to auditor being away for longer than X days
logger.debug("Finshed presolve()");
return constraints;
}
private boolean orArray(boolean[] a) {
for (boolean b : a) {
if(b)
return true;
}
return false;
}
protected List<Schedule> scheduleBatch() throws Exception {
initBatchVariables();
boolean[][][][] constraints = presolve();
// Solve relaxed problem excluding time slots constraints to find a lower bound (LB)
logger.debug("Start relaxedConstraints");
boolean[][][][] relaxedConstraints = new boolean[constraints.length][constraints[0].length][constraints[0][0].length][1];
for (int i = 0; i < relaxedConstraints.length; i++) {
for (int j = 0; j < relaxedConstraints[i].length; j++) {
for (int jp = 0; jp < relaxedConstraints[i][j].length; jp++) {
if (orArray(constraints[i][j][jp]))
relaxedConstraints[i][j][jp][0] = true;
else
relaxedConstraints[i][j][jp][0] = false;
}
}
}
logger.debug("Finished relaxedConstraints");
SolverResult srRelaxed = solve(relaxedConstraints);
ResultStatus resultStatusRelaxed = srRelaxed.getResultStatus();
HashMap<String, MPVariable> xRelaxed = srRelaxed.getVariables();
double lowerBound = -1;
// Check that the problem has an optimal solution.
if (resultStatusRelaxed != MPSolver.ResultStatus.OPTIMAL) {
logger.error("Could not find an optimal solution to the relaxed problem in the time limit of " + maxExecTime/1000/60 + " minutes");
} else {
lowerBound = srRelaxed.getSolver().objective().value();
logger.info("Found LB of cost: " + currencyFormatter.format(lowerBound) + " (" + currencyFormatter.format(calculateSolutionCost(xRelaxed, travelCostCalculationType)) +")");
}
SolverResult sr = null;
ResultStatus resultStatus = null;
HashMap<String, MPVariable> x = null;
double obj = Double.MAX_VALUE;
// Solve full problem
sr = solve(constraints);
resultStatus = sr.getResultStatus();
obj = sr.getSolver().objective().value();
if (resultStatus.equals(MPSolver.ResultStatus.OPTIMAL)) {
x = sr.getVariables();
logger.info("Found optimal Solution with objective value of " + currencyFormatter.format(obj) + " (" + currencyFormatter.format(calculateSolutionCost(x, travelCostCalculationType)) +")");
}
if (resultStatus.equals(MPSolver.ResultStatus.FEASIBLE)) {
x = sr.getVariables();
if(lowerBound>0)
logger.info("Found feasable solution with objective value of " + currencyFormatter.format(obj) + " vs lower bound of " + currencyFormatter.format(lowerBound) + " (+" + percentFormatter.format((obj-lowerBound)/lowerBound) + ")");
else
logger.info("Found feasable solution with objective value of " + currencyFormatter.format(obj));
}
// Move unallocated to next month within target.
Calendar auxStart = Calendar.getInstance();
Calendar auxEnd = Calendar.getInstance();
for (WorkItem wi : getUnallocated(x)) {
WorkItem wil = getWorkItemFromList(wi.getId());
auxStart.setTimeInMillis(wil.getTargetDate().getTime());
auxEnd.setTimeInMillis(wil.getEndAuditWindow().getTime());
auxStart.add(Calendar.MONTH, 1);
if (auxStart.before(auxEnd)) {
logger.debug("Moving unallocated audit " + wil.getName() + " from " + Utility.getPeriodformatter().format(wil.getTargetDate()) + " to " + Utility.getPeriodformatter().format(auxStart.getTime()));
wil.setTargetDate(new Date(auxStart.getTimeInMillis()));
wil.setCostOfNotAllocating(wil.getCostOfNotAllocating()+cost_of_not_performing);
wil.setLog(false);
} else {
wil.setLog(true);
wil.setComment("Not allocated due to missing availability");
logger.debug("Cannot allocate audit " + wil.getName() + " and cannot move to next period (" + Utility.getPeriodformatter().format(auxStart.getTime()) + ") as it is outside the audit window end date (" + Utility.getPeriodformatter().format(wil.getEndAuditWindow()) + ")");
}
}
return populateSchedule(x);
}
private WorkItem getWorkItemFromList(String workItemId) {
if (workItemId == null)
return null;
for (WorkItem wi : workItemList) {
if (wi.getId().equalsIgnoreCase(workItemId))
return wi;
}
return null;
}
private List<WorkItem> getUnallocated(HashMap<String, MPVariable> x) {
List<WorkItem> unallocated = new ArrayList<WorkItem>();
if (x == null)
return unallocated;
auditloop:
for (int j = 0; j < num_audits; j++) {
for (int jp = 0; jp < num_audits; jp++) {
for (int t = 0; t < num_time_slots; t++) {
Index idx = new Index(num_auditors-1, j, jp, t);
if(x.containsKey(idx.toKey()) && x.get(idx.toKey()).solutionValue()>0) {
unallocated.add(workItemListBatch.get(j));
continue auditloop;
}
}
}
}
return unallocated;
}
@SuppressWarnings("unused")
private List<Integer> getClosestAuditors(int j) {
Comparator<Resource> byDistance = (r1, r2) -> Double.compare(
Utility.calculateDistanceKm(
r1.getHome().getLatitude(), r1.getHome().getLongitude(),
workItemListBatch.get(j).getClientSite().getLatitude(), workItemListBatch.get(j).getClientSite().getLongitude()),
Utility.calculateDistanceKm(
r2.getHome().getLatitude(), r2.getHome().getLongitude(),
workItemListBatch.get(j).getClientSite().getLatitude(), workItemListBatch.get(j).getClientSite().getLongitude()));
int[] closestAuditors =
resources.stream()
.filter(r -> r.canPerform(workItemListBatch.get(j)))
.sorted(byDistance)
.limit(no_of_closest_auditors)
.mapToInt(r -> getResourceIndex(r))
.toArray();
List<Integer> closestAuditorsList = new ArrayList<Integer>();
for (int i = 0; i < closestAuditors.length; i++) {
closestAuditorsList.add(closestAuditors[i]);
}
return closestAuditorsList;
}
private int getResourceIndex(Resource resource) {
for (int i = 0; i < resources.size(); i++) {
if (resources.get(i).getId().equals(resource.getId()))
return i;
}
return -1;
}
@SuppressWarnings("unused")
private int[] getNumAuditsByPeriod(List<WorkItem> workItemList) {
// Return an array of x elements where x is the no. of periods and each element contains a pointer to the first audit in the period
List<Integer> aux = new ArrayList<Integer>();
// Work Items are already sorted by start date
String currentPeriod = Utility.getPeriodformatter().format(workItemList.get(0).getStartDate());
aux.add(0);
for (int i = 0; i < workItemList.size(); i++) {
if (!Utility.getPeriodformatter().format(workItemList.get(i).getStartDate()).equalsIgnoreCase(currentPeriod)) {
currentPeriod = Utility.getPeriodformatter().format(workItemList.get(i).getStartDate());
aux.add(i);
}
}
aux.add(workItemList.size());
int[] retValue = new int[aux.size()];
for (int i = 0; i < aux.size(); i++) {
retValue[i] = aux.get(i).intValue();
}
return retValue;
}
private double[][][] getAuditDurationMatrix() {
double[][][] auditDurations = new double[resources.size()+1][workItemListBatch.size()][workItemListBatch.size()];
for (int i = 0; i <= resources.size(); i++) {
for (int j = 0; j < workItemListBatch.size(); j++) {
for (int jp = 0; jp < workItemListBatch.size(); jp++) {
double distance = 0;
if (!workItemListBatch.get(j).getServiceDeliveryType().equalsIgnoreCase("Off Site")) {
try {
if(j==jp) {
distance = Utility.calculateDistanceKm(workItemListBatch.get(j).getClientSite(), resources.get(i).getHome(), db);
} else {
distance = Utility.calculateDistanceKm(workItemListBatch.get(jp).getClientSite(), workItemListBatch.get(j).getClientSite(), db);
}
} catch (Exception e) {
// Assume infinite distance
distance = Double.MAX_VALUE;
}
}
auditDurations[i][j][jp] =
workItemListBatch.get(j).getRequiredDuration()
+ workItemListBatch.get(j).getLinkedWorkItems().stream().mapToInt(wi -> (int) Math.ceil(wi.getRequiredDuration())).sum()
+ Math.round(Utility.calculateTravelTimeHrsRetail(distance, false));
}
}
}
return auditDurations;
}
private int[][] getResourceAvailailityMatrix() throws ParseException {
/* Returns a 2-dimensional array
* For each resource
* For each time slot
* -> no. of consecutive slots available.
*/
int[][] resourceAvailability = new int[resources.size()+1][getPeriodSlots(period)];
for(int t = 0; t < resourceAvailability[0].length; t++) {
// For each time slot
for (int i = 0; i < resourceAvailability.length-1; i++) {
// For each resource
// TODO: Commenting for testing purpose only. Remove in final version
Calendar date = getTimeFromSlot(t, period);
/*
Calendar tomorrow = Calendar.getInstance();
tomorrow.add(Calendar.DATE, 1);
if (date.before(tomorrow)) {
// Can't schedule in the past !!!
resourceAvailability[i][t] = 0;
} else {
*/
//logger.info("Time slot " + t + " = " + Utility.getMysqldateformat().format(date.getTime()));
Calendar firstWeekend = Calendar.getInstance();
firstWeekend.setTime(date.getTime());
firstWeekend.add(Calendar.DAY_OF_MONTH, Math.max(6-(date.get(Calendar.DAY_OF_WEEK)==1?7:date.get(Calendar.DAY_OF_WEEK)-1),0));
firstWeekend.set(Calendar.HOUR_OF_DAY, startHourBusinessDay);
//logger.info("First weekend = " + Utility.getMysqldateformat().format(firstWeekend.getTime()));
Calendar firstEventAfterDate = Calendar.getInstance();
firstEventAfterDate.setTime(resources.get(i).getCalender().getEvents().stream()
.filter(e -> e.getEndDateTime().getTime()>date.getTimeInMillis())
.map(e -> e.getStartDateTime()).min(Date::compareTo).orElse(firstWeekend.getTime()));
//logger.info("First event after date= " + Utility.getMysqldateformat().format(firstEventAfterDate.getTime()));
if (firstWeekend.before(firstEventAfterDate))
firstEventAfterDate.setTime(firstWeekend.getTime());
resourceAvailability[i][t] = 0;
date.add(Calendar.HOUR_OF_DAY, timeSlothours);
while (date.before(firstEventAfterDate)) {
//logger.info("Time slot " + t + " = " + Utility.getMysqldateformat().format(date.getTime()));
if(date.get(Calendar.HOUR_OF_DAY)-timeSlothours>=startHourBusinessDay && date.get(Calendar.HOUR_OF_DAY)<=endHourBusinessDay)
resourceAvailability[i][t]++;
date.add(Calendar.HOUR_OF_DAY, timeSlothours);
//}
//logger.info("Slot available at date = " + resourceAvailability[i][t]);
}
}
resourceAvailability[resourceAvailability.length-1][t] = Integer.MAX_VALUE;
}
return resourceAvailability;
}
private double[] getResourceCapacityMatrix() {
HashMap<String, Integer> periodWorkingDays = parameters.getPeriodsWorkingDays();
double[] resourceCapacity = new double[resources.size()+1];
for (int i = 0; i < resourceCapacity.length-1; i++) {
// For each resource
double bopDays = (double) (Math.ceil(resources.get(i).getCalender().getEvents().stream().filter(e -> e.getPeriod().equalsIgnoreCase(period.toString()) && e.getType().equals(ResourceEventType.SF_BOP)).mapToDouble(ResourceEvent::getDurationWorkingDays).sum() * 2) / 2);
double auditDays = (double) (Math.ceil(resources.get(i).getCalender().getEvents().stream().filter(e -> e.getPeriod().equalsIgnoreCase(period.toString()) && (e.getType().equals(ResourceEventType.ALLOCATOR_WIR)||e.getType().equals(ResourceEventType.SF_WIR)||e.getType().equals(ResourceEventType.ALLOCATOR_TRAVEL))).mapToDouble(ResourceEvent::getDurationWorkingDays).sum() * 2) / 2);
resourceCapacity[i] = Math.max(((periodWorkingDays.get(period) - bopDays)*resources.get(i).getCapacity()/100 - auditDays)*8,0);
}
resourceCapacity[resourceCapacity.length-1] = infinity;
return resourceCapacity;
}
private Calendar getTimeFromSlot(int slotNo, String period) throws ParseException {
Calendar periodC = Calendar.getInstance();
periodC.setTime(Utility.getPeriodformatter().parse(period));
return getTimeFromSlot(slotNo, periodC);
}
private Calendar getTimeFromSlot(int slotNo, Calendar period) {
Calendar date = Calendar.getInstance();
date.setTime(period.getTime());
date.add(Calendar.DAY_OF_MONTH, slotNo/no_of_time_slots_day);
date.set(Calendar.HOUR_OF_DAY, startHourBusinessDay + (slotNo%no_of_time_slots_day)*timeSlothours);
return date;
}
private int getSlotFromTime(Calendar date) throws ParseException {
Calendar start = Calendar.getInstance();
start.setTime(Utility.getPeriodformatter().parse(period));
int daysFromStart = (int) Math.floor((date.getTimeInMillis()-start.getTimeInMillis())/1000/60/60/24);
return (daysFromStart)*no_of_time_slots_day
+ Math.max(date.get(Calendar.HOUR_OF_DAY)-startHourBusinessDay,0)/timeSlothours;
}
private int getSlotFromTime(Date date) throws ParseException {
Calendar aux = Calendar.getInstance();
aux.setTime(date);
return getSlotFromTime(aux);
}
private int getPeriodSlots(Calendar period) {
/* 1 Slot = 1/2 Day
* i.e. Period January 2017
* slot 0 = 1/1/17 am
* slot 1 = 1/1/17 pm
* slot 2 = 2/1/17 am
* ...
* slot 61 = 31/1/17 pm
*/
int no_of_slots = period.getMaximum(Calendar.DAY_OF_MONTH)*no_of_time_slots_day;
return no_of_slots;
}
private int getPeriodSlots(Date period) {
Calendar periodC = Calendar.getInstance();
periodC.setTime(period);
return getPeriodSlots(periodC);
}
private int getPeriodSlots(String period) throws ParseException {
Date periodD = Utility.getPeriodformatter().parse(period);
return getPeriodSlots(periodD);
}
private double[][][] getCostMatrix() throws Exception {
double[][][] costs = new double[resources.size()+1][workItemListBatch.size()][workItemListBatch.size()];
for (int j = 0; j < workItemListBatch.size(); j++) {
for (int jp = 0; jp < workItemListBatch.size(); jp++) {
for (int i = 0; i < resources.size(); i++) {
// At this point I do not know if the audit is the last in the milk run. However, if we minimise the one way travel cost, we minimise the return travel cost.
costs[i][j][jp] = Utility.calculateAuditCost(resources.get(i), workItemListBatch.get(j), workItemListBatch.get(j),travelCostCalculationType, db, true, jp==j, false);
}
// Cost of not performing the audit
costs[resources.size()][j][jp] = workItemListBatch.get(j).getCostOfNotAllocating();
}
}
return costs;
}
private Index getPreviousAuditInMilkRun(Index idx, HashMap<String, MPVariable> solution) {
if (idx.getAudit()==idx.getPreviousAudit())
return idx;
for (int jp=0; jp<num_audits; jp++)
for (int t=0;t<num_time_slots; t++)
if(solution.containsKey(idx.getKey(idx.getAuditor(), idx.getPreviousAudit(), jp, t)) && solution.get(idx.getKey(idx.getAuditor(), idx.getPreviousAudit(), jp, t)).solutionValue()>0)
return new Index(idx.getAuditor(), idx.getPreviousAudit(), jp, t);
return null;
}
private Index getFollowingAuditInMilkRun(Index idx, HashMap<String, MPVariable> solution) {
for (int jp=0; jp<num_audits; jp++) {
for (int t=0;t<num_time_slots; t++) {
if(solution.containsKey(idx.getKey(idx.getAuditor(), jp, idx.getAudit(), t)) && solution.get(idx.getKey(idx.getAuditor(), jp, idx.getAudit(), t)).solutionValue()>0 )
return new Index(idx.getAuditor(), jp, idx.getAudit(), t);
}
}
return null; // Last Audit in milk run
}
private Index getFirstAuditInMilkRun(Index idx, HashMap<String, MPVariable> solution) {
Index previousAudit = getPreviousAuditInMilkRun(idx, solution);
if(previousAudit.getAudit() == idx.getAudit())
return idx;
else
return getPreviousAuditInMilkRun(previousAudit, solution);
}
private String getMilkRunId(Index idx, HashMap<String, MPVariable> solution) {
return workItemListBatch.get(getFirstAuditInMilkRun(idx, solution).getAudit()).getId();
}
private String getMilkRunId(String key, HashMap<String, MPVariable> solution) {
return getMilkRunId(new Index(key), solution);
}
private List<Schedule> populateSchedule(HashMap<String, MPVariable> x) throws Exception {
List<Schedule> returnSchedule = new ArrayList<Schedule>();
if(x == null)
return returnSchedule;
// The value of each variable in the solution.
for (String key :x.keySet()) {
if (x.get(key).solutionValue()>0) {
Index idx = new Index(key);
// Initialise Schedule
List<Schedule> schedules = Schedule.getSchedules(workItemListBatch.get(idx.getAudit()));
if (idx.getAuditor()<num_auditors-1) {
// Assigned to actual resource. I.e. Allocated
workItemListBatch.get(idx.getAudit()).setLog(true);
for (Schedule schedule : schedules) {
schedule.setResourceId(resources.get(idx.getAuditor()).getId());
schedule.setResourceName(resources.get(idx.getAuditor()).getName());
schedule.setResourceType(resources.get(idx.getAuditor()).getType());
schedule.setStatus(ScheduleStatus.ALLOCATED);
schedule.setWorkItemGroup(getMilkRunId(key,x));
schedule.setTotalCost(Utility.calculateAuditCost(resources.get(idx.getAuditor()), workItemListBatch.get(idx.getAudit()), workItemListBatch.get(idx.getPreviousAudit()), travelCostCalculationType, db, (idx.getAudit()!=idx.getPreviousAudit() || getFollowingAuditInMilkRun(idx, x)!=null), idx.getAudit()==idx.getPreviousAudit(), getFollowingAuditInMilkRun(idx, x)!=null));
if (workItemListBatch.get(idx.getAudit()).getServiceDeliveryType().equalsIgnoreCase("Off Site"))
schedule.setDistanceKm(0);
else
if (idx.getAudit()==idx.getPreviousAudit())
schedule.setDistanceKm(Utility.calculateDistanceKm(workItemListBatch.get(idx.getAudit()).getClientSite(), resources.get(idx.getAuditor()).getHome(), db));
else
schedule.setDistanceKm(Utility.calculateDistanceKm(workItemListBatch.get(idx.getPreviousAudit()).getClientSite(), workItemListBatch.get(idx.getAudit()).getClientSite(), db));
schedule.setTravelDuration(Math.round(Utility.calculateTravelTimeHrsRetail(schedule.getDistanceKm(), false)));
}
Schedule travelling = new Schedule(workItemListBatch.get(idx.getAudit()));
travelling.setType(ScheduleType.TRAVEL);
travelling.setDistanceKm(schedules.get(0).getDistanceKm());
travelling.setResourceId(schedules.get(0).getResourceId());
travelling.setResourceName(schedules.get(0).getResourceName());
travelling.setResourceType(schedules.get(0).getResourceType());
travelling.setTravelDuration(schedules.get(0).getTravelDuration());
travelling.setDuration(schedules.get(0).getTravelDuration());
travelling.setStatus(ScheduleStatus.ALLOCATED);
if (idx.getAudit()==idx.getPreviousAudit())
travelling.setNotes("Travel from " + resources.get(idx.getAuditor()).getHome().getCity() + " (" + resources.get(idx.getAuditor()).getHome().getPostCode() + ")" +" to " + workItemListBatch.get(idx.getAudit()).getClientSite().getCity() + " (" + workItemListBatch.get(idx.getAudit()).getClientSite().getPostCode() + ")");
else
travelling.setNotes("Travel from " + workItemListBatch.get(idx.getPreviousAudit()).getClientSite().getCity() + " (" + workItemListBatch.get(idx.getPreviousAudit()).getClientSite().getPostCode() + ")" +" to " + workItemListBatch.get(idx.getAudit()).getClientSite().getCity() + " (" + workItemListBatch.get(idx.getAudit()).getClientSite().getPostCode() + ")");
//postProcessTravel(returnSchedule, travelling);
Schedule travellingReturn = new Schedule(workItemListBatch.get(idx.getAudit()));
travellingReturn.setType(ScheduleType.TRAVEL);
travellingReturn.setResourceId(schedules.get(0).getResourceId());
travellingReturn.setResourceName(schedules.get(0).getResourceName());
travellingReturn.setResourceType(schedules.get(0).getResourceType());
travellingReturn.setStatus(ScheduleStatus.ALLOCATED);
if (getFollowingAuditInMilkRun(idx, x) == null) {
// This is the last audit in the milk run. Add travel return home.
travellingReturn.setDistanceKm(Utility.calculateDistanceKm(workItemListBatch.get(idx.getAudit()).getClientSite(), resources.get(idx.getAuditor()).getHome(), db));
travellingReturn.setTravelDuration(Math.round(Utility.calculateTravelTimeHrsRetail(travellingReturn.getDistanceKm(), false)));
travellingReturn.setDuration(travellingReturn.getTravelDuration());
} else {
travellingReturn.setDistanceKm(0);
travellingReturn.setTravelDuration(0);
travellingReturn.setDuration(0);
}
//postProcessTravel(returnSchedule, travellingReturn);
// Set Start and End Dates for events
int slotPointer = idx.getTimeSlot();
travelling.setStartDate(getTimeFromSlot(slotPointer, period).getTime());
slotPointer += (int) Math.ceil(travelling.getTravelDuration()/timeSlothours);
travelling.setEndDate(getTimeFromSlot(slotPointer, period).getTime());
for (Schedule schedule : schedules) {
schedule.setStartDate(getTimeFromSlot(slotPointer, period).getTime());
slotPointer += (int) Math.ceil(schedule.getWorkItemDuration()/timeSlothours);
schedule.setEndDate(getTimeFromSlot(slotPointer, period).getTime());
}
travellingReturn.setStartDate(getTimeFromSlot(slotPointer, period).getTime());
slotPointer += (int) Math.ceil(travelling.getTravelDuration()/timeSlothours);
travellingReturn.setEndDate(getTimeFromSlot(slotPointer, period).getTime());
// Book resource for audit - One event for each time slot
Resource resource = resources.get(idx.getAuditor());
slotPointer = idx.getTimeSlot() + (int) Math.ceil(travelling.getTravelDuration()/timeSlothours);;
for (Schedule schedule : schedules) {
for (int t1 = 0; t1 < (int) Math.ceil(schedule.getWorkItemDuration()/timeSlothours); t1++) {
ResourceEvent eventToBook = new ResourceEvent();
eventToBook.setType(ResourceEventType.ALLOCATOR_WIR);
eventToBook.setStartDateTime(getTimeFromSlot(slotPointer, period).getTime());
slotPointer++;
eventToBook.setEndDateTime(getTimeFromSlot(slotPointer, period).getTime());
resource.bookFor(eventToBook);
}
}
// Book resource for travel
ResourceEvent travelToBook = new ResourceEvent();
travelToBook.setType(ResourceEventType.ALLOCATOR_TRAVEL);
travelToBook.setStartDateTime(travelling.getStartDate());
travelToBook.setEndDateTime(travelling.getEndDate());
resource.bookFor(travelToBook);
ResourceEvent travelToBookReturn = new ResourceEvent();
travelToBookReturn.setType(ResourceEventType.ALLOCATOR_TRAVEL);
travelToBookReturn.setStartDateTime(travellingReturn.getStartDate());
travelToBookReturn.setEndDateTime(travellingReturn.getEndDate());
resource.bookFor(travelToBookReturn);
// Add to return schedule
if(travelling.getDuration()>0)
returnSchedule.add(travelling);
if(travellingReturn.getDuration()>0)
returnSchedule.add(travellingReturn);
} else {
final int j1 = idx.getAudit();
schedules.stream().forEach(s -> s.setNotes(workItemListBatch.get(j1).getComment()));
schedules.stream().forEach(s -> s.setTotalCost(workItemListBatch.get(j1).getCostOfNotAllocating()));
}
// Add unallocated only if needs to be logged. Unallocated audits moved to next period are not logged to avoid duplications
if(workItemListBatch.get(idx.getAudit()).isLog()) {
returnSchedule.addAll(schedules);
}
}
}
return scheduleToEvents(returnSchedule);
}
private List<Schedule> scheduleToEvents(List<Schedule> schedules) throws ParseException {
List<Schedule> events = new ArrayList<Schedule>();
for (Schedule schedule : schedules) {
if (schedule.getStatus().equals(ScheduleStatus.NOT_ALLOCATED)) {
events.add(schedule);
} else {
for(int t = getSlotFromTime(schedule.getStartDate()); t < getSlotFromTime(schedule.getStartDate()) + (int) Math.ceil(schedule.getDuration()/timeSlothours); t++) {
Schedule event = new Schedule(schedule);
event.setStartDate(new Date(getTimeFromSlot(t, period).getTimeInMillis()));
event.setEndDate(new Date(getTimeFromSlot(t, period).getTimeInMillis()+timeSlothours*60*60*1000));
event.setDuration(timeSlothours);
events.add(event);
}
}
}
return events;
}
class Index {
private int auditor, audit, previousAudit, timeSlot;
public Index(int auditor, int audit, int previousAudit, int timeSlot) {
super();
this.auditor = auditor;
this.audit = audit;
this.previousAudit = previousAudit;
this.timeSlot = timeSlot;
}
public Index(String key) {
super();
String[] idx = key.split(",");
this.auditor = Integer.parseInt(idx[0]);
this.audit = Integer.parseInt(idx[1]);
this.previousAudit = Integer.parseInt(idx[2]);
this.timeSlot = Integer.parseInt(idx[3]);
}
public int getAuditor() {
return auditor;
}
public void setAuditor(int auditor) {
this.auditor = auditor;
}
public int getAudit() {
return audit;
}
public void setAudit(int audit) {
this.audit = audit;
}
public int getPreviousAudit() {
return previousAudit;
}
public void setPreviousAudit(int previousAudit) {
this.previousAudit = previousAudit;
}
public int getTimeSlot() {
return timeSlot;
}
public String getKey(int i, int j, int js, int t) {
return i + "," + j + "," + js + "," + t;
}
public String toKey() {
return getKey(getAuditor(), getAudit(), getPreviousAudit(), getTimeSlot());
}
public void setTimeSlot(int timeSlot) {
this.timeSlot = timeSlot;
}
}
class SolverResult {
private ResultStatus resultStatus = null;
private HashMap<String, MPVariable> variables = null;
private MPSolver solver = null;
public ResultStatus getResultStatus() {
return resultStatus;
}
public void setResultStatus(ResultStatus resultStatus) {
this.resultStatus = resultStatus;
}
public HashMap<String, MPVariable> getVariables() {
return variables;
}
public void setVariables(HashMap<String, MPVariable> variables) {
this.variables = variables;
}
public MPSolver getSolver() {
return solver;
}
public void setSolver(MPSolver solver) {
this.solver = solver;
}
}
protected void postProcessWorkItemList() {
final Calendar start = Calendar.getInstance();
start.setTime(parameters.getStartDate());
final Calendar end = Calendar.getInstance();
end.setTime(parameters.getEndDate());
if(parameters.getBoltOnStandards() != null) {
for (WorkItem wi : workItemList) {
if (parameters.getBoltOnStandards().contains(wi.getPrimaryStandard().getCompetencyName())) {
logger.debug("Found Bolt-On audit " + wi.getName() + " (" + wi.getPrimaryStandard().getCompetencyName() + ")");
wi.setPrimary(false);
// Find primary wi and add the bolt-on to it
WorkItem primaryWi = workItemList.stream().filter(wi2 ->
wi2.getClientSite().getFullAddress().equalsIgnoreCase(wi.getClientSite().getFullAddress()) &&
//Utility.getPeriodformatter().format(wi2.getTargetDate()).equalsIgnoreCase(Utility.getPeriodformatter().format(wi.getTargetDate())) &&
!wi2.getId().equals(wi.getId()))
.findFirst()
.orElse(null);
if (primaryWi != null) {
primaryWi.getLinkedWorkItems().add(wi);
logger.debug("Added Bolt-On audit " + wi.getName() + " (" + Utility.getActivitydateformatter().format(wi.getTargetDate()) + ") to " + primaryWi.getName() + " (" + Utility.getActivitydateformatter().format(primaryWi.getTargetDate()) + ")");
} else {
logger.debug("Could not add Bolt-On audit " + wi.getName() + " (" + Utility.getActivitydateformatter().format(wi.getTargetDate()) + ") to any other audit in scope.");
}
}
}
}
Calendar auxStart = Calendar.getInstance();
Calendar auxEnd = Calendar.getInstance();
for (WorkItem wi : workItemList) {
// Default Audit Window = Target Month
auxStart.setTime(wi.getTargetDate());
auxEnd.setTime(wi.getTargetDate());
auxStart.set(Calendar.DAY_OF_MONTH, 1);
auxEnd.set(Calendar.DAY_OF_MONTH, auxEnd.getActualMaximum(Calendar.DAY_OF_MONTH));
// Custom audit windows
// Audit Window outside period - override
if (auxStart.before(start))
auxStart.set(Calendar.MONTH,start.get(Calendar.MONTH));
if (auxEnd.before(start))
auxEnd.set(Calendar.MONTH,start.get(Calendar.MONTH));
if (auxStart.after(end))
auxStart.set(Calendar.MONTH,end.get(Calendar.MONTH));
if (auxEnd.after(end))
auxEnd.set(Calendar.MONTH,end.get(Calendar.MONTH));
wi.setTargetDate(new Date(auxStart.getTimeInMillis()));
wi.setStartAuditWindow(new Date(auxStart.getTimeInMillis()));
wi.setEndAuditWindow(new Date(auxEnd.getTimeInMillis()));
wi.setCostOfNotAllocating(cost_of_not_performing);
}
}
public void init() throws Exception {
// Init logger
logger = this.initLogger();
Utility.startTimeCounter("MIP3RetailProcessor.init");
// Init tables
this.db.executeStatement(this.db.getCreateScheduleTableSql());
this.db.executeStatement(this.db.getCreateScheduleBatchTableSql());
if (parameters.getBatchId() == null)
this.parameters.setBatchId(getNewBatchId());
this.parameters.setSubBatchId(getLastSubBatchId()+1);
// Init WorkItems and Resources
resources = getResourceBatch(parameters);
for (Resource r : resources) {
logger.debug(r.toCsv());
}
workItemList = getWorkItemBatch(parameters);
if (parameters.includePipeline()) {
List<WorkItem> pipelineWI = getPipelineWorkItems();
for (WorkItem workItem : pipelineWI) {
workItemList.add(workItem);
}
}
postProcessWorkItemList();
Utility.stopTimeCounter("MIP3RetailProcessor.init");
}
private List<WorkItem> getWorkItemBatch(ScheduleParameters parameters2) throws Exception {
List<WorkItem> retValue = new ArrayList<WorkItem>();
String query = "select a.Id, a.client_name as 'clientName', s.address as 'clientAddress', geo.Latitude as 'clientLatitude', geo.Longitude as 'clientLongitude', a.date as 'auditDate', a.audit_definition, a.call_time, a.audit_definition "
+ "from retail.audits a "
+ "inner join retail.sites s on a.site_id = s.Id "
+ "left join salesforce.saig_geocode_cache geo on s.address = geo.Address "
+ "where "
+ "a.auditor_name in ('" + StringUtils.join(parameters2.getResourceNames(), "','") + "') "
+ "and a.date between '" + Utility.getActivitydateformatter().format(parameters2.getStartDate()) + "' and '" + Utility.getActivitydateformatter().format(parameters2.getEndDate()) + "';";
ResultSet rs = db.executeSelect(query, -1);
while (rs.next()) {
WorkItem wi = new WorkItem();
wi.setName(rs.getString("id"));
wi.setId(rs.getString("id"));
Location clientSite = new Location();
clientSite.setName(rs.getString("clientName"));
clientSite.setAddress_1(rs.getString("clientAddress"));
clientSite.setLatitude(rs.getDouble("clientLatitude"));
clientSite.setLongitude(rs.getDouble("clientLongitude"));
wi.setClientSite(clientSite);
Calendar aux = Calendar.getInstance();
aux.setTime(Utility.getMysqldateformat().parse(rs.getString("auditDate")));
aux.set(Calendar.DATE, 1);
wi.setTargetDate(aux.getTime());
wi.setRequiredDuration(rs.getDouble("call_time")/60);
wi.setServiceDeliveryType("On Site");
List<Competency> competencies = new ArrayList<Competency>();
competencies.add(new Competency(rs.getString("audit_definition"), rs.getString("audit_definition"), CompetencyType.PRIMARYSTANDARD, ""));
wi.setRequiredCompetencies(competencies);
retValue.add(wi);
}
return retValue;
}
private List<Resource> getResourceBatch(ScheduleParameters parameters2) throws Exception {
List<Resource> retValue = new ArrayList<Resource>();
String query = "select r.*, "
+ "geo.Latitude, "
+ "geo.Longitude "
+ "from retail.auditors r "
+ "left join salesforce.saig_geocode_cache geo on r.`home_address` = geo.Address "
+ "where r.name in ('" + StringUtils.join(parameters2.getResourceNames(), "','") + "');";
ResultSet rs = db.executeSelect(query, -1);
while (rs.next()) {
Resource r = new Resource();
r.setName(rs.getString("name"));
r.setId(rs.getString("id"));
r.setHome(new Location(rs.getString("home_address"), rs.getString("home_address"), "", "", "", rs.getString("country"), "", "", rs.getDouble("latitude"), rs.getDouble("longitude")));
r.setCapacity(100);
r.setType(SfResourceType.Employee);
r.setHourlyRate(0.0);
r.setCalendar(new ResourceCalendar(r, parameters2.getCalendarStartDate(), parameters2.getCalendarEndDate()));
r.getCalender().setEvents(new ArrayList<ResourceEvent>());
retValue.add(r);
}
return retValue;
}
private int getLastSubBatchId() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
String query = "SELECT MAX(SubBatchId) FROM " + this.db.getScheduleBatchTableName() + " WHERE BatchId='" + this.getBatchId() + "'";
return db.executeScalarInt(query);
}
protected void saveSchedule(List<Schedule> scheduleList) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
// Early exit
if(scheduleList == null || scheduleList.size()==0)
return;
String insert = "INSERT INTO " + this.db.getScheduleTableName() +
" (`BatchId`, `SubBatchId`, `WorkItemId`, `WorkItemName`, `WorkItemSource`, `WorkItemCountry`, `WorkItemState`, `WorkItemTimeZone`, `ResourceId`, `ResourceName`, `ResourceType`, `StartDate`, `EndDate`, `Duration`, `TravelDuration`, `Status`, `Type`, `PrimaryStandard`, `Competencies`, `Comment`, `Distance`, `Notes`, `WorkItemGroup`, `TotalCost`) VALUES ";
for (Schedule schedule : scheduleList) {
insert += " \n('" + getBatchId() + "', " + getSubBatchId() + ", " + schedule.toSqlString() + ") ,";
}
this.db.executeStatement(Utility.removeLastChar(insert));
}
protected void saveBatchDetails(ScheduleParameters parameters) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
String insert = "INSERT INTO " + this.db.getScheduleBatchTableName() +
" (`BatchId`, `SubBatchId`, `RevenueOwnership`, `SchedulingOwnership`, `ReportingBusinessUnits`, `AuditCountries`, `ResourceCountries`, `ScoreContractorPenalties`,`ScoreAvailabilityDayReward`,`ScoreDistanceKmPenalty`,`ScoreCapabilityAuditPenalty`, `WorkItemStatuses`, `ResourceTypes`, `StartDate`, `EndDate`, `Comment`, `completed`, `created`) " +
"VALUES (" + parameters.toSqlString() + ", 0, utc_timestamp())";
this.db.executeStatement(insert);
}
protected void updateBatchDetails(ScheduleParameters parameters) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
String update = "UPDATE " + this.db.getScheduleBatchTableName() + " SET lastModified=utc_timestamp(), completed = 1 WHERE BatchId = '" + parameters.getBatchId() + "' AND SubBatchId = " + parameters.getSubBatchId();
this.db.executeStatement(update);
}
protected List<WorkItem> getPipelineWorkItems() {
return new ArrayList<WorkItem>();
};
protected List<Resource> sortResources(List<Resource> resourceList) {
return resourceList;
};
protected String getNewBatchId() {
return UUID.randomUUID().toString();
}
public String getBatchId() {
return this.parameters.getBatchId();
}
public int getSubBatchId() {
return this.parameters.getSubBatchId();
}
@Override
public void setDbHelper(DbHelper db) {
this.db = db;
}
@Override
public void setParameters(ScheduleParameters sp) {
this.parameters = sp;
}
}
| 53,966 | 0.689341 | 0.682671 | 1,272 | 41.426102 | 46.296768 | 406 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.908805 | false | false |
10
|
adeaf6152c16bd1a1cc86ea56a96e95569f5db90
| 21,990,232,617,062 |
64991278f1818980b7c8851ea38704e251c1b1e8
|
/app/src/main/java/com/example/emopay/aeps/DeviceInfo.java
|
d6e457a65fa79c7d9b33ca84d1eb55c5eae7928c
|
[] |
no_license
|
kumarrobo/EmoPay
|
https://github.com/kumarrobo/EmoPay
|
e89d8c12b1e87ca2c0aa9bf8a07d8791469f255b
|
76838586bc9d71b0b0de90a7387d385e32b83d10
|
refs/heads/master
| 2023-04-12T18:12:59.578000 | 2021-05-07T08:33:24 | 2021-05-07T08:33:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.emopay.aeps;
public class DeviceInfo {
public String dpId; // Unique code assigned to registered device provider
public String rdsId; //Unique ID of the certified registered device service.
public String rdsVer; //Registered devices service version
public String dc; //Unique Registered device code.
public String mi; //Registered device model ID
public String mc; //This attribute holds registered device public key certificate. This is signed with device provider key
public DeviceInfo(){}
public DeviceInfo(String dpId, String rdsId, String rdsVer, String dc, String mi, String mc) {
this.dpId = dpId;
this.rdsId = rdsId;
this.rdsVer = rdsVer;
this.dc = dc;
this.mi = mi;
this.mc = mc;
}
public String getDpId() {
return dpId;
}
public void setDpId(String dpId) {
this.dpId = dpId;
}
public String getRdsId() {
return rdsId;
}
public void setRdsId(String rdsId) {
this.rdsId = rdsId;
}
public String getRdsVer() {
return rdsVer;
}
public void setRdsVer(String rdsVer) {
this.rdsVer = rdsVer;
}
public String getDc() {
return dc;
}
public void setDc(String dc) {
this.dc = dc;
}
public String getMi() {
return mi;
}
public void setMi(String mi) {
this.mi = mi;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc;
}
}
|
UTF-8
|
Java
| 1,592 |
java
|
DeviceInfo.java
|
Java
|
[] | null |
[] |
package com.example.emopay.aeps;
public class DeviceInfo {
public String dpId; // Unique code assigned to registered device provider
public String rdsId; //Unique ID of the certified registered device service.
public String rdsVer; //Registered devices service version
public String dc; //Unique Registered device code.
public String mi; //Registered device model ID
public String mc; //This attribute holds registered device public key certificate. This is signed with device provider key
public DeviceInfo(){}
public DeviceInfo(String dpId, String rdsId, String rdsVer, String dc, String mi, String mc) {
this.dpId = dpId;
this.rdsId = rdsId;
this.rdsVer = rdsVer;
this.dc = dc;
this.mi = mi;
this.mc = mc;
}
public String getDpId() {
return dpId;
}
public void setDpId(String dpId) {
this.dpId = dpId;
}
public String getRdsId() {
return rdsId;
}
public void setRdsId(String rdsId) {
this.rdsId = rdsId;
}
public String getRdsVer() {
return rdsVer;
}
public void setRdsVer(String rdsVer) {
this.rdsVer = rdsVer;
}
public String getDc() {
return dc;
}
public void setDc(String dc) {
this.dc = dc;
}
public String getMi() {
return mi;
}
public void setMi(String mi) {
this.mi = mi;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc;
}
}
| 1,592 | 0.591709 | 0.591709 | 70 | 21.742857 | 25.027805 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
10
|
32b144433db23db9509c7701391d989bd79be0d2
| 25,151,328,523,024 |
337a2834f8593ce7b2387039c67b155b27b3b89d
|
/java-basics/java-io/java-io-inputoutput/src/main/java/xin/io/output/FileOutputShorCut.java
|
c5c0aeb0c9ab784d0dc24f29afd570fe0e564452
|
[] |
no_license
|
xinxinxin123/JavaStudy
|
https://github.com/xinxinxin123/JavaStudy
|
43ac4f2084d0d5585d6c6920b75d9a360fadb9d2
|
8414b309a51468203c9e104b1fcf7e991c32d49f
|
refs/heads/master
| 2019-04-10T19:42:13.790000 | 2019-04-03T06:18:25 | 2019-04-03T06:18:25 | 90,948,510 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package xin.io.output;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Description: <br>
* 文本文件输出
* @author <br>
* @taskId <br>
*/
public class FileOutputShorCut {
static String file = ".\\java-basics\\java-io\\java-io-temp\\src\\main\\resources\\BasicFileOutput.out";
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File(".\\java-basics\\java-io\\java-io-temp\\src\\main\\java\\output\\BasicFileOutput.java")));
PrintWriter pw = new PrintWriter(file); //java SE5在PrintWriter中添加了一个辅助构造器,不能再去做装饰工作
String s;
int lineCount = 1;
while ((s = br.readLine()) != null) {
pw.println(lineCount++ +" :"+ s);
}
pw.close();
br.close();
}
}
|
UTF-8
|
Java
| 945 |
java
|
FileOutputShorCut.java
|
Java
|
[] | null |
[] |
package xin.io.output;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Description: <br>
* 文本文件输出
* @author <br>
* @taskId <br>
*/
public class FileOutputShorCut {
static String file = ".\\java-basics\\java-io\\java-io-temp\\src\\main\\resources\\BasicFileOutput.out";
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File(".\\java-basics\\java-io\\java-io-temp\\src\\main\\java\\output\\BasicFileOutput.java")));
PrintWriter pw = new PrintWriter(file); //java SE5在PrintWriter中添加了一个辅助构造器,不能再去做装饰工作
String s;
int lineCount = 1;
while ((s = br.readLine()) != null) {
pw.println(lineCount++ +" :"+ s);
}
pw.close();
br.close();
}
}
| 945 | 0.64342 | 0.64117 | 31 | 27.67742 | 34.929779 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false |
10
|
e4fb2468e4e23b0fedcb330a32fefdd590bdb2f4
| 18,923,625,943,682 |
8a9af0d90c3bc9cfdbb2a8995c750a4b1f563e35
|
/src/main/java/com/fangshuo/dbinfo/model/project/Property.java
|
bd8201d7a798e3ecd7379b8497f2f16b89665249
|
[] |
no_license
|
JunZhou2016/CodingRoboterV1.0
|
https://github.com/JunZhou2016/CodingRoboterV1.0
|
5c0ff43b92d0e55afc284dd2f563906401f9e9b4
|
9f1ac19fbfa647d86eb9e9efc9ca437e62202c53
|
refs/heads/master
| 2020-03-29T08:54:21.237000 | 2018-10-24T07:47:52 | 2018-10-24T07:47:52 | 149,732,195 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fangshuo.dbinfo.model.project;
/**
*
* Copyright: Copyright (c) 2018 Jun_Zhou
*
* @ClassName: Property.java
* @Description: 实体属性信息描述载体;
*
* @version: v1.0.0
* @author: JunZhou
* @Email: 1769676159@qq.com
* @Site: CERNO
* @date: 2018年9月27日 上午9:47:52
*/
public class Property {
private String propertyName;// 实体的属性名称;
private String propertyNameUpperCamel;// 首字母大写的实体属性名称;
private String propertyComment;// 实体的属性的注释;
private String propertyLengthAndType;;// 实体的属性的长度和类型;
private String isNullAble;// 是否允许为空;
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public String getPropertyNameUpperCamel() {
return propertyNameUpperCamel;
}
public void setPropertyNameUpperCamel(String propertyNameUpperCamel) {
this.propertyNameUpperCamel = propertyNameUpperCamel;
}
public String getPropertyComment() {
return propertyComment;
}
public void setPropertyComment(String propertyComment) {
this.propertyComment = propertyComment;
}
public String getPropertyLengthAndType() {
return propertyLengthAndType;
}
public void setPropertyLengthAndType(String propertyLengthAndType) {
this.propertyLengthAndType = propertyLengthAndType;
}
public String getIsNullAble() {
return isNullAble;
}
public void setIsNullAble(String isNullAble) {
this.isNullAble = isNullAble;
}
}
|
UTF-8
|
Java
| 1,549 |
java
|
Property.java
|
Java
|
[
{
"context": "project;\n\n/**\n * \n * Copyright: Copyright (c) 2018 Jun_Zhou\n * \n * @ClassName: Property.java\n * @Description:",
"end": 93,
"score": 0.9989283680915833,
"start": 85,
"tag": "NAME",
"value": "Jun_Zhou"
},
{
"context": "n: 实体属性信息描述载体;\n * \n * @version: v1.0.0\n * @author: JunZhou\n * @Email: 1769676159@qq.com\n * @Site: CERNO\n * @",
"end": 199,
"score": 0.9995720982551575,
"start": 192,
"tag": "NAME",
"value": "JunZhou"
},
{
"context": "* @version: v1.0.0\n * @author: JunZhou\n * @Email: 1769676159@qq.com\n * @Site: CERNO\n * @date: 2018年9月27日 上午9:47:52\n *",
"end": 228,
"score": 0.999853789806366,
"start": 211,
"tag": "EMAIL",
"value": "1769676159@qq.com"
}
] | null |
[] |
package com.fangshuo.dbinfo.model.project;
/**
*
* Copyright: Copyright (c) 2018 Jun_Zhou
*
* @ClassName: Property.java
* @Description: 实体属性信息描述载体;
*
* @version: v1.0.0
* @author: JunZhou
* @Email: <EMAIL>
* @Site: CERNO
* @date: 2018年9月27日 上午9:47:52
*/
public class Property {
private String propertyName;// 实体的属性名称;
private String propertyNameUpperCamel;// 首字母大写的实体属性名称;
private String propertyComment;// 实体的属性的注释;
private String propertyLengthAndType;;// 实体的属性的长度和类型;
private String isNullAble;// 是否允许为空;
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public String getPropertyNameUpperCamel() {
return propertyNameUpperCamel;
}
public void setPropertyNameUpperCamel(String propertyNameUpperCamel) {
this.propertyNameUpperCamel = propertyNameUpperCamel;
}
public String getPropertyComment() {
return propertyComment;
}
public void setPropertyComment(String propertyComment) {
this.propertyComment = propertyComment;
}
public String getPropertyLengthAndType() {
return propertyLengthAndType;
}
public void setPropertyLengthAndType(String propertyLengthAndType) {
this.propertyLengthAndType = propertyLengthAndType;
}
public String getIsNullAble() {
return isNullAble;
}
public void setIsNullAble(String isNullAble) {
this.isNullAble = isNullAble;
}
}
| 1,539 | 0.761705 | 0.74144 | 62 | 22.080645 | 20.971024 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.096774 | false | false |
10
|
c2e958890f3cad0e99551d2b405974515e2299d5
| 7,679,401,570,210 |
0756e9bbc386aa802d8141fb9e7a77e005378399
|
/src/ProblemsIn_Java/Uva/BinaryLand.java
|
d679d5d0a0e03c64af569628f5602f2fb571dbce
|
[] |
no_license
|
dayepesb/OnlineJudges
|
https://github.com/dayepesb/OnlineJudges
|
85eae4de8a5c6c74cd7419bc314410b478dcbb6b
|
0069c8aa644e6952348b7bf903ddd50f19b4e8e7
|
refs/heads/master
| 2021-07-15T06:49:35.228000 | 2020-05-10T07:33:46 | 2020-05-10T07:33:46 | 133,302,544 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ProblemsIn_Java.Uva;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.StringTokenizer;
public class BinaryLand {
static final int dirs[][] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
static int visit[][][][], fc, cc, fil, col, INF = 10000000;
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st;
String line;
char arr[][];
for (; (line = in.readLine()) != null;) {
st = new StringTokenizer(line);
fil = Integer.parseInt(st.nextToken());
col = Integer.parseInt(st.nextToken());
visit = new int[fil+1][col+1][fil+1][col+1];
arr = new char[fil][col];
for (int i = 0; i < fil; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < fil; k++) {
Arrays.fill(visit[i][j][k], INF);
}
}
}
st = new StringTokenizer(in.readLine());
fc = Integer.parseInt(st.nextToken()) - 1;
cc = Integer.parseInt(st.nextToken()) - 1;
int[] ini = { Integer.parseInt(st.nextToken()) - 1, Integer.parseInt(st.nextToken()) - 1,
Integer.parseInt(st.nextToken()) - 1, Integer.parseInt(st.nextToken()) - 1 };
for (int i = 0; i < arr.length; i++) {
arr[i] = in.readLine().toCharArray();
}
int res = bfs(ini,arr);
out.println(res == INF ? "NO LOVE" : res);
}
out.close();
}
static int bfs(int[] ini,char arr[][]) {
Deque<int[]> cola = new ArrayDeque<>();
cola.add(ini);
visit[ini[0]][ini[1]][ini[2]][ini[3]] = 0;
while (!cola.isEmpty()) {
int[] u = cola.poll();
int rg = u[0], cg = u[1], rm = u[2], cm = u[3];
for (int[] dir : dirs) {
int r1, c1, r2, c2;
r1 = rg + dir[0];
c1 = cg + dir[1];
r2 = rm + dir[0];
c2 = cm - dir[1];
if (r1 >= fil || r1 < 0 || c1 >= col || c1 < 0 || arr[r1][c1] == '#') {r1 = rg;c1 = cg;}
if (r2 >= fil || r2 < 0 || c2 >= col || c2 < 0 || arr[r2][c2] == '#') {r2 = rm;c2 = cm;}
if (visit[r1][c1][r2][c2] > visit[rg][cg][rm][cm] + 1) {
visit[r1][c1][r2][c2] = visit[rg][cg][rm][cm] + 1;
cola.add(new int[] { r1, c1, r2, c2 });
}
if(visit[fc][cc][fc][cc]!=INF){
return visit[fc][cc][fc][cc];
}
}
}
return INF;
}
}
|
UTF-8
|
Java
| 2,395 |
java
|
BinaryLand.java
|
Java
|
[] | null |
[] |
package ProblemsIn_Java.Uva;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.StringTokenizer;
public class BinaryLand {
static final int dirs[][] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
static int visit[][][][], fc, cc, fil, col, INF = 10000000;
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st;
String line;
char arr[][];
for (; (line = in.readLine()) != null;) {
st = new StringTokenizer(line);
fil = Integer.parseInt(st.nextToken());
col = Integer.parseInt(st.nextToken());
visit = new int[fil+1][col+1][fil+1][col+1];
arr = new char[fil][col];
for (int i = 0; i < fil; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < fil; k++) {
Arrays.fill(visit[i][j][k], INF);
}
}
}
st = new StringTokenizer(in.readLine());
fc = Integer.parseInt(st.nextToken()) - 1;
cc = Integer.parseInt(st.nextToken()) - 1;
int[] ini = { Integer.parseInt(st.nextToken()) - 1, Integer.parseInt(st.nextToken()) - 1,
Integer.parseInt(st.nextToken()) - 1, Integer.parseInt(st.nextToken()) - 1 };
for (int i = 0; i < arr.length; i++) {
arr[i] = in.readLine().toCharArray();
}
int res = bfs(ini,arr);
out.println(res == INF ? "NO LOVE" : res);
}
out.close();
}
static int bfs(int[] ini,char arr[][]) {
Deque<int[]> cola = new ArrayDeque<>();
cola.add(ini);
visit[ini[0]][ini[1]][ini[2]][ini[3]] = 0;
while (!cola.isEmpty()) {
int[] u = cola.poll();
int rg = u[0], cg = u[1], rm = u[2], cm = u[3];
for (int[] dir : dirs) {
int r1, c1, r2, c2;
r1 = rg + dir[0];
c1 = cg + dir[1];
r2 = rm + dir[0];
c2 = cm - dir[1];
if (r1 >= fil || r1 < 0 || c1 >= col || c1 < 0 || arr[r1][c1] == '#') {r1 = rg;c1 = cg;}
if (r2 >= fil || r2 < 0 || c2 >= col || c2 < 0 || arr[r2][c2] == '#') {r2 = rm;c2 = cm;}
if (visit[r1][c1][r2][c2] > visit[rg][cg][rm][cm] + 1) {
visit[r1][c1][r2][c2] = visit[rg][cg][rm][cm] + 1;
cola.add(new int[] { r1, c1, r2, c2 });
}
if(visit[fc][cc][fc][cc]!=INF){
return visit[fc][cc][fc][cc];
}
}
}
return INF;
}
}
| 2,395 | 0.554071 | 0.51858 | 79 | 29.329113 | 23.358906 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.582278 | false | false |
10
|
fa285db14ebd5d135329aa4336024ba7e4120156
| 2,241,972,956,825 |
330c45a1a567cc3cc5f920cc6db20940f204db00
|
/matlab/rank/src/test/java/uk/ac/bristol/labynkyr/TestDistinguishingTable.java
|
5a68245863a9b1384a0663ae118b88888e50d867
|
[
"BSD-2-Clause"
] |
permissive
|
Salties/labynkyr
|
https://github.com/Salties/labynkyr
|
45e23500d5f2855ecb5062aeb25f00e4f8c8e712
|
6095bba70baceff6c8ea2bb70031a77e778f24c8
|
refs/heads/master
| 2021-01-13T10:35:20.041000 | 2016-09-27T16:34:19 | 2016-09-27T16:34:19 | 69,376,858 | 0 | 0 | null | true | 2016-09-27T16:30:58 | 2016-09-27T16:30:58 | 2016-09-15T18:58:18 | 2016-09-15T18:59:56 | 272 | 0 | 0 | 0 | null | null | null |
/*
* University of Bristol – Open Access Software Licence
* Copyright (c) 2016, The University of Bristol, a chartered
* corporation having Royal Charter number RC000648 and a charity
* (number X1121) and its place of administration being at Senate
* House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Any use of the software for scientific publications or commercial
* purposes should be reported to the University of Bristol
* (OSI-notifications@bristol.ac.uk and quote reference 2514). This is
* for impact and usage monitoring purposes only.
*
* Enquiries about further applications and development opportunities
* are welcome. Please contact elisabeth.oswald@bristol.ac.uk
*/
package uk.ac.bristol.labynkyr;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.junit.Test;
public class TestDistinguishingTable {
@Test
public void test_mapToWeight_4bits() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 10.0) - 5.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.translateVectorsToPositive();
table.normaliseDistinguishingVectors();
table.takeLogarithm(2.0);
table.applyAbsoluteValue();
final int precisionBits = 4;
final WeightTable weightTable = table.mapToWeight(precisionBits);
final int maxScore = Collections.max(weightTable.allWeights());
assertTrue(maxScore < 16);
}
@Test
public void test_mapToWeight_12bits() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 14.0) - 12.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.translateVectorsToPositive();
table.normaliseDistinguishingVectors();
table.takeLogarithm(2.0);
table.applyAbsoluteValue();
final int precisionBits = 12;
final WeightTable weightTable = table.mapToWeight(precisionBits);
final int maxScore = Collections.max(weightTable.allWeights());
assertTrue(maxScore < 4096);
}
@Test
public void test_normaliseDistinguishingVectors() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 10.0) - 5.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.normaliseDistinguishingVectors();
// Actual
double sum1 = 0.0;
for(int index = 0 ; index < vectorSize ; index++) {
sum1 += table.allScores().get(index);
}
double sum2 = 0.0;
for(int index = vectorSize ; index < 2 * vectorSize ; index++) {
sum2 += table.allScores().get(index);
}
assertEquals(1.0, sum1, 0.0001);
assertEquals(1.0, sum2, 0.0001);
}
@Test
public void test_applyAbsoluteValue() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 10.0) - 5.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.applyAbsoluteValue();
final double minElement = Collections.min(table.allScores());
final double maxElement = Collections.max(table.allScores());
assertTrue(minElement >= 0.0);
assertTrue(maxElement <= 5.0);
}
@Test
public void test_translateVectorsToPositive() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 10.0) - 5.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.translateVectorsToPositive();
final double minElement = Collections.min(table.allScores());
final double maxElement = Collections.max(table.allScores());
assertEquals(0.0, minElement, 0.00001);
assertTrue(maxElement > 9.0);
}
@Test
public void test_translateVectorsToPositive_alreadyPositive() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 4.0) + 1.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.translateVectorsToPositive();
final double minElement = Collections.min(table.allScores());
final double maxElement = Collections.max(table.allScores());
assertTrue(minElement >= 1.0);
assertTrue(maxElement <= 5.0);
}
@Test
public void test_takeLogarithm() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
Double[] expected = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 4.0) + 1.0;
scores[index] = nextRand;
expected[index] = Math.log(nextRand) / Math.log(2.0);
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.takeLogarithm(2.0);
for(int index = 0 ; index < 2 * vectorSize ; index++) {
assertEquals(expected[index], table.allScores().get(index), 0.0001);
}
}
@Test
public void test_score() {
final List<Double> scores = Arrays.asList(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8);
final DistinguishingTable table = new DistinguishingTable(2, 2, scores);
assertEquals(1.1, table.score(0, 0), 0.0001);
assertEquals(2.2, table.score(0, 1), 0.0001);
assertEquals(3.3, table.score(0, 2), 0.0001);
assertEquals(4.4, table.score(0, 3), 0.0001);
assertEquals(5.5, table.score(1, 0), 0.0001);
assertEquals(6.6, table.score(1, 1), 0.0001);
assertEquals(7.7, table.score(1, 2), 0.0001);
assertEquals(8.8, table.score(1, 3), 0.0001);
}
}
|
UTF-8
|
Java
| 7,907 |
java
|
TestDistinguishingTable.java
|
Java
|
[
{
"context": "ould be reported to the University of Bristol\n * (OSI-notifications@bristol.ac.uk and quote reference 2514). This is\n * for impact ",
"end": 1814,
"score": 0.9997994303703308,
"start": 1783,
"tag": "EMAIL",
"value": "OSI-notifications@bristol.ac.uk"
},
{
"context": "pment opportunities\n * are welcome. Please contact elisabeth.oswald@bristol.ac.uk\n*/\npackage uk.ac.bristol.labynkyr;\n\nimport static",
"end": 2034,
"score": 0.9999331831932068,
"start": 2004,
"tag": "EMAIL",
"value": "elisabeth.oswald@bristol.ac.uk"
}
] | null |
[] |
/*
* University of Bristol – Open Access Software Licence
* Copyright (c) 2016, The University of Bristol, a chartered
* corporation having Royal Charter number RC000648 and a charity
* (number X1121) and its place of administration being at Senate
* House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Any use of the software for scientific publications or commercial
* purposes should be reported to the University of Bristol
* (<EMAIL> and quote reference 2514). This is
* for impact and usage monitoring purposes only.
*
* Enquiries about further applications and development opportunities
* are welcome. Please contact <EMAIL>
*/
package uk.ac.bristol.labynkyr;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.junit.Test;
public class TestDistinguishingTable {
@Test
public void test_mapToWeight_4bits() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 10.0) - 5.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.translateVectorsToPositive();
table.normaliseDistinguishingVectors();
table.takeLogarithm(2.0);
table.applyAbsoluteValue();
final int precisionBits = 4;
final WeightTable weightTable = table.mapToWeight(precisionBits);
final int maxScore = Collections.max(weightTable.allWeights());
assertTrue(maxScore < 16);
}
@Test
public void test_mapToWeight_12bits() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 14.0) - 12.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.translateVectorsToPositive();
table.normaliseDistinguishingVectors();
table.takeLogarithm(2.0);
table.applyAbsoluteValue();
final int precisionBits = 12;
final WeightTable weightTable = table.mapToWeight(precisionBits);
final int maxScore = Collections.max(weightTable.allWeights());
assertTrue(maxScore < 4096);
}
@Test
public void test_normaliseDistinguishingVectors() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 10.0) - 5.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.normaliseDistinguishingVectors();
// Actual
double sum1 = 0.0;
for(int index = 0 ; index < vectorSize ; index++) {
sum1 += table.allScores().get(index);
}
double sum2 = 0.0;
for(int index = vectorSize ; index < 2 * vectorSize ; index++) {
sum2 += table.allScores().get(index);
}
assertEquals(1.0, sum1, 0.0001);
assertEquals(1.0, sum2, 0.0001);
}
@Test
public void test_applyAbsoluteValue() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 10.0) - 5.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.applyAbsoluteValue();
final double minElement = Collections.min(table.allScores());
final double maxElement = Collections.max(table.allScores());
assertTrue(minElement >= 0.0);
assertTrue(maxElement <= 5.0);
}
@Test
public void test_translateVectorsToPositive() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 10.0) - 5.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.translateVectorsToPositive();
final double minElement = Collections.min(table.allScores());
final double maxElement = Collections.max(table.allScores());
assertEquals(0.0, minElement, 0.00001);
assertTrue(maxElement > 9.0);
}
@Test
public void test_translateVectorsToPositive_alreadyPositive() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 4.0) + 1.0;
scores[index] = nextRand;
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.translateVectorsToPositive();
final double minElement = Collections.min(table.allScores());
final double maxElement = Collections.max(table.allScores());
assertTrue(minElement >= 1.0);
assertTrue(maxElement <= 5.0);
}
@Test
public void test_takeLogarithm() {
final int vectorSize = 1 << 8;
Double[] scores = new Double[2 * vectorSize];
Double[] expected = new Double[2 * vectorSize];
// Generate random data
Random rand = new Random();
for(int index = 0 ; index < scores.length ; index++) {
final double nextRand = (rand.nextDouble() * 4.0) + 1.0;
scores[index] = nextRand;
expected[index] = Math.log(nextRand) / Math.log(2.0);
}
DistinguishingTable table = new DistinguishingTable(2, 8, Arrays.asList(scores));
table.takeLogarithm(2.0);
for(int index = 0 ; index < 2 * vectorSize ; index++) {
assertEquals(expected[index], table.allScores().get(index), 0.0001);
}
}
@Test
public void test_score() {
final List<Double> scores = Arrays.asList(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8);
final DistinguishingTable table = new DistinguishingTable(2, 2, scores);
assertEquals(1.1, table.score(0, 0), 0.0001);
assertEquals(2.2, table.score(0, 1), 0.0001);
assertEquals(3.3, table.score(0, 2), 0.0001);
assertEquals(4.4, table.score(0, 3), 0.0001);
assertEquals(5.5, table.score(1, 0), 0.0001);
assertEquals(6.6, table.score(1, 1), 0.0001);
assertEquals(7.7, table.score(1, 2), 0.0001);
assertEquals(8.8, table.score(1, 3), 0.0001);
}
}
| 7,860 | 0.708286 | 0.675395 | 235 | 32.638298 | 25.763264 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.114894 | false | false |
10
|
b8ce9226c9136bb0273750d1079ea1d3ce3b0223
| 31,834,297,615,641 |
e6c2bab77085cd3d103c044d1a1c1ff4b22cd4ed
|
/chapter_002/src/test/java/ru/job4j/tracker/TrackerTest.java
|
454b4e2d77b021fab908345a3b20978665f22f38
|
[
"Apache-2.0"
] |
permissive
|
urgenmagger/JavaCourse
|
https://github.com/urgenmagger/JavaCourse
|
16d7496436670cc80985c94f1727ab9f66380011
|
dad9de9c66125bdfef4a7a803abb43d96c2bdfd7
|
refs/heads/master
| 2021-01-20T07:40:15.237000 | 2019-01-08T19:41:53 | 2019-01-08T19:41:53 | 90,025,818 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ru.job4j.tracker;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created by Megger.
*/
public class TrackerTest {
/**
* Test.
*
* @Test add new item.
*/
@Test
public void whenAddNewItemThenTrackerHasSameItem() {
Tracker tracker = new Tracker();
Item item = new Item("test1", "testDescription", 123L);
tracker.add(item);
assertThat(tracker.findAll().get(0), is(item));
}
/**
* Test.
*
* @Test update item.
*/
@Test
public void whenReplaceNameThenReturnNewName() {
Tracker tracker = new Tracker();
// Добавляем вторую заявку, чтобы проверить, что она не изменится.
Item immutable = new Item("testImmutable", "immutable item", 123L);
Item previous = new Item("test1", "testDescription", 123L);
// Добавляем заявку в трекер. Теперь в объект проинициализирован id.
tracker.add(previous);
tracker.add(immutable);
// Создаем новую заявку.
Item next = new Item("test2", "testDescription2", 1234L);
// Проставляем старый id из previous, который был сгенерирован выше.
next.setId(previous.getId());
// Обновляем заявку в трекере.
tracker.replace(previous.getId(), next);
// Проверяем, что заявка с таким id имеет новые имя test2.
List<Item> list = new ArrayList<>();
list.add(immutable);
list.add(next);
assertThat(tracker.findById(previous.getId()).getName(), is("test2"));
}
/**
* Test.
*
* @Test findById.
*/
@Test
public void findByIdTest() {
Tracker tracker = new Tracker();
Item find = new Item("test1", "testDescription", 123L);
tracker.add(find);
assertThat(tracker.findById(find.getId()).getName(), is("test1"));
}
/**
* Test.
*
* @Test method delete.
*/
@Test
public void deleteTest() {
Tracker tracker = new Tracker();
Item delItem = new Item("test1", "testDescription", 123L);
Item delItem1 = new Item("test2", "testDescription", 123L);
Item delItem2 = new Item("test3", "testDescription", 123L);
tracker.add(delItem);
tracker.add(delItem1);
tracker.add(delItem2);
tracker.deleteItem(delItem2.getId());
List<Item> list = new ArrayList<>();
list.add(delItem);
list.add(delItem1);
assertThat(tracker.findAll(), is(list));
}
/**
* Test.
*
* @Test method findByName.
*/
@Test
public void findByNameTest() {
Tracker tracker = new Tracker();
Item delItem = new Item("test1", "testDescription", 123L);
Item delItem1 = new Item("test1", "description", 123L);
Item delItem2 = new Item("test3", "testDescription1", 123L);
tracker.add(delItem);
tracker.add(delItem1);
tracker.add(delItem2);
tracker.findByName(delItem1.getName());
List<Item> list = new ArrayList<>();
list.add(delItem);
list.add(delItem1);
assertThat(tracker.findByName(delItem1.getName()), is(list));
}
/**
* Test.
*
* @Test method findAll.
*/
@Test
public void findAllTest() {
Tracker tracker = new Tracker();
Item delItem = new Item("test1", "testDescription", 123L);
Item delItem1 = new Item("test1", "testDescription", 123L);
Item delItem2 = new Item("test3", "testDescription1", 123L);
tracker.add(delItem);
tracker.add(delItem1);
tracker.add(delItem2);
List<Item> list = new ArrayList<>();
list.add(delItem);
list.add(delItem1);
list.add(delItem2);
assertThat(tracker.findAll(), is(list));
}
}
|
UTF-8
|
Java
| 4,136 |
java
|
TrackerTest.java
|
Java
|
[
{
"context": "ic org.junit.Assert.assertThat;\n\n/**\n * Created by Megger.\n */\npublic class TrackerTest {\n /**\n * Te",
"end": 210,
"score": 0.9653894305229187,
"start": 204,
"tag": "NAME",
"value": "Megger"
}
] | null |
[] |
package ru.job4j.tracker;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created by Megger.
*/
public class TrackerTest {
/**
* Test.
*
* @Test add new item.
*/
@Test
public void whenAddNewItemThenTrackerHasSameItem() {
Tracker tracker = new Tracker();
Item item = new Item("test1", "testDescription", 123L);
tracker.add(item);
assertThat(tracker.findAll().get(0), is(item));
}
/**
* Test.
*
* @Test update item.
*/
@Test
public void whenReplaceNameThenReturnNewName() {
Tracker tracker = new Tracker();
// Добавляем вторую заявку, чтобы проверить, что она не изменится.
Item immutable = new Item("testImmutable", "immutable item", 123L);
Item previous = new Item("test1", "testDescription", 123L);
// Добавляем заявку в трекер. Теперь в объект проинициализирован id.
tracker.add(previous);
tracker.add(immutable);
// Создаем новую заявку.
Item next = new Item("test2", "testDescription2", 1234L);
// Проставляем старый id из previous, который был сгенерирован выше.
next.setId(previous.getId());
// Обновляем заявку в трекере.
tracker.replace(previous.getId(), next);
// Проверяем, что заявка с таким id имеет новые имя test2.
List<Item> list = new ArrayList<>();
list.add(immutable);
list.add(next);
assertThat(tracker.findById(previous.getId()).getName(), is("test2"));
}
/**
* Test.
*
* @Test findById.
*/
@Test
public void findByIdTest() {
Tracker tracker = new Tracker();
Item find = new Item("test1", "testDescription", 123L);
tracker.add(find);
assertThat(tracker.findById(find.getId()).getName(), is("test1"));
}
/**
* Test.
*
* @Test method delete.
*/
@Test
public void deleteTest() {
Tracker tracker = new Tracker();
Item delItem = new Item("test1", "testDescription", 123L);
Item delItem1 = new Item("test2", "testDescription", 123L);
Item delItem2 = new Item("test3", "testDescription", 123L);
tracker.add(delItem);
tracker.add(delItem1);
tracker.add(delItem2);
tracker.deleteItem(delItem2.getId());
List<Item> list = new ArrayList<>();
list.add(delItem);
list.add(delItem1);
assertThat(tracker.findAll(), is(list));
}
/**
* Test.
*
* @Test method findByName.
*/
@Test
public void findByNameTest() {
Tracker tracker = new Tracker();
Item delItem = new Item("test1", "testDescription", 123L);
Item delItem1 = new Item("test1", "description", 123L);
Item delItem2 = new Item("test3", "testDescription1", 123L);
tracker.add(delItem);
tracker.add(delItem1);
tracker.add(delItem2);
tracker.findByName(delItem1.getName());
List<Item> list = new ArrayList<>();
list.add(delItem);
list.add(delItem1);
assertThat(tracker.findByName(delItem1.getName()), is(list));
}
/**
* Test.
*
* @Test method findAll.
*/
@Test
public void findAllTest() {
Tracker tracker = new Tracker();
Item delItem = new Item("test1", "testDescription", 123L);
Item delItem1 = new Item("test1", "testDescription", 123L);
Item delItem2 = new Item("test3", "testDescription1", 123L);
tracker.add(delItem);
tracker.add(delItem1);
tracker.add(delItem2);
List<Item> list = new ArrayList<>();
list.add(delItem);
list.add(delItem1);
list.add(delItem2);
assertThat(tracker.findAll(), is(list));
}
}
| 4,136 | 0.586233 | 0.564995 | 134 | 28.171642 | 22.731569 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.753731 | false | false |
10
|
220568ee6953ac7d91853bb7a8d68848ee4553b5
| 2,465,311,247,404 |
2a03fc16fd10bfbde4cee277256f50d6e97b5144
|
/day10/JavaIfClass2.java
|
c85c2df1f39841f64ab9d169686c44c94bbbccde
|
[] |
no_license
|
vepailjanov/gitfile
|
https://github.com/vepailjanov/gitfile
|
cbcc7f27613e4fb3726924ad353d7779883e080b
|
28f6dec6fabb435de4d7b2b31afdba8ef96d3ce8
|
refs/heads/master
| 2022-08-24T16:26:58.328000 | 2020-05-26T17:35:41 | 2020-05-26T17:35:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package day10;
import java.util.Scanner;
public class JavaIfClass2 {
public static void main(String[] args) {
Scanner myscan = new Scanner( System.in);
String s1 = myscan.nextLine();
String s2 = myscan.nextLine();
int total = s1.length() + s2.length();
if (total > 10){
System.out.println("right");
}else if (total >5){
System.out.println("wrong");
}else if (total > 3){
System.out.println("maybe");
}
}
}
|
UTF-8
|
Java
| 520 |
java
|
JavaIfClass2.java
|
Java
|
[] | null |
[] |
package day10;
import java.util.Scanner;
public class JavaIfClass2 {
public static void main(String[] args) {
Scanner myscan = new Scanner( System.in);
String s1 = myscan.nextLine();
String s2 = myscan.nextLine();
int total = s1.length() + s2.length();
if (total > 10){
System.out.println("right");
}else if (total >5){
System.out.println("wrong");
}else if (total > 3){
System.out.println("maybe");
}
}
}
| 520 | 0.540385 | 0.519231 | 23 | 21.608696 | 17.765965 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false |
10
|
401f5585a90e5324273b2038c1316b904e360aa3
| 30,631,706,774,954 |
7648bc4bb9a106cc83edf3fdeeb68977d44f4b0b
|
/src/test/java/Bizarre/Union.java
|
835b91219288b43be0eb6f6823ee5ca48084a962
|
[] |
no_license
|
Parveenr21/CJ
|
https://github.com/Parveenr21/CJ
|
38112901602e356ee078de9af53423d1537e84b4
|
3eff70d8a2eecf631b356c447d58c4f432a865ef
|
refs/heads/master
| 2022-07-23T16:45:24.001000 | 2021-05-22T08:36:03 | 2021-05-22T08:36:03 | 28,764,885 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Bizarre;
/*
* func(new int[]{1,2}); //called
*
* ab iski definition main
*
*
* return int[] func(int a[])
*
* {
*
* sort();
*
* }
*/
|
UTF-8
|
Java
| 173 |
java
|
Union.java
|
Java
|
[] | null |
[] |
package Bizarre;
/*
* func(new int[]{1,2}); //called
*
* ab iski definition main
*
*
* return int[] func(int a[])
*
* {
*
* sort();
*
* }
*/
| 173 | 0.421965 | 0.410405 | 15 | 9.666667 | 10.51771 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false |
10
|
5938859039e816fda3aeb39b71519bb297c19b6c
| 4,123,168,629,536 |
1097500df16344aa08a2b5e7582ad0d37297db42
|
/app/src/main/java/tuhh/nme/mp/components/Event.java
|
9593c5b016106c093a08264755d3c5830dbbacf1
|
[] |
no_license
|
Makman2/MP
|
https://github.com/Makman2/MP
|
bdc16e3354d9fa1d47face4d3d89e6374037f426
|
8826376100563d8a3beeecffc1fa805d150efeb9
|
refs/heads/master
| 2021-06-03T14:38:18.885000 | 2017-12-02T21:21:07 | 2017-12-02T21:21:07 | 33,422,070 | 0 | 2 | null | false | 2015-07-09T23:12:17 | 2015-04-04T22:08:51 | 2015-05-03T21:21:37 | 2015-07-09T23:12:16 | 1,255 | 0 | 0 | 13 |
Java
| null | null |
package tuhh.nme.mp.components;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* A list of handlers. This class allows multiple registration of more than one listener and
* easy calling.
*
* To use an event, just override the onRaise() function and put in the specific listener raise.
*
* To register/unregister an event, call the attach/detach functions. You can also get all
* registered listeners by iterating over this class or using getListeners().
*
* @param <ListenerType> The type of the listeners that will be registered.
*/
public abstract class Event<ListenerType> implements Iterable<ListenerType>
{
/**
* Instantiates a new Event.
*/
public Event()
{
m_Listeners = new HashSet<>();
}
/**
* Attaches a listener to this event.
*
* @param listener The listener to attach.
* @throws InternalError Thrown when the passed listener was already registered.
*/
public void attach(ListenerType listener) throws InternalError
{
if (!m_Listeners.add(listener))
{
throw new InternalError("The given listener is already registered.");
}
}
/**
* Detaches a listener from this event.
*
* @param listener The listener to detach.
* @throws InternalError Thrown when the passed listener was not registered.
*/
public void detach(ListenerType listener) throws InternalError
{
if (!m_Listeners.remove(listener))
{
throw new InternalError("The passed listener was not attached to this event.");
}
}
/**
* Detaches all registered listeners.
*/
public void detachAll()
{
m_Listeners.clear();
}
/**
* Invokes each registered listener.
*
* @param params Additional params to invoke the listener with.
*/
public final void raise(Object... params) throws Error
{
if (!isInvocationValid(params))
{
throw new InvalidInvocationException("Invalid call invocation.");
}
for (ListenerType elem : m_Listeners)
{
onRaise(elem, params);
}
}
/**
* Returns a Set of all registered listeners.
*
* @return The set that contains all registered listeners.
*/
public Set<ListenerType> getListeners()
{
return Collections.unmodifiableSet(m_Listeners);
}
/**
* Returns an iterator to the registered listeners.
*
* @return The iterator.
*/
@Override
public Iterator<ListenerType> iterator()
{
return m_Listeners.iterator();
}
/**
* Checks whether the invoked params are suited for listener invocation.
*
* You should override this function and check for argument number to defeat invocation errors.
* But you don't need to override this function, in this case every invocation is valid.
*
* Parameter types should be not checked, you need to cast them anyway in onRaise() where the
* casts would raise automatically a ClassCastException.
*
* @param params The parameters passed to the raise.
* @return true if invocation with these arguments is valid, otherwise false.
*/
protected boolean isInvocationValid(Object ... params)
{
return true;
}
/**
* Raised when raise() is invoked.
*
* Override this function to invoke the specific listening function in your listener.
*
* @param listener The listener that shall be invoked.
* @param params Additional parameters to invoke the listener with.
* @throws Error Any Error that can occur during invocation.
*/
protected abstract void onRaise(ListenerType listener, Object... params) throws Error;
/**
* The Set that stores all attached listeners.
*/
private Set<ListenerType> m_Listeners;
}
|
UTF-8
|
Java
| 3,976 |
java
|
Event.java
|
Java
|
[] | null |
[] |
package tuhh.nme.mp.components;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* A list of handlers. This class allows multiple registration of more than one listener and
* easy calling.
*
* To use an event, just override the onRaise() function and put in the specific listener raise.
*
* To register/unregister an event, call the attach/detach functions. You can also get all
* registered listeners by iterating over this class or using getListeners().
*
* @param <ListenerType> The type of the listeners that will be registered.
*/
public abstract class Event<ListenerType> implements Iterable<ListenerType>
{
/**
* Instantiates a new Event.
*/
public Event()
{
m_Listeners = new HashSet<>();
}
/**
* Attaches a listener to this event.
*
* @param listener The listener to attach.
* @throws InternalError Thrown when the passed listener was already registered.
*/
public void attach(ListenerType listener) throws InternalError
{
if (!m_Listeners.add(listener))
{
throw new InternalError("The given listener is already registered.");
}
}
/**
* Detaches a listener from this event.
*
* @param listener The listener to detach.
* @throws InternalError Thrown when the passed listener was not registered.
*/
public void detach(ListenerType listener) throws InternalError
{
if (!m_Listeners.remove(listener))
{
throw new InternalError("The passed listener was not attached to this event.");
}
}
/**
* Detaches all registered listeners.
*/
public void detachAll()
{
m_Listeners.clear();
}
/**
* Invokes each registered listener.
*
* @param params Additional params to invoke the listener with.
*/
public final void raise(Object... params) throws Error
{
if (!isInvocationValid(params))
{
throw new InvalidInvocationException("Invalid call invocation.");
}
for (ListenerType elem : m_Listeners)
{
onRaise(elem, params);
}
}
/**
* Returns a Set of all registered listeners.
*
* @return The set that contains all registered listeners.
*/
public Set<ListenerType> getListeners()
{
return Collections.unmodifiableSet(m_Listeners);
}
/**
* Returns an iterator to the registered listeners.
*
* @return The iterator.
*/
@Override
public Iterator<ListenerType> iterator()
{
return m_Listeners.iterator();
}
/**
* Checks whether the invoked params are suited for listener invocation.
*
* You should override this function and check for argument number to defeat invocation errors.
* But you don't need to override this function, in this case every invocation is valid.
*
* Parameter types should be not checked, you need to cast them anyway in onRaise() where the
* casts would raise automatically a ClassCastException.
*
* @param params The parameters passed to the raise.
* @return true if invocation with these arguments is valid, otherwise false.
*/
protected boolean isInvocationValid(Object ... params)
{
return true;
}
/**
* Raised when raise() is invoked.
*
* Override this function to invoke the specific listening function in your listener.
*
* @param listener The listener that shall be invoked.
* @param params Additional parameters to invoke the listener with.
* @throws Error Any Error that can occur during invocation.
*/
protected abstract void onRaise(ListenerType listener, Object... params) throws Error;
/**
* The Set that stores all attached listeners.
*/
private Set<ListenerType> m_Listeners;
}
| 3,976 | 0.642606 | 0.642606 | 137 | 28.021898 | 29.815849 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.167883 | false | false |
10
|
2fea3ccb11ad8c93da71e7513583434c3a725264
| 10,574,209,516,782 |
0cd3a21de54b2374d17d09602487f4ae1c7a0f1c
|
/gradleHarjoitus/src/main/java/Main.java
|
98ff57c39c980812ccdc129dbdb2222ae2f600cc
|
[] |
no_license
|
AventusM/ohtu-viikko1
|
https://github.com/AventusM/ohtu-viikko1
|
3e1a2285ad88c93676d60c5f25b6c1320d91009e
|
f55363b33032dee302ce4b2c0462525a7426bacd
|
refs/heads/master
| 2021-08-09T01:25:36.589000 | 2017-11-11T19:26:20 | 2017-11-11T19:26:20 | 108,759,986 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.*;
import ohtu.Multiplier;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//System.out.print("Nimesi? ");
Multiplier kolme = new Multiplier(3);
System.out.println("Anna luku: ");
int luku = input.nextInt();
System.out.println("luku kertaa kolme on " + kolme.multipliedBy(luku));
//String nimi = input.nextLine();
//System.out.println("Moikka " + nimi);
}
}
|
UTF-8
|
Java
| 480 |
java
|
Main.java
|
Java
|
[] | null |
[] |
import java.util.*;
import ohtu.Multiplier;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//System.out.print("Nimesi? ");
Multiplier kolme = new Multiplier(3);
System.out.println("Anna luku: ");
int luku = input.nextInt();
System.out.println("luku kertaa kolme on " + kolme.multipliedBy(luku));
//String nimi = input.nextLine();
//System.out.println("Moikka " + nimi);
}
}
| 480 | 0.633333 | 0.63125 | 15 | 31 | 19.889696 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
10
|
873ad4315a9cf97025582e6c8aff7a1435cf04a6
| 14,963,666,090,888 |
633ac65158309f1578ae637a4ec640fcb68544f0
|
/transaction/src/main/java/com/franktran/transaction/employee/EmployeeController.java
|
e4f55fa0e0b213bb632d16ee428029374cb76b5b
|
[] |
no_license
|
franktranvantu/spring-boot
|
https://github.com/franktranvantu/spring-boot
|
c78df3116c658c201e2655332d97e2c915572db4
|
00c25eab59fe2945449644fd972fb3b95443d85e
|
refs/heads/master
| 2021-07-08T03:40:29.080000 | 2021-05-14T10:29:40 | 2021-05-14T10:29:40 | 241,910,724 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.franktran.transaction.employee;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@PostMapping
public String createEmployee(@RequestBody EmployeeRequestVO employeeRequest) {
return employeeService.createEmployee(employeeRequest);
}
}
|
UTF-8
|
Java
| 717 |
java
|
EmployeeController.java
|
Java
|
[] | null |
[] |
package com.franktran.transaction.employee;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@PostMapping
public String createEmployee(@RequestBody EmployeeRequestVO employeeRequest) {
return employeeService.createEmployee(employeeRequest);
}
}
| 717 | 0.806137 | 0.806137 | 22 | 31.59091 | 27.388882 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
10
|
c343a6c9b33d8d3bfea257fe7457f9295c96c900
| 15,650,860,874,465 |
3d2b89813963f8e104be4b1a2f15f74a927b3d18
|
/src/Producten/Recepten/BasisRecept.java
|
892046e0038d0639bf52aebf2bc35b108fecfe38
|
[] |
no_license
|
IndyVC/StefanDataMigration
|
https://github.com/IndyVC/StefanDataMigration
|
fffd62cf4fe68f38804e6fb8bea2774368812d76
|
572bb2f1ec83ed7415b22a737259072912861934
|
refs/heads/master
| 2022-03-14T08:18:45.330000 | 2019-09-11T10:44:08 | 2019-09-11T10:44:08 | 201,220,042 | 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 Producten.Recepten;
import Algemeen.Omschrijving;
import New.New;
import Producten.AfgewerktProduct;
import Producten.BasisProduct;
import Producten.ReceptProduct;
import Producten.VerkoopProduct;
import Producten.VoorbereidProduct;
import TussenTabellen.AfgewerktProductBasisRecept;
import TussenTabellen.BasisProductBasisRecept;
import TussenTabellen.ReceptProductBasisRecept;
import TussenTabellen.VerkoopProductBasisRecept;
import TussenTabellen.VoorbereidProductBasisRecept;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author stefa
*/
public class BasisRecept implements New{
public int BasisReceptId;
public Omschrijving Omschrijving;
public double Hoeveelheid;
public double Percentage;
public int Volgnummer;
public boolean Hulpstof;
public boolean Telbasis;
public int AantalPersonen;
public List<BasisProductBasisRecept> BasisReceptBasisProducten;
public List<AfgewerktProductBasisRecept> BasisReceptAfgewerkteProducten;
public List<VerkoopProductBasisRecept> BasisReceptverkoopProducten;
public List<VoorbereidProductBasisRecept> BasisReceptVoorbereidProducten;
public List<ReceptProductBasisRecept> BasisReceptReceptProducten;
public BasisRecept() {
}
public BasisRecept(int BasisReceptId, Omschrijving Omschrijving, double Hoeveelheid, double Percentage, int Volgnummer, boolean Hulpstof, boolean Telbasis, int AantalPersonen) {
this.BasisReceptId = BasisReceptId;
this.Omschrijving = Omschrijving;
this.Hoeveelheid = Hoeveelheid;
this.Percentage = Percentage;
this.Volgnummer = Volgnummer;
this.Hulpstof = Hulpstof;
this.Telbasis = Telbasis;
this.AantalPersonen = AantalPersonen;
BasisReceptBasisProducten = new ArrayList();
BasisReceptAfgewerkteProducten = new ArrayList();
BasisReceptverkoopProducten =new ArrayList();
BasisReceptVoorbereidProducten = new ArrayList();
BasisReceptReceptProducten = new ArrayList();
}
public int getBasisReceptId() {
return BasisReceptId;
}
public void setBasisReceptId(int BasisReceptId) {
this.BasisReceptId = BasisReceptId;
}
public Omschrijving getOmschrijving() {
return Omschrijving;
}
public void setOmschrijving(Omschrijving Omschrijving) {
this.Omschrijving = Omschrijving;
}
public double getHoeveelheid() {
return Hoeveelheid;
}
public void setHoeveelheid(double Hoeveelheid) {
this.Hoeveelheid = Hoeveelheid;
}
public double getPercentage() {
return Percentage;
}
public void setPercentage(double Percentage) {
this.Percentage = Percentage;
}
public int getVolgnummer() {
return Volgnummer;
}
public void setVolgnummer(int Volgnummer) {
this.Volgnummer = Volgnummer;
}
public boolean getHulpstof() {
return Hulpstof;
}
public void setHulpstof(boolean Hulpstof) {
this.Hulpstof = Hulpstof;
}
public boolean getTelbasis() {
return Telbasis;
}
public void setTelbasis(boolean Telbasis) {
this.Telbasis = Telbasis;
}
public int getAantalPersonen() {
return AantalPersonen;
}
public void setAantalPersonen(int AantalPersonen) {
this.AantalPersonen = AantalPersonen;
}
public List<BasisProductBasisRecept> getBasisReceptBasisProducten() {
return BasisReceptBasisProducten;
}
public void setBasisReceptBasisProducten(List<BasisProductBasisRecept> BasisReceptBasisProducten) {
this.BasisReceptBasisProducten = BasisReceptBasisProducten;
}
public List<AfgewerktProductBasisRecept> getBasisReceptAfgewerkteProducten() {
return BasisReceptAfgewerkteProducten;
}
public void setBasisReceptAfgewerkteProducten(List<AfgewerktProductBasisRecept> BasisReceptAfgewerkteProducten) {
this.BasisReceptAfgewerkteProducten = BasisReceptAfgewerkteProducten;
}
public List<VerkoopProductBasisRecept> getBasisReceptverkoopProducten() {
return BasisReceptverkoopProducten;
}
public void setBasisReceptverkoopProducten(List<VerkoopProductBasisRecept> BasisReceptverkoopProducten) {
this.BasisReceptverkoopProducten = BasisReceptverkoopProducten;
}
public List<VoorbereidProductBasisRecept> getBasisReceptVoorbereidProducten() {
return BasisReceptVoorbereidProducten;
}
public void setBasisReceptVoorbereidProducten(List<VoorbereidProductBasisRecept> BasisReceptVoorbereidProducten) {
this.BasisReceptVoorbereidProducten = BasisReceptVoorbereidProducten;
}
public List<ReceptProductBasisRecept> getBasisReceptReceptProducten() {
return BasisReceptReceptProducten;
}
public void setBasisReceptReceptProducten(List<ReceptProductBasisRecept> BasisReceptReceptProducten) {
this.BasisReceptReceptProducten = BasisReceptReceptProducten;
}
@Override
public void setId(int id) {
this.BasisReceptId=id;
}
@Override
public int getId() {
return this.BasisReceptId;
}
}
|
UTF-8
|
Java
| 5,554 |
java
|
BasisRecept.java
|
Java
|
[
{
"context": "st;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author stefa\r\n */\r\npublic class BasisRecept implements New{\r\n\r",
"end": 773,
"score": 0.9988594055175781,
"start": 768,
"tag": "USERNAME",
"value": "stefa"
}
] | 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 Producten.Recepten;
import Algemeen.Omschrijving;
import New.New;
import Producten.AfgewerktProduct;
import Producten.BasisProduct;
import Producten.ReceptProduct;
import Producten.VerkoopProduct;
import Producten.VoorbereidProduct;
import TussenTabellen.AfgewerktProductBasisRecept;
import TussenTabellen.BasisProductBasisRecept;
import TussenTabellen.ReceptProductBasisRecept;
import TussenTabellen.VerkoopProductBasisRecept;
import TussenTabellen.VoorbereidProductBasisRecept;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author stefa
*/
public class BasisRecept implements New{
public int BasisReceptId;
public Omschrijving Omschrijving;
public double Hoeveelheid;
public double Percentage;
public int Volgnummer;
public boolean Hulpstof;
public boolean Telbasis;
public int AantalPersonen;
public List<BasisProductBasisRecept> BasisReceptBasisProducten;
public List<AfgewerktProductBasisRecept> BasisReceptAfgewerkteProducten;
public List<VerkoopProductBasisRecept> BasisReceptverkoopProducten;
public List<VoorbereidProductBasisRecept> BasisReceptVoorbereidProducten;
public List<ReceptProductBasisRecept> BasisReceptReceptProducten;
public BasisRecept() {
}
public BasisRecept(int BasisReceptId, Omschrijving Omschrijving, double Hoeveelheid, double Percentage, int Volgnummer, boolean Hulpstof, boolean Telbasis, int AantalPersonen) {
this.BasisReceptId = BasisReceptId;
this.Omschrijving = Omschrijving;
this.Hoeveelheid = Hoeveelheid;
this.Percentage = Percentage;
this.Volgnummer = Volgnummer;
this.Hulpstof = Hulpstof;
this.Telbasis = Telbasis;
this.AantalPersonen = AantalPersonen;
BasisReceptBasisProducten = new ArrayList();
BasisReceptAfgewerkteProducten = new ArrayList();
BasisReceptverkoopProducten =new ArrayList();
BasisReceptVoorbereidProducten = new ArrayList();
BasisReceptReceptProducten = new ArrayList();
}
public int getBasisReceptId() {
return BasisReceptId;
}
public void setBasisReceptId(int BasisReceptId) {
this.BasisReceptId = BasisReceptId;
}
public Omschrijving getOmschrijving() {
return Omschrijving;
}
public void setOmschrijving(Omschrijving Omschrijving) {
this.Omschrijving = Omschrijving;
}
public double getHoeveelheid() {
return Hoeveelheid;
}
public void setHoeveelheid(double Hoeveelheid) {
this.Hoeveelheid = Hoeveelheid;
}
public double getPercentage() {
return Percentage;
}
public void setPercentage(double Percentage) {
this.Percentage = Percentage;
}
public int getVolgnummer() {
return Volgnummer;
}
public void setVolgnummer(int Volgnummer) {
this.Volgnummer = Volgnummer;
}
public boolean getHulpstof() {
return Hulpstof;
}
public void setHulpstof(boolean Hulpstof) {
this.Hulpstof = Hulpstof;
}
public boolean getTelbasis() {
return Telbasis;
}
public void setTelbasis(boolean Telbasis) {
this.Telbasis = Telbasis;
}
public int getAantalPersonen() {
return AantalPersonen;
}
public void setAantalPersonen(int AantalPersonen) {
this.AantalPersonen = AantalPersonen;
}
public List<BasisProductBasisRecept> getBasisReceptBasisProducten() {
return BasisReceptBasisProducten;
}
public void setBasisReceptBasisProducten(List<BasisProductBasisRecept> BasisReceptBasisProducten) {
this.BasisReceptBasisProducten = BasisReceptBasisProducten;
}
public List<AfgewerktProductBasisRecept> getBasisReceptAfgewerkteProducten() {
return BasisReceptAfgewerkteProducten;
}
public void setBasisReceptAfgewerkteProducten(List<AfgewerktProductBasisRecept> BasisReceptAfgewerkteProducten) {
this.BasisReceptAfgewerkteProducten = BasisReceptAfgewerkteProducten;
}
public List<VerkoopProductBasisRecept> getBasisReceptverkoopProducten() {
return BasisReceptverkoopProducten;
}
public void setBasisReceptverkoopProducten(List<VerkoopProductBasisRecept> BasisReceptverkoopProducten) {
this.BasisReceptverkoopProducten = BasisReceptverkoopProducten;
}
public List<VoorbereidProductBasisRecept> getBasisReceptVoorbereidProducten() {
return BasisReceptVoorbereidProducten;
}
public void setBasisReceptVoorbereidProducten(List<VoorbereidProductBasisRecept> BasisReceptVoorbereidProducten) {
this.BasisReceptVoorbereidProducten = BasisReceptVoorbereidProducten;
}
public List<ReceptProductBasisRecept> getBasisReceptReceptProducten() {
return BasisReceptReceptProducten;
}
public void setBasisReceptReceptProducten(List<ReceptProductBasisRecept> BasisReceptReceptProducten) {
this.BasisReceptReceptProducten = BasisReceptReceptProducten;
}
@Override
public void setId(int id) {
this.BasisReceptId=id;
}
@Override
public int getId() {
return this.BasisReceptId;
}
}
| 5,554 | 0.7139 | 0.7139 | 180 | 28.855556 | 29.60858 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438889 | false | false |
10
|
24bb742f634813cb0b31e5b3e512904ad7c46ffc
| 29,111,288,371,156 |
2cb9abd2ad177ad8cbb1f088d8a5efc457c6b31f
|
/UI/Core/src/main/java/de/thm/mni/mhpp11/smbj/ui/messages/StartUIMessage.java
|
04514ae4384709251e27c534ed8b6b75542cd954
|
[
"MIT"
] |
permissive
|
hobbypunk90/SMBJ
|
https://github.com/hobbypunk90/SMBJ
|
345173e3baae09b284983bf9cba87f4f3316dd68
|
36b1c7033a383b4311c70a3a502fb8bbe6e204d4
|
refs/heads/master
| 2021-08-22T14:58:40.891000 | 2017-11-30T13:25:17 | 2017-11-30T13:25:17 | 112,613,604 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.thm.mni.mhpp11.smbj.ui.messages;
import de.thm.mni.mhpp11.smbj.actors.IActor;
import de.thm.mni.mhpp11.smbj.manager.messages.InitStartMessage;
import javafx.stage.Stage;
import lombok.EqualsAndHashCode;
import lombok.Value;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
@Value
@EqualsAndHashCode(callSuper = true)
public class StartUIMessage extends InitStartMessage {
Stage stage;
List<?> params;
public StartUIMessage(Class<? extends IActor> actorClass, Stage stage) {
this(null, actorClass, stage);
}
public StartUIMessage(Class<? extends IActor> actorClass, Stage stage, List<?> params) {
this(null, actorClass, stage, params);
}
public StartUIMessage(UUID source, Class<? extends IActor> actorClass, Stage stage) {
this(source, actorClass, stage, Collections.EMPTY_LIST);
}
public StartUIMessage(UUID source, Class<? extends IActor> actorClass, Stage stage, List<?> params) {
super(source, actorClass);
this.stage = stage;
this.params = params;
}
@Override
public Void init(UUID id, IActor actor) {
return null;
}
@Override
public Void answer(UUID id, IActor actor) {
return null;
}
public String toString() {
return String.format("StartUIMessage(payload=%s, stage=%s)", getPayload().getSimpleName(), stage);
}
}
|
UTF-8
|
Java
| 1,361 |
java
|
StartUIMessage.java
|
Java
|
[] | null |
[] |
package de.thm.mni.mhpp11.smbj.ui.messages;
import de.thm.mni.mhpp11.smbj.actors.IActor;
import de.thm.mni.mhpp11.smbj.manager.messages.InitStartMessage;
import javafx.stage.Stage;
import lombok.EqualsAndHashCode;
import lombok.Value;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
@Value
@EqualsAndHashCode(callSuper = true)
public class StartUIMessage extends InitStartMessage {
Stage stage;
List<?> params;
public StartUIMessage(Class<? extends IActor> actorClass, Stage stage) {
this(null, actorClass, stage);
}
public StartUIMessage(Class<? extends IActor> actorClass, Stage stage, List<?> params) {
this(null, actorClass, stage, params);
}
public StartUIMessage(UUID source, Class<? extends IActor> actorClass, Stage stage) {
this(source, actorClass, stage, Collections.EMPTY_LIST);
}
public StartUIMessage(UUID source, Class<? extends IActor> actorClass, Stage stage, List<?> params) {
super(source, actorClass);
this.stage = stage;
this.params = params;
}
@Override
public Void init(UUID id, IActor actor) {
return null;
}
@Override
public Void answer(UUID id, IActor actor) {
return null;
}
public String toString() {
return String.format("StartUIMessage(payload=%s, stage=%s)", getPayload().getSimpleName(), stage);
}
}
| 1,361 | 0.714181 | 0.709772 | 52 | 25.173077 | 27.670952 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.807692 | false | false |
10
|
ed82d576909b13fdd17128d03da12b16c90f91fe
| 283,467,889,101 |
2fa837bc12fb3afe8ec66131102431493ac8f1a9
|
/Bomberman/src/personaje/Sirius.java
|
3986517c416a8100aa7774f93dc50bec9f1945eb
|
[] |
no_license
|
EstebanCanela/tdp2015
|
https://github.com/EstebanCanela/tdp2015
|
4a434b8b71b99920ed129cc0980ab5ca256258ad
|
d1c59c67c97889f1dc59823e591d4c4006d2dd31
|
refs/heads/master
| 2020-05-16T14:06:17.413000 | 2015-11-26T22:52:43 | 2015-11-26T22:52:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package personaje;
import threads.ThreadEnemigo;
import threads.ThreadSirius;
import logica.Nivel;
import celda.Celda;
import entidades.SiriusGrafica;
/**
* Clase Sirius
* @author Esteban Federico Canela y German Herrou
*
*/
public class Sirius extends Enemigo {
protected ThreadEnemigo th;
/**
* Constructor de Sirius
* @param c Celda a la que pertenece
* @param n Nivel al que pertenece
* @param b Bomberman al que debe perseguir
*/
public Sirius(Celda c,Nivel n,Bomberman b){
super(c,n,false,50);
miGrafico=new SiriusGrafica(velocidad,getCelda().getPosX(),getCelda().getPosY());
th=new ThreadSirius(this,n,b);
th.start();
}
public void morir(){
super.morir();
th.detener();
}
}
|
UTF-8
|
Java
| 760 |
java
|
Sirius.java
|
Java
|
[
{
"context": "iriusGrafica;\r\n\r\n/**\r\n * Clase Sirius \r\n * @author Esteban Federico Canela y German Herrou\r\n *\r\n */\r\n\r\npublic class Sirius e",
"end": 218,
"score": 0.9998769760131836,
"start": 195,
"tag": "NAME",
"value": "Esteban Federico Canela"
},
{
"context": "lase Sirius \r\n * @author Esteban Federico Canela y German Herrou\r\n *\r\n */\r\n\r\npublic class Sirius extends Enemigo {",
"end": 234,
"score": 0.9998738765716553,
"start": 221,
"tag": "NAME",
"value": "German Herrou"
}
] | null |
[] |
package personaje;
import threads.ThreadEnemigo;
import threads.ThreadSirius;
import logica.Nivel;
import celda.Celda;
import entidades.SiriusGrafica;
/**
* Clase Sirius
* @author <NAME> y <NAME>
*
*/
public class Sirius extends Enemigo {
protected ThreadEnemigo th;
/**
* Constructor de Sirius
* @param c Celda a la que pertenece
* @param n Nivel al que pertenece
* @param b Bomberman al que debe perseguir
*/
public Sirius(Celda c,Nivel n,Bomberman b){
super(c,n,false,50);
miGrafico=new SiriusGrafica(velocidad,getCelda().getPosX(),getCelda().getPosY());
th=new ThreadSirius(this,n,b);
th.start();
}
public void morir(){
super.morir();
th.detener();
}
}
| 736 | 0.675 | 0.672368 | 37 | 18.594595 | 18.332455 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.324324 | false | false |
10
|
baab0a9de7ae232510fa1c65cddd2af6f435b3d9
| 30,700,426,288,014 |
02d4924b99f3b71b49544b4a05da7ad75858d52a
|
/60_web/10_shop/src/com/bc/mybatis/Cart.java
|
f9fab657d16742d4ced42cc575b12dd0267e192b
|
[] |
no_license
|
javaara/bit_MyStudy
|
https://github.com/javaara/bit_MyStudy
|
5585520cd2bb5d728983654b1c477b42226ef668
|
e7dfbc68b770d8f3b86e1e6e9cf552950b31abb6
|
refs/heads/master
| 2020-09-28T16:57:49.479000 | 2020-06-28T09:15:23 | 2020-06-28T09:15:23 | 226,819,125 | 0 | 0 | null | false | 2020-06-28T09:15:24 | 2019-12-09T08:14:35 | 2020-06-28T09:08:50 | 2020-06-28T09:15:23 | 96,211 | 0 | 0 | 0 |
Java
| false | false |
package com.bc.mybatis;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
//장바구니 역할 클래스
public class Cart {
private List<ShopVO> list; //카트에 담긴 제품 목록
private int total; //카트에 담긴 전체 제품 가격 합계금액
public Cart() {
list = new ArrayList<ShopVO>();
}
public List<ShopVO> getList() { return list; }
public int getTotal() { return total; }
/**
* 장바구니 담기 요청 처리(카트에 제품 추가)
* list에 없으면 제품 추가
* list에 동일한 제품이 있으면 수량만 하나 증가 처리
* @param p_num
* @param dao
*/
public void addProduct(String p_num, ShopDAO dao) {
//카트에 제품이 있는지 확인
ShopVO vo = findProduct(p_num);
if (vo != null) { //카트에 있음 -> 수량 증가 처리
//1. 수량 증가 처리
vo.setQuant(vo.getQuant() + 1);
//2. 카트의 total 값 합산(제품 하나 가격 추가)
total += vo.getP_saleprice();
} else { //카트에 없음 -> 제품을 카트에 등록
//1. p_num 조회해서 VO객체 만들기
vo = dao.selectOne(p_num);
//2. 수량 1 증가 처리
vo.setQuant(1);
//3. 카트 목록에 추가
list.add(vo);
//4. total 값 계산(제품 하나 가격 추가)
total += vo.getP_saleprice();
}
}
//카트에 제품이 있는지 확인
public ShopVO findProduct(String p_num) {
ShopVO vo = null;
Iterator<ShopVO> ite = list.iterator();
while (ite.hasNext()) {
ShopVO listVO = ite.next();
if (listVO.getP_num().equals(p_num)) {
vo = listVO;
break;
}
}
//개선된 for문으로 작성(실습)
return vo;
}
//목록(list)에 있는 제품 삭제 처리
public void delProduct(String p_num) {
ShopVO vo = findProduct(p_num);
if (vo != null) {
list.remove(vo);
//카트의 전체 제품 가격에서 삭제된 제품금액 빼기
total = total - vo.getTotalprice();
}
}
//카트 목록(list) 제품의 수량 변경 처리
public void setQuant(String p_num, int su) {
ShopVO vo = findProduct(p_num);
if (vo == null) return;
//1. 카트 합계 금액 - 수량 변경전 제품 합계 금액
total = total - vo.getTotalprice();
//2. 제품의 수량 변경
vo.setQuant(su);
//3. 카트 합계 금액 + 수량 변경 후 제품 합계 금액
total = total + vo.getTotalprice();
}
}
|
UTF-8
|
Java
| 2,414 |
java
|
Cart.java
|
Java
|
[] | null |
[] |
package com.bc.mybatis;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
//장바구니 역할 클래스
public class Cart {
private List<ShopVO> list; //카트에 담긴 제품 목록
private int total; //카트에 담긴 전체 제품 가격 합계금액
public Cart() {
list = new ArrayList<ShopVO>();
}
public List<ShopVO> getList() { return list; }
public int getTotal() { return total; }
/**
* 장바구니 담기 요청 처리(카트에 제품 추가)
* list에 없으면 제품 추가
* list에 동일한 제품이 있으면 수량만 하나 증가 처리
* @param p_num
* @param dao
*/
public void addProduct(String p_num, ShopDAO dao) {
//카트에 제품이 있는지 확인
ShopVO vo = findProduct(p_num);
if (vo != null) { //카트에 있음 -> 수량 증가 처리
//1. 수량 증가 처리
vo.setQuant(vo.getQuant() + 1);
//2. 카트의 total 값 합산(제품 하나 가격 추가)
total += vo.getP_saleprice();
} else { //카트에 없음 -> 제품을 카트에 등록
//1. p_num 조회해서 VO객체 만들기
vo = dao.selectOne(p_num);
//2. 수량 1 증가 처리
vo.setQuant(1);
//3. 카트 목록에 추가
list.add(vo);
//4. total 값 계산(제품 하나 가격 추가)
total += vo.getP_saleprice();
}
}
//카트에 제품이 있는지 확인
public ShopVO findProduct(String p_num) {
ShopVO vo = null;
Iterator<ShopVO> ite = list.iterator();
while (ite.hasNext()) {
ShopVO listVO = ite.next();
if (listVO.getP_num().equals(p_num)) {
vo = listVO;
break;
}
}
//개선된 for문으로 작성(실습)
return vo;
}
//목록(list)에 있는 제품 삭제 처리
public void delProduct(String p_num) {
ShopVO vo = findProduct(p_num);
if (vo != null) {
list.remove(vo);
//카트의 전체 제품 가격에서 삭제된 제품금액 빼기
total = total - vo.getTotalprice();
}
}
//카트 목록(list) 제품의 수량 변경 처리
public void setQuant(String p_num, int su) {
ShopVO vo = findProduct(p_num);
if (vo == null) return;
//1. 카트 합계 금액 - 수량 변경전 제품 합계 금액
total = total - vo.getTotalprice();
//2. 제품의 수량 변경
vo.setQuant(su);
//3. 카트 합계 금액 + 수량 변경 후 제품 합계 금액
total = total + vo.getTotalprice();
}
}
| 2,414 | 0.596688 | 0.590278 | 90 | 19.799999 | 14.576388 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.1 | false | false |
10
|
44fa0bbef7213b9bd55e287406a6ea1b5172e36a
| 36,283,883,752,191 |
05d9c296b305352dba358ee1e917511b72947b23
|
/Project without pictures and sounds/Enemy.java
|
a02f2aff395ecf814f03cc2265045ede83f22936
|
[] |
no_license
|
NotBattleFrog/ZombieShooter
|
https://github.com/NotBattleFrog/ZombieShooter
|
79528cd9f1118c048aadeb695b7cc83ae8a13d30
|
7b00619384668717f4aaa1e24d060c9e14bae3fe
|
refs/heads/master
| 2020-05-23T23:36:45.765000 | 2017-03-18T07:19:36 | 2017-03-18T07:19:36 | 84,801,582 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Enemy here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Enemy extends Animation
{
/**
* Act - do whatever the Enemy wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
int hp;
int speed;
int time;
int cpic;
int no;
static double dd;
public Enemy(int hp,int speed,double dd){
this.hp = hp;
this.speed = speed;
this.dd = dd;
time =60;
cpic=0;
no = 30;
}
public void act()
{
turnTowards(MyWorld.x.getX(),MyWorld.x.getY());
still();
anima();
time++;
}
public void still(){
if(no>=30){
move(speed);
}
no++;
}
public void hit(int damage){
hp = hp - damage;
if(hp<=0){
if(Math.random()<dd){
getWorld().addObject(new SupplyCrate(),getX(),getY());
}
getWorld().addObject(new Dead(getRotation()),getX(),getY());
MyWorld.score+=100;
getWorld().removeObject(this);
MyWorld.money+=MyWorld.drop;
}
}
public void anima(){
cpic = (cpic+1)%pic.length;
setImage(pic[cpic]);
}
}
|
UTF-8
|
Java
| 1,467 |
java
|
Enemy.java
|
Java
|
[] | null |
[] |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Enemy here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Enemy extends Animation
{
/**
* Act - do whatever the Enemy wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
int hp;
int speed;
int time;
int cpic;
int no;
static double dd;
public Enemy(int hp,int speed,double dd){
this.hp = hp;
this.speed = speed;
this.dd = dd;
time =60;
cpic=0;
no = 30;
}
public void act()
{
turnTowards(MyWorld.x.getX(),MyWorld.x.getY());
still();
anima();
time++;
}
public void still(){
if(no>=30){
move(speed);
}
no++;
}
public void hit(int damage){
hp = hp - damage;
if(hp<=0){
if(Math.random()<dd){
getWorld().addObject(new SupplyCrate(),getX(),getY());
}
getWorld().addObject(new Dead(getRotation()),getX(),getY());
MyWorld.score+=100;
getWorld().removeObject(this);
MyWorld.money+=MyWorld.drop;
}
}
public void anima(){
cpic = (cpic+1)%pic.length;
setImage(pic[cpic]);
}
}
| 1,467 | 0.495569 | 0.487389 | 63 | 21.285715 | 19.892113 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.587302 | false | false |
10
|
c77f4e9faf6f74e4a1577589aa811df9b41e0089
| 26,809,185,929,844 |
013fe5939361ebb0e860b04ac6818b591f3b2cc9
|
/Lab13-Pattern/src/Server.java
|
19d86f1ad670ab773d46b304c2d749f7aea95f8a
|
[] |
no_license
|
Agnescao/SoftwareDesignLab-Java-
|
https://github.com/Agnescao/SoftwareDesignLab-Java-
|
96304d52daf69db4b1423ec135a10eea8ae74ac9
|
b255c9d2ad0d60edbc33ae874e433f93157b5b85
|
refs/heads/master
| 2021-01-22T23:21:18.282000 | 2017-09-10T09:37:00 | 2017-09-10T09:37:00 | 85,629,745 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Server
{ private String ipnumber="172.16.254.4";
private String name="Gamma";
private String location="Athlone";
private int sequence=0;
private static int count=0;
private static Server single;
private static boolean created = false;
public Server()
{
single=this; created=true;
count++;
sequence=count;
}
public static Server getInstance(){
if (!created){
single=new Server();
}
return single;
}
public String readNumber(){return ipnumber;}
public void print_details()
{
System.out.println("Name:= " + name);
System.out.println("ipNumber:= " + ipnumber);
System.out.println ("Location:= " + location);
System.out.println ("Sequence:= "+sequence);
System.out.println ();
}
}
|
UTF-8
|
Java
| 884 |
java
|
Server.java
|
Java
|
[
{
"context": "class Server \n{ private String ipnumber=\"172.16.254.4\";\n private String name=\"Gamma\";\n ",
"end": 59,
"score": 0.9997758269309998,
"start": 47,
"tag": "IP_ADDRESS",
"value": "172.16.254.4"
},
{
"context": "ber=\"172.16.254.4\";\n private String name=\"Gamma\";\n private String location=\"Athlone\";\n ",
"end": 97,
"score": 0.9285765290260315,
"start": 92,
"tag": "NAME",
"value": "Gamma"
}
] | null |
[] |
class Server
{ private String ipnumber="172.16.254.4";
private String name="Gamma";
private String location="Athlone";
private int sequence=0;
private static int count=0;
private static Server single;
private static boolean created = false;
public Server()
{
single=this; created=true;
count++;
sequence=count;
}
public static Server getInstance(){
if (!created){
single=new Server();
}
return single;
}
public String readNumber(){return ipnumber;}
public void print_details()
{
System.out.println("Name:= " + name);
System.out.println("ipNumber:= " + ipnumber);
System.out.println ("Location:= " + location);
System.out.println ("Sequence:= "+sequence);
System.out.println ();
}
}
| 884 | 0.56448 | 0.552036 | 33 | 25.757576 | 17.271505 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false |
10
|
c904b81e2698dea50fbf53c703e5e676f1141532
| 30,382,598,715,806 |
8bca26d4803850c870e600e13ddb903860affa48
|
/src/test/java/materialsdbsvc/ServicesTest.java
|
a629a6fd4a23c66060eb34469598bb78f1bf8a44
|
[
"MIT"
] |
permissive
|
PhystechCo/CentralDBServices
|
https://github.com/PhystechCo/CentralDBServices
|
27d41bb3f1b824d6ae147b07e6188a16be8d2596
|
c99568b0c8893c20d5748d416d26df2de18f7a23
|
refs/heads/master
| 2020-04-01T05:04:36.448000 | 2019-01-30T22:01:41 | 2019-01-30T22:01:41 | 152,889,302 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
*
*/
package materialsdbsvc;
import static org.junit.Assert.*;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Supplier;
import org.apache.commons.math3.exception.MathParseException;
import org.junit.Test;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonReader;
import co.phystech.aosorio.config.Constants;
import co.phystech.aosorio.controllers.ExtQuotedMaterialsController;
import co.phystech.aosorio.controllers.FittingsController;
import co.phystech.aosorio.controllers.NoSqlController;
import co.phystech.aosorio.models.ExtQuotedMaterials;
import co.phystech.aosorio.models.Fittings;
import co.phystech.aosorio.models.Materials;
import co.phystech.aosorio.models.QuotedMaterials;
import co.phystech.aosorio.services.Formula;
import co.phystech.aosorio.services.FormulaFactory;
import co.phystech.aosorio.services.GeneralSvc;
import co.phystech.aosorio.services.OpenExchangeSvc;
import co.phystech.aosorio.services.StatisticsSvc;
import co.phystech.aosorio.services.Utilities;
import spark.Request;
import spark.Response;
/**
* @author AOSORIO
*
*/
public class ServicesTest {
public class Densities {
String type;
double density;
}
private final static Logger slf4jLogger = LoggerFactory.getLogger(ServicesTest.class);
private static Datastore datastore;
@Test
public void materialsCounterTest() {
// Test the book counter service
Request pRequest = null;
Response pResponse = null;
JsonObject json = (JsonObject) StatisticsSvc.getBasicStats(pRequest, pResponse);
slf4jLogger.info("Number of materials: " + json.get("materials"));
assertTrue(json.has("materials"));
}
@Test
public void readJsonFromUrlTest() {
try {
JsonObject json = GeneralSvc.readJsonFromUrl("https://httpbin.org/get");
if (json.isJsonObject()) {
slf4jLogger.debug(json.toString());
if (json.has("origin"))
slf4jLogger.debug(json.get("origin").toString());
} else {
slf4jLogger.debug("null object");
}
} catch (JsonParseException | IOException e) {
slf4jLogger.debug("IOException");
}
assertTrue(true);
}
@Test
public void openExchangeTest() {
double usdTRM = OpenExchangeSvc.getUSDTRM();
slf4jLogger.debug(String.valueOf(usdTRM));
assertTrue(true);
}
@Test
public void formulasTest() {
Supplier<FormulaFactory> formulaFactory = FormulaFactory::new;
Formula formula = formulaFactory.get().getFormula("CYLINDERVOL");
slf4jLogger.debug(formula.getName());
formula.addVariable("OD", 8.0);
formula.addVariable("ID", 4.0);
formula.addVariable("H", 10.0);
double vol1 = formula.eval();
assertEquals(376.991, vol1, 0.01);
formula.addVariable("OD", 8.0);
formula.addVariable("H", 10.0);
double vol2 = formula.eval();
assertEquals(502.654, vol2, 0.01);
}
@Test
public void weightCalculationTest() {
QuotedMaterials material = new QuotedMaterials();
material.setDescription("PIPE,SS316L, 1\", STANDARD,SMLS,SA312,SCH40");
material.setDimensions("1\",SCH40");
material.setCategory("PIPE");
material.setType("SS");
material.setQuantity(108);
Supplier<FormulaFactory> formulaFactory = FormulaFactory::new;
Formula formula = formulaFactory.get().getFormula("CYLINDERVOL");
slf4jLogger.debug(formula.getName());
double outerDiam = Utilities.getODMM(material) / 1000.0;
double innerDiam = Utilities.getIDMM(material) / 1000.0;
String info = material.getDimensions() + "\t" + String.valueOf(outerDiam) + "\t" + String.valueOf(innerDiam);
slf4jLogger.debug(info);
formula.addVariable("OD", outerDiam);
formula.addVariable("ID", innerDiam);
formula.addVariable("H", material.getQuantity());
double density = 8.0 * 1000.0; // kg/m3
double volume = formula.eval();
double weight = volume * density;
slf4jLogger.debug(String.valueOf(weight));
assertEquals(275.417, weight, 0.001);
}
@Test
public void theoreticalWeightsTest() {
List<ExtQuotedMaterials> pipes = ExtQuotedMaterialsController.readBy("category", "PIPE");
Iterator<ExtQuotedMaterials> itrPipes = pipes.iterator();
while (itrPipes.hasNext()) {
ExtQuotedMaterials material = itrPipes.next();
double weight = GeneralSvc.calculateMaterialWeight(material);
String info = "* " + material.getItemcode() + "\t" + material.getDimensions() + "\t" + material.getType()
+ "\t" + String.format("%.2f", weight) + "\t" + String.valueOf(material.getGivenWeight());
slf4jLogger.debug(info);
}
}
@Test
public void scheduleFinderTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("PIPE").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
double outerDiam = Utilities.getODMM(material);
double innerDiam = Utilities.getIDMM(material);
String info = material.getDimensions() + "\t" + String.format("%.2f", outerDiam) + "\t"
+ String.format("%.2f", innerDiam);
slf4jLogger.debug(info);
}
assertTrue(true);
}
@Test
public void getDensitiesTest() {
ArrayList<String> types = new ArrayList<String>();
types.add("SS");
types.add("HASTELLOY");
types.add("CS");
try {
JsonReader jsonReader = new JsonReader(
new FileReader(ClassLoader.getSystemResource(Constants.CONFIG_DENSITIES_FILE).getPath()));
jsonReader.beginArray();
Gson gson = new Gson();
int idx = 0;
while (jsonReader.hasNext()) {
Densities item = gson.fromJson(jsonReader, Densities.class);
assertEquals(types.get(idx), item.type);
idx += 1;
if (idx == types.size())
break;
}
jsonReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void getDensityTest() {
slf4jLogger.info(String.valueOf(Utilities.getDensity("SS")));
assertEquals(8.00, Utilities.getDensity("SS"), 0.001);
assertEquals(8.94, Utilities.getDensity("HASTELLOY"), 0.001);
assertEquals(7.85, Utilities.getDensity("CS"), 0.001);
}
@Test
public void parsingDimensionTest() {
double x1 = Utilities.parseDimension("1/2\"");
assertEquals(0.5 * Constants.UNIT_INCH_to_MM, x1, 0.1);
double x2 = Utilities.parseDimension("12\"");
assertEquals(12.0 * Constants.UNIT_INCH_to_MM, x2, 0.1);
double x3 = Utilities.parseDimension("7/8\"");
assertEquals(0.875 * Constants.UNIT_INCH_to_MM, x3, 0.1);
}
@Test
public void barVolumeTest() {
QuotedMaterials material = new QuotedMaterials();
material.setDescription("BAR,ROUND,MEDIUM CS 10MM,1/2\",AISI C1045");
material.setDimensions("MEDIUM CS 10MM,1/2\"");
material.setCategory("BAR");
material.setType("SS");
material.setQuantity(100);
double diameter = Utilities.getBarODMM(material);
assertEquals(0.5 * Constants.UNIT_INCH_to_MM, diameter, 0.01);
double volume = GeneralSvc.calculateMaterialWeight(material);
assertEquals(101.341, volume, 0.001);
}
@Test
public void hollowBarVolumeTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("description").contains("HOLLOW").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setCategory(material.getCategory());
quoted.setType(material.getType());
quoted.setQuantity(100.0);
slf4jLogger.debug("*HOLLOW*: " + material.getDimensions());
try {
ArrayList<Double> dims = Utilities.getHollowBarDimsMM(material);
slf4jLogger.debug("*X= " + quoted.getType() + "\t" + String.valueOf(dims.get(0)) + "\t"
+ String.valueOf(dims.get(1)) + "\t"
+ String.valueOf(GeneralSvc.calculateMaterialWeight(quoted)));
} catch ( MathParseException ex) {
slf4jLogger.info(" PARSE ERROR AT HOLLOW*: " + material.getItemcode());
}
}
}
@Test
public void platesVolumeTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").contains("PLATE").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setCategory(material.getCategory());
quoted.setType(material.getType());
quoted.setQuantity(100.0);
quoted.setUnit("M2");
try {
if( !material.getDimensions().contains("MM"))
continue;
ArrayList<Double> dims = Utilities.getPlateDimsMM(material);
double weight = GeneralSvc.calculateMaterialWeight(quoted);
slf4jLogger.debug("*PLATE*: " + material.getDimensions());
slf4jLogger.debug("*PLATE*: " + quoted.getType() + "\t" + String.valueOf(dims.get(0)) + "\t"
+ String.valueOf(dims.get(1)) + "\t" + String.valueOf(dims.get(2)) + "\t"
+ String.valueOf(weight));
} catch (MathParseException ex) {
slf4jLogger.info(" PARSE ERROR at PLATE: " + material.getItemcode());
} catch ( Exception ex) {
slf4jLogger.info(ex.getMessage());
slf4jLogger.info(" ERROR at: " + material.getItemcode());
}
}
}
@Test
public void channelVolumeTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("BEAM").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setCategory(material.getCategory());
quoted.setType(material.getType());
quoted.setQuantity(100.0);
ArrayList<Double> dims = null;
try {
dims = Utilities.getBeamDimsINCH(material);
} catch (NullPointerException ex) {
dims = Utilities.getBeamDimsMM(material);
}
double weight = GeneralSvc.calculateMaterialWeight(quoted);
slf4jLogger.debug("*CHANNEL*: " + material.getDimensions());
slf4jLogger.debug("*CHANNEL*: " + quoted.getType() + "\t" + String.format("%.2f", dims.get(0)) + "\t"
+ String.format("%.2f", dims.get(1)) + "\t" + String.format("%.2f", dims.get(2)) + "\t"
+ String.format("%.2f", weight));
}
}
@Test
public void angleVolumeTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("ANGLE").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setCategory(material.getCategory());
quoted.setType(material.getType());
quoted.setQuantity(100.0);
ArrayList<Double> dims = null;
try {
dims = Utilities.getBeamDimsINCH(material);
} catch (NullPointerException ex) {
dims = Utilities.getBeamDimsMM(material);
}
double weight = GeneralSvc.calculateMaterialWeight(quoted);
slf4jLogger.debug("*ANGLE*: " + material.getDimensions());
slf4jLogger.debug("*ANGLE*: " + quoted.getType() + "\t" + String.format("%.2f", dims.get(0)) + "\t"
+ String.format("%.2f", dims.get(1)) + "\t" + String.format("%.2f", dims.get(2)) + "\t"
+ String.format("%.2f", weight));
}
}
@Test
public void platesVolumeCalculationTest() {
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription("PLATE, SS316L, 4' X 8' X 1/32\", 1219.2MM X 2438.4MM X 0.79MM");
quoted.setDimensions("4' X 8' X 1/32\", 1219.2MM X 2438.4MM X 0.79MM");
quoted.setCategory("PLATE");
quoted.setType("SS");
quoted.setQuantity(11.88);
quoted.setUnit("M2");
ArrayList<Double> dims = Utilities.getPlateDimsMM(quoted);
double weight = GeneralSvc.calculateMaterialWeight(quoted);
slf4jLogger.info("*PLATE*: " + quoted.getDimensions());
slf4jLogger.info("*PLATE*: " + quoted.getType() + "\t" + String.valueOf(dims.get(0)) + "\t"
+ String.valueOf(dims.get(1)) + "\t" + String.valueOf(dims.get(2)) + "\t" + String.valueOf(weight));
}
@Test
public void elbowParsingTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("ELBOW").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
for (String elbow : Constants.FITTING_ELBOWS) {
boolean xcheck = Utilities.checkFittingCategory(elbow, material.getDescription(), 3);
if (xcheck) {
slf4jLogger.debug("*ELBOW*: " + material.getDescription());
slf4jLogger.debug("*ELBOW*: " + elbow);
}
}
}
}
@Test
public void elbowWeightTest() {
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription("ELBOW, 90º, CS,6\", SCH40,BW,LR,SMLS, ASTM A234 GR WPB");
quoted.setDimensions("6\", SCH40");
String clean_dsc = quoted.getDescription().replaceAll("[^a-zA-Z0-9\",]", "");
slf4jLogger.info("*ELBOW*: " + clean_dsc);
for (String category : Constants.FITTING_ELBOWS) {
boolean xcheck = Utilities.checkFittingCategory(category, quoted.getDescription(), 3);
if (xcheck) {
String schedule = Utilities.getPipeSchedule(quoted);
String pipeSize = Utilities.getDimensionINCH(quoted).get(0);
Fittings fitting = FittingsController.read(category, schedule, pipeSize);
double weight = fitting.getWeight();
slf4jLogger.debug("*ELBOW*: " + quoted.getDescription());
slf4jLogger.debug("*ELBOW*: " + schedule);
slf4jLogger.debug("*ELBOW*: " + Utilities.getDimensionINCH(quoted));
slf4jLogger.debug("*ELBOW*: " + String.valueOf(weight));
}
}
}
@Test
public void allElbowsWeightTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("ELBOW").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setItemcode(material.getItemcode());
quoted.setCategory(material.getCategory());
quoted.setQuantity(10.0);
double weight = Utilities.getFittingWeight(quoted, Constants.FITTING_ELBOWS, 3);
double weight_total = GeneralSvc.calculateMaterialWeight(quoted);
if (weight > 0.0) {
slf4jLogger.debug("*ELBOW*: " + quoted.getDescription());
slf4jLogger.debug("*ELBOW*: " + quoted.getItemcode());
slf4jLogger.debug("*ELBOW*: " + Utilities.getPipeSchedule(quoted));
slf4jLogger.debug("*ELBOW*: " + Utilities.getDimensionINCH(quoted));
slf4jLogger.debug("*ELBOW*: " + String.valueOf(weight));
slf4jLogger.debug("*ELBOW*: " + String.valueOf(weight_total));
}
}
}
@Test
public void hastelloyTubeTest() {
Supplier<FormulaFactory> formulaFactory = FormulaFactory::new;
Formula formula = formulaFactory.get().getFormula("CYLINDERVOL");
double wt = 0.035;
double od = 0.5;
double id = 0.5 - (2.0 * wt);
formula.addVariable("OD", od * Constants.UNIT_INCH_to_MM * Constants.UNIT_MM_to_M);
formula.addVariable("ID", id * Constants.UNIT_INCH_to_MM * Constants.UNIT_MM_to_M);
formula.addVariable("H", 16.459);
double volume = formula.eval();
double density = Utilities.getDensity("HASTELLOY") * Constants.UNIT_KG_o_M3;
double weight = volume * density;
slf4jLogger.info("Tubing Hastelloy volume: " + String.valueOf(volume));
slf4jLogger.info("Tubing Hastelloy weight: " + String.valueOf(weight));
assertEquals(4.85377, weight, 0.001);
Materials material = new Materials();
material.setDimensions("16\",SCH40");
formula.addVariable("OD", Utilities.getODMM(material) * Constants.UNIT_MM_to_M);
formula.addVariable("ID", Utilities.getIDMM(material) * Constants.UNIT_MM_to_M);
formula.addVariable("H", 24.00);
volume = formula.eval();
density = Utilities.getDensity("TITANIUM") * Constants.UNIT_KG_o_M3;
weight = volume * density;
slf4jLogger.info("Tubing Titanium volume: " + String.valueOf(volume));
slf4jLogger.info("Tubing Titanium weight: " + String.valueOf(weight));
assertEquals(1696.45, weight, 0.01);
formula.addVariable("OD", 80.0 * Constants.UNIT_MM_to_M);
formula.addVariable("H", 2.00);
volume = formula.eval();
density = Utilities.getDensity("TITANIUM") * Constants.UNIT_KG_o_M3;
weight = volume * density;
slf4jLogger.info("BAR Titanium volume: " + String.valueOf(volume));
slf4jLogger.info("BAR Titanium weight: " + String.valueOf(weight));
assertEquals(45.30, weight, 0.1);
}
}
|
UTF-8
|
Java
| 17,642 |
java
|
ServicesTest.java
|
Java
|
[
{
"context": "rk.Request;\nimport spark.Response;\n\n/**\n * @author AOSORIO\n *\n */\npublic class ServicesTest {\n\n\tpublic class",
"end": 1400,
"score": 0.9995233416557312,
"start": 1393,
"tag": "USERNAME",
"value": "AOSORIO"
}
] | null |
[] |
/**
*
*/
package materialsdbsvc;
import static org.junit.Assert.*;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Supplier;
import org.apache.commons.math3.exception.MathParseException;
import org.junit.Test;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonReader;
import co.phystech.aosorio.config.Constants;
import co.phystech.aosorio.controllers.ExtQuotedMaterialsController;
import co.phystech.aosorio.controllers.FittingsController;
import co.phystech.aosorio.controllers.NoSqlController;
import co.phystech.aosorio.models.ExtQuotedMaterials;
import co.phystech.aosorio.models.Fittings;
import co.phystech.aosorio.models.Materials;
import co.phystech.aosorio.models.QuotedMaterials;
import co.phystech.aosorio.services.Formula;
import co.phystech.aosorio.services.FormulaFactory;
import co.phystech.aosorio.services.GeneralSvc;
import co.phystech.aosorio.services.OpenExchangeSvc;
import co.phystech.aosorio.services.StatisticsSvc;
import co.phystech.aosorio.services.Utilities;
import spark.Request;
import spark.Response;
/**
* @author AOSORIO
*
*/
public class ServicesTest {
public class Densities {
String type;
double density;
}
private final static Logger slf4jLogger = LoggerFactory.getLogger(ServicesTest.class);
private static Datastore datastore;
@Test
public void materialsCounterTest() {
// Test the book counter service
Request pRequest = null;
Response pResponse = null;
JsonObject json = (JsonObject) StatisticsSvc.getBasicStats(pRequest, pResponse);
slf4jLogger.info("Number of materials: " + json.get("materials"));
assertTrue(json.has("materials"));
}
@Test
public void readJsonFromUrlTest() {
try {
JsonObject json = GeneralSvc.readJsonFromUrl("https://httpbin.org/get");
if (json.isJsonObject()) {
slf4jLogger.debug(json.toString());
if (json.has("origin"))
slf4jLogger.debug(json.get("origin").toString());
} else {
slf4jLogger.debug("null object");
}
} catch (JsonParseException | IOException e) {
slf4jLogger.debug("IOException");
}
assertTrue(true);
}
@Test
public void openExchangeTest() {
double usdTRM = OpenExchangeSvc.getUSDTRM();
slf4jLogger.debug(String.valueOf(usdTRM));
assertTrue(true);
}
@Test
public void formulasTest() {
Supplier<FormulaFactory> formulaFactory = FormulaFactory::new;
Formula formula = formulaFactory.get().getFormula("CYLINDERVOL");
slf4jLogger.debug(formula.getName());
formula.addVariable("OD", 8.0);
formula.addVariable("ID", 4.0);
formula.addVariable("H", 10.0);
double vol1 = formula.eval();
assertEquals(376.991, vol1, 0.01);
formula.addVariable("OD", 8.0);
formula.addVariable("H", 10.0);
double vol2 = formula.eval();
assertEquals(502.654, vol2, 0.01);
}
@Test
public void weightCalculationTest() {
QuotedMaterials material = new QuotedMaterials();
material.setDescription("PIPE,SS316L, 1\", STANDARD,SMLS,SA312,SCH40");
material.setDimensions("1\",SCH40");
material.setCategory("PIPE");
material.setType("SS");
material.setQuantity(108);
Supplier<FormulaFactory> formulaFactory = FormulaFactory::new;
Formula formula = formulaFactory.get().getFormula("CYLINDERVOL");
slf4jLogger.debug(formula.getName());
double outerDiam = Utilities.getODMM(material) / 1000.0;
double innerDiam = Utilities.getIDMM(material) / 1000.0;
String info = material.getDimensions() + "\t" + String.valueOf(outerDiam) + "\t" + String.valueOf(innerDiam);
slf4jLogger.debug(info);
formula.addVariable("OD", outerDiam);
formula.addVariable("ID", innerDiam);
formula.addVariable("H", material.getQuantity());
double density = 8.0 * 1000.0; // kg/m3
double volume = formula.eval();
double weight = volume * density;
slf4jLogger.debug(String.valueOf(weight));
assertEquals(275.417, weight, 0.001);
}
@Test
public void theoreticalWeightsTest() {
List<ExtQuotedMaterials> pipes = ExtQuotedMaterialsController.readBy("category", "PIPE");
Iterator<ExtQuotedMaterials> itrPipes = pipes.iterator();
while (itrPipes.hasNext()) {
ExtQuotedMaterials material = itrPipes.next();
double weight = GeneralSvc.calculateMaterialWeight(material);
String info = "* " + material.getItemcode() + "\t" + material.getDimensions() + "\t" + material.getType()
+ "\t" + String.format("%.2f", weight) + "\t" + String.valueOf(material.getGivenWeight());
slf4jLogger.debug(info);
}
}
@Test
public void scheduleFinderTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("PIPE").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
double outerDiam = Utilities.getODMM(material);
double innerDiam = Utilities.getIDMM(material);
String info = material.getDimensions() + "\t" + String.format("%.2f", outerDiam) + "\t"
+ String.format("%.2f", innerDiam);
slf4jLogger.debug(info);
}
assertTrue(true);
}
@Test
public void getDensitiesTest() {
ArrayList<String> types = new ArrayList<String>();
types.add("SS");
types.add("HASTELLOY");
types.add("CS");
try {
JsonReader jsonReader = new JsonReader(
new FileReader(ClassLoader.getSystemResource(Constants.CONFIG_DENSITIES_FILE).getPath()));
jsonReader.beginArray();
Gson gson = new Gson();
int idx = 0;
while (jsonReader.hasNext()) {
Densities item = gson.fromJson(jsonReader, Densities.class);
assertEquals(types.get(idx), item.type);
idx += 1;
if (idx == types.size())
break;
}
jsonReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void getDensityTest() {
slf4jLogger.info(String.valueOf(Utilities.getDensity("SS")));
assertEquals(8.00, Utilities.getDensity("SS"), 0.001);
assertEquals(8.94, Utilities.getDensity("HASTELLOY"), 0.001);
assertEquals(7.85, Utilities.getDensity("CS"), 0.001);
}
@Test
public void parsingDimensionTest() {
double x1 = Utilities.parseDimension("1/2\"");
assertEquals(0.5 * Constants.UNIT_INCH_to_MM, x1, 0.1);
double x2 = Utilities.parseDimension("12\"");
assertEquals(12.0 * Constants.UNIT_INCH_to_MM, x2, 0.1);
double x3 = Utilities.parseDimension("7/8\"");
assertEquals(0.875 * Constants.UNIT_INCH_to_MM, x3, 0.1);
}
@Test
public void barVolumeTest() {
QuotedMaterials material = new QuotedMaterials();
material.setDescription("BAR,ROUND,MEDIUM CS 10MM,1/2\",AISI C1045");
material.setDimensions("MEDIUM CS 10MM,1/2\"");
material.setCategory("BAR");
material.setType("SS");
material.setQuantity(100);
double diameter = Utilities.getBarODMM(material);
assertEquals(0.5 * Constants.UNIT_INCH_to_MM, diameter, 0.01);
double volume = GeneralSvc.calculateMaterialWeight(material);
assertEquals(101.341, volume, 0.001);
}
@Test
public void hollowBarVolumeTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("description").contains("HOLLOW").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setCategory(material.getCategory());
quoted.setType(material.getType());
quoted.setQuantity(100.0);
slf4jLogger.debug("*HOLLOW*: " + material.getDimensions());
try {
ArrayList<Double> dims = Utilities.getHollowBarDimsMM(material);
slf4jLogger.debug("*X= " + quoted.getType() + "\t" + String.valueOf(dims.get(0)) + "\t"
+ String.valueOf(dims.get(1)) + "\t"
+ String.valueOf(GeneralSvc.calculateMaterialWeight(quoted)));
} catch ( MathParseException ex) {
slf4jLogger.info(" PARSE ERROR AT HOLLOW*: " + material.getItemcode());
}
}
}
@Test
public void platesVolumeTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").contains("PLATE").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setCategory(material.getCategory());
quoted.setType(material.getType());
quoted.setQuantity(100.0);
quoted.setUnit("M2");
try {
if( !material.getDimensions().contains("MM"))
continue;
ArrayList<Double> dims = Utilities.getPlateDimsMM(material);
double weight = GeneralSvc.calculateMaterialWeight(quoted);
slf4jLogger.debug("*PLATE*: " + material.getDimensions());
slf4jLogger.debug("*PLATE*: " + quoted.getType() + "\t" + String.valueOf(dims.get(0)) + "\t"
+ String.valueOf(dims.get(1)) + "\t" + String.valueOf(dims.get(2)) + "\t"
+ String.valueOf(weight));
} catch (MathParseException ex) {
slf4jLogger.info(" PARSE ERROR at PLATE: " + material.getItemcode());
} catch ( Exception ex) {
slf4jLogger.info(ex.getMessage());
slf4jLogger.info(" ERROR at: " + material.getItemcode());
}
}
}
@Test
public void channelVolumeTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("BEAM").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setCategory(material.getCategory());
quoted.setType(material.getType());
quoted.setQuantity(100.0);
ArrayList<Double> dims = null;
try {
dims = Utilities.getBeamDimsINCH(material);
} catch (NullPointerException ex) {
dims = Utilities.getBeamDimsMM(material);
}
double weight = GeneralSvc.calculateMaterialWeight(quoted);
slf4jLogger.debug("*CHANNEL*: " + material.getDimensions());
slf4jLogger.debug("*CHANNEL*: " + quoted.getType() + "\t" + String.format("%.2f", dims.get(0)) + "\t"
+ String.format("%.2f", dims.get(1)) + "\t" + String.format("%.2f", dims.get(2)) + "\t"
+ String.format("%.2f", weight));
}
}
@Test
public void angleVolumeTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("ANGLE").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setCategory(material.getCategory());
quoted.setType(material.getType());
quoted.setQuantity(100.0);
ArrayList<Double> dims = null;
try {
dims = Utilities.getBeamDimsINCH(material);
} catch (NullPointerException ex) {
dims = Utilities.getBeamDimsMM(material);
}
double weight = GeneralSvc.calculateMaterialWeight(quoted);
slf4jLogger.debug("*ANGLE*: " + material.getDimensions());
slf4jLogger.debug("*ANGLE*: " + quoted.getType() + "\t" + String.format("%.2f", dims.get(0)) + "\t"
+ String.format("%.2f", dims.get(1)) + "\t" + String.format("%.2f", dims.get(2)) + "\t"
+ String.format("%.2f", weight));
}
}
@Test
public void platesVolumeCalculationTest() {
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription("PLATE, SS316L, 4' X 8' X 1/32\", 1219.2MM X 2438.4MM X 0.79MM");
quoted.setDimensions("4' X 8' X 1/32\", 1219.2MM X 2438.4MM X 0.79MM");
quoted.setCategory("PLATE");
quoted.setType("SS");
quoted.setQuantity(11.88);
quoted.setUnit("M2");
ArrayList<Double> dims = Utilities.getPlateDimsMM(quoted);
double weight = GeneralSvc.calculateMaterialWeight(quoted);
slf4jLogger.info("*PLATE*: " + quoted.getDimensions());
slf4jLogger.info("*PLATE*: " + quoted.getType() + "\t" + String.valueOf(dims.get(0)) + "\t"
+ String.valueOf(dims.get(1)) + "\t" + String.valueOf(dims.get(2)) + "\t" + String.valueOf(weight));
}
@Test
public void elbowParsingTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("ELBOW").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
for (String elbow : Constants.FITTING_ELBOWS) {
boolean xcheck = Utilities.checkFittingCategory(elbow, material.getDescription(), 3);
if (xcheck) {
slf4jLogger.debug("*ELBOW*: " + material.getDescription());
slf4jLogger.debug("*ELBOW*: " + elbow);
}
}
}
}
@Test
public void elbowWeightTest() {
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription("ELBOW, 90º, CS,6\", SCH40,BW,LR,SMLS, ASTM A234 GR WPB");
quoted.setDimensions("6\", SCH40");
String clean_dsc = quoted.getDescription().replaceAll("[^a-zA-Z0-9\",]", "");
slf4jLogger.info("*ELBOW*: " + clean_dsc);
for (String category : Constants.FITTING_ELBOWS) {
boolean xcheck = Utilities.checkFittingCategory(category, quoted.getDescription(), 3);
if (xcheck) {
String schedule = Utilities.getPipeSchedule(quoted);
String pipeSize = Utilities.getDimensionINCH(quoted).get(0);
Fittings fitting = FittingsController.read(category, schedule, pipeSize);
double weight = fitting.getWeight();
slf4jLogger.debug("*ELBOW*: " + quoted.getDescription());
slf4jLogger.debug("*ELBOW*: " + schedule);
slf4jLogger.debug("*ELBOW*: " + Utilities.getDimensionINCH(quoted));
slf4jLogger.debug("*ELBOW*: " + String.valueOf(weight));
}
}
}
@Test
public void allElbowsWeightTest() {
datastore = NoSqlController.getInstance().getDatabase();
Query<Materials> query = datastore.createQuery(Materials.class);
List<Materials> result = query.field("category").equal("ELBOW").asList();
Iterator<Materials> itr = result.iterator();
while (itr.hasNext()) {
Materials material = itr.next();
QuotedMaterials quoted = new QuotedMaterials();
quoted.setDescription(material.getDescription());
quoted.setDimensions(material.getDimensions());
quoted.setItemcode(material.getItemcode());
quoted.setCategory(material.getCategory());
quoted.setQuantity(10.0);
double weight = Utilities.getFittingWeight(quoted, Constants.FITTING_ELBOWS, 3);
double weight_total = GeneralSvc.calculateMaterialWeight(quoted);
if (weight > 0.0) {
slf4jLogger.debug("*ELBOW*: " + quoted.getDescription());
slf4jLogger.debug("*ELBOW*: " + quoted.getItemcode());
slf4jLogger.debug("*ELBOW*: " + Utilities.getPipeSchedule(quoted));
slf4jLogger.debug("*ELBOW*: " + Utilities.getDimensionINCH(quoted));
slf4jLogger.debug("*ELBOW*: " + String.valueOf(weight));
slf4jLogger.debug("*ELBOW*: " + String.valueOf(weight_total));
}
}
}
@Test
public void hastelloyTubeTest() {
Supplier<FormulaFactory> formulaFactory = FormulaFactory::new;
Formula formula = formulaFactory.get().getFormula("CYLINDERVOL");
double wt = 0.035;
double od = 0.5;
double id = 0.5 - (2.0 * wt);
formula.addVariable("OD", od * Constants.UNIT_INCH_to_MM * Constants.UNIT_MM_to_M);
formula.addVariable("ID", id * Constants.UNIT_INCH_to_MM * Constants.UNIT_MM_to_M);
formula.addVariable("H", 16.459);
double volume = formula.eval();
double density = Utilities.getDensity("HASTELLOY") * Constants.UNIT_KG_o_M3;
double weight = volume * density;
slf4jLogger.info("Tubing Hastelloy volume: " + String.valueOf(volume));
slf4jLogger.info("Tubing Hastelloy weight: " + String.valueOf(weight));
assertEquals(4.85377, weight, 0.001);
Materials material = new Materials();
material.setDimensions("16\",SCH40");
formula.addVariable("OD", Utilities.getODMM(material) * Constants.UNIT_MM_to_M);
formula.addVariable("ID", Utilities.getIDMM(material) * Constants.UNIT_MM_to_M);
formula.addVariable("H", 24.00);
volume = formula.eval();
density = Utilities.getDensity("TITANIUM") * Constants.UNIT_KG_o_M3;
weight = volume * density;
slf4jLogger.info("Tubing Titanium volume: " + String.valueOf(volume));
slf4jLogger.info("Tubing Titanium weight: " + String.valueOf(weight));
assertEquals(1696.45, weight, 0.01);
formula.addVariable("OD", 80.0 * Constants.UNIT_MM_to_M);
formula.addVariable("H", 2.00);
volume = formula.eval();
density = Utilities.getDensity("TITANIUM") * Constants.UNIT_KG_o_M3;
weight = volume * density;
slf4jLogger.info("BAR Titanium volume: " + String.valueOf(volume));
slf4jLogger.info("BAR Titanium weight: " + String.valueOf(weight));
assertEquals(45.30, weight, 0.1);
}
}
| 17,642 | 0.700641 | 0.679553 | 639 | 26.607199 | 27.537495 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.067293 | false | false |
10
|
ba1c30670f8d4a014049f6155d1c611cb0deb88e
| 38,053,410,264,910 |
2c7a1217c41f96b7222434947393721ce9ec8954
|
/src/hemebiotech/Class3.java
|
d3b15db7c95b7a3d28c430f4598b9db9154647f2
|
[] |
no_license
|
LaetitiDamen/hemeBiotech
|
https://github.com/LaetitiDamen/hemeBiotech
|
b26210cfdb2fde0578b9590efa8a8e9778883442
|
5d61d88831d888a9a3347e30f197f587e47ee4ba
|
refs/heads/master
| 2022-12-28T16:50:41.418000 | 2020-10-17T12:15:17 | 2020-10-17T12:15:17 | 304,870,799 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package hemebiotech;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
/**
*
* @author Laetitia Damen
*
*/
public class Class3 {
/**
* Sort in natural order and write out as the file resuts.out.txt
*
* @param map = Object of class Map<String, Integer> with parameters (String)key = w (word list)
* and parameters values (Integer) = i (occurrences)
* @throws IOException = show up when an I/O Exception occurs
*/
static void docOut(Map<String, Integer> map) throws IOException {
Map<String, Integer> newmap = new TreeMap<String, Integer>(map); // Sort map in natural order in the TreeMap
File doc2 = new File(" results.out.txt"); // String variable containing the file path to generate
BufferedWriter writOut = null;
try {
writOut = new BufferedWriter(new FileWriter(doc2));
} catch (IOException e) {
e.printStackTrace();
}
for (Entry<String, Integer> entry : newmap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
writOut.write(key + " = " + value + System.getProperty("line.separator"));
}
System.out.println("New File Create: " + doc2);
System.out.println("File location: " + doc2.getAbsolutePath());
writOut.flush();
writOut.close();
}
}
|
UTF-8
|
Java
| 1,386 |
java
|
Class3.java
|
Java
|
[
{
"context": "try;\nimport java.util.TreeMap;\n\n/**\n * \n * @author Laetitia Damen\n *\n */\n\n\n\npublic class Class3 {\n\t\n\t/**\n\t * Sort i",
"end": 239,
"score": 0.9998791217803955,
"start": 225,
"tag": "NAME",
"value": "Laetitia Damen"
}
] | null |
[] |
package hemebiotech;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
/**
*
* @author <NAME>
*
*/
public class Class3 {
/**
* Sort in natural order and write out as the file resuts.out.txt
*
* @param map = Object of class Map<String, Integer> with parameters (String)key = w (word list)
* and parameters values (Integer) = i (occurrences)
* @throws IOException = show up when an I/O Exception occurs
*/
static void docOut(Map<String, Integer> map) throws IOException {
Map<String, Integer> newmap = new TreeMap<String, Integer>(map); // Sort map in natural order in the TreeMap
File doc2 = new File(" results.out.txt"); // String variable containing the file path to generate
BufferedWriter writOut = null;
try {
writOut = new BufferedWriter(new FileWriter(doc2));
} catch (IOException e) {
e.printStackTrace();
}
for (Entry<String, Integer> entry : newmap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
writOut.write(key + " = " + value + System.getProperty("line.separator"));
}
System.out.println("New File Create: " + doc2);
System.out.println("File location: " + doc2.getAbsolutePath());
writOut.flush();
writOut.close();
}
}
| 1,378 | 0.686147 | 0.68254 | 54 | 24.629629 | 28.872194 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false |
10
|
a0ade441297d3a1fb144732e6a1d58281dbb3a60
| 37,014,028,186,597 |
fdb24888800cebd5bd405e3b41282f836e19aed8
|
/qrlibrary/src/main/java/com/sunyy/qrcode/mylibrary/DecodeHandler.java
|
16c438ecf4c3662a295d08f9994c7749547be441
|
[] |
no_license
|
sunyangyang/QRCode
|
https://github.com/sunyangyang/QRCode
|
0bddb60317adeeb2771fa712ceffe6f8972abf56
|
f24a69e3a5a9f1d4bb21cd15dec9bb2ac180696c
|
refs/heads/master
| 2021-09-07T20:06:17.888000 | 2018-02-28T10:10:06 | 2018-02-28T10:10:06 | 116,646,852 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sunyy.qrcode.mylibrary;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.HybridBinarizer;
import java.io.ByteArrayOutputStream;
import java.util.Hashtable;
import java.util.Map;
import camera.OpenCamera;
import static com.sunyy.qrcode.mylibrary.QRFragment.DECODE;
import static com.sunyy.qrcode.mylibrary.QRFragment.DECODE_FAILED;
import static com.sunyy.qrcode.mylibrary.QRFragment.DECODE_SUCCEEDED;
import static com.sunyy.qrcode.mylibrary.QRFragment.QUIT;
import static com.sunyy.qrcode.mylibrary.QRFragment.ZOOM_CHANGE;
final class DecodeHandler extends Handler {
private static final String TAG = DecodeHandler.class.getSimpleName();
private QRFragment mFragment;
private QRCommonFragment mCommonFragment;
private final MultiFormatReader multiFormatReader;
private boolean running = true;
private Map<DecodeHintType, Object> mHints;
private int mChange = 1;
DecodeHandler(QRFragment fragment, Map<DecodeHintType, Object> hints) {
mHints = new Hashtable<>();
mHints.put(DecodeHintType.CHARACTER_SET, "utf-8");
mHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(mHints);
this.mFragment = fragment;
}
DecodeHandler(QRCommonFragment fragment, Map<DecodeHintType, Object> hints) {
mHints = new Hashtable<>();
mHints.put(DecodeHintType.CHARACTER_SET, "utf-8");
mHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(mHints);
this.mCommonFragment = fragment;
}
@Override
public void handleMessage(Message message) {
if (message == null || !running) {
return;
}
switch (message.what) {
case DECODE:
decode((byte[]) message.obj, message.arg1, message.arg2);
break;
case QUIT:
running = false;
Looper.myLooper().quit();
break;
case ZOOM_CHANGE:
Camera camera = (Camera) message.obj;
Camera.Parameters parameters = camera.getParameters();
int zoom = message.arg1;
int maxZoom = message.arg2;
mChange++;
zoom += mChange;
parameters.setZoom(zoom);
camera.setParameters(parameters);
if (zoom < maxZoom / 4) {
Message message1 = new Message();
message1.what = ZOOM_CHANGE;
message1.arg1 = zoom;
message1.arg2 = maxZoom;
message1.obj = camera;
sendMessageDelayed(message1, 40);
} else {
Message message1;
if (mFragment != null) {
message1 = Message.obtain(mFragment.getHandler(), DECODE_FAILED);
} else {
message1 = Message.obtain(mCommonFragment.getHandler(), DECODE_FAILED);
}
message1.sendToTarget();
}
break;
}
}
/**
* Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,
* reuse the same reader objects from one decode to the next.
*
* @param data The YUV preview frame.
* @param width The width of the preview frame.
* @param height The height of the preview frame.
*/
private void decode(byte[] data, int width, int height) {
long start = System.currentTimeMillis();
Result rawResult = null;
PlanarYUVLuminanceSource source;
if(this.mFragment != null) {
source = this.mFragment.getCameraManager().buildLuminanceSource(data, width, height);
} else {
source = this.mCommonFragment.getCameraManager().buildLuminanceSource(data, width, height);
}
if(source != null) {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = this.multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException var26) {
;
} finally {
this.multiFormatReader.reset();
}
}
Handler handler;
if(this.mFragment != null) {
handler = this.mFragment.getHandler();
} else {
handler = this.mCommonFragment.getHandler();
}
if(rawResult != null) {
long end = System.currentTimeMillis();
LogUtils.d(TAG, "Found barcode in " + (end - start) + " ms");
if(handler != null) {
Rect rect;
if(this.mFragment != null) {
rect = this.mFragment.getCameraManager().getFramingRect();
} else {
rect = this.mCommonFragment.getCameraManager().getFramingRect();
}
if(rect != null) {
Camera camera;
if(this.mFragment != null) {
camera = this.mFragment.getCameraManager().getOpenCamera().getCamera();
} else {
camera = this.mCommonFragment.getCameraManager().getOpenCamera().getCamera();
}
Camera.Parameters parameters = camera.getParameters();
int maxZoom = parameters.getMaxZoom();
int zoom = parameters.getZoom();
if(parameters.isZoomSupported()) {
ResultPoint[] points = rawResult.getResultPoints();
int pos = 1;
float pointY = points[0].getX();
float pointX = points[0].getY();
if (points.length > 2) {
pos = 2;
}
float point2Y = points[pos].getX();
float point2X = points[pos].getY();
int len = Math.max((int)Math.abs(pointX - point2X), (int)Math.abs(pointY - point2Y));
Message message;
if(len <= rect.width() / 4 && isInRect(pointX, pointY, point2X, point2Y, rect)) {
++zoom;
this.mChange = 1;
if(zoom > maxZoom) {
zoom = maxZoom;
}
if(zoom < maxZoom / 4) {
message = new Message();
message.what = ZOOM_CHANGE;
message.arg1 = zoom;
message.arg2 = maxZoom;
message.obj = camera;
this.sendMessageDelayed(message, 100L);
} else {
parameters.setZoom(zoom);
camera.setParameters(parameters);
message = Message.obtain(handler, DECODE_FAILED);
message.sendToTarget();
}
} else {
message = Message.obtain(handler, DECODE_SUCCEEDED, rawResult);
Bundle bundle = new Bundle();
bundleThumbnail(source, bundle);
message.setData(bundle);
message.sendToTarget();
}
} else {
Message message = Message.obtain(handler, DECODE_SUCCEEDED, rawResult);
Bundle bundle = new Bundle();
bundleThumbnail(source, bundle);
message.setData(bundle);
message.sendToTarget();
}
} else {
Message message = Message.obtain(handler, DECODE_SUCCEEDED, rawResult);
Bundle bundle = new Bundle();
bundleThumbnail(source, bundle);
message.setData(bundle);
message.sendToTarget();
}
}
} else if(handler != null) {
Message message = Message.obtain(handler, DECODE_FAILED);
message.sendToTarget();
}
}
private static void bundleThumbnail(PlanarYUVLuminanceSource source, Bundle bundle) {
int[] pixels = source.renderThumbnail();
int width = source.getThumbnailWidth();
int height = source.getThumbnailHeight();
Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
bundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray());
bundle.putFloat(DecodeThread.BARCODE_SCALED_FACTOR, (float) width / source.getWidth());
}
private static boolean isInRect(float x1, float y1, float x2, float y2, Rect rect) {
if (rect.left < x1 && x1 < rect.right &&
rect.left < x2 && x2 < rect.right &&
rect.top < y1 && y1 < rect.bottom &&
rect.top < y2 && y2 < rect.bottom) {
return true;
}
return false;
}
}
|
UTF-8
|
Java
| 10,676 |
java
|
DecodeHandler.java
|
Java
|
[] | null |
[] |
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sunyy.qrcode.mylibrary;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.HybridBinarizer;
import java.io.ByteArrayOutputStream;
import java.util.Hashtable;
import java.util.Map;
import camera.OpenCamera;
import static com.sunyy.qrcode.mylibrary.QRFragment.DECODE;
import static com.sunyy.qrcode.mylibrary.QRFragment.DECODE_FAILED;
import static com.sunyy.qrcode.mylibrary.QRFragment.DECODE_SUCCEEDED;
import static com.sunyy.qrcode.mylibrary.QRFragment.QUIT;
import static com.sunyy.qrcode.mylibrary.QRFragment.ZOOM_CHANGE;
final class DecodeHandler extends Handler {
private static final String TAG = DecodeHandler.class.getSimpleName();
private QRFragment mFragment;
private QRCommonFragment mCommonFragment;
private final MultiFormatReader multiFormatReader;
private boolean running = true;
private Map<DecodeHintType, Object> mHints;
private int mChange = 1;
DecodeHandler(QRFragment fragment, Map<DecodeHintType, Object> hints) {
mHints = new Hashtable<>();
mHints.put(DecodeHintType.CHARACTER_SET, "utf-8");
mHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(mHints);
this.mFragment = fragment;
}
DecodeHandler(QRCommonFragment fragment, Map<DecodeHintType, Object> hints) {
mHints = new Hashtable<>();
mHints.put(DecodeHintType.CHARACTER_SET, "utf-8");
mHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(mHints);
this.mCommonFragment = fragment;
}
@Override
public void handleMessage(Message message) {
if (message == null || !running) {
return;
}
switch (message.what) {
case DECODE:
decode((byte[]) message.obj, message.arg1, message.arg2);
break;
case QUIT:
running = false;
Looper.myLooper().quit();
break;
case ZOOM_CHANGE:
Camera camera = (Camera) message.obj;
Camera.Parameters parameters = camera.getParameters();
int zoom = message.arg1;
int maxZoom = message.arg2;
mChange++;
zoom += mChange;
parameters.setZoom(zoom);
camera.setParameters(parameters);
if (zoom < maxZoom / 4) {
Message message1 = new Message();
message1.what = ZOOM_CHANGE;
message1.arg1 = zoom;
message1.arg2 = maxZoom;
message1.obj = camera;
sendMessageDelayed(message1, 40);
} else {
Message message1;
if (mFragment != null) {
message1 = Message.obtain(mFragment.getHandler(), DECODE_FAILED);
} else {
message1 = Message.obtain(mCommonFragment.getHandler(), DECODE_FAILED);
}
message1.sendToTarget();
}
break;
}
}
/**
* Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,
* reuse the same reader objects from one decode to the next.
*
* @param data The YUV preview frame.
* @param width The width of the preview frame.
* @param height The height of the preview frame.
*/
private void decode(byte[] data, int width, int height) {
long start = System.currentTimeMillis();
Result rawResult = null;
PlanarYUVLuminanceSource source;
if(this.mFragment != null) {
source = this.mFragment.getCameraManager().buildLuminanceSource(data, width, height);
} else {
source = this.mCommonFragment.getCameraManager().buildLuminanceSource(data, width, height);
}
if(source != null) {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = this.multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException var26) {
;
} finally {
this.multiFormatReader.reset();
}
}
Handler handler;
if(this.mFragment != null) {
handler = this.mFragment.getHandler();
} else {
handler = this.mCommonFragment.getHandler();
}
if(rawResult != null) {
long end = System.currentTimeMillis();
LogUtils.d(TAG, "Found barcode in " + (end - start) + " ms");
if(handler != null) {
Rect rect;
if(this.mFragment != null) {
rect = this.mFragment.getCameraManager().getFramingRect();
} else {
rect = this.mCommonFragment.getCameraManager().getFramingRect();
}
if(rect != null) {
Camera camera;
if(this.mFragment != null) {
camera = this.mFragment.getCameraManager().getOpenCamera().getCamera();
} else {
camera = this.mCommonFragment.getCameraManager().getOpenCamera().getCamera();
}
Camera.Parameters parameters = camera.getParameters();
int maxZoom = parameters.getMaxZoom();
int zoom = parameters.getZoom();
if(parameters.isZoomSupported()) {
ResultPoint[] points = rawResult.getResultPoints();
int pos = 1;
float pointY = points[0].getX();
float pointX = points[0].getY();
if (points.length > 2) {
pos = 2;
}
float point2Y = points[pos].getX();
float point2X = points[pos].getY();
int len = Math.max((int)Math.abs(pointX - point2X), (int)Math.abs(pointY - point2Y));
Message message;
if(len <= rect.width() / 4 && isInRect(pointX, pointY, point2X, point2Y, rect)) {
++zoom;
this.mChange = 1;
if(zoom > maxZoom) {
zoom = maxZoom;
}
if(zoom < maxZoom / 4) {
message = new Message();
message.what = ZOOM_CHANGE;
message.arg1 = zoom;
message.arg2 = maxZoom;
message.obj = camera;
this.sendMessageDelayed(message, 100L);
} else {
parameters.setZoom(zoom);
camera.setParameters(parameters);
message = Message.obtain(handler, DECODE_FAILED);
message.sendToTarget();
}
} else {
message = Message.obtain(handler, DECODE_SUCCEEDED, rawResult);
Bundle bundle = new Bundle();
bundleThumbnail(source, bundle);
message.setData(bundle);
message.sendToTarget();
}
} else {
Message message = Message.obtain(handler, DECODE_SUCCEEDED, rawResult);
Bundle bundle = new Bundle();
bundleThumbnail(source, bundle);
message.setData(bundle);
message.sendToTarget();
}
} else {
Message message = Message.obtain(handler, DECODE_SUCCEEDED, rawResult);
Bundle bundle = new Bundle();
bundleThumbnail(source, bundle);
message.setData(bundle);
message.sendToTarget();
}
}
} else if(handler != null) {
Message message = Message.obtain(handler, DECODE_FAILED);
message.sendToTarget();
}
}
private static void bundleThumbnail(PlanarYUVLuminanceSource source, Bundle bundle) {
int[] pixels = source.renderThumbnail();
int width = source.getThumbnailWidth();
int height = source.getThumbnailHeight();
Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
bundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray());
bundle.putFloat(DecodeThread.BARCODE_SCALED_FACTOR, (float) width / source.getWidth());
}
private static boolean isInRect(float x1, float y1, float x2, float y2, Rect rect) {
if (rect.left < x1 && x1 < rect.right &&
rect.left < x2 && x2 < rect.right &&
rect.top < y1 && y1 < rect.bottom &&
rect.top < y2 && y2 < rect.bottom) {
return true;
}
return false;
}
}
| 10,676 | 0.545897 | 0.539341 | 261 | 39.904213 | 25.797813 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false |
10
|
3c04cf297044bd23400eaf29a445f0b6a7702079
| 37,014,028,184,772 |
4e793604878772123c73bfebce852226c6f4b750
|
/src/main/java/org/diabeticlog/api/SpreadsheetApi.java
|
681e693419ff2b4bd48dccb100c57e43395cedee
|
[
"Apache-2.0"
] |
permissive
|
pierreh/diabetic-log
|
https://github.com/pierreh/diabetic-log
|
69be2849a69eb2120e3c3a3799dded9506e9cfde
|
b7cfb90c1756ab1a16af7ff308c6245dca2554a9
|
refs/heads/master
| 2021-01-10T06:16:23.623000 | 2015-11-07T15:12:45 | 2015-11-07T15:12:45 | 45,740,946 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.diabeticlog.api;
public class SpreadsheetApi {
private String user;
public SpreadsheetApi(String user) {
this.user = user;
}
public void storeDay(DayVo day) {
}
}
|
UTF-8
|
Java
| 202 |
java
|
SpreadsheetApi.java
|
Java
|
[] | null |
[] |
package org.diabeticlog.api;
public class SpreadsheetApi {
private String user;
public SpreadsheetApi(String user) {
this.user = user;
}
public void storeDay(DayVo day) {
}
}
| 202 | 0.663366 | 0.663366 | 15 | 12.466666 | 14.60989 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
10
|
619724acf3f3b441f6ddd412be907135efef585f
| 38,182,259,283,252 |
77b143f6783a4f4f8ea8a729d44f337802bfac69
|
/src/MenuFactory.java
|
7ccf6faa57d07388c24691eaf53a30cfed82f0e4
|
[] |
no_license
|
ETBunce/MahJong
|
https://github.com/ETBunce/MahJong
|
3128791857a07fbca4fa216ddfef86f121d00b18
|
26d8342fda4c106d128025283f86db9eb1230c2a
|
refs/heads/master
| 2023-07-05T22:44:57.649000 | 2021-08-11T02:07:43 | 2021-08-11T02:07:43 | 311,175,694 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
public class MenuFactory {
private static JMenuBar bar;
private static Object target;
public static void setMenuBar(JMenuBar newBar) {
bar = newBar;
}
public static void setTarget(Object newTarget) {
target = newTarget;
}
public static void configure(JMenuBar newBar, Object newTarget) {
bar = newBar;
target = newTarget;
}
// newMenu
public static JMenu newMenu(String name) {
if (bar == null) return null;
JMenu menu = new JMenu(name);
bar.add(menu);
return menu;
}
public static JMenu newMenu(String name, int mnemonic) {
if (bar == null) return null;
JMenu menu = newMenu(name);
menu.setMnemonic(mnemonic);
return menu;
}
// newItem
public static JMenuItem newItem(String name) {
if (bar == null) return null;
JMenuItem item = new JMenuItem(name);
return item;
}
public static JMenuItem newItem(String name, JMenu menu) {
if (bar == null) return null;
JMenuItem item = newItem(name);
menu.add(item);
return item;
}
public static JMenuItem newItem(String name, JMenu menu, String method) {
if (bar == null) return null;
JMenuItem item = newItem(name);
item.addActionListener((ActionListener)EventHandler.create(ActionListener.class, target, method));
menu.add(item);
return item;
}
public static JMenuItem newItem(String name, int mnemonic, JMenu menu) {
if (bar == null) return null;
JMenuItem item = newItem(name, menu);
item.setMnemonic(mnemonic);
return item;
}
public static JMenuItem newItem(String name, int mnemonic, KeyStroke accel, JMenu menu) {
if (bar == null) return null;
JMenuItem item = newItem(name, mnemonic, menu);
item.setAccelerator(accel);
return item;
}
public static JMenuItem newItem(String name, int mnemonic, KeyStroke accel, JMenu menu, String method) {
if (bar == null || target == null) return null;
JMenuItem item = newItem(name, mnemonic, accel, menu);
item.addActionListener((ActionListener)EventHandler.create(ActionListener.class, target, method));
return item;
}
}
|
UTF-8
|
Java
| 2,098 |
java
|
MenuFactory.java
|
Java
|
[] | null |
[] |
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
public class MenuFactory {
private static JMenuBar bar;
private static Object target;
public static void setMenuBar(JMenuBar newBar) {
bar = newBar;
}
public static void setTarget(Object newTarget) {
target = newTarget;
}
public static void configure(JMenuBar newBar, Object newTarget) {
bar = newBar;
target = newTarget;
}
// newMenu
public static JMenu newMenu(String name) {
if (bar == null) return null;
JMenu menu = new JMenu(name);
bar.add(menu);
return menu;
}
public static JMenu newMenu(String name, int mnemonic) {
if (bar == null) return null;
JMenu menu = newMenu(name);
menu.setMnemonic(mnemonic);
return menu;
}
// newItem
public static JMenuItem newItem(String name) {
if (bar == null) return null;
JMenuItem item = new JMenuItem(name);
return item;
}
public static JMenuItem newItem(String name, JMenu menu) {
if (bar == null) return null;
JMenuItem item = newItem(name);
menu.add(item);
return item;
}
public static JMenuItem newItem(String name, JMenu menu, String method) {
if (bar == null) return null;
JMenuItem item = newItem(name);
item.addActionListener((ActionListener)EventHandler.create(ActionListener.class, target, method));
menu.add(item);
return item;
}
public static JMenuItem newItem(String name, int mnemonic, JMenu menu) {
if (bar == null) return null;
JMenuItem item = newItem(name, menu);
item.setMnemonic(mnemonic);
return item;
}
public static JMenuItem newItem(String name, int mnemonic, KeyStroke accel, JMenu menu) {
if (bar == null) return null;
JMenuItem item = newItem(name, mnemonic, menu);
item.setAccelerator(accel);
return item;
}
public static JMenuItem newItem(String name, int mnemonic, KeyStroke accel, JMenu menu, String method) {
if (bar == null || target == null) return null;
JMenuItem item = newItem(name, mnemonic, accel, menu);
item.addActionListener((ActionListener)EventHandler.create(ActionListener.class, target, method));
return item;
}
}
| 2,098 | 0.714967 | 0.714967 | 74 | 27.351351 | 25.177443 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.283784 | false | false |
10
|
3eb766e58c323087794d731f34ffea93b1ff8aad
| 18,863,496,432,784 |
df72a66ed82c541f6c608c62f33280f5d1785d5c
|
/estimulo/src/com/estimulo/logistics/production/dao/MrpDAOImpl.java
|
e791dbde599afb0f2c6819dc02dd91b6d554bed5
|
[] |
no_license
|
yogaras/reTest
|
https://github.com/yogaras/reTest
|
ec69116b2d6205d53f533ec95e8e0d67cd4b9211
|
4800a4b70fa18aabc7564ff6c039d9ac85061125
|
refs/heads/master
| 2023-02-12T22:57:20.859000 | 2020-12-18T10:04:36 | 2020-12-18T10:04:36 | 322,554,750 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.estimulo.logistics.production.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.estimulo.common.db.DataSourceTransactionManager;
import com.estimulo.common.exception.DataAccessException;
import com.estimulo.logistics.production.to.MrpTO;
import com.estimulo.logistics.production.to.OpenMrpTO;
import oracle.jdbc.internal.OracleTypes;
public class MrpDAOImpl implements MrpDAO {
// SLF4J logger
private static Logger logger = LoggerFactory.getLogger(MrpDAOImpl.class);
// 싱글톤
private static MrpDAO instance = new MrpDAOImpl();
private MrpDAOImpl() {
}
public static MrpDAO getInstance() {
if (logger.isDebugEnabled()) {
logger.debug("@ MrpDAOImpl 객체접근");
}
return instance;
}
// 참조변수 선언
private static DataSourceTransactionManager dataSourceTransactionManager = DataSourceTransactionManager
.getInstance();
public ArrayList<MrpTO> selectMrpList(String mrpGatheringStatusCondition) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : selectMrpList 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<MrpTO> mrpList = new ArrayList<MrpTO>();
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
SELECT * FROM MRP WHERE MRP_GATHERING_STATUS IS NULL
*/
query.append("SELECT * FROM MRP ");
if(mrpGatheringStatusCondition.equals("null") || mrpGatheringStatusCondition == null) {
query.append(
"WHERE MRP_GATHERING_STATUS IS NULL ORDER BY MRP_NO");
} else if(mrpGatheringStatusCondition.equals("notNull")) {
query.append(
"WHERE MRP_GATHERING_STATUS IS NOT NULL ORDER BY MRP_NO");
}
pstmt = conn.prepareStatement(query.toString());
rs = pstmt.executeQuery();
MrpTO bean = null;
while (rs.next()) {
bean = new MrpTO();
bean.setMrpNo(rs.getString("MRP_NO"));
bean.setMpsNo(rs.getString("MPS_NO"));
bean.setMrpGatheringNo(rs.getString("MRP_GATHERING_NO"));
bean.setItemClassification(rs.getString("ITEM_CLASSIFICATION"));
bean.setItemCode(rs.getString("ITEM_CODE"));
bean.setItemName(rs.getString("ITEM_NAME"));
bean.setOrderDate(rs.getString("ORDER_DATE"));
bean.setRequiredDate(rs.getString("REQUIRED_DATE"));
bean.setRequiredAmount(rs.getInt("REQUIRED_AMOUNT"));
bean.setUnitOfMrp(rs.getString("UNIT_OF_MRP"));
bean.setMrpGatheringStatus(rs.getString("MRP_GATHERING_STATUS"));
mrpList.add(bean);
}
return mrpList;
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public ArrayList<MrpTO> selectMrpList(String dateSearchCondtion, String startDate, String endDate) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : selectMrpList 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<MrpTO> mrpList = new ArrayList<MrpTO>();
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
SELECT * FROM MRP WHERE ( CASE ? WHEN 'orderDate' THEN
TO_DATE(ORDER_DATE, 'YYYY-MM-DD') WHEN 'requiredDate' THEN
TO_DATE(REQUIRED_DATE, 'YYYY-MM-DD') END )
BETWEEN TO_DATE(?,'YYYY-MM-DD') AND TO_DATE(?,'YYYY-MM-DD')
*/
query.append(
"SELECT * FROM MRP WHERE ( CASE ? WHEN 'orderDate' THEN\r\n" +
"TO_DATE(ORDER_DATE, 'YYYY-MM-DD') WHEN 'requiredDate' THEN\r\n" +
"TO_DATE(REQUIRED_DATE, 'YYYY-MM-DD') END ) \r\n" +
"BETWEEN TO_DATE(?,'YYYY-MM-DD') AND TO_DATE(?,'YYYY-MM-DD')");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, dateSearchCondtion);
pstmt.setString(2, startDate);
pstmt.setString(3, endDate);
rs = pstmt.executeQuery();
MrpTO bean = null;
while (rs.next()) {
bean = new MrpTO();
bean.setMrpNo(rs.getString("MRP_NO"));
bean.setMpsNo(rs.getString("MPS_NO"));
bean.setMrpGatheringNo(rs.getString("MRP_GATHERING_NO"));
bean.setItemClassification(rs.getString("ITEM_CLASSIFICATION"));
bean.setItemCode(rs.getString("ITEM_CODE"));
bean.setItemName(rs.getString("ITEM_NAME"));
bean.setOrderDate(rs.getString("ORDER_DATE"));
bean.setRequiredDate(rs.getString("REQUIRED_DATE"));
bean.setRequiredAmount(rs.getInt("REQUIRED_AMOUNT"));
bean.setUnitOfMrp(rs.getString("UNIT_OF_MRP"));
bean.setMrpGatheringStatus(rs.getString("MRP_GATHERING_STATUS"));
mrpList.add(bean);
}
return mrpList;
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public ArrayList<MrpTO> selectMrpListAsMrpGatheringNo(String mrpGatheringNo) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : selectMrpListAsMrpGatheringNo 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<MrpTO> mrpList = new ArrayList<MrpTO>();
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
SELECT * FROM MRP WHERE MRP_GATHERING_NO =?
*/
query.append(
"SELECT * FROM MRP WHERE MRP_GATHERING_NO =?");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, mrpGatheringNo);
rs = pstmt.executeQuery();
MrpTO bean = null;
while (rs.next()) {
bean = new MrpTO();
bean.setMrpNo(rs.getString("MRP_NO"));
bean.setMpsNo(rs.getString("MPS_NO"));
bean.setMrpGatheringNo(rs.getString("MRP_GATHERING_NO"));
bean.setItemClassification(rs.getString("ITEM_CLASSIFICATION"));
bean.setItemCode(rs.getString("ITEM_CODE"));
bean.setItemName(rs.getString("ITEM_NAME"));
bean.setOrderDate(rs.getString("ORDER_DATE"));
bean.setRequiredDate(rs.getString("REQUIRED_DATE"));
bean.setRequiredAmount(rs.getInt("REQUIRED_AMOUNT"));
bean.setUnitOfMrp(rs.getString("UNIT_OF_MRP"));
bean.setMrpGatheringStatus(rs.getString("MRP_GATHERING_STATUS"));
mrpList.add(bean);
}
return mrpList;
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
@Override
public HashMap<String,Object> openMrp(String mpsNoList) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : openMrp 시작");
}
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
ArrayList<OpenMrpTO> openMrpList = new ArrayList<OpenMrpTO>();
HashMap<String,Object> resultMap = new HashMap<>();
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
query.append(" {call P_MRP_OPEN(?,?,?,?)} ");
System.out.println(" @ 프로시저 호출");
cs = conn.prepareCall(query.toString());
cs.setString(1,mpsNoList);
cs.registerOutParameter(2,OracleTypes.NUMBER);
cs.registerOutParameter(3,OracleTypes.VARCHAR); //https://docs.oracle.com/cd/E11882_01/appdev.112/e13995/index.html?oracle/jdbc/OracleTypes.html
cs.registerOutParameter(4,OracleTypes.CURSOR);
cs.executeUpdate();
int errorCode = cs.getInt(2);
String errorMsg = cs.getString(3);
rs = (ResultSet) cs.getObject(4);
OpenMrpTO bean = null;
while (rs.next()) {
bean = new OpenMrpTO(); //MRP_OPEN_TEMP 에 저장된 값이 담기게 되고 여기서 세팅을 해준다.
bean.setMpsNo(rs.getString("MPS_NO"));
bean.setBomNo(rs.getString("BOM_NO"));
bean.setItemClassification(rs.getString("ITEM_CLASSIFICATION"));
bean.setItemCode(rs.getString("ITEM_CODE"));
bean.setItemName(rs.getString("ITEM_NAME"));
bean.setUnitOfMrp(rs.getString("UNIT_OF_MRP"));
bean.setPlanAmount(rs.getString("PLAN_AMOUNT"));
bean.setOrderDate(rs.getString("ORDER_DATE"));
bean.setRequiredDate(rs.getString("REQUIRED_DATE"));
bean.setTotalLossRate(rs.getString("TOTAL_LOSS_RATE"));
bean.setCaculatedAmount(rs.getString("CACULATED_AMOUNT"));
bean.setRequiredAmount(rs.getInt("REQUIRED_AMOUNT"));
openMrpList.add(bean);
}
resultMap.put("gridRowJson", openMrpList);
resultMap.put("errorCode",errorCode);
resultMap.put("errorMsg",errorMsg);
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(cs, rs);
}
return resultMap;
}
public int selectMrpCount(String mrpRegisterDate) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : selectMrpCount 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
* SELECT * FROM MRP WHERE INSTR(MRP_NO, REPLACE( ? , '-' , '' ) ) > 0
*/
query.append("SELECT * FROM MRP WHERE INSTR(MRP_NO, REPLACE( ? , '-' , '' ) ) > 0");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, mrpRegisterDate);
rs = pstmt.executeQuery();
TreeSet<Integer> intSet = new TreeSet<>();
while (rs.next()) {
String mrpNo = rs.getString("MRP_NO");
// MRP 일련번호에서 마지막 3자리만 가져오기
int no = Integer.parseInt(mrpNo.substring(mrpNo.length()-3, mrpNo.length()));
intSet.add(no);
}
if (intSet.isEmpty()) {
return 1;
} else {
return intSet.pollLast() + 1; // 가장 높은 번호 + 1
}
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public void insertMrp(MrpTO bean) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : insertMrp 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
Insert into MRP
(MRP_NO, MPS_NO, MRP_GATHERING_NO, ITEM_CLASSIFICATION,
ITEM_CODE, ITEM_NAME, UNIT_OR_MRP,
REQUIRED_AMOUNT, LEAD_TIME, SCHEDULED_COMPLETE_DATE,
MRP_GATHERING_STATUS)
values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
*/
query.append(
"Insert into MRP\r\n" +
"(MRP_NO, MPS_NO, MRP_GATHERING_NO, ITEM_CLASSIFICATION, \r\n" +
"ITEM_CODE, ITEM_NAME, UNIT_OF_MRP, \r\n" +
"REQUIRED_AMOUNT, ORDER_DATE, REQUIRED_DATE,\r\n" +
"MRP_GATHERING_STATUS)\r\n" +
"values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, bean.getMrpNo());
pstmt.setString(2, bean.getMpsNo());
pstmt.setString(3, bean.getMrpGatheringNo());
pstmt.setString(4, bean.getItemClassification());
pstmt.setString(5, bean.getItemCode());
pstmt.setString(6, bean.getItemName());
pstmt.setString(7, bean.getUnitOfMrp());
pstmt.setInt(8, bean.getRequiredAmount());
pstmt.setString(9, bean.getOrderDate());
pstmt.setString(10, bean.getRequiredDate());
pstmt.setString(11, bean.getMrpGatheringStatus());
rs = pstmt.executeQuery();
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public void updateMrp(MrpTO bean) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : updateMrp 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
* UPDATE MRP SET MPS_NO = ? , MRP_GATHERING_NO = ? , ITEM_CLASSIFICATION = ? ,
* ITEM_CODE = ? , ITEM_NAME = ? , UNIT_OF_MRP = ? , REQUIRED_AMOUNT = ? ,
* ORDER_DATE = ? , REQUIRED_DATE = ? , MRP_GATHERING_STATUS = ? WHERE
* MRP_NO = ?
*/
query.append("UPDATE MRP SET MPS_NO = ? , MRP_GATHERING_NO = ? ,\r\n"
+ "ITEM_CLASSIFICATION = ? , ITEM_CODE = ? ,\r\n" + "ITEM_NAME = ? , UNIT_OR_MRP = ? ,\r\n"
+ "REQUIRED_AMOUNT = ? , ORDER_DATE = ? ,\r\n"
+ "REQUIRED_DATE = ? , MRP_GATHERING_STATUS = ? \r\n" + "WHERE MRP_NO = ?");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, bean.getMpsNo());
pstmt.setString(2, bean.getMrpGatheringNo());
pstmt.setString(3, bean.getItemClassification());
pstmt.setString(4, bean.getItemCode());
pstmt.setString(5, bean.getItemName());
pstmt.setString(6, bean.getUnitOfMrp());
pstmt.setInt(7, bean.getRequiredAmount());
pstmt.setString(8, bean.getOrderDate());
pstmt.setString(9, bean.getRequiredDate());
pstmt.setString(10, bean.getMrpGatheringStatus());
pstmt.setString(11, bean.getMrpNo());
rs = pstmt.executeQuery();
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public void changeMrpGatheringStatus(String mrpNo, String mrpGatheringNo, String mrpGatheringStatus) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : changeMrpGatheringStatus 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
UPDATE MRP SET MRP_GATHERING_NO = ? , MRP_GATHERING_STATUS = ? WHERE MRP_NO = ?
*/
query.append(
"UPDATE MRP SET MRP_GATHERING_NO = ? , MRP_GATHERING_STATUS = ? WHERE MRP_NO = ?\r\n" +
"");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, mrpGatheringNo);
pstmt.setString(2, mrpGatheringStatus);
pstmt.setString(3, mrpNo);
rs = pstmt.executeQuery();
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public void deleteMrp(MrpTO bean) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : deleteMrp 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
query.append("DELETE FROM MRP WHERE MRP_NO = ?");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, bean.getMrpNo());
rs = pstmt.executeQuery();
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
}
|
UTF-8
|
Java
| 17,816 |
java
|
MrpDAOImpl.java
|
Java
|
[] | null |
[] |
package com.estimulo.logistics.production.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.estimulo.common.db.DataSourceTransactionManager;
import com.estimulo.common.exception.DataAccessException;
import com.estimulo.logistics.production.to.MrpTO;
import com.estimulo.logistics.production.to.OpenMrpTO;
import oracle.jdbc.internal.OracleTypes;
public class MrpDAOImpl implements MrpDAO {
// SLF4J logger
private static Logger logger = LoggerFactory.getLogger(MrpDAOImpl.class);
// 싱글톤
private static MrpDAO instance = new MrpDAOImpl();
private MrpDAOImpl() {
}
public static MrpDAO getInstance() {
if (logger.isDebugEnabled()) {
logger.debug("@ MrpDAOImpl 객체접근");
}
return instance;
}
// 참조변수 선언
private static DataSourceTransactionManager dataSourceTransactionManager = DataSourceTransactionManager
.getInstance();
public ArrayList<MrpTO> selectMrpList(String mrpGatheringStatusCondition) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : selectMrpList 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<MrpTO> mrpList = new ArrayList<MrpTO>();
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
SELECT * FROM MRP WHERE MRP_GATHERING_STATUS IS NULL
*/
query.append("SELECT * FROM MRP ");
if(mrpGatheringStatusCondition.equals("null") || mrpGatheringStatusCondition == null) {
query.append(
"WHERE MRP_GATHERING_STATUS IS NULL ORDER BY MRP_NO");
} else if(mrpGatheringStatusCondition.equals("notNull")) {
query.append(
"WHERE MRP_GATHERING_STATUS IS NOT NULL ORDER BY MRP_NO");
}
pstmt = conn.prepareStatement(query.toString());
rs = pstmt.executeQuery();
MrpTO bean = null;
while (rs.next()) {
bean = new MrpTO();
bean.setMrpNo(rs.getString("MRP_NO"));
bean.setMpsNo(rs.getString("MPS_NO"));
bean.setMrpGatheringNo(rs.getString("MRP_GATHERING_NO"));
bean.setItemClassification(rs.getString("ITEM_CLASSIFICATION"));
bean.setItemCode(rs.getString("ITEM_CODE"));
bean.setItemName(rs.getString("ITEM_NAME"));
bean.setOrderDate(rs.getString("ORDER_DATE"));
bean.setRequiredDate(rs.getString("REQUIRED_DATE"));
bean.setRequiredAmount(rs.getInt("REQUIRED_AMOUNT"));
bean.setUnitOfMrp(rs.getString("UNIT_OF_MRP"));
bean.setMrpGatheringStatus(rs.getString("MRP_GATHERING_STATUS"));
mrpList.add(bean);
}
return mrpList;
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public ArrayList<MrpTO> selectMrpList(String dateSearchCondtion, String startDate, String endDate) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : selectMrpList 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<MrpTO> mrpList = new ArrayList<MrpTO>();
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
SELECT * FROM MRP WHERE ( CASE ? WHEN 'orderDate' THEN
TO_DATE(ORDER_DATE, 'YYYY-MM-DD') WHEN 'requiredDate' THEN
TO_DATE(REQUIRED_DATE, 'YYYY-MM-DD') END )
BETWEEN TO_DATE(?,'YYYY-MM-DD') AND TO_DATE(?,'YYYY-MM-DD')
*/
query.append(
"SELECT * FROM MRP WHERE ( CASE ? WHEN 'orderDate' THEN\r\n" +
"TO_DATE(ORDER_DATE, 'YYYY-MM-DD') WHEN 'requiredDate' THEN\r\n" +
"TO_DATE(REQUIRED_DATE, 'YYYY-MM-DD') END ) \r\n" +
"BETWEEN TO_DATE(?,'YYYY-MM-DD') AND TO_DATE(?,'YYYY-MM-DD')");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, dateSearchCondtion);
pstmt.setString(2, startDate);
pstmt.setString(3, endDate);
rs = pstmt.executeQuery();
MrpTO bean = null;
while (rs.next()) {
bean = new MrpTO();
bean.setMrpNo(rs.getString("MRP_NO"));
bean.setMpsNo(rs.getString("MPS_NO"));
bean.setMrpGatheringNo(rs.getString("MRP_GATHERING_NO"));
bean.setItemClassification(rs.getString("ITEM_CLASSIFICATION"));
bean.setItemCode(rs.getString("ITEM_CODE"));
bean.setItemName(rs.getString("ITEM_NAME"));
bean.setOrderDate(rs.getString("ORDER_DATE"));
bean.setRequiredDate(rs.getString("REQUIRED_DATE"));
bean.setRequiredAmount(rs.getInt("REQUIRED_AMOUNT"));
bean.setUnitOfMrp(rs.getString("UNIT_OF_MRP"));
bean.setMrpGatheringStatus(rs.getString("MRP_GATHERING_STATUS"));
mrpList.add(bean);
}
return mrpList;
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public ArrayList<MrpTO> selectMrpListAsMrpGatheringNo(String mrpGatheringNo) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : selectMrpListAsMrpGatheringNo 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<MrpTO> mrpList = new ArrayList<MrpTO>();
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
SELECT * FROM MRP WHERE MRP_GATHERING_NO =?
*/
query.append(
"SELECT * FROM MRP WHERE MRP_GATHERING_NO =?");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, mrpGatheringNo);
rs = pstmt.executeQuery();
MrpTO bean = null;
while (rs.next()) {
bean = new MrpTO();
bean.setMrpNo(rs.getString("MRP_NO"));
bean.setMpsNo(rs.getString("MPS_NO"));
bean.setMrpGatheringNo(rs.getString("MRP_GATHERING_NO"));
bean.setItemClassification(rs.getString("ITEM_CLASSIFICATION"));
bean.setItemCode(rs.getString("ITEM_CODE"));
bean.setItemName(rs.getString("ITEM_NAME"));
bean.setOrderDate(rs.getString("ORDER_DATE"));
bean.setRequiredDate(rs.getString("REQUIRED_DATE"));
bean.setRequiredAmount(rs.getInt("REQUIRED_AMOUNT"));
bean.setUnitOfMrp(rs.getString("UNIT_OF_MRP"));
bean.setMrpGatheringStatus(rs.getString("MRP_GATHERING_STATUS"));
mrpList.add(bean);
}
return mrpList;
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
@Override
public HashMap<String,Object> openMrp(String mpsNoList) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : openMrp 시작");
}
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
ArrayList<OpenMrpTO> openMrpList = new ArrayList<OpenMrpTO>();
HashMap<String,Object> resultMap = new HashMap<>();
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
query.append(" {call P_MRP_OPEN(?,?,?,?)} ");
System.out.println(" @ 프로시저 호출");
cs = conn.prepareCall(query.toString());
cs.setString(1,mpsNoList);
cs.registerOutParameter(2,OracleTypes.NUMBER);
cs.registerOutParameter(3,OracleTypes.VARCHAR); //https://docs.oracle.com/cd/E11882_01/appdev.112/e13995/index.html?oracle/jdbc/OracleTypes.html
cs.registerOutParameter(4,OracleTypes.CURSOR);
cs.executeUpdate();
int errorCode = cs.getInt(2);
String errorMsg = cs.getString(3);
rs = (ResultSet) cs.getObject(4);
OpenMrpTO bean = null;
while (rs.next()) {
bean = new OpenMrpTO(); //MRP_OPEN_TEMP 에 저장된 값이 담기게 되고 여기서 세팅을 해준다.
bean.setMpsNo(rs.getString("MPS_NO"));
bean.setBomNo(rs.getString("BOM_NO"));
bean.setItemClassification(rs.getString("ITEM_CLASSIFICATION"));
bean.setItemCode(rs.getString("ITEM_CODE"));
bean.setItemName(rs.getString("ITEM_NAME"));
bean.setUnitOfMrp(rs.getString("UNIT_OF_MRP"));
bean.setPlanAmount(rs.getString("PLAN_AMOUNT"));
bean.setOrderDate(rs.getString("ORDER_DATE"));
bean.setRequiredDate(rs.getString("REQUIRED_DATE"));
bean.setTotalLossRate(rs.getString("TOTAL_LOSS_RATE"));
bean.setCaculatedAmount(rs.getString("CACULATED_AMOUNT"));
bean.setRequiredAmount(rs.getInt("REQUIRED_AMOUNT"));
openMrpList.add(bean);
}
resultMap.put("gridRowJson", openMrpList);
resultMap.put("errorCode",errorCode);
resultMap.put("errorMsg",errorMsg);
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(cs, rs);
}
return resultMap;
}
public int selectMrpCount(String mrpRegisterDate) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : selectMrpCount 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
* SELECT * FROM MRP WHERE INSTR(MRP_NO, REPLACE( ? , '-' , '' ) ) > 0
*/
query.append("SELECT * FROM MRP WHERE INSTR(MRP_NO, REPLACE( ? , '-' , '' ) ) > 0");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, mrpRegisterDate);
rs = pstmt.executeQuery();
TreeSet<Integer> intSet = new TreeSet<>();
while (rs.next()) {
String mrpNo = rs.getString("MRP_NO");
// MRP 일련번호에서 마지막 3자리만 가져오기
int no = Integer.parseInt(mrpNo.substring(mrpNo.length()-3, mrpNo.length()));
intSet.add(no);
}
if (intSet.isEmpty()) {
return 1;
} else {
return intSet.pollLast() + 1; // 가장 높은 번호 + 1
}
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public void insertMrp(MrpTO bean) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : insertMrp 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
Insert into MRP
(MRP_NO, MPS_NO, MRP_GATHERING_NO, ITEM_CLASSIFICATION,
ITEM_CODE, ITEM_NAME, UNIT_OR_MRP,
REQUIRED_AMOUNT, LEAD_TIME, SCHEDULED_COMPLETE_DATE,
MRP_GATHERING_STATUS)
values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
*/
query.append(
"Insert into MRP\r\n" +
"(MRP_NO, MPS_NO, MRP_GATHERING_NO, ITEM_CLASSIFICATION, \r\n" +
"ITEM_CODE, ITEM_NAME, UNIT_OF_MRP, \r\n" +
"REQUIRED_AMOUNT, ORDER_DATE, REQUIRED_DATE,\r\n" +
"MRP_GATHERING_STATUS)\r\n" +
"values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, bean.getMrpNo());
pstmt.setString(2, bean.getMpsNo());
pstmt.setString(3, bean.getMrpGatheringNo());
pstmt.setString(4, bean.getItemClassification());
pstmt.setString(5, bean.getItemCode());
pstmt.setString(6, bean.getItemName());
pstmt.setString(7, bean.getUnitOfMrp());
pstmt.setInt(8, bean.getRequiredAmount());
pstmt.setString(9, bean.getOrderDate());
pstmt.setString(10, bean.getRequiredDate());
pstmt.setString(11, bean.getMrpGatheringStatus());
rs = pstmt.executeQuery();
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public void updateMrp(MrpTO bean) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : updateMrp 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
* UPDATE MRP SET MPS_NO = ? , MRP_GATHERING_NO = ? , ITEM_CLASSIFICATION = ? ,
* ITEM_CODE = ? , ITEM_NAME = ? , UNIT_OF_MRP = ? , REQUIRED_AMOUNT = ? ,
* ORDER_DATE = ? , REQUIRED_DATE = ? , MRP_GATHERING_STATUS = ? WHERE
* MRP_NO = ?
*/
query.append("UPDATE MRP SET MPS_NO = ? , MRP_GATHERING_NO = ? ,\r\n"
+ "ITEM_CLASSIFICATION = ? , ITEM_CODE = ? ,\r\n" + "ITEM_NAME = ? , UNIT_OR_MRP = ? ,\r\n"
+ "REQUIRED_AMOUNT = ? , ORDER_DATE = ? ,\r\n"
+ "REQUIRED_DATE = ? , MRP_GATHERING_STATUS = ? \r\n" + "WHERE MRP_NO = ?");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, bean.getMpsNo());
pstmt.setString(2, bean.getMrpGatheringNo());
pstmt.setString(3, bean.getItemClassification());
pstmt.setString(4, bean.getItemCode());
pstmt.setString(5, bean.getItemName());
pstmt.setString(6, bean.getUnitOfMrp());
pstmt.setInt(7, bean.getRequiredAmount());
pstmt.setString(8, bean.getOrderDate());
pstmt.setString(9, bean.getRequiredDate());
pstmt.setString(10, bean.getMrpGatheringStatus());
pstmt.setString(11, bean.getMrpNo());
rs = pstmt.executeQuery();
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public void changeMrpGatheringStatus(String mrpNo, String mrpGatheringNo, String mrpGatheringStatus) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : changeMrpGatheringStatus 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
/*
UPDATE MRP SET MRP_GATHERING_NO = ? , MRP_GATHERING_STATUS = ? WHERE MRP_NO = ?
*/
query.append(
"UPDATE MRP SET MRP_GATHERING_NO = ? , MRP_GATHERING_STATUS = ? WHERE MRP_NO = ?\r\n" +
"");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, mrpGatheringNo);
pstmt.setString(2, mrpGatheringStatus);
pstmt.setString(3, mrpNo);
rs = pstmt.executeQuery();
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
public void deleteMrp(MrpTO bean) {
if (logger.isDebugEnabled()) {
logger.debug("MrpDAOImpl : deleteMrp 시작");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSourceTransactionManager.getConnection();
StringBuffer query = new StringBuffer();
query.append("DELETE FROM MRP WHERE MRP_NO = ?");
pstmt = conn.prepareStatement(query.toString());
pstmt.setString(1, bean.getMrpNo());
rs = pstmt.executeQuery();
} catch (Exception sqle) {
throw new DataAccessException(sqle.getMessage());
} finally {
dataSourceTransactionManager.close(pstmt, rs);
}
}
}
| 17,816 | 0.565013 | 0.561219 | 561 | 29.479502 | 26.600296 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.670232 | false | false |
10
|
5c409c9866935cbe17e94c770a73d5e99ef02e07
| 34,256,659,207,115 |
36c118265ceacceae84cbae269fa21bccf51346c
|
/recruitment-center/recruitment-center-client/src/main/java/com/andy/recruitment/user/constant/UserStatus.java
|
0407513782d084b4054c3dc42fd2ebe913fbae5a
|
[] |
no_license
|
pangxianhai/clinical-recruitment
|
https://github.com/pangxianhai/clinical-recruitment
|
d078aa4e848011c6030df984f4bb414cc0f51929
|
e1fd9d6aabc91058f66e6e15baf82e120f3275d8
|
refs/heads/master
| 2023-01-12T09:47:48.697000 | 2020-07-26T16:42:48 | 2020-07-26T16:42:48 | 161,619,163 | 0 | 0 | null | false | 2023-01-07T04:52:29 | 2018-12-13T09:58:49 | 2020-07-26T16:43:03 | 2023-01-07T04:52:29 | 16,598 | 0 | 0 | 54 |
Java
| false | false |
package com.andy.recruitment.user.constant;
import com.xgimi.commons.base.BaseType;
import java.util.List;
/**
* 用户状态
*
* @author 庞先海 2018-12-28
*/
public class UserStatus extends BaseType {
public static final UserStatus NORMAL = new UserStatus(1, "正常");
public static final UserStatus FREEZE = new UserStatus(2, "冻结");
public UserStatus(int code, String desc) {
super(code, desc);
}
public static List<UserStatus> getValues() {
return BaseType.getValues(UserStatus.class);
}
public static UserStatus parse(Integer code) {
return BaseType.parse(UserStatus.getValues(), code);
}
}
|
UTF-8
|
Java
| 670 |
java
|
UserStatus.java
|
Java
|
[
{
"context": "import java.util.List;\n\n/**\n * 用户状态\n *\n * @author 庞先海 2018-12-28\n */\npublic class UserStatus extends Ba",
"end": 138,
"score": 0.9992855191230774,
"start": 135,
"tag": "NAME",
"value": "庞先海"
}
] | null |
[] |
package com.andy.recruitment.user.constant;
import com.xgimi.commons.base.BaseType;
import java.util.List;
/**
* 用户状态
*
* @author 庞先海 2018-12-28
*/
public class UserStatus extends BaseType {
public static final UserStatus NORMAL = new UserStatus(1, "正常");
public static final UserStatus FREEZE = new UserStatus(2, "冻结");
public UserStatus(int code, String desc) {
super(code, desc);
}
public static List<UserStatus> getValues() {
return BaseType.getValues(UserStatus.class);
}
public static UserStatus parse(Integer code) {
return BaseType.parse(UserStatus.getValues(), code);
}
}
| 670 | 0.682099 | 0.666667 | 28 | 22.142857 | 23.761786 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464286 | false | false |
10
|
988ba83da08035b268a6460b151209e553e20a1a
| 39,127,152,082,665 |
4cb47003ba7551d4ead9473fe66b8f6f766203b2
|
/src/Model/Account.java
|
0f90650586ebc464550ac688a1559b6350a253d7
|
[] |
no_license
|
AfonsoTaborda/Semester-Project-2-Market-Place-Client-Server-System
|
https://github.com/AfonsoTaborda/Semester-Project-2-Market-Place-Client-Server-System
|
9fc7bb939a9ffe2693efdb168ef17dfd8637f5fe
|
9259ee8433bddfac0d303ea2b3298020b3053b5b
|
refs/heads/master
| 2021-06-16T22:25:36.322000 | 2017-06-11T21:37:47 | 2017-06-11T21:37:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Model;
import java.io.Serializable;
/**
* Created by Afonso on 5/25/2017.
*/
public class Account implements Serializable{
private int accountID;
private String userName;
private String email;
private Person person;
public Account(int accountID, String userName, String email, Person person) {
this.accountID = accountID;
this.userName = userName;
this.email = email;
this.person = person;
}
/*
public void setAccountID(int accountID) {
this.accountID = accountID;
}*/
public int getAccountID() {
return accountID;
}
public Person getPerson()
{
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
|
UTF-8
|
Java
| 1,054 |
java
|
Account.java
|
Java
|
[
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by Afonso on 5/25/2017.\n */\npublic class Account implements",
"end": 70,
"score": 0.9983446002006531,
"start": 64,
"tag": "USERNAME",
"value": "Afonso"
},
{
"context": "izable{\n\tprivate int accountID;\n private String userName;\n private String email;\n private Person per",
"end": 186,
"score": 0.8567949533462524,
"start": 178,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " person;\n\n public Account(int accountID, String userName, String email, Person person) {\n \tthis.account",
"end": 291,
"score": 0.7687373757362366,
"start": 283,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "his.accountID = accountID;\n this.userName = userName;\n this.email = email;\n this.person ",
"end": 389,
"score": 0.9988953471183777,
"start": 381,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "serName(String userName) {\n this.userName = userName;\n }\n\n public String getUserName() {\n ",
"end": 842,
"score": 0.9985224604606628,
"start": 834,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "\n\n public String getUserName() {\n return userName;\n }\n\n public void setEmail(String email) {\n",
"end": 908,
"score": 0.9984032511711121,
"start": 900,
"tag": "USERNAME",
"value": "userName"
}
] | null |
[] |
package Model;
import java.io.Serializable;
/**
* Created by Afonso on 5/25/2017.
*/
public class Account implements Serializable{
private int accountID;
private String userName;
private String email;
private Person person;
public Account(int accountID, String userName, String email, Person person) {
this.accountID = accountID;
this.userName = userName;
this.email = email;
this.person = person;
}
/*
public void setAccountID(int accountID) {
this.accountID = accountID;
}*/
public int getAccountID() {
return accountID;
}
public Person getPerson()
{
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
| 1,054 | 0.61575 | 0.609108 | 53 | 18.886793 | 16.999067 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490566 | false | false |
10
|
a06494ceb62ec450ae2a63b3f87f48c0e94522a7
| 15,238,543,974,007 |
f9b9009d6b004d9debe9fd0dd78aa0d25c92db96
|
/src/cn/itcast/ssh/utils/ManagerTaskHandler.java
|
0b693d86a0b3041bfa7f4ce24fd54f8a036de82d
|
[] |
no_license
|
Arcticxiong/activitiDemo02
|
https://github.com/Arcticxiong/activitiDemo02
|
f307a654947e35579855a49596428f8982dc41ad
|
df574c0e6a8f8a575e8e920a88ea8d7576f74c0d
|
refs/heads/master
| 2020-03-21T07:16:04.368000 | 2018-06-22T07:35:03 | 2018-06-22T07:35:03 | 138,270,776 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.itcast.ssh.utils;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import cn.itcast.ssh.domain.Employee;
import cn.itcast.ssh.service.IEmployeeService;
/**
* 员工经理任务分配
*
*/
@SuppressWarnings("serial")
public class ManagerTaskHandler implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
//* 获取当前登录人
Employee employee = SessionContext.get();
//* 通过当前登录人,获取当前登录人对应的审核人的对象
// 获取当前登录人的姓名
String name = employee.getName();
// 以名称作为查询条件,查询用户信息表,获取当前用户的信息
// 从web容器中获取spring容器的UI想
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
IEmployeeService employeeService = (IEmployeeService)ac.getBean("employeeService");
Employee employeeManager = employeeService.findEmployeeByName(name);
String managerName = employeeManager.getManager().getName();
//* 将审核人的办理人,设置到完成任务后下一个任务的办理人中
delegateTask.setAssignee(managerName);
}
}
|
UTF-8
|
Java
| 1,414 |
java
|
ManagerTaskHandler.java
|
Java
|
[] | null |
[] |
package cn.itcast.ssh.utils;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import cn.itcast.ssh.domain.Employee;
import cn.itcast.ssh.service.IEmployeeService;
/**
* 员工经理任务分配
*
*/
@SuppressWarnings("serial")
public class ManagerTaskHandler implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
//* 获取当前登录人
Employee employee = SessionContext.get();
//* 通过当前登录人,获取当前登录人对应的审核人的对象
// 获取当前登录人的姓名
String name = employee.getName();
// 以名称作为查询条件,查询用户信息表,获取当前用户的信息
// 从web容器中获取spring容器的UI想
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
IEmployeeService employeeService = (IEmployeeService)ac.getBean("employeeService");
Employee employeeManager = employeeService.findEmployeeByName(name);
String managerName = employeeManager.getManager().getName();
//* 将审核人的办理人,设置到完成任务后下一个任务的办理人中
delegateTask.setAssignee(managerName);
}
}
| 1,414 | 0.806397 | 0.805556 | 36 | 32 | 28.118795 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false |
10
|
10cb078b8f60c610cf7ac574c4b45a274f65b548
| 17,008,070,497,167 |
77203eac3d470151b087445a56dda2f1edcc02f1
|
/src/main/java/com/itlike/system/entity/Attribute.java
|
31e6e170db3866fb6310fb5b27a27d731a429609
|
[] |
no_license
|
1620272426/managementPro
|
https://github.com/1620272426/managementPro
|
48117d428097302a0cc4d49e7ae1b1d9c8f33e4c
|
ce08ea32d5b46caa1ce3f85589962b2a98de0f31
|
refs/heads/master
| 2023-02-12T04:11:07.665000 | 2021-01-08T05:52:51 | 2021-01-08T05:52:51 | 326,915,472 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.itlike.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author linlin
* @since 2021-01-05
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="Attribute对象", description="属性表")
public class Attribute implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 属性组id
*/
@TableId(value = "attributeId", type = IdType.AUTO)
@ApiModelProperty(value = "属性组id")
private Integer attributeid;
/**
* 属性名称
*/
@TableField("AttributeGroup")
@ApiModelProperty(value = "属性名称")
private String attributegroup;
/**
* 属性价格
*/
@ApiModelProperty(value = "属性价格")
private String price;
/**
* 图片
*/
@ApiModelProperty(value = "图片")
private String picture;
/**
* 产品id
*/
@ApiModelProperty(value = "产品id")
@TableField("productId")
private Integer productid;
}
|
UTF-8
|
Java
| 1,372 |
java
|
Attribute.java
|
Java
|
[
{
"context": "al.Accessors;\n\n/**\n * <p>\n *\n * </p>\n *\n * @author linlin\n * @since 2021-01-05\n */\n@Data\n@EqualsAndHashCode",
"end": 445,
"score": 0.9993420839309692,
"start": 439,
"tag": "USERNAME",
"value": "linlin"
}
] | null |
[] |
package com.itlike.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author linlin
* @since 2021-01-05
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="Attribute对象", description="属性表")
public class Attribute implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 属性组id
*/
@TableId(value = "attributeId", type = IdType.AUTO)
@ApiModelProperty(value = "属性组id")
private Integer attributeid;
/**
* 属性名称
*/
@TableField("AttributeGroup")
@ApiModelProperty(value = "属性名称")
private String attributegroup;
/**
* 属性价格
*/
@ApiModelProperty(value = "属性价格")
private String price;
/**
* 图片
*/
@ApiModelProperty(value = "图片")
private String picture;
/**
* 产品id
*/
@ApiModelProperty(value = "产品id")
@TableField("productId")
private Integer productid;
}
| 1,372 | 0.675115 | 0.668203 | 64 | 19.34375 | 17.585699 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28125 | false | false |
10
|
01437e449f71ac569fee389dc4c49440548cf51b
| 22,445,499,093,664 |
633458c2b404a3d46d9c59946b88a682a52fd5c6
|
/interview-programs/src/com/iq/test/Palindrome.java
|
d306e3e3ce039947a7f1a63b67c8856b4e22698c
|
[] |
no_license
|
harivattikalla/firstgit
|
https://github.com/harivattikalla/firstgit
|
f254ac7d81187a41347f976070f8ca6279aefa9a
|
098194a6e18e88ab6cad4f91cfb22d8456185a5e
|
refs/heads/master
| 2020-04-15T09:20:15.337000 | 2019-11-11T10:48:32 | 2019-11-11T10:48:32 | 164,545,782 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.iq.test;
public class Palindrome {
public static void main(String[] args) {
int n = 454;
int temp=n;
int sum=0;
while(n>0) {
int r=n%10;//4 5 4
sum=(sum*10)+r;// 4 45 454
n=n/10;//45 4 0
}
if(temp==sum) {
System.out.println("pal");
}
}
public static void m1(int n) {
String val=String.valueOf(n);
int len=val.length();
String reverse = "";
for(int i=len-1;i>=0;i--) {
reverse=reverse+val.charAt(i);
}
if(val.equals(reverse)) {
System.out.println("palindrome");
}
}
}
|
UTF-8
|
Java
| 558 |
java
|
Palindrome.java
|
Java
|
[] | null |
[] |
package com.iq.test;
public class Palindrome {
public static void main(String[] args) {
int n = 454;
int temp=n;
int sum=0;
while(n>0) {
int r=n%10;//4 5 4
sum=(sum*10)+r;// 4 45 454
n=n/10;//45 4 0
}
if(temp==sum) {
System.out.println("pal");
}
}
public static void m1(int n) {
String val=String.valueOf(n);
int len=val.length();
String reverse = "";
for(int i=len-1;i>=0;i--) {
reverse=reverse+val.charAt(i);
}
if(val.equals(reverse)) {
System.out.println("palindrome");
}
}
}
| 558 | 0.55914 | 0.510753 | 33 | 14.909091 | 12.551382 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false |
10
|
9d1517b1c24f88621c566fa65f70d9f189a5be22
| 25,615,184,961,013 |
fb174a0782e734c257643129f9bb67317cb0854d
|
/C0201-ActivityTest-Upgrade/app/src/main/java/com/example/activitytest/ThirdActivity.java
|
a899beaa988e3f248629365f37986b8f83e9e9dc
|
[] |
no_license
|
canwdev/learn_android_1stcode
|
https://github.com/canwdev/learn_android_1stcode
|
5f3b722663ed8aa7ecaf30ea856fdafcd4d62cd8
|
40c0f3b0a59ce4cd246782dbdc9928a8df84d960
|
refs/heads/master
| 2020-12-30T18:02:29.850000 | 2017-11-10T05:18:58 | 2017-11-10T05:18:58 | 90,942,806 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.activitytest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class ThirdActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
// TaskID 返回栈ID
Log.d("SecondActivity", "TaskID: "+getTaskId());
}
}
|
UTF-8
|
Java
| 446 |
java
|
ThirdActivity.java
|
Java
|
[] | null |
[] |
package com.example.activitytest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class ThirdActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
// TaskID 返回栈ID
Log.d("SecondActivity", "TaskID: "+getTaskId());
}
}
| 446 | 0.720455 | 0.718182 | 16 | 26.5 | 20.778595 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
10
|
482959764268b61c866a8f517138130ad77f941d
| 28,484,223,113,205 |
3f91c368edc6b789cc284fc1404c84807787cd2c
|
/src/main/java/com/sourcecoding/pb/business/authentication/controller/LinkedInAuthenticationProvider.java
|
8f616565a67a96dd5bc27c5fe1f9e2543bc4c9dd
|
[] |
no_license
|
revprez/conair
|
https://github.com/revprez/conair
|
ac6de70bb7321e60118eadf069733b2410e1ee76
|
1a05ccc449d4acf497bc5e8b098b972a73863156
|
refs/heads/master
| 2021-01-11T21:23:32.571000 | 2016-03-20T18:37:57 | 2016-03-20T18:37:57 | 78,776,035 | 1 | 0 | null | true | 2017-01-12T18:46:04 | 2017-01-12T18:46:04 | 2016-01-29T11:17:10 | 2016-03-20T18:38:37 | 2,148 | 0 | 0 | 0 | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sourcecoding.pb.business.authentication.controller;
import com.sourcecoding.pb.business.authentication.entity.User;
import javax.ws.rs.container.ContainerRequestContext;
/**
*
* @author Matthias
*/
public class LinkedInAuthenticationProvider implements AuthenticationProvider {
@Override
public User authenticateUser(ContainerRequestContext requestContext) {
return new User();
}
}
|
UTF-8
|
Java
| 606 |
java
|
LinkedInAuthenticationProvider.java
|
Java
|
[
{
"context": "tainer.ContainerRequestContext;\n\n/**\n *\n * @author Matthias\n */\npublic class LinkedInAuthenticationProvider i",
"end": 395,
"score": 0.9997877478599548,
"start": 387,
"tag": "NAME",
"value": "Matthias"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sourcecoding.pb.business.authentication.controller;
import com.sourcecoding.pb.business.authentication.entity.User;
import javax.ws.rs.container.ContainerRequestContext;
/**
*
* @author Matthias
*/
public class LinkedInAuthenticationProvider implements AuthenticationProvider {
@Override
public User authenticateUser(ContainerRequestContext requestContext) {
return new User();
}
}
| 606 | 0.768977 | 0.768977 | 22 | 26.545454 | 29.572296 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false |
10
|
e3c526aef32fc45c66b7d4d913e4b798b791c46d
| 14,843,406,988,717 |
3fd2ddc28dd0d249c339ab1a42f9ebeff741958e
|
/src/com/util/webServices/ws/ValidarComprobante.java
|
b9161347c258218394741cd79d325151f432c6b3
|
[] |
no_license
|
cimaitec/invoicec.cedetec.core
|
https://github.com/cimaitec/invoicec.cedetec.core
|
a1b461534e58b07bbba353b910dcd0a21dd41845
|
83b11210613d75f0ea2908c66ec328d6a052fcb3
|
refs/heads/master
| 2021-01-01T19:39:15.995000 | 2015-03-27T17:33:36 | 2015-03-27T17:33:36 | 32,995,604 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.util.webServices.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="validarComprobante", propOrder={"xml"})
public class ValidarComprobante
{
protected byte[] xml;
public byte[] getXml()
{
return this.xml;
}
public void setXml(byte[] value)
{
this.xml = ((byte[])value);
}
}
|
UTF-8
|
Java
| 457 |
java
|
ValidarComprobante.java
|
Java
|
[] | null |
[] |
package com.util.webServices.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="validarComprobante", propOrder={"xml"})
public class ValidarComprobante
{
protected byte[] xml;
public byte[] getXml()
{
return this.xml;
}
public void setXml(byte[] value)
{
this.xml = ((byte[])value);
}
}
| 457 | 0.733042 | 0.733042 | 21 | 20.809525 | 18.422604 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false |
10
|
4fb7b5fa860cc7bacfc7bad38c82d2a80355cadd
| 3,882,650,446,339 |
369c0956f3301255a1b28e55b5c66fccb9da0816
|
/org.eclipse.bpel.common.uiTest/src/org/eclipse/bpel/common/ui/layouts/FillParentLayoutTest.java
|
15efe01d364112ff2e5caf605d1981e06ba55bb3
|
[] |
no_license
|
mateusmangueira/sistema-real-es
|
https://github.com/mateusmangueira/sistema-real-es
|
1bdc2971214ee1189b57c0376e8f04b03752ac89
|
39750301e4e825232ce88c95ef0931d66986e6fc
|
refs/heads/master
| 2020-08-14T14:31:51.617000 | 2019-10-30T21:50:10 | 2019-10-30T21:50:10 | 215,184,277 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.eclipse.bpel.common.ui.layouts;
import org.eclipse.bpel.common.ui.tray.TrayScrollBar;
import org.eclipse.draw2d.IFigure;
import org.junit.*;
import static org.junit.Assert.*;
/**
* The class <code>FillParentLayoutTest</code> contains tests for the class <code>{@link FillParentLayout}</code>.
*
* @generatedBy CodePro at 14/10/19 22:32
* @author mateu
* @version $Revision: 1.0 $
*/
public class FillParentLayoutTest {
/**
* Run the FillParentLayout() constructor test.
*
* @throws Exception
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Test
public void testFillParentLayout_1()
throws Exception {
FillParentLayout result = new FillParentLayout();
// add additional test code here
assertNotNull(result);
assertEquals(true, result.getStretchMinorAxis());
assertEquals(true, result.isStretchMinorAxis());
assertEquals(0, result.getSpacing());
assertEquals(1, result.getMinorAlignment());
assertEquals(false, result.isHorizontal());
assertEquals(false, result.isObservingVisibility());
}
/**
* Run the void layout(IFigure) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Test
public void testLayout_1()
throws Exception {
FillParentLayout fixture = new FillParentLayout();
IFigure parent = new TrayScrollBar();
fixture.layout(parent);
// add additional test code here
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NullPointerException
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createButton(TrayScrollBar.java:93)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createDefaultUpButton(TrayScrollBar.java:89)
// at org.eclipse.draw2d.ScrollBar.initialize(ScrollBar.java:295)
// at org.eclipse.draw2d.ScrollBar.<init>(ScrollBar.java:69)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.<init>(TrayScrollBar.java:36)
}
/**
* Run the void layout(IFigure) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Test
public void testLayout_2()
throws Exception {
FillParentLayout fixture = new FillParentLayout();
IFigure parent = new TrayScrollBar();
fixture.layout(parent);
// add additional test code here
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NullPointerException
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createButton(TrayScrollBar.java:93)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createDefaultUpButton(TrayScrollBar.java:89)
// at org.eclipse.draw2d.ScrollBar.initialize(ScrollBar.java:295)
// at org.eclipse.draw2d.ScrollBar.<init>(ScrollBar.java:69)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.<init>(TrayScrollBar.java:36)
}
/**
* Run the void layout(IFigure) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Test
public void testLayout_3()
throws Exception {
FillParentLayout fixture = new FillParentLayout();
IFigure parent = new TrayScrollBar();
fixture.layout(parent);
// add additional test code here
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NullPointerException
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createButton(TrayScrollBar.java:93)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createDefaultUpButton(TrayScrollBar.java:89)
// at org.eclipse.draw2d.ScrollBar.initialize(ScrollBar.java:295)
// at org.eclipse.draw2d.ScrollBar.<init>(ScrollBar.java:69)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.<init>(TrayScrollBar.java:36)
}
/**
* Perform pre-test initialization.
*
* @throws Exception
* if the initialization fails for some reason
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Before
public void setUp()
throws Exception {
// add additional set up code here
}
/**
* Perform post-test clean-up.
*
* @throws Exception
* if the clean-up fails for some reason
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@After
public void tearDown()
throws Exception {
// Add additional tear down code here
}
/**
* Launch the test.
*
* @param args the command line arguments
*
* @generatedBy CodePro at 14/10/19 22:32
*/
public static void main(String[] args) {
new org.junit.runner.JUnitCore().run(FillParentLayoutTest.class);
}
}
|
UTF-8
|
Java
| 4,509 |
java
|
FillParentLayoutTest.java
|
Java
|
[
{
"context": " @generatedBy CodePro at 14/10/19 22:32\n * @author mateu\n * @version $Revision: 1.0 $\n */\npublic class Fil",
"end": 369,
"score": 0.9505842328071594,
"start": 364,
"tag": "USERNAME",
"value": "mateu"
}
] | null |
[] |
package org.eclipse.bpel.common.ui.layouts;
import org.eclipse.bpel.common.ui.tray.TrayScrollBar;
import org.eclipse.draw2d.IFigure;
import org.junit.*;
import static org.junit.Assert.*;
/**
* The class <code>FillParentLayoutTest</code> contains tests for the class <code>{@link FillParentLayout}</code>.
*
* @generatedBy CodePro at 14/10/19 22:32
* @author mateu
* @version $Revision: 1.0 $
*/
public class FillParentLayoutTest {
/**
* Run the FillParentLayout() constructor test.
*
* @throws Exception
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Test
public void testFillParentLayout_1()
throws Exception {
FillParentLayout result = new FillParentLayout();
// add additional test code here
assertNotNull(result);
assertEquals(true, result.getStretchMinorAxis());
assertEquals(true, result.isStretchMinorAxis());
assertEquals(0, result.getSpacing());
assertEquals(1, result.getMinorAlignment());
assertEquals(false, result.isHorizontal());
assertEquals(false, result.isObservingVisibility());
}
/**
* Run the void layout(IFigure) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Test
public void testLayout_1()
throws Exception {
FillParentLayout fixture = new FillParentLayout();
IFigure parent = new TrayScrollBar();
fixture.layout(parent);
// add additional test code here
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NullPointerException
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createButton(TrayScrollBar.java:93)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createDefaultUpButton(TrayScrollBar.java:89)
// at org.eclipse.draw2d.ScrollBar.initialize(ScrollBar.java:295)
// at org.eclipse.draw2d.ScrollBar.<init>(ScrollBar.java:69)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.<init>(TrayScrollBar.java:36)
}
/**
* Run the void layout(IFigure) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Test
public void testLayout_2()
throws Exception {
FillParentLayout fixture = new FillParentLayout();
IFigure parent = new TrayScrollBar();
fixture.layout(parent);
// add additional test code here
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NullPointerException
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createButton(TrayScrollBar.java:93)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createDefaultUpButton(TrayScrollBar.java:89)
// at org.eclipse.draw2d.ScrollBar.initialize(ScrollBar.java:295)
// at org.eclipse.draw2d.ScrollBar.<init>(ScrollBar.java:69)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.<init>(TrayScrollBar.java:36)
}
/**
* Run the void layout(IFigure) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Test
public void testLayout_3()
throws Exception {
FillParentLayout fixture = new FillParentLayout();
IFigure parent = new TrayScrollBar();
fixture.layout(parent);
// add additional test code here
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NullPointerException
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createButton(TrayScrollBar.java:93)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.createDefaultUpButton(TrayScrollBar.java:89)
// at org.eclipse.draw2d.ScrollBar.initialize(ScrollBar.java:295)
// at org.eclipse.draw2d.ScrollBar.<init>(ScrollBar.java:69)
// at org.eclipse.bpel.common.ui.tray.TrayScrollBar.<init>(TrayScrollBar.java:36)
}
/**
* Perform pre-test initialization.
*
* @throws Exception
* if the initialization fails for some reason
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@Before
public void setUp()
throws Exception {
// add additional set up code here
}
/**
* Perform post-test clean-up.
*
* @throws Exception
* if the clean-up fails for some reason
*
* @generatedBy CodePro at 14/10/19 22:32
*/
@After
public void tearDown()
throws Exception {
// Add additional tear down code here
}
/**
* Launch the test.
*
* @param args the command line arguments
*
* @generatedBy CodePro at 14/10/19 22:32
*/
public static void main(String[] args) {
new org.junit.runner.JUnitCore().run(FillParentLayoutTest.class);
}
}
| 4,509 | 0.705478 | 0.67709 | 152 | 28.671053 | 28.242086 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.328947 | false | false |
10
|
db38c6f2812a54c3307a9142eb39d371029145a5
| 5,660,766,914,304 |
4f2748323c3766417fa5fcde3f1edc78e01851c8
|
/src/main/java/me/pauzen/alphacore/points/TrackerLeaderboard.java
|
6ad0e4372b3b202a95e1bd8aec079fe8def01933
|
[] |
no_license
|
BuzzyOG/AlphaCore
|
https://github.com/BuzzyOG/AlphaCore
|
2ae9205570cc1c0f6872aa33e8344ee40f58d7c5
|
53c1a91428f298414419cad7bbd9ad00b411a069
|
refs/heads/master
| 2021-01-18T02:49:12.728000 | 2015-02-19T14:22:36 | 2015-02-19T14:22:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Created by Filip P. on 2/2/15 11:16 PM.
*/
package me.pauzen.alphacore.points;
import me.pauzen.alphacore.utils.misc.Todo;
import me.pauzen.alphacore.utils.reflection.Nullifiable;
import me.pauzen.alphacore.utils.reflection.Nullify;
@Todo("Allow use for any Tracker." +
"Revise.")
public class TrackerLeaderboard implements Nullifiable {
@Nullify
private static TrackerLeaderboard manager;
public static void registerManager() {
manager = new TrackerLeaderboard();
}
public static TrackerLeaderboard getManager() {
return manager;
}
/*private TreeSet<CorePlayer> sortedPoints = new TreeSet<>((o1, o2) -> {
int difference = o1 - o2.getPoints();
return difference == 0 ? 1 : difference;
}
);
public TreeSet<CorePlayer> getArrangedPlayers() {
return sortedPoints;
}
private TrackerLeaderboard() {
}
public void update() {
FakeCorePlayer fakeMyPlayer = new FakeCorePlayer(null);
sortedPoints.add(fakeMyPlayer);
sortedPoints.remove(fakeMyPlayer);
}
*/
}
|
UTF-8
|
Java
| 1,099 |
java
|
TrackerLeaderboard.java
|
Java
|
[
{
"context": "/*\n * Created by Filip P. on 2/2/15 11:16 PM.\n */\n\npackage me.pauzen.alphac",
"end": 25,
"score": 0.9998272657394409,
"start": 18,
"tag": "NAME",
"value": "Filip P"
}
] | null |
[] |
/*
* Created by <NAME>. on 2/2/15 11:16 PM.
*/
package me.pauzen.alphacore.points;
import me.pauzen.alphacore.utils.misc.Todo;
import me.pauzen.alphacore.utils.reflection.Nullifiable;
import me.pauzen.alphacore.utils.reflection.Nullify;
@Todo("Allow use for any Tracker." +
"Revise.")
public class TrackerLeaderboard implements Nullifiable {
@Nullify
private static TrackerLeaderboard manager;
public static void registerManager() {
manager = new TrackerLeaderboard();
}
public static TrackerLeaderboard getManager() {
return manager;
}
/*private TreeSet<CorePlayer> sortedPoints = new TreeSet<>((o1, o2) -> {
int difference = o1 - o2.getPoints();
return difference == 0 ? 1 : difference;
}
);
public TreeSet<CorePlayer> getArrangedPlayers() {
return sortedPoints;
}
private TrackerLeaderboard() {
}
public void update() {
FakeCorePlayer fakeMyPlayer = new FakeCorePlayer(null);
sortedPoints.add(fakeMyPlayer);
sortedPoints.remove(fakeMyPlayer);
}
*/
}
| 1,098 | 0.66697 | 0.654231 | 45 | 23.422222 | 22.520597 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
10
|
c2cba7bf8fac9c44d3905dbd33fa4ac36e61afe1
| 14,723,147,908,517 |
807dc74f7d58fc192ff88415c27a6d6ffd463483
|
/Quit.java
|
faf0dd812189c56e448af183a9c78bd135cfa919
|
[] |
no_license
|
brr3/IOOPM-Inlupp3
|
https://github.com/brr3/IOOPM-Inlupp3
|
b2674bcf9d30d4149cbbaa5816efd9e1ef0b7bfc
|
2b11390a96def883b3756384a8307d02fd18ed77
|
refs/heads/master
| 2020-04-04T20:03:33.459000 | 2019-01-01T11:06:12 | 2019-01-01T11:06:12 | 156,232,403 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.ioopm.calculator.ast;
public class Quit extends Command {
private static final Quit theInstance = new Quit();
private Quit() {}
public static Quit instance() {
return theInstance;
}
public String getName() {
return "quit";
}
@Override
public boolean isCommand() {
return true;
}
}
|
UTF-8
|
Java
| 359 |
java
|
Quit.java
|
Java
|
[] | null |
[] |
package org.ioopm.calculator.ast;
public class Quit extends Command {
private static final Quit theInstance = new Quit();
private Quit() {}
public static Quit instance() {
return theInstance;
}
public String getName() {
return "quit";
}
@Override
public boolean isCommand() {
return true;
}
}
| 359 | 0.607242 | 0.607242 | 21 | 16.095238 | 15.868221 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.238095 | false | false |
10
|
94705663bbcc48dd6e8af580de9ab57becd45c37
| 25,151,328,510,786 |
e32479a53c8ade548fd7e100e6dd4ceba9f92f8e
|
/tool/symbolicexecution/jpf-symbc-differential/src/main/gov/nasa/jpf/symbc/bytecode/shadow/util/IFInstrSymbHelper.java
|
e65ec6dbf0a1a1d8413744e6aa29d88f88dadb17
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
yannicnoller/hydiff
|
https://github.com/yannicnoller/hydiff
|
5d4981006523c6a7ce6afcc0f44017799359c65c
|
4df7df1d2f00bf28d6fb2e2ed7a14103084c39f3
|
refs/heads/master
| 2021-08-28T03:42:09.297000 | 2021-08-09T07:02:18 | 2021-08-09T07:02:18 | 207,993,923 | 24 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package gov.nasa.jpf.symbc.bytecode.shadow.util;
import gov.nasa.jpf.jvm.bytecode.IfInstruction;
import gov.nasa.jpf.symbc.bytecode.shadow.LCMP;
import gov.nasa.jpf.symbc.numeric.Comparator;
import gov.nasa.jpf.vm.Instruction;
import gov.nasa.jpf.vm.ThreadInfo;
public class IFInstrSymbHelper {
public static Instruction getNextInstructionAndSetPCChoiceLong(ThreadInfo ti,
LCMP instr,
Object op_v1,
Object op_v2,
Comparator firstComparator,
Comparator secondComparator,
Comparator thirdComparator) {
throw new UnsupportedOperationException();
}
public static Instruction getNextInstructionAndSetPCChoiceReal(ThreadInfo ti,
Instruction instr,
Object op_v1,
Object op_v2,
Comparator firstComparator,
Comparator secondComparator,
Comparator thirdComparator) {
throw new UnsupportedOperationException(instr.getSourceLine());
}
//handles symbolic integer if-instructions with a single operand
public static Instruction getNextInstructionAndSetPCChoice(ThreadInfo ti,
IfInstruction instr,
Object op_v,
Comparator trueComparator,
Comparator falseComparator){
throw new UnsupportedOperationException();
}
}
|
UTF-8
|
Java
| 1,272 |
java
|
IFInstrSymbHelper.java
|
Java
|
[] | null |
[] |
package gov.nasa.jpf.symbc.bytecode.shadow.util;
import gov.nasa.jpf.jvm.bytecode.IfInstruction;
import gov.nasa.jpf.symbc.bytecode.shadow.LCMP;
import gov.nasa.jpf.symbc.numeric.Comparator;
import gov.nasa.jpf.vm.Instruction;
import gov.nasa.jpf.vm.ThreadInfo;
public class IFInstrSymbHelper {
public static Instruction getNextInstructionAndSetPCChoiceLong(ThreadInfo ti,
LCMP instr,
Object op_v1,
Object op_v2,
Comparator firstComparator,
Comparator secondComparator,
Comparator thirdComparator) {
throw new UnsupportedOperationException();
}
public static Instruction getNextInstructionAndSetPCChoiceReal(ThreadInfo ti,
Instruction instr,
Object op_v1,
Object op_v2,
Comparator firstComparator,
Comparator secondComparator,
Comparator thirdComparator) {
throw new UnsupportedOperationException(instr.getSourceLine());
}
//handles symbolic integer if-instructions with a single operand
public static Instruction getNextInstructionAndSetPCChoice(ThreadInfo ti,
IfInstruction instr,
Object op_v,
Comparator trueComparator,
Comparator falseComparator){
throw new UnsupportedOperationException();
}
}
| 1,272 | 0.728774 | 0.725629 | 42 | 29.285715 | 23.080898 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.285714 | false | false |
10
|
9ab203f8f0cfff86181093a2e6746be61a6f560c
| 3,401,614,166,656 |
c0b38cc5e0c7cf40391518906dc378232c6b2b23
|
/src/d3bcSoftware/d3bot/commands/GuildLog.java
|
42073c7ff59c83d1dc052a9fa9f20a05bbb4020c
|
[] |
no_license
|
BACompton/D3Bot
|
https://github.com/BACompton/D3Bot
|
62b3aace0ee9ce4c91e45f67a51de795c5ac704e
|
ba3db09b6c917b47dabe1fa9b7a0d5338745a5a9
|
refs/heads/master
| 2021-01-23T13:30:26.194000 | 2017-10-08T11:49:58 | 2017-10-08T11:49:58 | 102,666,926 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package d3bcSoftware.d3bot.commands;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import d3bcSoftware.d3bot.Bot;
import d3bcSoftware.d3bot.Command;
import d3bcSoftware.d3bot.logging.Emote;
import d3bcSoftware.d3bot.logging.Format;
import d3bcSoftware.d3bot.logging.LogState;
import d3bcSoftware.d3bot.logging.Logger;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
/**
* Details the GuildLog command. This command allows guilds served by D3-Bot to manage the text channel where the bot
* will log its activity.
* @author Boyd Compton
*/
public class GuildLog implements Command {
/*---- Constants ----*/
private final static String USAGE = Format.CODE + "%s%s %s";
private final static String HANDLE = "log";
private final static String FILE = "/guilds.json";
private final static String SAVE_GUILD = "Saving guilds' logging channels.";
private final static String LOAD_GUILD = "Loading guilds' logging channels.";
private final static String LOAD_ERROR = "Unable to load guilds' logging channels.";
private final static String SAVE_ERROR = "Unable to save guilds' logging channels.";
private final static String PERM_WARNING = Emote.X + " Administrator permission required to preform this action.";
private final static String ACTION_UNKN = Emote.QUESTION_MARK
+ "Unknown action. Please refer the following usage.\n\n%s";
private final static String SET_CHANNEL = Emote.CHECK + " Updated logging channel from "
+ Format.CODE + "%s" + Format.CODE + " to " + Format.CODE + "%s" + Format.CODE + ".";
private final static String REMOVED_CHANNEL = Emote.CHECK + " Removed Guild's Logging channel.";
private final static String LOG_CHANNEL = "Current logging channel is " + Format.CODE + "%s" + Format.CODE + ".";
/**
* Details actions that are supported within the GuildLog command.
* @author Boyd Compton
*/
private enum Action {
SET("set", "Binds the text channel as the guild's logging channel."),
REMOVE("remove", "Unbinds a text channel as the guild's logging channel."),
HELP("?", "Outputs the command usage.");
/*---- Constants ----*/
private final static String ACTION_DESC = "-%s: %s\n\n";
private final static String END_NOTE = Format.ITALICS + "Requires administrator permission" + Format.ITALICS;
/*---- Instance Variables ----*/
public String name;
private String description;
/*---- Constructors ----*/
private Action(String name, String description) {
this.name = name;
this.description = description;
}
/*---- Helper Functions ----*/
/**
* Builds the usage and descriptions for viable action.
* @return Formatted usage for all available actions.
*/
public static String usage() {
String usage = "[";
String desc = Format.CODE_BLOCK.toString();
// Build the usage and description for each action.
for(Action a: values()) {
usage += a.name + "|";
desc += String.format(ACTION_DESC, a.name, a.description);
}
usage = usage.substring(0, usage.length()-1) + "]" + Format.CODE + "\n";
desc += Format.CODE_BLOCK + "\n" + END_NOTE;
return usage + desc;
}
/**
* Retrieves the action with the specified identifier.
* @param name The action identifier
* @return The action that exactly matches identifier or null if no action is found.
*/
public static Action find(String name) {
for(Action a: values())
if(a.name.equals(name))
return a;
return null;
}
}
/*---- Constructors ----*/
@Override
public void loadData() {
File guildsFile = new File(getDataPath() + FILE);
if(guildsFile.exists()) {
JSONParser parser = new JSONParser();
try {
JSONObject guilds = (JSONObject)(parser.parse(new FileReader(guildsFile)));
Logger logger = Bot.getLogger();
JDA bot = Bot.getBot();
logger.serverLog(LogState.INFO, LOAD_GUILD);
// Set active active logging channels
if(bot != null)
for(Object key:guilds.keySet()) {
Guild g = bot.getGuildById(Long.parseLong((String) key));
TextChannel chan = g.getTextChannelById(Long.parseLong((String)guilds.get(key)));
logger.setGuildLogging(g, chan);
}
} catch (IOException | ParseException e) {
Bot.getLogger().serverLog(LogState.WARNING, LOAD_ERROR);
}
}
}
/*---- Command Actions ----*/
@SuppressWarnings("unchecked")
@Override
public void saveData() {
JSONObject guilds = new JSONObject();
String guildsStr = "";
if(Bot.getBot() == null)
return;
// Build JSONObject
for(Guild g: Bot.getLogger().getGuilds())
guilds.put(g.getId(), Bot.getLogger().getGuildLogging(g).getId());
guildsStr = guilds.toJSONString();
try {
Bot.getLogger().serverLog(LogState.INFO, SAVE_GUILD);
PrintWriter guildPW = new PrintWriter(getDataPath() + FILE);
guildPW.print(guildsStr);
guildPW.flush();
guildPW.close();
} catch (FileNotFoundException e) {
Bot.getLogger().serverLog(LogState.WARNING, SAVE_ERROR);
}
}
@Override
public void action(MessageReceivedEvent e, String[] args) {
TextChannel log = Bot.getLogger().getGuildLogging(e.getGuild());
String channel = log == null ? "none" : log.getName();
// Detail the current logging channel.
if(args.length == 0) {
e.getTextChannel()
.sendMessage(String.format(LOG_CHANNEL, channel))
.queue();
} else if(e.getMember().hasPermission(Permission.ADMINISTRATOR)) {
Action action = Action.find(args[0]);
if(action == Action.SET) {
TextChannel chan = e.getTextChannel();
Bot.getLogger().setGuildLogging(e.getGuild(), chan);
chan.sendMessage(String.format(SET_CHANNEL, channel, chan.getName()))
.queue();
} else if(action == Action.REMOVE) {
Bot.getLogger().setGuildLogging(e.getGuild(), null);
e.getTextChannel().sendMessage(REMOVED_CHANNEL).queue();;
} else if(action == Action.HELP) {
e.getTextChannel().sendMessage(help()).queue();
}
// Response to an unknown action.
else if(action == null) {
e.getTextChannel().sendMessage(String.format(ACTION_UNKN, help())).queue();;
}
}
// Missing Permission response.
else
e.getTextChannel().sendMessage(PERM_WARNING).queue();
}
@Override
public String getHandle() {
return HANDLE;
}
@Override
public String help() {
return String.format(USAGE, Bot.getPrefix(), HANDLE, Action.usage());
}
@Override
public String getDataPath() {
return String.format(DATA_PATH, HANDLE);
}
}
|
UTF-8
|
Java
| 8,193 |
java
|
GuildLog.java
|
Java
|
[
{
"context": "where the bot\n * will log its activity.\n * @author Boyd Compton\n */\npublic class GuildLog implements Command {\n ",
"end": 944,
"score": 0.9998458027839661,
"start": 932,
"tag": "NAME",
"value": "Boyd Compton"
},
{
"context": "ported within the GuildLog command.\n * @author Boyd Compton\n */\n private enum Action {\n SET(\"se",
"end": 2336,
"score": 0.9998522996902466,
"start": 2324,
"tag": "NAME",
"value": "Boyd Compton"
}
] | null |
[] |
package d3bcSoftware.d3bot.commands;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import d3bcSoftware.d3bot.Bot;
import d3bcSoftware.d3bot.Command;
import d3bcSoftware.d3bot.logging.Emote;
import d3bcSoftware.d3bot.logging.Format;
import d3bcSoftware.d3bot.logging.LogState;
import d3bcSoftware.d3bot.logging.Logger;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
/**
* Details the GuildLog command. This command allows guilds served by D3-Bot to manage the text channel where the bot
* will log its activity.
* @author <NAME>
*/
public class GuildLog implements Command {
/*---- Constants ----*/
private final static String USAGE = Format.CODE + "%s%s %s";
private final static String HANDLE = "log";
private final static String FILE = "/guilds.json";
private final static String SAVE_GUILD = "Saving guilds' logging channels.";
private final static String LOAD_GUILD = "Loading guilds' logging channels.";
private final static String LOAD_ERROR = "Unable to load guilds' logging channels.";
private final static String SAVE_ERROR = "Unable to save guilds' logging channels.";
private final static String PERM_WARNING = Emote.X + " Administrator permission required to preform this action.";
private final static String ACTION_UNKN = Emote.QUESTION_MARK
+ "Unknown action. Please refer the following usage.\n\n%s";
private final static String SET_CHANNEL = Emote.CHECK + " Updated logging channel from "
+ Format.CODE + "%s" + Format.CODE + " to " + Format.CODE + "%s" + Format.CODE + ".";
private final static String REMOVED_CHANNEL = Emote.CHECK + " Removed Guild's Logging channel.";
private final static String LOG_CHANNEL = "Current logging channel is " + Format.CODE + "%s" + Format.CODE + ".";
/**
* Details actions that are supported within the GuildLog command.
* @author <NAME>
*/
private enum Action {
SET("set", "Binds the text channel as the guild's logging channel."),
REMOVE("remove", "Unbinds a text channel as the guild's logging channel."),
HELP("?", "Outputs the command usage.");
/*---- Constants ----*/
private final static String ACTION_DESC = "-%s: %s\n\n";
private final static String END_NOTE = Format.ITALICS + "Requires administrator permission" + Format.ITALICS;
/*---- Instance Variables ----*/
public String name;
private String description;
/*---- Constructors ----*/
private Action(String name, String description) {
this.name = name;
this.description = description;
}
/*---- Helper Functions ----*/
/**
* Builds the usage and descriptions for viable action.
* @return Formatted usage for all available actions.
*/
public static String usage() {
String usage = "[";
String desc = Format.CODE_BLOCK.toString();
// Build the usage and description for each action.
for(Action a: values()) {
usage += a.name + "|";
desc += String.format(ACTION_DESC, a.name, a.description);
}
usage = usage.substring(0, usage.length()-1) + "]" + Format.CODE + "\n";
desc += Format.CODE_BLOCK + "\n" + END_NOTE;
return usage + desc;
}
/**
* Retrieves the action with the specified identifier.
* @param name The action identifier
* @return The action that exactly matches identifier or null if no action is found.
*/
public static Action find(String name) {
for(Action a: values())
if(a.name.equals(name))
return a;
return null;
}
}
/*---- Constructors ----*/
@Override
public void loadData() {
File guildsFile = new File(getDataPath() + FILE);
if(guildsFile.exists()) {
JSONParser parser = new JSONParser();
try {
JSONObject guilds = (JSONObject)(parser.parse(new FileReader(guildsFile)));
Logger logger = Bot.getLogger();
JDA bot = Bot.getBot();
logger.serverLog(LogState.INFO, LOAD_GUILD);
// Set active active logging channels
if(bot != null)
for(Object key:guilds.keySet()) {
Guild g = bot.getGuildById(Long.parseLong((String) key));
TextChannel chan = g.getTextChannelById(Long.parseLong((String)guilds.get(key)));
logger.setGuildLogging(g, chan);
}
} catch (IOException | ParseException e) {
Bot.getLogger().serverLog(LogState.WARNING, LOAD_ERROR);
}
}
}
/*---- Command Actions ----*/
@SuppressWarnings("unchecked")
@Override
public void saveData() {
JSONObject guilds = new JSONObject();
String guildsStr = "";
if(Bot.getBot() == null)
return;
// Build JSONObject
for(Guild g: Bot.getLogger().getGuilds())
guilds.put(g.getId(), Bot.getLogger().getGuildLogging(g).getId());
guildsStr = guilds.toJSONString();
try {
Bot.getLogger().serverLog(LogState.INFO, SAVE_GUILD);
PrintWriter guildPW = new PrintWriter(getDataPath() + FILE);
guildPW.print(guildsStr);
guildPW.flush();
guildPW.close();
} catch (FileNotFoundException e) {
Bot.getLogger().serverLog(LogState.WARNING, SAVE_ERROR);
}
}
@Override
public void action(MessageReceivedEvent e, String[] args) {
TextChannel log = Bot.getLogger().getGuildLogging(e.getGuild());
String channel = log == null ? "none" : log.getName();
// Detail the current logging channel.
if(args.length == 0) {
e.getTextChannel()
.sendMessage(String.format(LOG_CHANNEL, channel))
.queue();
} else if(e.getMember().hasPermission(Permission.ADMINISTRATOR)) {
Action action = Action.find(args[0]);
if(action == Action.SET) {
TextChannel chan = e.getTextChannel();
Bot.getLogger().setGuildLogging(e.getGuild(), chan);
chan.sendMessage(String.format(SET_CHANNEL, channel, chan.getName()))
.queue();
} else if(action == Action.REMOVE) {
Bot.getLogger().setGuildLogging(e.getGuild(), null);
e.getTextChannel().sendMessage(REMOVED_CHANNEL).queue();;
} else if(action == Action.HELP) {
e.getTextChannel().sendMessage(help()).queue();
}
// Response to an unknown action.
else if(action == null) {
e.getTextChannel().sendMessage(String.format(ACTION_UNKN, help())).queue();;
}
}
// Missing Permission response.
else
e.getTextChannel().sendMessage(PERM_WARNING).queue();
}
@Override
public String getHandle() {
return HANDLE;
}
@Override
public String help() {
return String.format(USAGE, Bot.getPrefix(), HANDLE, Action.usage());
}
@Override
public String getDataPath() {
return String.format(DATA_PATH, HANDLE);
}
}
| 8,181 | 0.573172 | 0.570243 | 216 | 36.930557 | 27.902605 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527778 | false | false |
10
|
a2023342d762bedf733a234e8f2e137c6badd8bb
| 12,403,865,564,485 |
36a858c0ec63ff3fde173a233a4bae5ecd6a4d86
|
/batch/batch-enrichment/src/main/java/ReplicatedMapEnrichment.java
|
02f1da5a66d72df7c9c75742fd6a49fd206b21be
|
[
"Apache-2.0"
] |
permissive
|
arundudani/hazelcast-jet-code-samples
|
https://github.com/arundudani/hazelcast-jet-code-samples
|
682a181c60cc9c181f6588b87ef85ca05d53e407
|
2c7df1ff0a6312c22af2c0d572bc396bd5bd6265
|
refs/heads/master
| 2020-03-21T16:04:08.230000 | 2018-06-25T12:00:22 | 2018-06-25T12:00:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. 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.
*/
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.pipeline.BatchSource;
import com.hazelcast.jet.pipeline.ContextFactories;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.Sources;
import trades.TickerInfo;
import trades.Trade;
import static com.hazelcast.jet.datamodel.Tuple2.tuple2;
/**
* This sample shows, how to enrich batch or stream of items with additional
* information by matching them by key. This version shows how to use {@link
* com.hazelcast.core.ReplicatedMap} from Hazelcast IMDG.
* <p>
* {@code ReplicatedMap} has an advantage in the ability to update the map while
* the job is running, however it does have a very small performance penalty. It
* is suitable if it is managed separately from the job or when used in a
* streaming job and you need to mutate it over time.
* <p>
* The {@code ReplicatedMap} can be even easily replaced with an {@code IMap}:
* it has considerably higher performance penalty, but might be suitable if the
* volume of the data is high.
*/
public class ReplicatedMapEnrichment {
private static final String TICKER_INFO_MAP_NAME = "tickerInfoMap";
private static final String TRADES_LIST_NAME = "tickerInfoMap";
public static void main(String[] args) {
System.setProperty("hazelcast.logging.type", "log4j");
JetInstance instance = Jet.newJetInstance();
Jet.newJetInstance();
try {
TickerInfo.populateMap(instance.getHazelcastInstance().getReplicatedMap(TICKER_INFO_MAP_NAME));
Trade.populateTrades(instance.getList(TRADES_LIST_NAME));
Pipeline p = Pipeline.create();
BatchSource<Trade> tradesSource = Sources.list(TRADES_LIST_NAME);
p.drawFrom(tradesSource)
.mapUsingContext(ContextFactories.replicatedMapContext(TICKER_INFO_MAP_NAME),
(map, trade) -> tuple2(trade, map.get(trade.getTicker())))
.drainTo(Sinks.logger());
instance.newJob(p).join();
} finally {
Jet.shutdownAll();
}
}
}
|
UTF-8
|
Java
| 2,787 |
java
|
ReplicatedMapEnrichment.java
|
Java
|
[
{
"context": "/*\n * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed",
"end": 32,
"score": 0.6051958203315735,
"start": 31,
"tag": "NAME",
"value": "H"
}
] | null |
[] |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. 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.
*/
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.pipeline.BatchSource;
import com.hazelcast.jet.pipeline.ContextFactories;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.Sources;
import trades.TickerInfo;
import trades.Trade;
import static com.hazelcast.jet.datamodel.Tuple2.tuple2;
/**
* This sample shows, how to enrich batch or stream of items with additional
* information by matching them by key. This version shows how to use {@link
* com.hazelcast.core.ReplicatedMap} from Hazelcast IMDG.
* <p>
* {@code ReplicatedMap} has an advantage in the ability to update the map while
* the job is running, however it does have a very small performance penalty. It
* is suitable if it is managed separately from the job or when used in a
* streaming job and you need to mutate it over time.
* <p>
* The {@code ReplicatedMap} can be even easily replaced with an {@code IMap}:
* it has considerably higher performance penalty, but might be suitable if the
* volume of the data is high.
*/
public class ReplicatedMapEnrichment {
private static final String TICKER_INFO_MAP_NAME = "tickerInfoMap";
private static final String TRADES_LIST_NAME = "tickerInfoMap";
public static void main(String[] args) {
System.setProperty("hazelcast.logging.type", "log4j");
JetInstance instance = Jet.newJetInstance();
Jet.newJetInstance();
try {
TickerInfo.populateMap(instance.getHazelcastInstance().getReplicatedMap(TICKER_INFO_MAP_NAME));
Trade.populateTrades(instance.getList(TRADES_LIST_NAME));
Pipeline p = Pipeline.create();
BatchSource<Trade> tradesSource = Sources.list(TRADES_LIST_NAME);
p.drawFrom(tradesSource)
.mapUsingContext(ContextFactories.replicatedMapContext(TICKER_INFO_MAP_NAME),
(map, trade) -> tuple2(trade, map.get(trade.getTicker())))
.drainTo(Sinks.logger());
instance.newJob(p).join();
} finally {
Jet.shutdownAll();
}
}
}
| 2,787 | 0.712235 | 0.706494 | 69 | 39.391304 | 29.644375 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false |
10
|
58149782b45696ac9d9655f861bba59068605518
| 11,940,009,149,688 |
df0ec490c97645c24459f8eefc72faf522174cf4
|
/rapidminer-extension-cluster-evaluation/rapidminer-extension-cluster-evaluation/src/main/java/com/rapidminer/operator/gui/DunnIndexIOObject.java
|
8d36e36ac415fab43271f425e800dbaa829ce3e5
|
[] |
no_license
|
Najah-lshanableh/RapidMiner-cluster-evaluation
|
https://github.com/Najah-lshanableh/RapidMiner-cluster-evaluation
|
25f709838cc9a275a31da88a69f7d6c0352a84ed
|
4aefdaa10c6942bf2010fd8afc2cbdd67d7cdf6e
|
refs/heads/master
| 2021-05-09T15:56:38.379000 | 2015-05-09T15:35:43 | 2015-05-09T15:35:43 | 119,103,568 | 0 | 1 | null | true | 2018-01-26T21:10:55 | 2018-01-26T21:10:55 | 2015-05-09T15:26:48 | 2015-05-09T15:36:15 | 2,020 | 0 | 0 | 0 | null | false | null |
package com.rapidminer.operator.gui;
import com.rapidminer.operator.DunnIndexData;
import com.rapidminer.operator.ResultObjectAdapter;
/**
* IO object for result of Dunn Index operator.
* @author Jan Jakeš
*
*/
public class DunnIndexIOObject extends ResultObjectAdapter {
/** Version. */
private static final long serialVersionUID = 1L;
/** Dunn Index value. */
private Double index;
/**
* Constructs a new instance.
* @param data {@link DunnIndexData}
*/
public DunnIndexIOObject(DunnIndexData data) {
index = data.getDunnIndex();
}
/** Prepares data to print. */
@Override
public String toResultString() {
StringBuilder builder = new StringBuilder();
builder.append("Dunn index of given clustered dataset:\n");
builder.append("Value: " + index);
return builder.toString();
}
/** Name of IO object. */
@Override
public String getName() {
return "Dunn Index";
}
}
|
WINDOWS-1250
|
Java
| 920 |
java
|
DunnIndexIOObject.java
|
Java
|
[
{
"context": "ject for result of Dunn Index operator.\n * @author Jan Jakeš\n *\n */\npublic class DunnIndexIOObject extends Res",
"end": 209,
"score": 0.9998226761817932,
"start": 200,
"tag": "NAME",
"value": "Jan Jakeš"
}
] | null |
[] |
package com.rapidminer.operator.gui;
import com.rapidminer.operator.DunnIndexData;
import com.rapidminer.operator.ResultObjectAdapter;
/**
* IO object for result of Dunn Index operator.
* @author <NAME>
*
*/
public class DunnIndexIOObject extends ResultObjectAdapter {
/** Version. */
private static final long serialVersionUID = 1L;
/** Dunn Index value. */
private Double index;
/**
* Constructs a new instance.
* @param data {@link DunnIndexData}
*/
public DunnIndexIOObject(DunnIndexData data) {
index = data.getDunnIndex();
}
/** Prepares data to print. */
@Override
public String toResultString() {
StringBuilder builder = new StringBuilder();
builder.append("Dunn index of given clustered dataset:\n");
builder.append("Value: " + index);
return builder.toString();
}
/** Name of IO object. */
@Override
public String getName() {
return "Dunn Index";
}
}
| 916 | 0.700762 | 0.699674 | 44 | 19.886364 | 19.086187 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false |
10
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.