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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36c9852fe321ecd376da8ad2fe6d9fa715088fd4 | 5,153,960,760,817 | 4126736869ef71d31e68d66e3cc9555747b54ee5 | /src/main/java/xyz/baddeveloper/lwsl/server/events/OnPacketSentEvent.java | 26c6a11017445bca89b0a346f5de32c70f33509b | [
"Apache-2.0"
] | permissive | StijnSimons/LWSL | https://github.com/StijnSimons/LWSL | cc648919d7e56dc4bc4e5084059a4130ad43240e | 6cb702741c487d6f4ecb1725546e3c5de3cbe176 | refs/heads/master | 2020-03-19T16:12:18.689000 | 2020-01-25T20:07:54 | 2020-01-25T20:07:54 | 136,705,245 | 18 | 6 | Apache-2.0 | false | 2020-10-12T23:15:21 | 2018-06-09T08:30:42 | 2020-10-12T06:59:30 | 2020-10-12T23:15:20 | 86 | 18 | 5 | 2 | Java | false | false | package xyz.baddeveloper.lwsl.server.events;
import xyz.baddeveloper.lwsl.packet.Packet;
import xyz.baddeveloper.lwsl.server.SocketHandler;
public interface OnPacketSentEvent {
void onPacketSent(SocketHandler socketHandler, Packet packet);
}
| UTF-8 | Java | 249 | java | OnPacketSentEvent.java | Java | [] | null | [] | package xyz.baddeveloper.lwsl.server.events;
import xyz.baddeveloper.lwsl.packet.Packet;
import xyz.baddeveloper.lwsl.server.SocketHandler;
public interface OnPacketSentEvent {
void onPacketSent(SocketHandler socketHandler, Packet packet);
}
| 249 | 0.823293 | 0.823293 | 9 | 26.666666 | 24.805914 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 6 |
ff2ed305d0027af5a947275cf9c86a08997ef419 | 13,082,470,393,116 | 99a31def937930c340ab6159ab994e4f07b00b6e | /fstcomp/composer/CmdLineInterpreter.java | 0b4ab0bf123fb631959de61e4423ca9aab2c93a1 | [] | no_license | DrThouraya/featureHouseExtension | https://github.com/DrThouraya/featureHouseExtension | 8d89d5d4eb4987402af1a96f65e18de2319628e8 | 442a07a52d5bf39af2eb35c3021190907821ed5e | refs/heads/master | 2020-04-13T09:19:31.650000 | 2016-09-14T22:04:06 | 2016-09-14T22:04:06 | 68,247,516 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package composer;
import java.io.File;
public class CmdLineInterpreter {
public static final String INPUT_OPTION_EQUATIONFILE = "--expression";
public static final String INPUT_OPTION_AHEAD_EQUATION_FILE = "--ahead";
public static final String INPUT_OPTION_BASE_DIRECTORY = "--base-directory";
public static final String INPUT_OPTION_SHOW_GUI = "--gui";
public static final String INPUT_OPTION_SHOW_XML = "--xml";
public static final String INPUT_OPTION_SHOW_SUM = "--sum";
public static final String INPUT_OPTION_SHOW_FST = "--fst";
public static final String INPUT_OPTION_FILE_OUTPUT = "--write";
public static final String INPUT_OPTION_OUTPUT_DIRECTORY = "--output-directory";
public static final String INPUT_OPTION_RESOLVE_REFERENCES = "--resolve-references";
public static final String INPUT_OPTION_HELP = "--help";
public static final String INPUT_OPTION_COUNT = "--count";
public boolean isCount = false;
public boolean isAheadEquationFile;
public String equationFileName;
public String equationBaseDirectoryName;
public String outputDirectoryName=null;
public boolean isBaseDirectoryName = false;
public boolean showXML = false;
public boolean showFST = false;
public boolean showSum = false;
public boolean showGui = false;
public boolean fileOutput = false;
public void parseCmdLineArguments(String[] args) {
boolean errorOccured = false;
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals(INPUT_OPTION_EQUATIONFILE)) {
i++;
if (i < args.length) {
equationFileName = args[i];
if(!isBaseDirectoryName)
equationBaseDirectoryName = getDirectoryName(new File(equationFileName)) + File.separator;
equationFileName = equationFileName.replace("\\", File.separator);
equationFileName = equationFileName.replace("/", File.separator);
} else {
System.out.println("Error occured option: " + INPUT_OPTION_EQUATIONFILE);
errorOccured = true;
}
} else if (args[i].equals(INPUT_OPTION_BASE_DIRECTORY)) {
i++;
if (i < args.length) {
equationBaseDirectoryName = args[i];
equationBaseDirectoryName = equationBaseDirectoryName.replace("\\", File.separator);
equationBaseDirectoryName = equationBaseDirectoryName.replace("/", File.separator);
isBaseDirectoryName = true;
} else {
System.out.println("Error occured option: " + INPUT_OPTION_BASE_DIRECTORY);
errorOccured = true;
}
} else if (args[i].equals(INPUT_OPTION_OUTPUT_DIRECTORY)) {
i++;
if (i < args.length) {
outputDirectoryName = args[i];
} else {
System.out.println("Error occured option: " + INPUT_OPTION_OUTPUT_DIRECTORY);
errorOccured = true;
}
} else if (args[i].equals(INPUT_OPTION_COUNT)) {
isCount = true;
} else if (args[i].equals(INPUT_OPTION_FILE_OUTPUT)) {
fileOutput = true;
} else if (args[i].equals(INPUT_OPTION_SHOW_GUI)) {
showGui = true;
} else if (args[i].equals(INPUT_OPTION_SHOW_XML)) {
showXML = true;
} else if (args[i].equals(INPUT_OPTION_SHOW_FST)) {
showFST = true;
} else if (args[i].equals(INPUT_OPTION_SHOW_SUM)) {
showSum = true;
} else if (args[i].equals(INPUT_OPTION_AHEAD_EQUATION_FILE)) {
isAheadEquationFile = true;
} else if (args[i].equals(INPUT_OPTION_RESOLVE_REFERENCES)) {
System.out.println("The option '" + INPUT_OPTION_RESOLVE_REFERENCES + "' is obsolete.");
} else if (args[i].equals(INPUT_OPTION_HELP)) {
printHelp(false);
} else {
errorOccured = true;
}
}
} else {
errorOccured = true;
}
if (errorOccured) {
printHelp(errorOccured);
}
}
private static void printHelp(boolean errorOccured) {
if (errorOccured) {
System.out.println("Incorrect command line parameters!");
}
System.out.println("Use `java -jar FeatureHouse.jar "
+ INPUT_OPTION_EQUATIONFILE + " <file name> ["
+ INPUT_OPTION_BASE_DIRECTORY + " <directory name>]'"
);
System.out.println("The option `" + INPUT_OPTION_EQUATIONFILE
+ "' defines the name of the file that lists the input features/components.");
System.out.println("The option `" + INPUT_OPTION_BASE_DIRECTORY
+ "' defines the working directory, which is the search path for the input features/components.");
}
private static String getDirectoryName(File file) {
String result = "";
if (file.isDirectory()) {
result = file.getPath();
} else {
result = file.getAbsoluteFile().getParentFile().getPath();
}
return result;
}
}
| UTF-8 | Java | 4,594 | java | CmdLineInterpreter.java | Java | [] | null | [] | package composer;
import java.io.File;
public class CmdLineInterpreter {
public static final String INPUT_OPTION_EQUATIONFILE = "--expression";
public static final String INPUT_OPTION_AHEAD_EQUATION_FILE = "--ahead";
public static final String INPUT_OPTION_BASE_DIRECTORY = "--base-directory";
public static final String INPUT_OPTION_SHOW_GUI = "--gui";
public static final String INPUT_OPTION_SHOW_XML = "--xml";
public static final String INPUT_OPTION_SHOW_SUM = "--sum";
public static final String INPUT_OPTION_SHOW_FST = "--fst";
public static final String INPUT_OPTION_FILE_OUTPUT = "--write";
public static final String INPUT_OPTION_OUTPUT_DIRECTORY = "--output-directory";
public static final String INPUT_OPTION_RESOLVE_REFERENCES = "--resolve-references";
public static final String INPUT_OPTION_HELP = "--help";
public static final String INPUT_OPTION_COUNT = "--count";
public boolean isCount = false;
public boolean isAheadEquationFile;
public String equationFileName;
public String equationBaseDirectoryName;
public String outputDirectoryName=null;
public boolean isBaseDirectoryName = false;
public boolean showXML = false;
public boolean showFST = false;
public boolean showSum = false;
public boolean showGui = false;
public boolean fileOutput = false;
public void parseCmdLineArguments(String[] args) {
boolean errorOccured = false;
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals(INPUT_OPTION_EQUATIONFILE)) {
i++;
if (i < args.length) {
equationFileName = args[i];
if(!isBaseDirectoryName)
equationBaseDirectoryName = getDirectoryName(new File(equationFileName)) + File.separator;
equationFileName = equationFileName.replace("\\", File.separator);
equationFileName = equationFileName.replace("/", File.separator);
} else {
System.out.println("Error occured option: " + INPUT_OPTION_EQUATIONFILE);
errorOccured = true;
}
} else if (args[i].equals(INPUT_OPTION_BASE_DIRECTORY)) {
i++;
if (i < args.length) {
equationBaseDirectoryName = args[i];
equationBaseDirectoryName = equationBaseDirectoryName.replace("\\", File.separator);
equationBaseDirectoryName = equationBaseDirectoryName.replace("/", File.separator);
isBaseDirectoryName = true;
} else {
System.out.println("Error occured option: " + INPUT_OPTION_BASE_DIRECTORY);
errorOccured = true;
}
} else if (args[i].equals(INPUT_OPTION_OUTPUT_DIRECTORY)) {
i++;
if (i < args.length) {
outputDirectoryName = args[i];
} else {
System.out.println("Error occured option: " + INPUT_OPTION_OUTPUT_DIRECTORY);
errorOccured = true;
}
} else if (args[i].equals(INPUT_OPTION_COUNT)) {
isCount = true;
} else if (args[i].equals(INPUT_OPTION_FILE_OUTPUT)) {
fileOutput = true;
} else if (args[i].equals(INPUT_OPTION_SHOW_GUI)) {
showGui = true;
} else if (args[i].equals(INPUT_OPTION_SHOW_XML)) {
showXML = true;
} else if (args[i].equals(INPUT_OPTION_SHOW_FST)) {
showFST = true;
} else if (args[i].equals(INPUT_OPTION_SHOW_SUM)) {
showSum = true;
} else if (args[i].equals(INPUT_OPTION_AHEAD_EQUATION_FILE)) {
isAheadEquationFile = true;
} else if (args[i].equals(INPUT_OPTION_RESOLVE_REFERENCES)) {
System.out.println("The option '" + INPUT_OPTION_RESOLVE_REFERENCES + "' is obsolete.");
} else if (args[i].equals(INPUT_OPTION_HELP)) {
printHelp(false);
} else {
errorOccured = true;
}
}
} else {
errorOccured = true;
}
if (errorOccured) {
printHelp(errorOccured);
}
}
private static void printHelp(boolean errorOccured) {
if (errorOccured) {
System.out.println("Incorrect command line parameters!");
}
System.out.println("Use `java -jar FeatureHouse.jar "
+ INPUT_OPTION_EQUATIONFILE + " <file name> ["
+ INPUT_OPTION_BASE_DIRECTORY + " <directory name>]'"
);
System.out.println("The option `" + INPUT_OPTION_EQUATIONFILE
+ "' defines the name of the file that lists the input features/components.");
System.out.println("The option `" + INPUT_OPTION_BASE_DIRECTORY
+ "' defines the working directory, which is the search path for the input features/components.");
}
private static String getDirectoryName(File file) {
String result = "";
if (file.isDirectory()) {
result = file.getPath();
} else {
result = file.getAbsoluteFile().getParentFile().getPath();
}
return result;
}
}
| 4,594 | 0.677188 | 0.676752 | 143 | 31.125874 | 27.859505 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.104895 | false | false | 6 |
efe240efc3c939735be2064e6556a85fd165dcec | 14,345,190,777,759 | 7da7ee1ed863d4cd4cadef835b16d8950c6952d6 | /AtCoder/ABC032/java/B問題/Main.java | 5c8ad802907e984f999f28c072985adb05ef1e3a | [] | no_license | rikuya6/ICPC_learning | https://github.com/rikuya6/ICPC_learning | 8fd226bcd9f13f37a4d55d6de57702d0ed7182b8 | d01e4c764f93f0330cc687365e3ac397e46f9559 | refs/heads/master | 2022-06-04T10:12:57.981000 | 2020-05-06T04:58:15 | 2020-05-06T04:58:15 | 52,092,562 | 0 | 0 | null | false | 2018-09-23T13:29:19 | 2016-02-19T14:20:22 | 2018-09-22T13:17:26 | 2018-09-23T13:29:19 | 478 | 0 | 0 | 0 | C++ | false | null | import java.util.*;
public class Main{
public static void main(String [] args){
String s;
// ArrayList<String> sub = new ArrayList<>();
int k, cnt = 0;
Set<String> set = new HashSet<>();
Scanner sc = new Scanner(System.in);
s = sc.next(); k = sc.nextInt(); sc.close();
for(int i=0; i<s.length()-k + 1; i++){
// sub.add(s.substring(i, i + k));
// System.out.println(sub.get(i));
if(set.add(s.substring(i, i + k))) cnt++;
}
System.out.println(cnt);
}
}
| UTF-8 | Java | 478 | java | Main.java | Java | [] | null | [] | import java.util.*;
public class Main{
public static void main(String [] args){
String s;
// ArrayList<String> sub = new ArrayList<>();
int k, cnt = 0;
Set<String> set = new HashSet<>();
Scanner sc = new Scanner(System.in);
s = sc.next(); k = sc.nextInt(); sc.close();
for(int i=0; i<s.length()-k + 1; i++){
// sub.add(s.substring(i, i + k));
// System.out.println(sub.get(i));
if(set.add(s.substring(i, i + k))) cnt++;
}
System.out.println(cnt);
}
}
| 478 | 0.587866 | 0.58159 | 18 | 25.555555 | 16.347689 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.611111 | false | false | 6 |
bd0687761d259b118fcc81ca253b9e52aaab6616 | 15,771,119,919,067 | e481d89bcee90cdf3ab1d173346d0bf9f0670194 | /business/src/main/java/com/liushuang/business/mongo/MongoServer.java | f08538c2a6be0a65df708638f1b2cef6e4c58cea | [] | no_license | liushuang1205/springcloud | https://github.com/liushuang1205/springcloud | ad62018976790f72e4ca3ffd6bfc45e3eb436a0f | 33dd6ef7f4246033d33b88d92423ce680ef58d55 | refs/heads/master | 2020-04-10T09:58:19.066000 | 2019-05-09T11:06:01 | 2019-05-09T11:06:01 | 160,950,617 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.liushuang.business.mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;
/**
* @author yangqi
* @date 2018/12/24 14:04
**/
public class MongoServer {
private static MongoClient client = null;
static {
client = new MongoClient(new ServerAddress("192.168.157.2", 27017),
new MongoClientOptions.Builder().build());
}
public static MongoClient getClient() {
return client;
}
public static MongoCollection<Document> getCollection(String db, String col) {
return client.getDatabase(db).getCollection(col);
}
public static final UpdateOptions UPSERT_OPTIONS = new UpdateOptions();
public static final BulkWriteOptions BULK_WRITE_OPTIONS = new BulkWriteOptions();
static {
UPSERT_OPTIONS.upsert(true);
BULK_WRITE_OPTIONS.ordered(false);
}
public static void close() {
if (client != null) {
client.close();
}
}
}
| UTF-8 | Java | 1,187 | java | MongoServer.java | Java | [
{
"context": "Options;\nimport org.bson.Document;\n\n/**\n * @author yangqi\n * @date 2018/12/24 14:04\n **/\npublic class Mongo",
"end": 332,
"score": 0.9992636442184448,
"start": 326,
"tag": "USERNAME",
"value": "yangqi"
},
{
"context": " client = new MongoClient(new ServerAdd... | null | [] | package com.liushuang.business.mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;
/**
* @author yangqi
* @date 2018/12/24 14:04
**/
public class MongoServer {
private static MongoClient client = null;
static {
client = new MongoClient(new ServerAddress("192.168.157.2", 27017),
new MongoClientOptions.Builder().build());
}
public static MongoClient getClient() {
return client;
}
public static MongoCollection<Document> getCollection(String db, String col) {
return client.getDatabase(db).getCollection(col);
}
public static final UpdateOptions UPSERT_OPTIONS = new UpdateOptions();
public static final BulkWriteOptions BULK_WRITE_OPTIONS = new BulkWriteOptions();
static {
UPSERT_OPTIONS.upsert(true);
BULK_WRITE_OPTIONS.ordered(false);
}
public static void close() {
if (client != null) {
client.close();
}
}
}
| 1,187 | 0.686605 | 0.663858 | 44 | 25.977272 | 24.313753 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 6 |
c5ecbf8f0fdad6c16f59e3f39f1b17c25fd35ed0 | 21,852,793,610,326 | 1495ebc01cbff3907b3acabc1799d44fd1f35ea1 | /src/test/java/browsers/Browser.java | 5a27ee9dd8bd2bb7672a6007e93e55f07270dce3 | [] | no_license | hi-cbh/anyptt | https://github.com/hi-cbh/anyptt | dc610b6f4c1e68be219e954646b0a0eb1460d166 | 40c1b7d302071df0da48767772f3d301608665ac | refs/heads/master | 2021-07-19T10:09:34.881000 | 2017-10-25T02:15:42 | 2017-10-25T02:15:42 | 108,208,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package browsers;
import java.util.Arrays;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Browser {
//打开浏览器
public static WebDriver open_browser(String browserName){
WebDriver driver;
if(browserName.equals("ie")){
System.setProperty("webdriver.ie.driver","C:\\Users\\Administrator\\workspace_work\\testapp\\run\\IEDriverServer1.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
driver = new InternetExplorerDriver(ieCapabilities);
//Log.info("IE 浏览器实例已经被声明");
}
else if(browserName.equals("chrome")){
System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
DesiredCapabilities capabilites = DesiredCapabilities.chrome();
capabilites.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
capabilites.setCapability("chrome.binary", "run/chromedriver.exe");
capabilites.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilites);
//Log.info("chrome 浏览器实例已经被声明");
}
else{
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
driver = new FirefoxDriver();
//Log.info("firefox 浏览器实例已经被声明");
}
driver.manage().window().maximize();
return driver;
}
}
| UTF-8 | Java | 1,856 | java | Browser.java | Java | [] | null | [] | package browsers;
import java.util.Arrays;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Browser {
//打开浏览器
public static WebDriver open_browser(String browserName){
WebDriver driver;
if(browserName.equals("ie")){
System.setProperty("webdriver.ie.driver","C:\\Users\\Administrator\\workspace_work\\testapp\\run\\IEDriverServer1.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
driver = new InternetExplorerDriver(ieCapabilities);
//Log.info("IE 浏览器实例已经被声明");
}
else if(browserName.equals("chrome")){
System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
DesiredCapabilities capabilites = DesiredCapabilities.chrome();
capabilites.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
capabilites.setCapability("chrome.binary", "run/chromedriver.exe");
capabilites.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilites);
//Log.info("chrome 浏览器实例已经被声明");
}
else{
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
driver = new FirefoxDriver();
//Log.info("firefox 浏览器实例已经被声明");
}
driver.manage().window().maximize();
return driver;
}
}
| 1,856 | 0.75028 | 0.7486 | 46 | 37.826088 | 33.495815 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.369565 | false | false | 6 |
52b0a5eff2ed7782f3d0c40f2f585f111916924a | 28,312,424,421,469 | 30bfc4341c64acd1059ef9db5aa4fb01ca78f9eb | /.svn/pristine/52/52b0a5eff2ed7782f3d0c40f2f585f111916924a.svn-base | 3e43b49450eb7cc9faf082e93f1e59cb5005893a | [] | no_license | cash2one/webTYJ_Java | https://github.com/cash2one/webTYJ_Java | bdd77157d2de4e3bce2db29a849ec4b8cf92d018 | 3c97f1adc9b889507ba0239f6d155efbe568f86f | refs/heads/master | 2021-08-19T22:33:31.256000 | 2017-11-27T15:54:03 | 2017-11-27T15:54:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.flf.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import com.flf.entity.PageRestful;
import com.flf.entity.Lost;
import com.flf.entity.Search;
import com.flf.mapper.LostMapper;
import com.flf.service.LostService;
public class LostServiceImpl implements LostService{
private LostMapper lostMapper;
public LostMapper getLostMapper() {
return lostMapper;
}
public void setLostMapper(LostMapper lostMapper) {
this.lostMapper = lostMapper;
}
@Override
public List<Lost> listAllLost() {
// TODO Auto-generated method stub
return lostMapper.listAllLost();
}
@Override
public PageRestful listPageAllLost(Lost lost) {
// TODO Auto-generated method stub
PageRestful pagerestful=new PageRestful();
List<Lost> losts=lostMapper.listPageLost(lost);
losts.add(0,null);
pagerestful.setLosts(losts);
pagerestful.setPage(lost.getPage());
return pagerestful;
//return lostMapper.listPageLost(lost);
}
@Override
public Lost getLostById(String id) {
// TODO Auto-generated method stub
return lostMapper.getLostById(id);
}
@Override
public int insertLost(Lost lost) {
// TODO Auto-generated method stub
return lostMapper.insertLost(lost);
}
@Override
public int updateLost(Lost lost) {
// TODO Auto-generated method stub
return lostMapper.updateLost( lost);
}
/*@Override
public PageRestful listPageLostRestful(Lost lost) {
// TODO Auto-generated method stub
PageRestful pagerestful=new PageRestful();
List<Lost> losts =lostMapper.listPageLost(lost);
losts.add(0,null);
pagerestful.setLosts(losts);
pagerestful.setPage(lost.getPage());
return pagerestful;
}*/
@Override
public List<Lost> listAllLostRestful() {
// TODO Auto-generated method stub
List<Lost>losts=lostMapper.listAllLost();
return losts;
}
@Override
public Lost getLostByIdRestful(String id) {
// TODO Auto-generated method stub
return lostMapper.getLostById(id);
}
@Override
public void deleteLostRestful(String id) {
// TODO Auto-generated method stub
lostMapper.deleteLost(id);
}
@Override
public void insertLostRestful(Lost lost) {
// TODO Auto-generated method stub
lostMapper.insertLost(lost);
}
@Override
public void updateLostRestful(Lost lost) {
// TODO Auto-generated method stub
lostMapper.updateLost( lost);
}
/**
* 创建by肖聪
* 2015/8/3
* 遗失物品领取
* @param lost
*/
@Override
public void updateLostClaim(Lost lost) {
// TODO Auto-generated method stub
lostMapper.updateLostClaim( lost);
}
/**
* 创建by 肖聪
* 2015/8/3
* 物品遗失更据条件查询
* @param lost
* @return
*/
@Override
public List<Lost> listAllLostBySearch(Search search) {
// TODO Auto-generated method stub
return lostMapper.listAllLostBySearch(search);
}
@Override
public List<Lost> listAllLostSearch(Search search) {
// TODO Auto-generated method stub
return lostMapper.listAllLostSearch(search);
}
@Override
public List<Lost> listAllGetSearch(Search search) {
// TODO Auto-generated method stub
return lostMapper.listAllGetSearch(search);
}
@Override
public List<Lost> listAllUpSearch(Search search) {
// TODO Auto-generated method stub
return lostMapper.listAllUpSearch(search);
}
@Override
public List<Lost> listPageLost(Lost lost) {
// TODO Auto-generated method stub
return null;
}
@Override
public String listAllCount() {
// TODO Auto-generated method stub
Map<String,Integer> data = new HashMap<String, Integer>();
int lostPick=lostMapper.countLostByState(0);
int lostLose=lostMapper.countLostByState(1);
int lostGet=lostMapper.countLostByState(2);
data.put("lostPick",lostPick);
data.put("lostWait",lostLose-lostGet>=0?lostLose-lostGet:0);
return JSONObject.fromObject(data).toString();
}
}
| UTF-8 | Java | 4,063 | 52b0a5eff2ed7782f3d0c40f2f585f111916924a.svn-base | Java | [
{
"context": "er.updateLost( lost);\r\n\t}\r\n\t\r\n\t /**\r\n * 创建by肖聪\r\n * 2015/8/3\r\n * 遗失物品领取\r\n * @param lo",
"end": 2509,
"score": 0.9927191734313965,
"start": 2507,
"tag": "NAME",
"value": "肖聪"
},
{
"context": "pdateLostClaim( lost);\r\n\t}\r\n\t\r\n\t /**... | null | [] | package com.flf.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import com.flf.entity.PageRestful;
import com.flf.entity.Lost;
import com.flf.entity.Search;
import com.flf.mapper.LostMapper;
import com.flf.service.LostService;
public class LostServiceImpl implements LostService{
private LostMapper lostMapper;
public LostMapper getLostMapper() {
return lostMapper;
}
public void setLostMapper(LostMapper lostMapper) {
this.lostMapper = lostMapper;
}
@Override
public List<Lost> listAllLost() {
// TODO Auto-generated method stub
return lostMapper.listAllLost();
}
@Override
public PageRestful listPageAllLost(Lost lost) {
// TODO Auto-generated method stub
PageRestful pagerestful=new PageRestful();
List<Lost> losts=lostMapper.listPageLost(lost);
losts.add(0,null);
pagerestful.setLosts(losts);
pagerestful.setPage(lost.getPage());
return pagerestful;
//return lostMapper.listPageLost(lost);
}
@Override
public Lost getLostById(String id) {
// TODO Auto-generated method stub
return lostMapper.getLostById(id);
}
@Override
public int insertLost(Lost lost) {
// TODO Auto-generated method stub
return lostMapper.insertLost(lost);
}
@Override
public int updateLost(Lost lost) {
// TODO Auto-generated method stub
return lostMapper.updateLost( lost);
}
/*@Override
public PageRestful listPageLostRestful(Lost lost) {
// TODO Auto-generated method stub
PageRestful pagerestful=new PageRestful();
List<Lost> losts =lostMapper.listPageLost(lost);
losts.add(0,null);
pagerestful.setLosts(losts);
pagerestful.setPage(lost.getPage());
return pagerestful;
}*/
@Override
public List<Lost> listAllLostRestful() {
// TODO Auto-generated method stub
List<Lost>losts=lostMapper.listAllLost();
return losts;
}
@Override
public Lost getLostByIdRestful(String id) {
// TODO Auto-generated method stub
return lostMapper.getLostById(id);
}
@Override
public void deleteLostRestful(String id) {
// TODO Auto-generated method stub
lostMapper.deleteLost(id);
}
@Override
public void insertLostRestful(Lost lost) {
// TODO Auto-generated method stub
lostMapper.insertLost(lost);
}
@Override
public void updateLostRestful(Lost lost) {
// TODO Auto-generated method stub
lostMapper.updateLost( lost);
}
/**
* 创建by肖聪
* 2015/8/3
* 遗失物品领取
* @param lost
*/
@Override
public void updateLostClaim(Lost lost) {
// TODO Auto-generated method stub
lostMapper.updateLostClaim( lost);
}
/**
* 创建by 肖聪
* 2015/8/3
* 物品遗失更据条件查询
* @param lost
* @return
*/
@Override
public List<Lost> listAllLostBySearch(Search search) {
// TODO Auto-generated method stub
return lostMapper.listAllLostBySearch(search);
}
@Override
public List<Lost> listAllLostSearch(Search search) {
// TODO Auto-generated method stub
return lostMapper.listAllLostSearch(search);
}
@Override
public List<Lost> listAllGetSearch(Search search) {
// TODO Auto-generated method stub
return lostMapper.listAllGetSearch(search);
}
@Override
public List<Lost> listAllUpSearch(Search search) {
// TODO Auto-generated method stub
return lostMapper.listAllUpSearch(search);
}
@Override
public List<Lost> listPageLost(Lost lost) {
// TODO Auto-generated method stub
return null;
}
@Override
public String listAllCount() {
// TODO Auto-generated method stub
Map<String,Integer> data = new HashMap<String, Integer>();
int lostPick=lostMapper.countLostByState(0);
int lostLose=lostMapper.countLostByState(1);
int lostGet=lostMapper.countLostByState(2);
data.put("lostPick",lostPick);
data.put("lostWait",lostLose-lostGet>=0?lostLose-lostGet:0);
return JSONObject.fromObject(data).toString();
}
}
| 4,063 | 0.700125 | 0.695392 | 170 | 21.617647 | 18.027454 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.358824 | false | false | 6 | |
5b02e9af3832d0beae958a25780263fdd1a0d517 | 28,415,503,636,610 | d511011b20348d96ddcf2488bd10e78600b4c2dc | /dao/src/main/java/ua/ksstroy/converter/projectuser/ProjectModelToProjectConverter.java | a5022a25673335316aa3ef146e110980a24ac57a | [] | no_license | esobolievv/ConstructionCalculator | https://github.com/esobolievv/ConstructionCalculator | 0812dd7262ad908d2534cd2dc6b76e13ad0b91df | 89e64744573565681bb20065b09423c586766ca0 | refs/heads/master | 2021-05-31T18:47:05.837000 | 2016-02-27T14:55:55 | 2016-02-27T14:55:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.ksstroy.converter.projectuser;
import ua.ksstroy.converter.Converter;
import ua.ksstroy.logic.project.Project;
import ua.ksstroy.models.project.ProjectModel;
public class ProjectModelToProjectConverter implements Converter<ProjectModel, Project> {
@Override
public Project convert(ProjectModel projectModel) {
Project project = new Project();
project.setId(projectModel.getId());
project.setProjectName(projectModel.getProjectName());
project.setDescription(projectModel.getDescription());
return project;
}
}
| UTF-8 | Java | 576 | java | ProjectModelToProjectConverter.java | Java | [] | null | [] | package ua.ksstroy.converter.projectuser;
import ua.ksstroy.converter.Converter;
import ua.ksstroy.logic.project.Project;
import ua.ksstroy.models.project.ProjectModel;
public class ProjectModelToProjectConverter implements Converter<ProjectModel, Project> {
@Override
public Project convert(ProjectModel projectModel) {
Project project = new Project();
project.setId(projectModel.getId());
project.setProjectName(projectModel.getProjectName());
project.setDescription(projectModel.getDescription());
return project;
}
}
| 576 | 0.753472 | 0.753472 | 17 | 32.882355 | 25.843153 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 6 |
36bb571ef6b63d7cd1c8c3ba696f43b74fcdb35f | 30,691,836,302,944 | 333104a519abcd38fde43f5c75d085857652c269 | /src/main/java/com/pranav/space_management_system/exceptions/util/AuditUtils.java | b484d3b183471fd209539ffe943e8f7b86825ea6 | [] | no_license | Iyad87/space-management-system | https://github.com/Iyad87/space-management-system | f35cc5e93e343656f46c9cf94e8cecff27329194 | 6c5a8e8c1932fc280792a343c7f25006bc7f941c | refs/heads/master | 2022-11-12T13:14:28.818000 | 2020-06-04T15:33:38 | 2020-06-04T15:33:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pranav.space_management_system.exceptions.util;
public class AuditUtils {
/**
* Private constructor for AuditUtils
*/
private AuditUtils() {
}
public static void privateConstructor() {
System.out.println("private constructor test");
}
} | UTF-8 | Java | 264 | java | AuditUtils.java | Java | [] | null | [] | package com.pranav.space_management_system.exceptions.util;
public class AuditUtils {
/**
* Private constructor for AuditUtils
*/
private AuditUtils() {
}
public static void privateConstructor() {
System.out.println("private constructor test");
}
} | 264 | 0.727273 | 0.727273 | 15 | 16.666666 | 20.19791 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 6 |
d9a2df09072cccbfcf7af69395a90ebb16926510 | 31,035,433,689,652 | 536cb02bd5fcd6c902f705dd55875c3e1c4fa0e8 | /tripExpenseCalculator/src/test/java/com/expense/calc/repository/UserRepositoryIntegrationTest.java | 9005465305de36b3d37cce816f88dcab4bf5e276 | [] | no_license | coolduebtn/expensecalculator | https://github.com/coolduebtn/expensecalculator | f9fc2ab19eae551e766386644142d8dbc6733f3d | dd9103fb471ef65d3483e313d5b5bcbf998d872b | refs/heads/master | 2021-01-19T16:56:54.430000 | 2014-02-04T16:53:39 | 2014-02-04T16:53:39 | 32,143,015 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.expense.calc.repository;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.expense.calc.builder.UserTestBuilder;
import com.expense.calc.model.User;
public class UserRepositoryIntegrationTest extends AbstractRepositoryIntegrationTest{
@Autowired
private UserRepository memberRepository;
@Test
public void persistMemberTest() {
User member = UserTestBuilder.aUser().build();
memberRepository.persist(member);
assertThat(member.getId()).isNotNull();
}
@Test
public void loadMemberTest() {
User member = UserTestBuilder.aUser().buildAndPersist();
User loadedMember = memberRepository.load(member.getId());
assertThat(loadedMember).isEqualTo(member);
}
@Test
public void deleteMemberTest() {
User member = UserTestBuilder.aUser().buildAndPersist();
memberRepository.delete(member);
User byId = memberRepository.getById(member.getId());
assertThat(byId).isNull();
}
@Test
public void loadUserByUsername() {
User member = UserTestBuilder.aUser().withUsername("chandan").buildAndPersist();
User fromDbUser = memberRepository.loadUserByUsername("chandan");
assertThat(fromDbUser).isEqualTo(member);
User fromDbUser2 = memberRepository.loadUserByUsername("chandu");
assertThat(fromDbUser2).isNull();
}
}
| UTF-8 | Java | 1,381 | java | UserRepositoryIntegrationTest.java | Java | [
{
"context": "er member = UserTestBuilder.aUser().withUsername(\"chandan\").buildAndPersist();\n\t\t\n\t\tUser fromDbUser = membe",
"end": 1132,
"score": 0.999748706817627,
"start": 1125,
"tag": "USERNAME",
"value": "chandan"
},
{
"context": "fromDbUser = memberRepository.loadUserByU... | null | [] | package com.expense.calc.repository;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.expense.calc.builder.UserTestBuilder;
import com.expense.calc.model.User;
public class UserRepositoryIntegrationTest extends AbstractRepositoryIntegrationTest{
@Autowired
private UserRepository memberRepository;
@Test
public void persistMemberTest() {
User member = UserTestBuilder.aUser().build();
memberRepository.persist(member);
assertThat(member.getId()).isNotNull();
}
@Test
public void loadMemberTest() {
User member = UserTestBuilder.aUser().buildAndPersist();
User loadedMember = memberRepository.load(member.getId());
assertThat(loadedMember).isEqualTo(member);
}
@Test
public void deleteMemberTest() {
User member = UserTestBuilder.aUser().buildAndPersist();
memberRepository.delete(member);
User byId = memberRepository.getById(member.getId());
assertThat(byId).isNull();
}
@Test
public void loadUserByUsername() {
User member = UserTestBuilder.aUser().withUsername("chandan").buildAndPersist();
User fromDbUser = memberRepository.loadUserByUsername("chandan");
assertThat(fromDbUser).isEqualTo(member);
User fromDbUser2 = memberRepository.loadUserByUsername("chandu");
assertThat(fromDbUser2).isNull();
}
}
| 1,381 | 0.77118 | 0.769732 | 50 | 26.620001 | 25.224504 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.56 | false | false | 6 |
314e4f80c8f3ad54a3fb78c018fc4941571903d1 | 1,838,246,013,131 | c797d437e0bd61a4ddd8106453df5029bb950037 | /src/tr/edu/deu/ceng/coffie/entity/auth/Loginnable.java | 9083184eec0e3b4aa29aa9e0857f387360a1108f | [] | no_license | mustafaonurdurkal/kafe | https://github.com/mustafaonurdurkal/kafe | b62c8b7f6396c3aeba0fcde917dcefc61b9a3832 | 55544c6a6597d78e30596a504828d942d1d5de61 | refs/heads/master | 2020-05-25T14:44:49.546000 | 2019-05-22T00:10:43 | 2019-05-22T00:10:43 | 187,852,785 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tr.edu.deu.ceng.coffie.entity.auth;
public interface Loginnable {
String getEmail();
String getPassword();
}
| UTF-8 | Java | 123 | java | Loginnable.java | Java | [] | null | [] | package tr.edu.deu.ceng.coffie.entity.auth;
public interface Loginnable {
String getEmail();
String getPassword();
}
| 123 | 0.739837 | 0.739837 | 8 | 14.375 | 15.3455 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 6 |
3f5b400e2bede93131f3ca54beddac3788d60b19 | 1,838,246,013,361 | a99a240176f6cff5bee016e2ba904fc901e0231f | /utils/metrics/src/main/java/quarks/metrics/Metrics.java | a7b971d6c28ca72fae7cd017a22dbae98cd0f74d | [
"Apache-2.0"
] | permissive | narayana-glassbeam/quarks | https://github.com/narayana-glassbeam/quarks | a32e1be06364bd202689d0eb6119dfd196751ebf | 6007de426b7addf63811699a9851eb1f4b84274b | refs/heads/master | 2021-01-18T06:32:31.108000 | 2016-02-25T00:51:52 | 2016-02-25T00:51:52 | 52,536,294 | 1 | 0 | null | true | 2016-02-25T15:40:08 | 2016-02-25T15:40:08 | 2016-02-25T15:39:01 | 2016-02-25T00:51:52 | 20,612 | 0 | 0 | 0 | null | null | null | /*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015, 2016
*/
package quarks.metrics;
import quarks.graph.Vertex;
import quarks.metrics.oplets.CounterOp;
import quarks.metrics.oplets.RateMeter;
import quarks.topology.TStream;
import quarks.topology.Topology;
/**
* This interface contains utility methods for manipulating metrics.
*/
public class Metrics {
/**
* Increment a counter metric when peeking at each tuple.
*
* @param <T>
* TStream tuple type
* @return a {@link TStream} containing the input tuples
*/
public static <T> TStream<T> counter(TStream<T> stream) {
return stream.pipe(new CounterOp<T>());
}
/**
* Measure current tuple throughput and calculate one-, five-, and
* fifteen-minute exponentially-weighted moving averages.
*
* @param <T>
* TStream tuple type
* @return a {@link TStream} containing the input tuples
*/
public static <T> TStream<T> rateMeter(TStream<T> stream) {
return stream.pipe(new RateMeter<T>());
}
/**
* Add counter metrics to all the topology's streams.
* <p>
* {@link CounterOp} oplets are inserted between every two graph
* vertices with the following exceptions:
* <ul>
* <li>Oplets are only inserted upstream from a FanOut oplet.</li>
* <li>If a chain of Peek oplets exists between oplets A and B, a Metric
* oplet is inserted after the last Peek, right upstream from oplet B.</li>
* <li>If a chain a Peek oplets is followed by a FanOut, a metric oplet is
* inserted between the last Peek and the FanOut oplet.</li>
* </ul>
* The implementation is not idempotent: previously inserted metric oplets
* are treated as regular graph vertices. Calling the method twice
* will insert a new set of metric oplets into the graph.
* @param t
* The topology
*/
public static void counter(Topology t) {
t.graph().peekAll(
() -> new CounterOp<>(),
(Vertex<?, ?, ?> v) -> !(v.getInstance() instanceof quarks.oplet.core.FanOut));
}
}
| UTF-8 | Java | 2,168 | java | Metrics.java | Java | [] | null | [] | /*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015, 2016
*/
package quarks.metrics;
import quarks.graph.Vertex;
import quarks.metrics.oplets.CounterOp;
import quarks.metrics.oplets.RateMeter;
import quarks.topology.TStream;
import quarks.topology.Topology;
/**
* This interface contains utility methods for manipulating metrics.
*/
public class Metrics {
/**
* Increment a counter metric when peeking at each tuple.
*
* @param <T>
* TStream tuple type
* @return a {@link TStream} containing the input tuples
*/
public static <T> TStream<T> counter(TStream<T> stream) {
return stream.pipe(new CounterOp<T>());
}
/**
* Measure current tuple throughput and calculate one-, five-, and
* fifteen-minute exponentially-weighted moving averages.
*
* @param <T>
* TStream tuple type
* @return a {@link TStream} containing the input tuples
*/
public static <T> TStream<T> rateMeter(TStream<T> stream) {
return stream.pipe(new RateMeter<T>());
}
/**
* Add counter metrics to all the topology's streams.
* <p>
* {@link CounterOp} oplets are inserted between every two graph
* vertices with the following exceptions:
* <ul>
* <li>Oplets are only inserted upstream from a FanOut oplet.</li>
* <li>If a chain of Peek oplets exists between oplets A and B, a Metric
* oplet is inserted after the last Peek, right upstream from oplet B.</li>
* <li>If a chain a Peek oplets is followed by a FanOut, a metric oplet is
* inserted between the last Peek and the FanOut oplet.</li>
* </ul>
* The implementation is not idempotent: previously inserted metric oplets
* are treated as regular graph vertices. Calling the method twice
* will insert a new set of metric oplets into the graph.
* @param t
* The topology
*/
public static void counter(Topology t) {
t.graph().peekAll(
() -> new CounterOp<>(),
(Vertex<?, ?, ?> v) -> !(v.getInstance() instanceof quarks.oplet.core.FanOut));
}
}
| 2,168 | 0.636531 | 0.632841 | 63 | 33.412697 | 27.042374 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 6 |
e3d9451786a046cbb5b1aec95959b12339e81018 | 9,586,367,064,852 | 1b6650c79dfd250b4c02b7957ef45b51ec20433d | /Index.java | aa42a809cd5c60f0db67975c553e4b2389a40ece | [] | no_license | HaginCodes/CubeReviewGenerator | https://github.com/HaginCodes/CubeReviewGenerator | d0f7b18130ef7682a186798adfc8361d9a665633 | 95e5bc06a3751124e8fe26a1b825404b1cb00df4 | refs/heads/master | 2021-01-10T17:45:56.168000 | 2015-11-21T04:12:07 | 2015-11-21T04:12:07 | 46,600,392 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* RubiksCubeGenerator.java 2015
*
* CopyRight ® Hagin Onyango & KGB Agent 2015. All rights reserved.
*/
import java.util.Scanner;
public class RubikCubeReviewG {
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.print("Hello Welcome to RubiksCubeReviewGenerator! Answer a few questions and you will have a Cube Review in no time. :)");
//Enter your name
System.out.println(" Please Enter Your name ");
String name = userInput.nextLine();
//enter the cube you want to review
System.out.println(" What rubiks cube do you want to review ");
String RubiksCube = userInput.nextLine();
//enter the company that made the cube
System.out.println(" What company made the cube ");
String CubeCompany = userInput.nextLine();
//Where did you buy the rubiks cube
System.out.println(" Where did you buy the puzzle ");
String CubeBought = userInput.nextLine();
//How much the puzzle cost
System.out.println(" How much was the puzzle you bought ");
float CubeCost = userInput.nextFloat();
//How much can it cut forwards
System.out.println(" How much can the puzzle cut forwards ");
int CubeCut = userInput.nextInt();
//How much can the cube reverse cut
System.out.println(" How much can the cube reverse cut ");
int CubeRevCut = userInput.nextInt();
//How much does the cube cut forwards
System.out.println(" How does the cube feel when you turn it. TWO ADJECTIVES ONLY ");
String CubeFeel = userInput.nextLine();
//Good or bad puzzle
System.out.println(" is the puzzle good or bad ");
String GJorBJ = userInput.nextLine();
//ranking of Puzzle
System.out.println(" What grade do you give this puzzle ");
String CubeGrade = userInput.nextLine();
//Review cube Paragraph
System.out.print("Hello guys " + name + " here going to bring you a review on the" + RubiksCube +
". This cube was made by " + CubeCompany + " I purchased this puzzle from the " + CubeBought +
" and you can get this puzzle from them for " + CubeCost + ". The "+ RubiksCube + " can cut " + CubeCut + " degrees forward, and " +
CubeRevCut + " degress backward. The cube feels " + CubeFeel + ". Over all the " + RubiksCube + " is a " +GJorBJ+ " I give this cube an "
+ CubeGrade + " Thank you guys, " + name + " signing out. ");
}
}
| UTF-8 | Java | 2,331 | java | Index.java | Java | [
{
"context": "* RubiksCubeGenerator.java 2015\n * \n * CopyRight ® Hagin Onyango & KGB Agent 2015. All rights reserved.\n */\nimport",
"end": 65,
"score": 0.9998955726623535,
"start": 52,
"tag": "NAME",
"value": "Hagin Onyango"
}
] | null | [] | /* RubiksCubeGenerator.java 2015
*
* CopyRight ® <NAME> & KGB Agent 2015. All rights reserved.
*/
import java.util.Scanner;
public class RubikCubeReviewG {
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.print("Hello Welcome to RubiksCubeReviewGenerator! Answer a few questions and you will have a Cube Review in no time. :)");
//Enter your name
System.out.println(" Please Enter Your name ");
String name = userInput.nextLine();
//enter the cube you want to review
System.out.println(" What rubiks cube do you want to review ");
String RubiksCube = userInput.nextLine();
//enter the company that made the cube
System.out.println(" What company made the cube ");
String CubeCompany = userInput.nextLine();
//Where did you buy the rubiks cube
System.out.println(" Where did you buy the puzzle ");
String CubeBought = userInput.nextLine();
//How much the puzzle cost
System.out.println(" How much was the puzzle you bought ");
float CubeCost = userInput.nextFloat();
//How much can it cut forwards
System.out.println(" How much can the puzzle cut forwards ");
int CubeCut = userInput.nextInt();
//How much can the cube reverse cut
System.out.println(" How much can the cube reverse cut ");
int CubeRevCut = userInput.nextInt();
//How much does the cube cut forwards
System.out.println(" How does the cube feel when you turn it. TWO ADJECTIVES ONLY ");
String CubeFeel = userInput.nextLine();
//Good or bad puzzle
System.out.println(" is the puzzle good or bad ");
String GJorBJ = userInput.nextLine();
//ranking of Puzzle
System.out.println(" What grade do you give this puzzle ");
String CubeGrade = userInput.nextLine();
//Review cube Paragraph
System.out.print("Hello guys " + name + " here going to bring you a review on the" + RubiksCube +
". This cube was made by " + CubeCompany + " I purchased this puzzle from the " + CubeBought +
" and you can get this puzzle from them for " + CubeCost + ". The "+ RubiksCube + " can cut " + CubeCut + " degrees forward, and " +
CubeRevCut + " degress backward. The cube feels " + CubeFeel + ". Over all the " + RubiksCube + " is a " +GJorBJ+ " I give this cube an "
+ CubeGrade + " Thank you guys, " + name + " signing out. ");
}
}
| 2,324 | 0.695708 | 0.692275 | 49 | 46.551022 | 32.437733 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.306123 | false | false | 6 |
c0a10eaa1034de825061b737f9c6d29d5967db66 | 31,559,419,702,620 | 7a1602f6f25dbda6afd69463691e2ac8a69a7e5a | /src/Controlador/ControladorRegistrarEntrada.java | 6ed79d496d4eaede03d553ca62988c847f18ff9e | [] | no_license | crisswebapp/proyecto2 | https://github.com/crisswebapp/proyecto2 | dea7b821feae4754abd7d282147ddd3ea09dbfea | b0d9c0672afde12948909a36c3a51d7a18928038 | refs/heads/master | 2020-07-16T07:08:05.786000 | 2020-06-25T00:26:48 | 2020-06-25T00:26:48 | 205,744,219 | 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 Controlador;
import Modelo.ConsultasDetalleEntrada;
import Modelo.ConsultasEntrada;
import Modelo.ConsultasInventario;
import Modelo.ConsultasProducto;
import Modelo.ConsultasProveedor;
import Modelo.DetalleEntrada;
import Modelo.Entrada;
import Modelo.Inventario;
import Modelo.Producto;
import Modelo.Proveedor;
import Modelo.Usuario;
import Vista.CantPrecioEnt;
import Vista.ListaInventario;
import Vista.VEntrada;
import Vista.RegistroEntrada;
import Vista.RegistroProducto;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Timestamp;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
/**
*
* @author criss
*/
public class ControladorRegistrarEntrada implements ActionListener, KeyListener,
TableModelListener,MouseListener{
private RegistroEntrada vista;
private Usuario modelo;
private VEntrada vistaEntrada = new VEntrada();
private RegistroProducto vistaRegistro = new RegistroProducto();
private ConsultasEntrada consultaE = new ConsultasEntrada();
private ConsultasProveedor consultaP = new ConsultasProveedor();
private ControladorRegistroProducto controladorRP =
new ControladorRegistroProducto(vistaRegistro);
//registra si el jtable esta activo
boolean active = false;
public ControladorRegistrarEntrada(RegistroEntrada vista, Usuario modelo){
this.vista= vista;
this.modelo= modelo;
vista.jtxtCodigo.addKeyListener(this);
vista.jlblNombreUsuario.setText(modelo.getNombreUsuario());
vista.jlblRecibido.setText(modelo.getNombreUsuario());
vista.btnNuevoProducto.addActionListener(this);
vista.btnAtras.addActionListener(this);
vista.btnAgregar.addActionListener(this);
vista.btnBuscar.addActionListener(this);
vista.jtableNuevaEntrada.getModel().addTableModelListener(this);
vista.btnComprar.addActionListener(this);
vista.btnElimdeCarr.addActionListener(this);
vista.btnElimdeCarr.setEnabled(false);
vista.btnComprar.setEnabled(false);
vista.jtableNuevaEntrada.addMouseListener(this);
siguienteId(vista.jlblNoEntrada);
//carga lista de proveedores
vista.jcmbProveedor.addItem("");
consultaP.listaProveedores(vista.jcmbProveedor);
vista.jtxtCodigo.requestFocus();
}
public void agregarProducto(){
Producto producto = new Producto();
DefaultTableModel model = (DefaultTableModel)vista.jtableNuevaEntrada.getModel();
ConsultasProducto consultaP = new ConsultasProducto();
boolean existe = false;
String regProducto [] = new String[6];
regProducto[1]= vista.jtxtCodigo.getText();
if(consultaP.consultar(regProducto)){
for(int i = 0; i<model.getRowCount();i++){
if(model.getValueAt(i, 1).toString().equals(producto.getCodigo())){
String valor = String.valueOf(Integer.valueOf((String)model.getValueAt(i, 6))+1);
model.setValueAt(valor, i, 6);
existe=true;
}
}
if(!existe){
try{
CantPrecioEnt panel = new CantPrecioEnt();
ControladorCantPrecioEnt control = new ControladorCantPrecioEnt(panel);
control.inciar();
control.insertarProducto(vista.jtableNuevaEntrada, regProducto);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Error al agregar producto");
}
}
vista.jtableNuevaEntrada.setModel(model);
vista.jtxtCodigo.setText("");
vista.jtxtCodigo.requestFocus();
}else{
JOptionPane.showMessageDialog(null,"Este producto no esta registrado");
}
}
public void siguienteId(JLabel id){
Entrada entrada = new Entrada();
if(consultaE.siguenteIdEntrada(entrada)){
id.setText(String.valueOf(entrada.getIdEntrada()));
}
}
public void calcularTotal(JLabel total){
TableModel model = (TableModel)vista.jtableNuevaEntrada.getModel();
String valor ="0";
for(int x=0; x<model.getRowCount();x++){
try{
double v = Double.valueOf((String)model.getValueAt(x, 9));
valor = String.valueOf(v + Double.valueOf(valor));
}catch(Exception e){}
}
total.setText(valor);
}
public static TableModel calcularSubTotal(TableModel datos){
for (int x =0; x<datos.getRowCount();x++){
String valor = null;
try{
valor = String.valueOf(Integer.valueOf((String)datos.getValueAt(x, 6)) *
Double.valueOf((String)datos.getValueAt(x, 7)));
}catch(Exception e){}
datos.setValueAt(valor, x, 9);
}
return datos;
}
public void realizarCompra(){
//***********Obejtos de la compra **************
Entrada entrada = new Entrada();
Proveedor proveedor = new Proveedor();
Inventario inventario = new Inventario();
ConsultasInventario consultasInv = new ConsultasInventario();
DetalleEntrada detalleEntrada = new DetalleEntrada();
ConsultasDetalleEntrada consultasDetEntrada = new ConsultasDetalleEntrada();
try{
//***********Datos de compra **************
//obtenemos el id del proveedor, deacuedo al seleccionado en el jcombox
proveedor.setNombre(vista.jcmbProveedor.getModel().getSelectedItem().toString());
if(consultaP.getId(proveedor)){
//agregamos el id del proveedor a nuestra clase entrada
entrada.setIdProveedor(proveedor.getIdProveedor());
}
//agregamos informacion necesaria a la clase entrada
entrada.setIdEntrada(Integer.parseInt(vista.jlblNoEntrada.getText()));
entrada.setIdUsuario(modelo.getIdUsuario());
//registro el momento de la compra(fecha y hora)
long now = System.currentTimeMillis();
Timestamp sqlTimestamp = new Timestamp(now);
entrada.setFechaCompra(sqlTimestamp);
entrada.setTotal(Double.parseDouble(vista.jlblTotal.getText()));
//registramos la venta
consultaE.registrar(entrada);
//Obtenemos el modelo de la tabla para recorrerla y guardar los datos de cada una
DefaultTableModel model = (DefaultTableModel)vista.jtableNuevaEntrada.getModel();
for(int i=0; i<model.getRowCount(); i++){
//***********Datos detalle venta *********
detalleEntrada.setIdCompra(entrada.getIdEntrada());
detalleEntrada.setIdProducto(Integer.parseInt((String)model.getValueAt(i, 0)));
detalleEntrada.setnActiculo(Integer.parseInt((String)model.getValueAt(i, 6)));
detalleEntrada.setPrecioCompra(Double.parseDouble((String)model.getValueAt(i, 7)));
detalleEntrada.setSubtotal(Double.parseDouble((String)model.getValueAt(i, 9)));
//registro del detalle venta
consultasDetEntrada.registrar(detalleEntrada);
//***********Datos Inventario*************
inventario.setIdProducto(Integer.parseInt((String)model.getValueAt(i, 0)));
inventario.setnArticulo(Integer.parseInt((String)model.getValueAt(i, 6)));
inventario.setPrecioCompra(Double.parseDouble((String)model.getValueAt(i, 7)));
inventario.setPrecioVenta(Double.parseDouble((String)model.getValueAt(i, 8)));
//registro del inventario
consultasInv.registrar(inventario);
}
JOptionPane.showMessageDialog(null,"Registro de Entrada Exitoso");
//limpio tabla
while(model.getRowCount()>0){
model.removeRow(0);
}
vista.jtableNuevaEntrada.setModel(model);
vista.jlblTotal.setText("0000.00");
siguienteId(vista.jlblNoEntrada);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Error al Guardar la Compra\n"+e);
}
}
public void iniciar(){
vista.setLocationRelativeTo(null);
vista.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==vista.btnNuevoProducto){
controladorRP.iniciar();
}else if(ae.getSource()==vista.btnAtras){
if(Double.parseDouble(this.vista.jlblTotal.getText())>0){
int op = JOptionPane.showConfirmDialog(null,"Hay productos en la lista"
+ " ¿Desea salir?\nperdera la informacion ya ingresada",
"Alerta",JOptionPane.YES_NO_OPTION);
if(op==0){
ControladorEntrada controladorE = new ControladorEntrada(vistaEntrada,modelo);
controladorE.iniciar();
vista.dispose();
}
}else{
ControladorEntrada controladorE = new ControladorEntrada(vistaEntrada,modelo);
controladorE.iniciar();
vista.dispose();
}
}else if(ae.getSource()==vista.btnAgregar){
agregarProducto();
}else if(ae.getSource()==vista.btnElimdeCarr){
DefaultTableModel model = (DefaultTableModel)vista.jtableNuevaEntrada.getModel();
int result=JOptionPane.showConfirmDialog(null, "Desea quitar este producto de "
+ "la lista","Alerta",JOptionPane.YES_NO_OPTION);
if (result==0){
model.removeRow(vista.jtableNuevaEntrada.getSelectedRow());
vista.jtableNuevaEntrada.setModel(model);
}
vista.jtableNuevaEntrada.clearSelection();
vista.btnElimdeCarr.setEnabled(false);
}else if(ae.getSource()==vista.btnBuscar){
ListaInventario vistaLista = new ListaInventario();
ControladorListaInventario controladorInv =
new ControladorListaInventario(vistaLista);
controladorInv.insertarTabla(vista.jtableNuevaEntrada);
controladorInv.iniciar();
}else if(ae.getSource()==vista.btnComprar){
if(vista.jcmbProveedor.getModel().getSelectedItem().equals("")){
JOptionPane.showMessageDialog(null,"Selecione un proveedor para continuar");
}else{
realizarCompra();
vista.jcmbProveedor.setSelectedIndex(0);
}
}
}
@Override
public void tableChanged(TableModelEvent tme) {
if(!active && tme.getType()==TableModelEvent.UPDATE){
active=true;
TableModel model = vista.jtableNuevaEntrada.getModel();
vista.jtableNuevaEntrada.setModel(calcularSubTotal(model));
calcularTotal(vista.jlblTotal);
active = false;
if(Double.parseDouble(vista.jlblTotal.getText())>0){
vista.btnComprar.setEnabled(true);
}else{
vista.btnComprar.setEnabled(false);
}
}else if(!active &&tme.getType()==TableModelEvent.INSERT){
active=true;
TableModel model = vista.jtableNuevaEntrada.getModel();
vista.jtableNuevaEntrada.setModel(calcularSubTotal(model));
calcularTotal(vista.jlblTotal);
active = false;
if(Double.parseDouble(vista.jlblTotal.getText())>0){
vista.btnComprar.setEnabled(true);
}else{
vista.btnComprar.setEnabled(false);
}
}else if(!active &&tme.getType()==TableModelEvent.DELETE){
active=true;
TableModel model = vista.jtableNuevaEntrada.getModel();
vista.jtableNuevaEntrada.setModel(calcularSubTotal(model));
calcularTotal(vista.jlblTotal);
active = false;
if(Double.parseDouble(vista.jlblTotal.getText())>0){
vista.btnComprar.setEnabled(true);
}else{
vista.btnComprar.setEnabled(false);
}
}
}
@Override
public void keyPressed(KeyEvent ke) {
if(ke.getSource()==vista.jtxtCodigo){
if(ke.getKeyCode()==KeyEvent.VK_ENTER){
if(!vista.jtxtCodigo.getText().equals("")){
agregarProducto();
}
}
}
}
@Override
public void mouseClicked(MouseEvent me) {
if(me.getSource()==vista.jtableNuevaEntrada){
if(me.getClickCount()==1){
vista.btnElimdeCarr.setEnabled(true);
}
}
}
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
}
| UTF-8 | Java | 14,257 | java | ControladorRegistrarEntrada.java | Java | [
{
"context": "t javax.swing.table.TableModel;\n\n/**\n *\n * @author criss\n */\npublic class ControladorRegistrarEntrada impl",
"end": 1220,
"score": 0.9990997314453125,
"start": 1215,
"tag": "USERNAME",
"value": "criss"
}
] | 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 Controlador;
import Modelo.ConsultasDetalleEntrada;
import Modelo.ConsultasEntrada;
import Modelo.ConsultasInventario;
import Modelo.ConsultasProducto;
import Modelo.ConsultasProveedor;
import Modelo.DetalleEntrada;
import Modelo.Entrada;
import Modelo.Inventario;
import Modelo.Producto;
import Modelo.Proveedor;
import Modelo.Usuario;
import Vista.CantPrecioEnt;
import Vista.ListaInventario;
import Vista.VEntrada;
import Vista.RegistroEntrada;
import Vista.RegistroProducto;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Timestamp;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
/**
*
* @author criss
*/
public class ControladorRegistrarEntrada implements ActionListener, KeyListener,
TableModelListener,MouseListener{
private RegistroEntrada vista;
private Usuario modelo;
private VEntrada vistaEntrada = new VEntrada();
private RegistroProducto vistaRegistro = new RegistroProducto();
private ConsultasEntrada consultaE = new ConsultasEntrada();
private ConsultasProveedor consultaP = new ConsultasProveedor();
private ControladorRegistroProducto controladorRP =
new ControladorRegistroProducto(vistaRegistro);
//registra si el jtable esta activo
boolean active = false;
public ControladorRegistrarEntrada(RegistroEntrada vista, Usuario modelo){
this.vista= vista;
this.modelo= modelo;
vista.jtxtCodigo.addKeyListener(this);
vista.jlblNombreUsuario.setText(modelo.getNombreUsuario());
vista.jlblRecibido.setText(modelo.getNombreUsuario());
vista.btnNuevoProducto.addActionListener(this);
vista.btnAtras.addActionListener(this);
vista.btnAgregar.addActionListener(this);
vista.btnBuscar.addActionListener(this);
vista.jtableNuevaEntrada.getModel().addTableModelListener(this);
vista.btnComprar.addActionListener(this);
vista.btnElimdeCarr.addActionListener(this);
vista.btnElimdeCarr.setEnabled(false);
vista.btnComprar.setEnabled(false);
vista.jtableNuevaEntrada.addMouseListener(this);
siguienteId(vista.jlblNoEntrada);
//carga lista de proveedores
vista.jcmbProveedor.addItem("");
consultaP.listaProveedores(vista.jcmbProveedor);
vista.jtxtCodigo.requestFocus();
}
public void agregarProducto(){
Producto producto = new Producto();
DefaultTableModel model = (DefaultTableModel)vista.jtableNuevaEntrada.getModel();
ConsultasProducto consultaP = new ConsultasProducto();
boolean existe = false;
String regProducto [] = new String[6];
regProducto[1]= vista.jtxtCodigo.getText();
if(consultaP.consultar(regProducto)){
for(int i = 0; i<model.getRowCount();i++){
if(model.getValueAt(i, 1).toString().equals(producto.getCodigo())){
String valor = String.valueOf(Integer.valueOf((String)model.getValueAt(i, 6))+1);
model.setValueAt(valor, i, 6);
existe=true;
}
}
if(!existe){
try{
CantPrecioEnt panel = new CantPrecioEnt();
ControladorCantPrecioEnt control = new ControladorCantPrecioEnt(panel);
control.inciar();
control.insertarProducto(vista.jtableNuevaEntrada, regProducto);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Error al agregar producto");
}
}
vista.jtableNuevaEntrada.setModel(model);
vista.jtxtCodigo.setText("");
vista.jtxtCodigo.requestFocus();
}else{
JOptionPane.showMessageDialog(null,"Este producto no esta registrado");
}
}
public void siguienteId(JLabel id){
Entrada entrada = new Entrada();
if(consultaE.siguenteIdEntrada(entrada)){
id.setText(String.valueOf(entrada.getIdEntrada()));
}
}
public void calcularTotal(JLabel total){
TableModel model = (TableModel)vista.jtableNuevaEntrada.getModel();
String valor ="0";
for(int x=0; x<model.getRowCount();x++){
try{
double v = Double.valueOf((String)model.getValueAt(x, 9));
valor = String.valueOf(v + Double.valueOf(valor));
}catch(Exception e){}
}
total.setText(valor);
}
public static TableModel calcularSubTotal(TableModel datos){
for (int x =0; x<datos.getRowCount();x++){
String valor = null;
try{
valor = String.valueOf(Integer.valueOf((String)datos.getValueAt(x, 6)) *
Double.valueOf((String)datos.getValueAt(x, 7)));
}catch(Exception e){}
datos.setValueAt(valor, x, 9);
}
return datos;
}
public void realizarCompra(){
//***********Obejtos de la compra **************
Entrada entrada = new Entrada();
Proveedor proveedor = new Proveedor();
Inventario inventario = new Inventario();
ConsultasInventario consultasInv = new ConsultasInventario();
DetalleEntrada detalleEntrada = new DetalleEntrada();
ConsultasDetalleEntrada consultasDetEntrada = new ConsultasDetalleEntrada();
try{
//***********Datos de compra **************
//obtenemos el id del proveedor, deacuedo al seleccionado en el jcombox
proveedor.setNombre(vista.jcmbProveedor.getModel().getSelectedItem().toString());
if(consultaP.getId(proveedor)){
//agregamos el id del proveedor a nuestra clase entrada
entrada.setIdProveedor(proveedor.getIdProveedor());
}
//agregamos informacion necesaria a la clase entrada
entrada.setIdEntrada(Integer.parseInt(vista.jlblNoEntrada.getText()));
entrada.setIdUsuario(modelo.getIdUsuario());
//registro el momento de la compra(fecha y hora)
long now = System.currentTimeMillis();
Timestamp sqlTimestamp = new Timestamp(now);
entrada.setFechaCompra(sqlTimestamp);
entrada.setTotal(Double.parseDouble(vista.jlblTotal.getText()));
//registramos la venta
consultaE.registrar(entrada);
//Obtenemos el modelo de la tabla para recorrerla y guardar los datos de cada una
DefaultTableModel model = (DefaultTableModel)vista.jtableNuevaEntrada.getModel();
for(int i=0; i<model.getRowCount(); i++){
//***********Datos detalle venta *********
detalleEntrada.setIdCompra(entrada.getIdEntrada());
detalleEntrada.setIdProducto(Integer.parseInt((String)model.getValueAt(i, 0)));
detalleEntrada.setnActiculo(Integer.parseInt((String)model.getValueAt(i, 6)));
detalleEntrada.setPrecioCompra(Double.parseDouble((String)model.getValueAt(i, 7)));
detalleEntrada.setSubtotal(Double.parseDouble((String)model.getValueAt(i, 9)));
//registro del detalle venta
consultasDetEntrada.registrar(detalleEntrada);
//***********Datos Inventario*************
inventario.setIdProducto(Integer.parseInt((String)model.getValueAt(i, 0)));
inventario.setnArticulo(Integer.parseInt((String)model.getValueAt(i, 6)));
inventario.setPrecioCompra(Double.parseDouble((String)model.getValueAt(i, 7)));
inventario.setPrecioVenta(Double.parseDouble((String)model.getValueAt(i, 8)));
//registro del inventario
consultasInv.registrar(inventario);
}
JOptionPane.showMessageDialog(null,"Registro de Entrada Exitoso");
//limpio tabla
while(model.getRowCount()>0){
model.removeRow(0);
}
vista.jtableNuevaEntrada.setModel(model);
vista.jlblTotal.setText("0000.00");
siguienteId(vista.jlblNoEntrada);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Error al Guardar la Compra\n"+e);
}
}
public void iniciar(){
vista.setLocationRelativeTo(null);
vista.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==vista.btnNuevoProducto){
controladorRP.iniciar();
}else if(ae.getSource()==vista.btnAtras){
if(Double.parseDouble(this.vista.jlblTotal.getText())>0){
int op = JOptionPane.showConfirmDialog(null,"Hay productos en la lista"
+ " ¿Desea salir?\nperdera la informacion ya ingresada",
"Alerta",JOptionPane.YES_NO_OPTION);
if(op==0){
ControladorEntrada controladorE = new ControladorEntrada(vistaEntrada,modelo);
controladorE.iniciar();
vista.dispose();
}
}else{
ControladorEntrada controladorE = new ControladorEntrada(vistaEntrada,modelo);
controladorE.iniciar();
vista.dispose();
}
}else if(ae.getSource()==vista.btnAgregar){
agregarProducto();
}else if(ae.getSource()==vista.btnElimdeCarr){
DefaultTableModel model = (DefaultTableModel)vista.jtableNuevaEntrada.getModel();
int result=JOptionPane.showConfirmDialog(null, "Desea quitar este producto de "
+ "la lista","Alerta",JOptionPane.YES_NO_OPTION);
if (result==0){
model.removeRow(vista.jtableNuevaEntrada.getSelectedRow());
vista.jtableNuevaEntrada.setModel(model);
}
vista.jtableNuevaEntrada.clearSelection();
vista.btnElimdeCarr.setEnabled(false);
}else if(ae.getSource()==vista.btnBuscar){
ListaInventario vistaLista = new ListaInventario();
ControladorListaInventario controladorInv =
new ControladorListaInventario(vistaLista);
controladorInv.insertarTabla(vista.jtableNuevaEntrada);
controladorInv.iniciar();
}else if(ae.getSource()==vista.btnComprar){
if(vista.jcmbProveedor.getModel().getSelectedItem().equals("")){
JOptionPane.showMessageDialog(null,"Selecione un proveedor para continuar");
}else{
realizarCompra();
vista.jcmbProveedor.setSelectedIndex(0);
}
}
}
@Override
public void tableChanged(TableModelEvent tme) {
if(!active && tme.getType()==TableModelEvent.UPDATE){
active=true;
TableModel model = vista.jtableNuevaEntrada.getModel();
vista.jtableNuevaEntrada.setModel(calcularSubTotal(model));
calcularTotal(vista.jlblTotal);
active = false;
if(Double.parseDouble(vista.jlblTotal.getText())>0){
vista.btnComprar.setEnabled(true);
}else{
vista.btnComprar.setEnabled(false);
}
}else if(!active &&tme.getType()==TableModelEvent.INSERT){
active=true;
TableModel model = vista.jtableNuevaEntrada.getModel();
vista.jtableNuevaEntrada.setModel(calcularSubTotal(model));
calcularTotal(vista.jlblTotal);
active = false;
if(Double.parseDouble(vista.jlblTotal.getText())>0){
vista.btnComprar.setEnabled(true);
}else{
vista.btnComprar.setEnabled(false);
}
}else if(!active &&tme.getType()==TableModelEvent.DELETE){
active=true;
TableModel model = vista.jtableNuevaEntrada.getModel();
vista.jtableNuevaEntrada.setModel(calcularSubTotal(model));
calcularTotal(vista.jlblTotal);
active = false;
if(Double.parseDouble(vista.jlblTotal.getText())>0){
vista.btnComprar.setEnabled(true);
}else{
vista.btnComprar.setEnabled(false);
}
}
}
@Override
public void keyPressed(KeyEvent ke) {
if(ke.getSource()==vista.jtxtCodigo){
if(ke.getKeyCode()==KeyEvent.VK_ENTER){
if(!vista.jtxtCodigo.getText().equals("")){
agregarProducto();
}
}
}
}
@Override
public void mouseClicked(MouseEvent me) {
if(me.getSource()==vista.jtableNuevaEntrada){
if(me.getClickCount()==1){
vista.btnElimdeCarr.setEnabled(true);
}
}
}
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
}
| 14,257 | 0.603956 | 0.601221 | 383 | 36.221931 | 26.547466 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561358 | false | false | 6 |
90c695565e63b263aa3947a56eb3581a0c9dcd81 | 13,520,557,094,349 | a34d93517cd372950ac04a220c690cc71777a144 | /bsuir.creditcalculator/bsuir.credit-calculator/bsuir.credit-calculator.web/src/main/java/by/bsuir/CreditCalculator/Web/Constants/Credits/DeleteCreditErrorConstants.java | 17a10275a2237214ae241a59524533b0995048c1 | [] | no_license | mishkasta/credit-calculator | https://github.com/mishkasta/credit-calculator | 0e6f00fd71120edd7884297b009618af2a220ae4 | 17aa3e4959fdcac87ecd48cc0c5b6bd205430f2b | refs/heads/master | 2020-05-20T02:54:11.371000 | 2019-05-16T07:39:21 | 2019-05-16T07:39:21 | 185,343,122 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.bsuir.CreditCalculator.Web.Constants.Credits;
public class DeleteCreditErrorConstants {
public static final String CREDIT_NOT_FOUND = "CREDIT_NOT_FOUND";
}
| UTF-8 | Java | 172 | java | DeleteCreditErrorConstants.java | Java | [] | null | [] | package by.bsuir.CreditCalculator.Web.Constants.Credits;
public class DeleteCreditErrorConstants {
public static final String CREDIT_NOT_FOUND = "CREDIT_NOT_FOUND";
}
| 172 | 0.796512 | 0.796512 | 5 | 33.400002 | 28.288513 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 6 |
0ee3c42762b499a34c0bc9c697367437660b4688 | 28,441,273,465,379 | cec2f3ff68d2a6665bacf7181985ee11e79ab682 | /src/main/java/com/devbugger/pagery/transform/pagery/TransformPageryBasePage.java | cb67c6ddae61131e5b96030edb5fb572a07396b7 | [] | no_license | scav/pagery | https://github.com/scav/pagery | 7050bd8f4f93f2082e4cf13518c7aeae02914b7f | 3b93bd8e175305d1cd70b60054dce4092323d0ae | refs/heads/master | 2021-01-17T17:09:07.955000 | 2016-08-07T21:01:07 | 2016-08-07T21:01:07 | 62,896,643 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.devbugger.pagery.transform.pagery;
import com.devbugger.pagery.configuration.Config;
import com.devbugger.pagery.configuration.PageryConfigSupport;
import com.devbugger.pagery.site.BasePage;
import com.devbugger.pagery.site.Page;
import java.util.List;
public interface TransformPageryBasePage<T, S> extends PageryConfigSupport {
/**
* Transform the content within a template based on the occurrence
* of markers defined in {@link PageryMarkers}
* @param t the page type
* @param s list of input data
* @param config active configuration file
* @return the transformed html as S
*/
T transform(Config config, T t, List<S> s);
/**
* This is a specialized, non-genric method for attaching
* {@link com.devbugger.pagery.site.BasePage} content to the given {@link Page}.
* @param basePage content to attach
* @param page receiver of content
* @param pages the pages used to attach menu tags
* @return page with basepage content attached
*/
Page attach(BasePage basePage, Page page, List<Page> pages);
}
| UTF-8 | Java | 1,104 | java | TransformPageryBasePage.java | Java | [] | null | [] | package com.devbugger.pagery.transform.pagery;
import com.devbugger.pagery.configuration.Config;
import com.devbugger.pagery.configuration.PageryConfigSupport;
import com.devbugger.pagery.site.BasePage;
import com.devbugger.pagery.site.Page;
import java.util.List;
public interface TransformPageryBasePage<T, S> extends PageryConfigSupport {
/**
* Transform the content within a template based on the occurrence
* of markers defined in {@link PageryMarkers}
* @param t the page type
* @param s list of input data
* @param config active configuration file
* @return the transformed html as S
*/
T transform(Config config, T t, List<S> s);
/**
* This is a specialized, non-genric method for attaching
* {@link com.devbugger.pagery.site.BasePage} content to the given {@link Page}.
* @param basePage content to attach
* @param page receiver of content
* @param pages the pages used to attach menu tags
* @return page with basepage content attached
*/
Page attach(BasePage basePage, Page page, List<Page> pages);
}
| 1,104 | 0.714674 | 0.714674 | 31 | 34.612904 | 25.195593 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false | 6 |
68005e88f3ebc67e67bff78cc76a57ce719012a8 | 24,017,457,136,208 | 99093c3b4dbd9a2b04027b9103effb1d3b6c2d92 | /app/src/main/java/com/example/sreekanthkasani/login/BarChart.java | 23fd55499bc8007063f986e29467b66334244c5b | [] | no_license | sreekanthkasani/loginApp | https://github.com/sreekanthkasani/loginApp | eed3ce48e22fa339daedc2138547d5641977db2b | 3aff2527a5b2de4708ac52a6abed2506bc24c5b7 | refs/heads/master | 2021-05-09T01:14:53.976000 | 2018-02-01T05:38:31 | 2018-02-01T05:38:31 | 119,782,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.sreekanthkasani.login;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by sreekanth kasani ') on 12/4/2017.
*/
public class BarChart extends Fragment {
public static BarChart newInstance(int page, String title){
BarChart BarChart = new BarChart();
Bundle args = new Bundle();
args.putInt("hello",page);
BarChart.setArguments(args);
return BarChart;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.intro2,container,false);
return view;
}
}
| UTF-8 | Java | 836 | java | BarChart.java | Java | [
{
"context": "\nimport android.view.ViewGroup;\n\n/**\n * Created by sreekanth kasani ') on 12/4/2017.\n */\n\npublic class BarChart exte",
"end": 282,
"score": 0.9995675683021545,
"start": 266,
"tag": "NAME",
"value": "sreekanth kasani"
}
] | null | [] | package com.example.sreekanthkasani.login;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by <NAME> ') on 12/4/2017.
*/
public class BarChart extends Fragment {
public static BarChart newInstance(int page, String title){
BarChart BarChart = new BarChart();
Bundle args = new Bundle();
args.putInt("hello",page);
BarChart.setArguments(args);
return BarChart;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.intro2,container,false);
return view;
}
}
| 826 | 0.712919 | 0.702153 | 29 | 27.827587 | 26.771149 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false | 6 |
a1052e69a7e854ad3c71133dec24ed3d0282263b | 3,736,621,605,068 | abb159c671e6f7859776acacf9a59a1330b8b37c | /magnolia/src/main/java/com/bitwise/magnolia/vo/school/DepartmentVo.java | 764b130d0b8ac23c74f4e37a81c350f372f90f54 | [] | no_license | bitwiseTek/magnolia-web | https://github.com/bitwiseTek/magnolia-web | e3a41e15f5e4fe9d7599baf2bd335f40d1226524 | 7af061976231f4cbc2b7aec00b8ec3693ae3439b | refs/heads/master | 2021-01-11T15:28:41.743000 | 2017-02-14T19:41:27 | 2017-02-14T19:41:27 | 80,354,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bitwise.magnolia.vo.school;
public class DepartmentVo {
private long departmentId;
private String name;
private String status;
public DepartmentVo(){
}
public long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(long departmentId) {
this.departmentId = departmentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| UTF-8 | Java | 554 | java | DepartmentVo.java | Java | [] | null | [] | package com.bitwise.magnolia.vo.school;
public class DepartmentVo {
private long departmentId;
private String name;
private String status;
public DepartmentVo(){
}
public long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(long departmentId) {
this.departmentId = departmentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| 554 | 0.709386 | 0.709386 | 37 | 13.972973 | 14.677592 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.162162 | false | false | 6 |
d7148509b4faeb2d0d4e1bb0aca2d9a05bbc0a18 | 14,774,687,536,118 | 48a759e876ed6e7fd1e5d03edcb3ba3ea0beaf8f | /mutfak2/src/com/chatt/demo/rw/model/UrunListRow.java | 5f04bf606b54ed331519649c5929ee7e2a20b31b | [] | no_license | iang12/Android | https://github.com/iang12/Android | b0fd329c17b968f016a2e159543dffc95206e1a5 | 0dd5f97463a55068edbe3b6656880d0d7b0804b3 | refs/heads/master | 2021-05-10T08:46:48.550000 | 2018-01-24T14:11:37 | 2018-01-24T14:11:37 | 118,903,406 | 30 | 0 | null | true | 2018-01-25T11:15:45 | 2018-01-25T11:15:45 | 2018-01-25T06:23:29 | 2018-01-24T14:11:38 | 115,296 | 0 | 0 | 0 | null | false | null | package com.chatt.demo.rw.model;
public class UrunListRow {
public String StokID = "-1";
public String Aciklama = "";
public String Fiyat = "0.0 TL";
}
| UTF-8 | Java | 156 | java | UrunListRow.java | Java | [] | null | [] | package com.chatt.demo.rw.model;
public class UrunListRow {
public String StokID = "-1";
public String Aciklama = "";
public String Fiyat = "0.0 TL";
}
| 156 | 0.692308 | 0.673077 | 7 | 21.285715 | 13.284946 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 6 |
e1af3996216b03141add64e26760945c1fb8ab31 | 14,860,586,905,393 | d1937004398c83958eaf0ef732a9b73e369b2d73 | /src/main/java/pl/repeat/generics/RectangleBox.java | e6be7a6e3dee7eb8388016a7e7b6e4c3a6d45152 | [] | no_license | YMnZSdlc/Wzorce | https://github.com/YMnZSdlc/Wzorce | 4347ffc275f32c938b1692a6b5776aba99d032cc | 50aacc18231a3025417b995663e8a8eb6c7bb287 | refs/heads/master | 2020-03-19T23:43:06.660000 | 2018-07-16T03:56:37 | 2018-07-16T03:56:37 | 137,016,874 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.repeat.generics;
class RectangleBox <T extends Rectangle> {
private T rectangle;
T getRectangle() {
return rectangle;
}
void setRectangle(T rectangle) {
this.rectangle = rectangle;
}
}
| UTF-8 | Java | 236 | java | RectangleBox.java | Java | [] | null | [] | package pl.repeat.generics;
class RectangleBox <T extends Rectangle> {
private T rectangle;
T getRectangle() {
return rectangle;
}
void setRectangle(T rectangle) {
this.rectangle = rectangle;
}
}
| 236 | 0.635593 | 0.635593 | 14 | 15.857142 | 15.18861 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 6 |
92ad708531f7b05c6687e76c21fb5228848b0606 | 28,509,992,938,594 | d7d4058a198138f59df1c593101fc2295267ab19 | /app/src/main/java/com/example/anzhuo/myapplication/Message/MessageFragment.java | a92766286f8aabe66c0ba0f47f4d6e733eecfbda | [] | no_license | Mylovejackdog/MyApplication2 | https://github.com/Mylovejackdog/MyApplication2 | 592a6a718ba9ce6cff76ef0e65af03bff3e03fb6 | f8127879b6599640bd208c7f3921bb4ab1376217 | refs/heads/master | 2020-09-14T11:34:50.508000 | 2016-10-14T06:05:46 | 2016-10-14T06:05:46 | 67,774,327 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.anzhuo.myapplication.Message;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.example.anzhuo.myapplication.My.Myactivity;
import com.example.anzhuo.myapplication.R;
/**
* Created by anzhuo on 2016/9/9.
*/
public class MessageFragment extends Fragment {
public ImageView iv_main;
public TextView tv_blacklist;
public LinearLayout contribute;
public LinearLayout message;
public LinearLayout fans;
public ListView lv_content;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.oldcar_message_layout, null);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
iv_main = (ImageView) view.findViewById(R.id.iv_main);
tv_blacklist = (TextView) view.findViewById(R.id.tv_blacklist);
contribute = (LinearLayout) view.findViewById(R.id.contribute);
message = (LinearLayout) view.findViewById(R.id.message);
fans = (LinearLayout) view.findViewById(R.id.fans);
lv_content = (ListView) view.findViewById(R.id.lv_content);
iv_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Myactivity.class);
startActivity(intent);
}
});
tv_blacklist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
contribute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Message_interaction_Activity.class);
startActivity(intent);
}
});
message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Message_message_Activity.class);
startActivity(intent);
}
});
fans.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Message_fans_Activity.class);
startActivity(intent);
}
});
lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
}
| UTF-8 | Java | 3,391 | java | MessageFragment.java | Java | [
{
"context": "example.anzhuo.myapplication.R;\n\n/**\n * Created by anzhuo on 2016/9/9.\n */\npublic class MessageFragment ext",
"end": 578,
"score": 0.9994003176689148,
"start": 572,
"tag": "USERNAME",
"value": "anzhuo"
}
] | null | [] | package com.example.anzhuo.myapplication.Message;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.example.anzhuo.myapplication.My.Myactivity;
import com.example.anzhuo.myapplication.R;
/**
* Created by anzhuo on 2016/9/9.
*/
public class MessageFragment extends Fragment {
public ImageView iv_main;
public TextView tv_blacklist;
public LinearLayout contribute;
public LinearLayout message;
public LinearLayout fans;
public ListView lv_content;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.oldcar_message_layout, null);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
iv_main = (ImageView) view.findViewById(R.id.iv_main);
tv_blacklist = (TextView) view.findViewById(R.id.tv_blacklist);
contribute = (LinearLayout) view.findViewById(R.id.contribute);
message = (LinearLayout) view.findViewById(R.id.message);
fans = (LinearLayout) view.findViewById(R.id.fans);
lv_content = (ListView) view.findViewById(R.id.lv_content);
iv_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Myactivity.class);
startActivity(intent);
}
});
tv_blacklist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
contribute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Message_interaction_Activity.class);
startActivity(intent);
}
});
message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Message_message_Activity.class);
startActivity(intent);
}
});
fans.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Message_fans_Activity.class);
startActivity(intent);
}
});
lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
}
| 3,391 | 0.602182 | 0.600118 | 90 | 36.655556 | 27.101522 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622222 | false | false | 6 |
c7f28d0de07d009780b7a9abca1e72460513bf84 | 14,834,817,096,007 | aa54812940a9b526a42e2f711a2fd519e30a68a8 | /GoldmanSachsCodeSprint/src/BuyMaximumStocks.java | c531803b9cd8ab342ee25733b2684db78e019c25 | [] | no_license | OlenaGlu/HackerSolveTasks | https://github.com/OlenaGlu/HackerSolveTasks | 01e27774093f3c5221f7de8124ea7a6dd78ee7e0 | 4d1c8a7527ba27688e8025d92d5df7a8d641e124 | refs/heads/master | 2021-01-20T22:22:33.429000 | 2017-08-30T06:22:30 | 2017-08-30T06:22:30 | 101,816,652 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Arrays;
import java.util.Scanner;
/**
* Created by olenag on 8/18/2017.
*/
// need update to situation whet you skip first day
public class BuyMaximumStocks {
static int maxPossible(long less, int price, int count) {
int res = 0;
if (count * price > less) {
count--;
return res = maxPossible(less, price, count);
} else {
res = count;
return res;
}
}
static long buyMaximumProducts(int n, long k, int[] a) {
// Complete this function
int max = 0;
int min = Integer.MAX_VALUE;
int simpleSum = 0;
long count = 0;
long less = k;
for (int i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
}
if (a[i] < min) {
min = a[i];
}
if ((a[i] * (i + 1)) < less) {
simpleSum = simpleSum + a[i] * (i + 1);
less = less - (a[i] * (i + 1));
count = count + i + 1;
} else {
int c = maxPossible(less, a[i], (i+1));
less = less - (a[i] * c);
count = count + c;
}
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int arr_i = 0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
long k = in.nextLong();
long result = buyMaximumProducts(n, k, arr);
System.out.println(result);
in.close();
}
}
| UTF-8 | Java | 1,754 | java | BuyMaximumStocks.java | Java | [
{
"context": ";\r\nimport java.util.Scanner;\r\n\r\n/**\r\n * Created by olenag on 8/18/2017.\r\n */\r\n// need update to situation w",
"end": 80,
"score": 0.9996575713157654,
"start": 74,
"tag": "USERNAME",
"value": "olenag"
}
] | null | [] | import java.util.Arrays;
import java.util.Scanner;
/**
* Created by olenag on 8/18/2017.
*/
// need update to situation whet you skip first day
public class BuyMaximumStocks {
static int maxPossible(long less, int price, int count) {
int res = 0;
if (count * price > less) {
count--;
return res = maxPossible(less, price, count);
} else {
res = count;
return res;
}
}
static long buyMaximumProducts(int n, long k, int[] a) {
// Complete this function
int max = 0;
int min = Integer.MAX_VALUE;
int simpleSum = 0;
long count = 0;
long less = k;
for (int i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
}
if (a[i] < min) {
min = a[i];
}
if ((a[i] * (i + 1)) < less) {
simpleSum = simpleSum + a[i] * (i + 1);
less = less - (a[i] * (i + 1));
count = count + i + 1;
} else {
int c = maxPossible(less, a[i], (i+1));
less = less - (a[i] * c);
count = count + c;
}
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int arr_i = 0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
long k = in.nextLong();
long result = buyMaximumProducts(n, k, arr);
System.out.println(result);
in.close();
}
}
| 1,754 | 0.414481 | 0.404219 | 62 | 26.290323 | 17.170292 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.693548 | false | false | 6 |
95cac506dc5f1ab279a4838c730ea2e841585796 | 21,809,843,959,949 | a0e4f155a7b594f78a56958bca2cadedced8ffcd | /compute/src/main/java/org/zstack/compute/host/HostReconnectTaskFactory.java | bb3c548f6dd739be0ff5a1e01aeaed057eae9f0d | [
"Apache-2.0"
] | permissive | zhao-qc/zstack | https://github.com/zhao-qc/zstack | e67533eabbbabd5ae9118d256f560107f9331be0 | b38cd2324e272d736f291c836f01966f412653fa | refs/heads/master | 2020-08-14T15:03:52.102000 | 2019-10-14T03:51:12 | 2019-10-14T03:51:12 | 215,187,833 | 3 | 0 | Apache-2.0 | true | 2019-10-15T02:27:17 | 2019-10-15T02:27:16 | 2019-10-15T02:26:59 | 2019-10-14T12:00:10 | 73,614 | 0 | 0 | 0 | null | false | false | package org.zstack.compute.host;
import org.zstack.header.core.NoErrorCompletion;
public interface HostReconnectTaskFactory {
HostReconnectTask createTask(String uuid, NoErrorCompletion completion);
String getHypervisorType();
}
| UTF-8 | Java | 240 | java | HostReconnectTaskFactory.java | Java | [] | null | [] | package org.zstack.compute.host;
import org.zstack.header.core.NoErrorCompletion;
public interface HostReconnectTaskFactory {
HostReconnectTask createTask(String uuid, NoErrorCompletion completion);
String getHypervisorType();
}
| 240 | 0.8125 | 0.8125 | 9 | 25.666666 | 25.789747 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 6 |
8e5e0e810da8d3250f471bc00942041878b9f136 | 17,016,660,492,000 | a82d26a81fd9ebb68d2e71cc518ee76e4b91be0b | /ruoyi-admin/src/main/java/com/ruoyi/Test/Absfnlskf.java | 1ee5c06a54edb69fbdd52dcd251a96277c6161df | [
"MIT"
] | permissive | One1111111/ruoyi | https://github.com/One1111111/ruoyi | b124dd5144e725b1286d0ebb7858b59bb25c77c7 | accf584155c013c990025779862a40d7a57ec425 | refs/heads/master | 2022-02-21T06:47:12.441000 | 2020-03-11T10:23:24 | 2020-03-11T10:23:24 | 235,507,346 | 0 | 0 | MIT | false | 2022-02-09T22:22:08 | 2020-01-22T05:46:46 | 2020-03-14T12:42:48 | 2022-02-09T22:22:08 | 5,955 | 0 | 0 | 5 | HTML | false | false | package com.ruoyi.Test;
import com.ruoyi.travel.domain.AttractionsTable;
import com.ruoyi.travel.domain.TrainTable;
import com.ruoyi.travel.service.impl.AttractionsTableServiceImpl;
import com.ruoyi.travel.service.impl.PassengersTableServiceImpl;
import com.ruoyi.travel.service.impl.TrainTableServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import static com.ruoyi.Test.Pc.getAddress;
import static com.ruoyi.Test.TT.getRandom;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Absfnlskf {
@Resource
AttractionsTableServiceImpl attractionsTableService;
@Autowired
TrainTableServiceImpl tableService;
@Resource
PassengersTableServiceImpl passengersTableService;
/* @Test
public void sayHello() throws Exception {
PassengersTable passengersTable = new PassengersTable();
Random rand = new Random();
List<String> cxfs = Arrays.asList("自驾游", "旅游团", "飞机", "高铁", "自行车");
List<String> gjz = Arrays.asList("特色美食", "特色民宿", "周边游", "避暑", "免签","中国古镇","夜游","博物馆");
String[] s = Pc.getAddress();
while (true) {
// passengersTable = null;
passengersTable.setName(getChineseName.ChineseName());
passengersTable.setSex(Long.valueOf(rand.nextInt(2)));
passengersTable.setAge(Long.valueOf(rand.nextInt(101)));
passengersTable.setPlace(s[rand.nextInt(s.length)]);
passengersTable.setSearch(gjz.get(rand.nextInt(gjz.size())));
passengersTable.setTripMode(cxfs.get(rand.nextInt(cxfs.size())));
passengersTable.setTravelCost(Double.valueOf(rand.nextInt(5000)+5000));
passengersTableService.insertPassengersTable(passengersTable);
}
}*/ //添加passengersTable数据
@Test
public void upAteattra() {
List<AttractionsTable> attractionsTables = attractionsTableService.selectAttractionsTableList(new AttractionsTable());
Random random = new Random();
for (int i = 0; i < attractionsTables.size(); i++) {
AttractionsTable attractionsTable = attractionsTables.get(i);
attractionsTable.setHumanTraffic(Long.valueOf(random.nextInt(10000) + 1000));
attractionsTableService.updateAttractionsTable(attractionsTable);
}
System.out.println("66666");
}
/**
* 列车数据添加
*/
@Test
public void a() {
Calendar rightNow = Calendar.getInstance();
TrainTable trainTable = new TrainTable();
ArrayList<String> Lt = new ArrayList<>();
ArrayList<String> dt = new ArrayList<>();
String[] address = getAddress();//省份地址
Random rand = new Random();
int n = 0;
Lt.add("G"); //高速动车
Lt.add("C"); //城际动车
Lt.add("D"); //普通动车
Lt.add("Z"); //直达特快列车
Lt.add("T"); //特快列车
Lt.add("K"); //快速列车
Lt.add("L"); //临客列车
Lt.add("Y"); //旅游列车
dt.add("高速动车");
dt.add("城际动车");
dt.add("普通动车");
dt.add("直达特快列车");
dt.add("特快列车");
dt.add("快速列车");
dt.add("临客列车");
dt.add("旅游列车");
while ( true) {
trainTable.setType(dt.get(rand.nextInt(dt.size())));
trainTable.setHairstanding(address[rand.nextInt(address.length)]);
trainTable.setTheterminal(address[rand.nextInt(address.length)]);
if (trainTable.getHairstanding().equals(trainTable.getTheterminal())) {
trainTable.setTheterminal(address[rand.nextInt(address.length)]);
}
trainTable.setTransferstation(address[rand.nextInt(address.length)]);
//出发时间 到站时间
rightNow.set(Calendar.HOUR,rand.nextInt(25));
rightNow.set(Calendar.MINUTE, rand.nextInt(60));
trainTable.setDrivingtime(rightNow.getTime());
int i = rightNow.get(rightNow.HOUR);
int m = rightNow.get(rightNow.MINUTE);
rightNow.set(rightNow.HOUR, i+rand.nextInt(4)+1);
rightNow.set(rightNow.MINUTE, m+rand.nextInt(60)+10);
trainTable.setTimeofarrival(rightNow.getTime());
trainTable.setStandNumber(Long.valueOf(rand.nextInt(20) + 5));
switch (trainTable.getType()) {
case "高速动车":
trainTable.setTrains("G" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*18));
break;
case "城际动车":
trainTable.setTrains("C" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*17));
break;
case "普通动车":
trainTable.setTrains("D" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*16));
break;
case "直达特快列车":
trainTable.setTrains("Z" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*15));
break;
case "特快列车":
trainTable.setTrains("T" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*14));
break;
case "快速列车":
trainTable.setTrains("K" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*13));
break;
case "临客列车":
trainTable.setTrains("L" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*12));
break;
case "旅游列车":
trainTable.setTrains("Y" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*11));
break;
}
List<TrainTable> trainTables = tableService.selectTrainTableList(new TrainTable());
trainTables.forEach(item -> {
if (item.getHairstanding().equals(trainTable.getHairstanding()) && item.getTheterminal().equals(trainTable.getTheterminal())) {
trainTable.setStandNumber(item.getStandNumber());
trainTable.setPrice(item.getPrice());
}
});
n++;
tableService.insertTrainTable(trainTable);
}
}
// /**
// * 文件上传测试
// */
// @PostMapping("/add")
// @ResponseBody
// public AjaxResult addSave(@RequestParam("file") MultipartFile file, FileInfo fileInfo) throws IOException
// {
// // 上传文件路径
// String filePath = RuoYiConfig.getUploadPath();
// // 上传并返回新文件名称
// String fileName = FileUploadUtils.upload(filePath, file);
// fileInfo.setFilePath(fileName);
// return toAjax(fileInfoService.insertFileInfo(fileInfo));
// }
}
| UTF-8 | Java | 7,614 | java | Absfnlskf.java | Java | [] | null | [] | package com.ruoyi.Test;
import com.ruoyi.travel.domain.AttractionsTable;
import com.ruoyi.travel.domain.TrainTable;
import com.ruoyi.travel.service.impl.AttractionsTableServiceImpl;
import com.ruoyi.travel.service.impl.PassengersTableServiceImpl;
import com.ruoyi.travel.service.impl.TrainTableServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import static com.ruoyi.Test.Pc.getAddress;
import static com.ruoyi.Test.TT.getRandom;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Absfnlskf {
@Resource
AttractionsTableServiceImpl attractionsTableService;
@Autowired
TrainTableServiceImpl tableService;
@Resource
PassengersTableServiceImpl passengersTableService;
/* @Test
public void sayHello() throws Exception {
PassengersTable passengersTable = new PassengersTable();
Random rand = new Random();
List<String> cxfs = Arrays.asList("自驾游", "旅游团", "飞机", "高铁", "自行车");
List<String> gjz = Arrays.asList("特色美食", "特色民宿", "周边游", "避暑", "免签","中国古镇","夜游","博物馆");
String[] s = Pc.getAddress();
while (true) {
// passengersTable = null;
passengersTable.setName(getChineseName.ChineseName());
passengersTable.setSex(Long.valueOf(rand.nextInt(2)));
passengersTable.setAge(Long.valueOf(rand.nextInt(101)));
passengersTable.setPlace(s[rand.nextInt(s.length)]);
passengersTable.setSearch(gjz.get(rand.nextInt(gjz.size())));
passengersTable.setTripMode(cxfs.get(rand.nextInt(cxfs.size())));
passengersTable.setTravelCost(Double.valueOf(rand.nextInt(5000)+5000));
passengersTableService.insertPassengersTable(passengersTable);
}
}*/ //添加passengersTable数据
@Test
public void upAteattra() {
List<AttractionsTable> attractionsTables = attractionsTableService.selectAttractionsTableList(new AttractionsTable());
Random random = new Random();
for (int i = 0; i < attractionsTables.size(); i++) {
AttractionsTable attractionsTable = attractionsTables.get(i);
attractionsTable.setHumanTraffic(Long.valueOf(random.nextInt(10000) + 1000));
attractionsTableService.updateAttractionsTable(attractionsTable);
}
System.out.println("66666");
}
/**
* 列车数据添加
*/
@Test
public void a() {
Calendar rightNow = Calendar.getInstance();
TrainTable trainTable = new TrainTable();
ArrayList<String> Lt = new ArrayList<>();
ArrayList<String> dt = new ArrayList<>();
String[] address = getAddress();//省份地址
Random rand = new Random();
int n = 0;
Lt.add("G"); //高速动车
Lt.add("C"); //城际动车
Lt.add("D"); //普通动车
Lt.add("Z"); //直达特快列车
Lt.add("T"); //特快列车
Lt.add("K"); //快速列车
Lt.add("L"); //临客列车
Lt.add("Y"); //旅游列车
dt.add("高速动车");
dt.add("城际动车");
dt.add("普通动车");
dt.add("直达特快列车");
dt.add("特快列车");
dt.add("快速列车");
dt.add("临客列车");
dt.add("旅游列车");
while ( true) {
trainTable.setType(dt.get(rand.nextInt(dt.size())));
trainTable.setHairstanding(address[rand.nextInt(address.length)]);
trainTable.setTheterminal(address[rand.nextInt(address.length)]);
if (trainTable.getHairstanding().equals(trainTable.getTheterminal())) {
trainTable.setTheterminal(address[rand.nextInt(address.length)]);
}
trainTable.setTransferstation(address[rand.nextInt(address.length)]);
//出发时间 到站时间
rightNow.set(Calendar.HOUR,rand.nextInt(25));
rightNow.set(Calendar.MINUTE, rand.nextInt(60));
trainTable.setDrivingtime(rightNow.getTime());
int i = rightNow.get(rightNow.HOUR);
int m = rightNow.get(rightNow.MINUTE);
rightNow.set(rightNow.HOUR, i+rand.nextInt(4)+1);
rightNow.set(rightNow.MINUTE, m+rand.nextInt(60)+10);
trainTable.setTimeofarrival(rightNow.getTime());
trainTable.setStandNumber(Long.valueOf(rand.nextInt(20) + 5));
switch (trainTable.getType()) {
case "高速动车":
trainTable.setTrains("G" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*18));
break;
case "城际动车":
trainTable.setTrains("C" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*17));
break;
case "普通动车":
trainTable.setTrains("D" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*16));
break;
case "直达特快列车":
trainTable.setTrains("Z" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*15));
break;
case "特快列车":
trainTable.setTrains("T" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*14));
break;
case "快速列车":
trainTable.setTrains("K" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*13));
break;
case "临客列车":
trainTable.setTrains("L" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*12));
break;
case "旅游列车":
trainTable.setTrains("Y" + getRandom(4));
trainTable.setPrice(Long.valueOf(trainTable.getStandNumber()*11));
break;
}
List<TrainTable> trainTables = tableService.selectTrainTableList(new TrainTable());
trainTables.forEach(item -> {
if (item.getHairstanding().equals(trainTable.getHairstanding()) && item.getTheterminal().equals(trainTable.getTheterminal())) {
trainTable.setStandNumber(item.getStandNumber());
trainTable.setPrice(item.getPrice());
}
});
n++;
tableService.insertTrainTable(trainTable);
}
}
// /**
// * 文件上传测试
// */
// @PostMapping("/add")
// @ResponseBody
// public AjaxResult addSave(@RequestParam("file") MultipartFile file, FileInfo fileInfo) throws IOException
// {
// // 上传文件路径
// String filePath = RuoYiConfig.getUploadPath();
// // 上传并返回新文件名称
// String fileName = FileUploadUtils.upload(filePath, file);
// fileInfo.setFilePath(fileName);
// return toAjax(fileInfoService.insertFileInfo(fileInfo));
// }
}
| 7,614 | 0.598924 | 0.589818 | 180 | 39.266666 | 28.468813 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727778 | false | false | 6 |
e78c6c69a0873d0e301fc877878fc2a02f789342 | 12,695,923,386,008 | 714ab2d432ba83a5c4b8bc2db28349b4ed9ae0a5 | /src/CleanStart/Mk06/SubVars/FunctionVar.java | 1282603cee07fff4e2b115dc99a68a8b3bd66189 | [] | no_license | MechaGent/LuaBytecodeDecompiler | https://github.com/MechaGent/LuaBytecodeDecompiler | 96c97367476a0cbecddb0e5dd09d499cc8418090 | 87c68442bb551040323aa80dfc63c10f1c854ce9 | refs/heads/master | 2021-01-11T13:56:35.113000 | 2017-06-20T15:24:58 | 2017-06-20T15:24:58 | 94,905,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CleanStart.Mk06.SubVars;
import CleanStart.Mk06.Var;
import CleanStart.Mk06.Enums.InferenceTypes;
import CleanStart.Mk06.FunctionObjects.FunctionObject;
public class FunctionVar extends Var
{
private static int instanceCounter = 0;
private final FunctionObject core;
public FunctionVar(String inNamePrefix, FunctionObject inCore)
{
super(inNamePrefix, instanceCounter++);
this.core = inCore;
}
public static FunctionVar getInstance(String inNamePrefix, FunctionObject inCore)
{
return new FunctionVar(inNamePrefix, inCore);
}
@Override
public InferenceTypes getInitialType()
{
return InferenceTypes.FunctionObject;
}
@Override
public String getMangledName(boolean appendMetadata)
{
return this.namePrefix + this.core.getName() + '_' + this.instanceNumber_specific;
}
@Override
public String getValueAsString()
{
return this.getMangledName(false);
}
@Override
public int getValueAsInt()
{
throw new UnsupportedOperationException();
}
@Override
public float getValueAsFloat()
{
throw new UnsupportedOperationException();
}
@Override
public boolean getValueAsBoolean()
{
throw new UnsupportedOperationException();
}
}
| UTF-8 | Java | 1,187 | java | FunctionVar.java | Java | [] | null | [] | package CleanStart.Mk06.SubVars;
import CleanStart.Mk06.Var;
import CleanStart.Mk06.Enums.InferenceTypes;
import CleanStart.Mk06.FunctionObjects.FunctionObject;
public class FunctionVar extends Var
{
private static int instanceCounter = 0;
private final FunctionObject core;
public FunctionVar(String inNamePrefix, FunctionObject inCore)
{
super(inNamePrefix, instanceCounter++);
this.core = inCore;
}
public static FunctionVar getInstance(String inNamePrefix, FunctionObject inCore)
{
return new FunctionVar(inNamePrefix, inCore);
}
@Override
public InferenceTypes getInitialType()
{
return InferenceTypes.FunctionObject;
}
@Override
public String getMangledName(boolean appendMetadata)
{
return this.namePrefix + this.core.getName() + '_' + this.instanceNumber_specific;
}
@Override
public String getValueAsString()
{
return this.getMangledName(false);
}
@Override
public int getValueAsInt()
{
throw new UnsupportedOperationException();
}
@Override
public float getValueAsFloat()
{
throw new UnsupportedOperationException();
}
@Override
public boolean getValueAsBoolean()
{
throw new UnsupportedOperationException();
}
}
| 1,187 | 0.770008 | 0.762426 | 59 | 19.118645 | 22.119923 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.220339 | false | false | 6 |
977432184bea9df1eabddbfcef1d3d61d7b5fef1 | 12,695,923,384,469 | 2997834bff4e164c755fb25a5072074cfc42c70c | /app/src/main/java/com/youshi/personjw/Test.java | 4d444fa4a26cebb8a9523f1a6b6ace744777be66 | [] | no_license | houdianjie/PersonJW | https://github.com/houdianjie/PersonJW | 05723c5145326b680d6fd9d02e7d96d7c5513629 | fa45592efbdf6d8d811ea1800523b36e1c8191f2 | refs/heads/master | 2021-01-23T05:25:50.581000 | 2017-09-05T10:58:33 | 2017-09-05T10:58:33 | 102,466,823 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.youshi.personjw;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.youshi.personjw.uitl.GetHttp;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* Created by dianjie on 2016/7/18.
*/
public class Test extends Activity {
private String cook;
private Button person_classroom_btn1;
private GetHttp getHttp;
private Person_MyHandler myHandler;
private TextView [][]person_course_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.person_classroom);
init();
}
private void init(){
person_classroom_btn1 = (Button) findViewById(R.id.person_classroom_btn1);
getHttp = GetHttp.getGetHttp();
myHandler = new Person_MyHandler();
// person_classroom_tv1 = (TextView) findViewById(R.id.person_classroom_tv1);
person_course_tv = new TextView[5][7];
sub_inti();
}
private void sub_inti(){
person_course_tv[0][0] = (TextView) findViewById(R.id.person_course_tv11);person_course_tv[0][1] = (TextView) findViewById(R.id.person_course_tv12);person_course_tv[0][2] = (TextView) findViewById(R.id.person_course_tv13);
person_course_tv[0][3] = (TextView) findViewById(R.id.person_course_tv14);person_course_tv[0][4] = (TextView) findViewById(R.id.person_course_tv15);person_course_tv[0][5] = (TextView) findViewById(R.id.person_course_tv16);
person_course_tv[0][6] = (TextView) findViewById(R.id.person_course_tv17);person_course_tv[1][0] = (TextView) findViewById(R.id.person_course_tv21);person_course_tv[1][1] = (TextView) findViewById(R.id.person_course_tv22);
person_course_tv[1][2] = (TextView) findViewById(R.id.person_course_tv23);person_course_tv[1][3] = (TextView) findViewById(R.id.person_course_tv24);person_course_tv[1][4] = (TextView) findViewById(R.id.person_course_tv25);
person_course_tv[1][5] = (TextView) findViewById(R.id.person_course_tv26);person_course_tv[1][6] = (TextView) findViewById(R.id.person_course_tv27);person_course_tv[2][0] = (TextView) findViewById(R.id.person_course_tv31);
person_course_tv[2][1] = (TextView) findViewById(R.id.person_course_tv32);person_course_tv[2][2] = (TextView) findViewById(R.id.person_course_tv33);person_course_tv[2][3] = (TextView) findViewById(R.id.person_course_tv34);
person_course_tv[2][4] = (TextView) findViewById(R.id.person_course_tv35);person_course_tv[2][5] = (TextView) findViewById(R.id.person_course_tv36);person_course_tv[2][6] = (TextView) findViewById(R.id.person_course_tv37);
person_course_tv[3][0] = (TextView) findViewById(R.id.person_course_tv41);person_course_tv[3][1] = (TextView) findViewById(R.id.person_course_tv42);person_course_tv[3][2] = (TextView) findViewById(R.id.person_course_tv43);
person_course_tv[3][3] = (TextView) findViewById(R.id.person_course_tv44);person_course_tv[3][4] = (TextView) findViewById(R.id.person_course_tv45);person_course_tv[3][5] = (TextView) findViewById(R.id.person_course_tv46);
person_course_tv[3][6] = (TextView) findViewById(R.id.person_course_tv47);person_course_tv[4][0] = (TextView) findViewById(R.id.person_course_tv51);person_course_tv[4][1] = (TextView) findViewById(R.id.person_course_tv52);
person_course_tv[4][2] = (TextView) findViewById(R.id.person_course_tv53);person_course_tv[4][3] = (TextView) findViewById(R.id.person_course_tv54);person_course_tv[4][4] = (TextView) findViewById(R.id.person_course_tv55);
person_course_tv[4][5] = (TextView) findViewById(R.id.person_course_tv56);person_course_tv[4][6] = (TextView) findViewById(R.id.person_course_tv57);
}
public void classroom_btn1_click(View v){
String s = parsehtml(s());
}
public void StoreResult(String a){
String []splits1 = a.split("\\|\\|");
String [][]splits2 = new String[splits1.length][] ;
for(int i=0;i<splits1.length;i++){
splits2[i] = splits1[i].split("#");
}
}
//重写Handler方法,主要为了实现子线程与主线程之间的 数据传递
class Person_MyHandler extends Handler {
// 子类必须重写此方法,接受数据
@Override
public void handleMessage(Message msg) {
// 此处可以更新UI
if(msg.what == 100){
Bundle b = msg.getData();
String result = b.getString("course_temp");
//tv2.setText(result);
}
super.handleMessage(msg);
}
}
//利用Jsoup解析网页内容
private String parsehtml(String result){
String total="",results = "";
int i = 0;
String []score = new String[100];
Document doc = Jsoup.parse(result);
System.out.println( doc.title());
Elements link_class = doc.select("tr.infolist_common[style=\"display:\"]");
// Elements link_class = doc.select("td.center > a");
for(Element link:link_class){
/* String name;
name = link.tagName();
score[i] = link.text();
if(name.equals("a") && flag == 0){
total += score[i]+",";
flag = 1;
} else if (name.equals("a") && flag == 1) {
total += score[i]+" ";
} else {
total += ","+score[i];
results += total + "||";
System.out.println(total);
flag = 0;
total = "";
}*/
String name;
name = link.tagName();
System.out.println(name);
score[i] = link.text();
total += score[i]+"||\n";
System.out.println(score[i]);
results = total;
}
return results;
}
//测试用的html字符串
private String s(){
return "aa";
}
}
| UTF-8 | Java | 6,183 | java | Test.java | Java | [
{
"context": "port org.jsoup.select.Elements;\n\n/**\n * Created by dianjie on 2016/7/18.\n */\npublic class Test extends Activ",
"end": 450,
"score": 0.9996725916862488,
"start": 443,
"tag": "USERNAME",
"value": "dianjie"
}
] | null | [] | package com.youshi.personjw;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.youshi.personjw.uitl.GetHttp;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* Created by dianjie on 2016/7/18.
*/
public class Test extends Activity {
private String cook;
private Button person_classroom_btn1;
private GetHttp getHttp;
private Person_MyHandler myHandler;
private TextView [][]person_course_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.person_classroom);
init();
}
private void init(){
person_classroom_btn1 = (Button) findViewById(R.id.person_classroom_btn1);
getHttp = GetHttp.getGetHttp();
myHandler = new Person_MyHandler();
// person_classroom_tv1 = (TextView) findViewById(R.id.person_classroom_tv1);
person_course_tv = new TextView[5][7];
sub_inti();
}
private void sub_inti(){
person_course_tv[0][0] = (TextView) findViewById(R.id.person_course_tv11);person_course_tv[0][1] = (TextView) findViewById(R.id.person_course_tv12);person_course_tv[0][2] = (TextView) findViewById(R.id.person_course_tv13);
person_course_tv[0][3] = (TextView) findViewById(R.id.person_course_tv14);person_course_tv[0][4] = (TextView) findViewById(R.id.person_course_tv15);person_course_tv[0][5] = (TextView) findViewById(R.id.person_course_tv16);
person_course_tv[0][6] = (TextView) findViewById(R.id.person_course_tv17);person_course_tv[1][0] = (TextView) findViewById(R.id.person_course_tv21);person_course_tv[1][1] = (TextView) findViewById(R.id.person_course_tv22);
person_course_tv[1][2] = (TextView) findViewById(R.id.person_course_tv23);person_course_tv[1][3] = (TextView) findViewById(R.id.person_course_tv24);person_course_tv[1][4] = (TextView) findViewById(R.id.person_course_tv25);
person_course_tv[1][5] = (TextView) findViewById(R.id.person_course_tv26);person_course_tv[1][6] = (TextView) findViewById(R.id.person_course_tv27);person_course_tv[2][0] = (TextView) findViewById(R.id.person_course_tv31);
person_course_tv[2][1] = (TextView) findViewById(R.id.person_course_tv32);person_course_tv[2][2] = (TextView) findViewById(R.id.person_course_tv33);person_course_tv[2][3] = (TextView) findViewById(R.id.person_course_tv34);
person_course_tv[2][4] = (TextView) findViewById(R.id.person_course_tv35);person_course_tv[2][5] = (TextView) findViewById(R.id.person_course_tv36);person_course_tv[2][6] = (TextView) findViewById(R.id.person_course_tv37);
person_course_tv[3][0] = (TextView) findViewById(R.id.person_course_tv41);person_course_tv[3][1] = (TextView) findViewById(R.id.person_course_tv42);person_course_tv[3][2] = (TextView) findViewById(R.id.person_course_tv43);
person_course_tv[3][3] = (TextView) findViewById(R.id.person_course_tv44);person_course_tv[3][4] = (TextView) findViewById(R.id.person_course_tv45);person_course_tv[3][5] = (TextView) findViewById(R.id.person_course_tv46);
person_course_tv[3][6] = (TextView) findViewById(R.id.person_course_tv47);person_course_tv[4][0] = (TextView) findViewById(R.id.person_course_tv51);person_course_tv[4][1] = (TextView) findViewById(R.id.person_course_tv52);
person_course_tv[4][2] = (TextView) findViewById(R.id.person_course_tv53);person_course_tv[4][3] = (TextView) findViewById(R.id.person_course_tv54);person_course_tv[4][4] = (TextView) findViewById(R.id.person_course_tv55);
person_course_tv[4][5] = (TextView) findViewById(R.id.person_course_tv56);person_course_tv[4][6] = (TextView) findViewById(R.id.person_course_tv57);
}
public void classroom_btn1_click(View v){
String s = parsehtml(s());
}
public void StoreResult(String a){
String []splits1 = a.split("\\|\\|");
String [][]splits2 = new String[splits1.length][] ;
for(int i=0;i<splits1.length;i++){
splits2[i] = splits1[i].split("#");
}
}
//重写Handler方法,主要为了实现子线程与主线程之间的 数据传递
class Person_MyHandler extends Handler {
// 子类必须重写此方法,接受数据
@Override
public void handleMessage(Message msg) {
// 此处可以更新UI
if(msg.what == 100){
Bundle b = msg.getData();
String result = b.getString("course_temp");
//tv2.setText(result);
}
super.handleMessage(msg);
}
}
//利用Jsoup解析网页内容
private String parsehtml(String result){
String total="",results = "";
int i = 0;
String []score = new String[100];
Document doc = Jsoup.parse(result);
System.out.println( doc.title());
Elements link_class = doc.select("tr.infolist_common[style=\"display:\"]");
// Elements link_class = doc.select("td.center > a");
for(Element link:link_class){
/* String name;
name = link.tagName();
score[i] = link.text();
if(name.equals("a") && flag == 0){
total += score[i]+",";
flag = 1;
} else if (name.equals("a") && flag == 1) {
total += score[i]+" ";
} else {
total += ","+score[i];
results += total + "||";
System.out.println(total);
flag = 0;
total = "";
}*/
String name;
name = link.tagName();
System.out.println(name);
score[i] = link.text();
total += score[i]+"||\n";
System.out.println(score[i]);
results = total;
}
return results;
}
//测试用的html字符串
private String s(){
return "aa";
}
}
| 6,183 | 0.624773 | 0.596075 | 134 | 44.238808 | 59.497044 | 230 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.813433 | false | false | 6 |
5fc8acfdd79e2b37df95b09040dc8c3d2609a0ca | 7,533,372,685,215 | 6b826cab54da27afc4a2dd5e971db69eee8cd4fb | /src/main/java/com/deconware/ops/dimensions/Extend.java | 2418936ecfba77d93c6caea1ed663b3d695579f3 | [] | no_license | bnorthan/deconware-ops | https://github.com/bnorthan/deconware-ops | 96d1d2ecbd8739782235d44dd7bf540a3f312d4a | a868c54e5a010f8ab600d705c506e56b0eb291eb | refs/heads/master | 2021-05-29T12:01:25.619000 | 2015-07-23T16:10:38 | 2015-07-23T16:10:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.deconware.ops.dimensions;
import net.imagej.ops.Op;
public interface Extend extends Op
{
String NAME = "extend";
}
| UTF-8 | Java | 131 | java | Extend.java | Java | [] | null | [] | package com.deconware.ops.dimensions;
import net.imagej.ops.Op;
public interface Extend extends Op
{
String NAME = "extend";
}
| 131 | 0.748092 | 0.748092 | 8 | 15.375 | 15.165236 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 6 |
69fbfc2447173856db4c6d8e52092e4b6f09b33f | 12,421,045,478,731 | bfd0ccc5e51e10a338cd48a175060693b9fc64d1 | /tsd/src/main/java/com/wangrui/tsd/controller/ManagController.java | a6abf05081151c76d4af90e58e21a3fb42dd4ac7 | [] | no_license | sunjava2006/202102 | https://github.com/sunjava2006/202102 | afa66e1e7e5e49bef9b3c0c002fa51b66bdb74f5 | 9f04c031cd4bf70fedcbec766fcf77ffa89f6068 | refs/heads/main | 2023-08-11T18:14:17.519000 | 2021-09-07T11:36:00 | 2021-09-07T11:36:00 | 367,238,609 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wangrui.tsd.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.wangrui.tsd.bean.Knowledge;
import com.wangrui.tsd.service.KnowledgeService;
@Controller
@RequestMapping("/manage")
public class ManagController {
@Value("${pageSize}")
int pageSize;
@Autowired
private KnowledgeService knowledgeService;
@GetMapping("/Knowledge/{page}/{size}")
public ModelAndView listKnowledge(@PathVariable("page")int page,
@PathVariable("size")int size,
ModelAndView mv) {
List<Knowledge> list = this.knowledgeService.listByPage(page, size);
mv.addObject("list", list);
mv.addObject("totalPage", this.knowledgeService.totalPage(size));
mv.addObject("currPage", page);
mv.addObject("size", size);
mv.setViewName("/knowledgeList");
return mv;
}
@RequestMapping("/deleteKnowledge/{id}")
public String deleteKnowledge(@PathVariable("id")int id) {
this.knowledgeService.deleteByID(id);
return "redirect:/manage/Knowledge/1/"+this.pageSize;
}
}
| UTF-8 | Java | 1,457 | java | ManagController.java | Java | [] | null | [] | package com.wangrui.tsd.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.wangrui.tsd.bean.Knowledge;
import com.wangrui.tsd.service.KnowledgeService;
@Controller
@RequestMapping("/manage")
public class ManagController {
@Value("${pageSize}")
int pageSize;
@Autowired
private KnowledgeService knowledgeService;
@GetMapping("/Knowledge/{page}/{size}")
public ModelAndView listKnowledge(@PathVariable("page")int page,
@PathVariable("size")int size,
ModelAndView mv) {
List<Knowledge> list = this.knowledgeService.listByPage(page, size);
mv.addObject("list", list);
mv.addObject("totalPage", this.knowledgeService.totalPage(size));
mv.addObject("currPage", page);
mv.addObject("size", size);
mv.setViewName("/knowledgeList");
return mv;
}
@RequestMapping("/deleteKnowledge/{id}")
public String deleteKnowledge(@PathVariable("id")int id) {
this.knowledgeService.deleteByID(id);
return "redirect:/manage/Knowledge/1/"+this.pageSize;
}
}
| 1,457 | 0.73919 | 0.738504 | 52 | 27.01923 | 24.020416 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.538462 | false | false | 6 |
b17c6e5d45f001401bd25294e405b7093b30129a | 10,256,381,940,556 | f2b6d20a53b6c5fb451914188e32ce932bdff831 | /src/okhttp3/ConnectionPool$1.java | 7e6e94234bcca50c74aae9e22dd0ab781dc21614 | [] | no_license | reverseengineeringer/com.linkedin.android | https://github.com/reverseengineeringer/com.linkedin.android | 08068c28267335a27a8571d53a706604b151faee | 4e7235e12a1984915075f82b102420392223b44d | refs/heads/master | 2021-04-09T11:30:00.434000 | 2016-07-21T03:54:43 | 2016-07-21T03:54:43 | 63,835,028 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package okhttp3;
final class ConnectionPool$1
implements Runnable
{
ConnectionPool$1(ConnectionPool paramConnectionPool) {}
public final void run()
{
long l1;
do
{
l1 = this$0.cleanup(System.nanoTime());
if (l1 == -1L) {
return;
}
} while (l1 <= 0L);
long l2 = l1 / 1000000L;
try
{
synchronized (this$0)
{
this$0.wait(l2, (int)(l1 - l2 * 1000000L));
}
}
catch (InterruptedException localInterruptedException)
{
for (;;) {}
}
}
}
/* Location:
* Qualified Name: okhttp3.ConnectionPool.1
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 671 | java | ConnectionPool$1.java | Java | [] | null | [] | package okhttp3;
final class ConnectionPool$1
implements Runnable
{
ConnectionPool$1(ConnectionPool paramConnectionPool) {}
public final void run()
{
long l1;
do
{
l1 = this$0.cleanup(System.nanoTime());
if (l1 == -1L) {
return;
}
} while (l1 <= 0L);
long l2 = l1 / 1000000L;
try
{
synchronized (this$0)
{
this$0.wait(l2, (int)(l1 - l2 * 1000000L));
}
}
catch (InterruptedException localInterruptedException)
{
for (;;) {}
}
}
}
/* Location:
* Qualified Name: okhttp3.ConnectionPool.1
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 671 | 0.557377 | 0.497765 | 37 | 17.162163 | 16.537449 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.27027 | false | false | 6 |
7052ed3b59380101fc4566f4875a48de93f843a2 | 214,748,398,446 | 0f0bf038c0d323276f990aa689c7f77e86ae5128 | /app/src/main/java/id/ac/pelitabangsa/fragmenappsadilukman/FirstFragment.java | 8785ee76eb734e6895d515790a2a1bd46e13fe46 | [] | no_license | Adie01/FragmenAppsAdiLukmann | https://github.com/Adie01/FragmenAppsAdiLukmann | e3a7543a2abc3e82f2465e871a33b3f5d0c0b682 | a05920ad5ba55b64e2d27e32a09851bf6a266aa0 | refs/heads/master | 2023-04-11T14:39:40.345000 | 2021-04-05T15:17:12 | 2021-04-05T15:17:12 | 359,399,574 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package id.ac.pelitabangsa.fragmenappsadilukman;
import android.app.Fragment;
public class FirstFragment extends Fragment {
}
| UTF-8 | Java | 128 | java | FirstFragment.java | Java | [] | null | [] | package id.ac.pelitabangsa.fragmenappsadilukman;
import android.app.Fragment;
public class FirstFragment extends Fragment {
}
| 128 | 0.828125 | 0.828125 | 6 | 20.333334 | 20.949675 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 6 |
e4e1d878a4f191802556741b4dc24ca27930a135 | 31,868,657,397,015 | 3963b193acdd6c7c67f92aa4826946e02911ea4d | /org.eclipse.epsilon.picto.diff/src/org/eclipse/epsilon/picto/diff/engines/dot/util/SubGraphPromise.java | 9b91fb333a6819fcc0792b98cbd24e969bd5cc9b | [] | no_license | epsilonlabs/picto-diff | https://github.com/epsilonlabs/picto-diff | 941e78b1b5ab76a47f48efa38bea52056a435c10 | 6545ae31d47292a1eb2ec7bcd15197eace91f471 | refs/heads/master | 2023-03-15T16:15:45.252000 | 2023-03-08T11:25:45 | 2023-03-08T11:25:45 | 246,094,416 | 0 | 0 | null | false | 2022-09-02T08:37:03 | 2020-03-09T17:04:29 | 2021-10-16T22:16:48 | 2022-09-02T08:37:02 | 24,376 | 0 | 0 | 1 | Java | false | false | package org.eclipse.epsilon.picto.diff.engines.dot.util;
import static guru.nidi.graphviz.model.Factory.mutGraph;
import org.eclipse.epsilon.picto.ContentPromise;
import guru.nidi.graphviz.engine.Format;
import guru.nidi.graphviz.engine.Graphviz;
import guru.nidi.graphviz.model.Link;
import guru.nidi.graphviz.model.MutableGraph;
import guru.nidi.graphviz.model.MutableNode;
import guru.nidi.graphviz.model.PortNode;
/**
* Lazy generation of subgraph views for each node
*/
public class SubGraphPromise implements ContentPromise {
private MutableGraph parentGraph;
private MutableNode node;
private String content;
public SubGraphPromise(MutableGraph parentGraph, MutableNode node) {
this.parentGraph = parentGraph;
this.node = node;
content = null;
}
@Override
public String getContent() throws Exception {
if (content == null) {
content = calculateSubGraph();
}
return content;
}
private String calculateSubGraph() {
MutableGraph subGraph = mutGraph();
subGraph.setName(node.name().toString());
MutableNode node_copy = GraphPromiseGenerator.getCopy(node);
subGraph.rootNodes().add(node_copy);
for (MutableNode n : parentGraph.nodes()) {
for (Link link : n.links()) {
boolean node_is_target = false;
if (link.to() instanceof PortNode) {
PortNode temp = (PortNode) link.to();
if (temp.name().toString().equals(node.name().toString())) {
node_is_target = true;
}
} else if (link.to() instanceof MutableNode) {
MutableNode temp = (MutableNode) link.to();
if (temp.name().toString().equals(node.name().toString())) {
node_is_target = true;
}
}
if (node_is_target) {
MutableNode source_copy = GraphPromiseGenerator.getCopy(n);
subGraph.rootNodes().add(source_copy);
GraphPromiseGenerator.link(link, source_copy, node_copy);
}
}
}
for (Link link : node.links()) {
String target_name = "";
if (link.to() instanceof PortNode) {
PortNode temp = (PortNode) link.to();
target_name = temp.name().toString();
} else if (link.to() instanceof MutableNode) {
MutableNode temp = (MutableNode) link.to();
target_name = temp.name().toString();
}
MutableNode target = GraphPromiseGenerator.findNode(target_name, parentGraph);
MutableNode target_copy = GraphPromiseGenerator.getCopy(target);
subGraph.rootNodes().add(target_copy);
GraphPromiseGenerator.link(link, node_copy, target_copy);
}
return Graphviz.fromGraph(subGraph).render(Format.DOT).toString();
}
}
| UTF-8 | Java | 2,526 | java | SubGraphPromise.java | Java | [] | null | [] | package org.eclipse.epsilon.picto.diff.engines.dot.util;
import static guru.nidi.graphviz.model.Factory.mutGraph;
import org.eclipse.epsilon.picto.ContentPromise;
import guru.nidi.graphviz.engine.Format;
import guru.nidi.graphviz.engine.Graphviz;
import guru.nidi.graphviz.model.Link;
import guru.nidi.graphviz.model.MutableGraph;
import guru.nidi.graphviz.model.MutableNode;
import guru.nidi.graphviz.model.PortNode;
/**
* Lazy generation of subgraph views for each node
*/
public class SubGraphPromise implements ContentPromise {
private MutableGraph parentGraph;
private MutableNode node;
private String content;
public SubGraphPromise(MutableGraph parentGraph, MutableNode node) {
this.parentGraph = parentGraph;
this.node = node;
content = null;
}
@Override
public String getContent() throws Exception {
if (content == null) {
content = calculateSubGraph();
}
return content;
}
private String calculateSubGraph() {
MutableGraph subGraph = mutGraph();
subGraph.setName(node.name().toString());
MutableNode node_copy = GraphPromiseGenerator.getCopy(node);
subGraph.rootNodes().add(node_copy);
for (MutableNode n : parentGraph.nodes()) {
for (Link link : n.links()) {
boolean node_is_target = false;
if (link.to() instanceof PortNode) {
PortNode temp = (PortNode) link.to();
if (temp.name().toString().equals(node.name().toString())) {
node_is_target = true;
}
} else if (link.to() instanceof MutableNode) {
MutableNode temp = (MutableNode) link.to();
if (temp.name().toString().equals(node.name().toString())) {
node_is_target = true;
}
}
if (node_is_target) {
MutableNode source_copy = GraphPromiseGenerator.getCopy(n);
subGraph.rootNodes().add(source_copy);
GraphPromiseGenerator.link(link, source_copy, node_copy);
}
}
}
for (Link link : node.links()) {
String target_name = "";
if (link.to() instanceof PortNode) {
PortNode temp = (PortNode) link.to();
target_name = temp.name().toString();
} else if (link.to() instanceof MutableNode) {
MutableNode temp = (MutableNode) link.to();
target_name = temp.name().toString();
}
MutableNode target = GraphPromiseGenerator.findNode(target_name, parentGraph);
MutableNode target_copy = GraphPromiseGenerator.getCopy(target);
subGraph.rootNodes().add(target_copy);
GraphPromiseGenerator.link(link, node_copy, target_copy);
}
return Graphviz.fromGraph(subGraph).render(Format.DOT).toString();
}
}
| 2,526 | 0.705859 | 0.705859 | 82 | 29.804878 | 22.576935 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.621951 | false | false | 6 |
cf25db364095b8524075fb798f5476b9c512b18b | 3,135,326,161,893 | 5698873293f1fbd3ef6e345fe91fb428db1d8087 | /src/main/java/com/clumsy/luckylister/data/FilterDao.java | 452da665313a4fe5794b582ec10c64fde0f31df7 | [
"MIT"
] | permissive | CaptnClumsy/LuckyLister | https://github.com/CaptnClumsy/LuckyLister | 2883e7205e15a295be8ac950885b6a68223e6bac | 69e90c21def9af069a3dc9d156bc80b4290f363f | refs/heads/master | 2022-04-30T21:17:49.751000 | 2020-08-18T17:18:34 | 2020-08-18T17:18:34 | 189,113,415 | 1 | 0 | MIT | false | 2022-03-08T21:17:53 | 2019-05-28T22:45:27 | 2020-08-18T17:18:43 | 2022-03-08T21:17:52 | 69,791 | 1 | 0 | 1 | JavaScript | false | false | package com.clumsy.luckylister.data;
import com.clumsy.luckylister.entities.FilterEntity;
import lombok.Data;
@Data
public class FilterDao {
private Boolean shiny_costumes;
private Boolean shiny_shadows;
private Boolean shiny_alolan;
private Boolean shiny_other;
private Boolean lucky_costumes;
private Boolean lucky_alolan;
private Boolean lucky_other;
private Boolean hundo_costumes;
private Boolean hundo_shadows;
private Boolean hundo_alolan;
private Boolean hundo_other;
public FilterDao() {
}
public FilterDao(final boolean shiny_costumes, final boolean shiny_shadows, final boolean shiny_alolan, final boolean shiny_other,
final boolean lucky_costumes, final boolean lucky_alolan, final boolean lucky_other,
final boolean hundo_costumes, final boolean hundo_shadows, final boolean hundo_alolan, final boolean hundo_other) {
this.shiny_costumes=shiny_costumes;
this.shiny_shadows=shiny_shadows;
this.shiny_alolan=shiny_alolan;
this.shiny_other=shiny_other;
this.lucky_costumes=lucky_costumes;
this.lucky_alolan=lucky_alolan;
this.lucky_other=lucky_other;
this.hundo_costumes=hundo_costumes;
this.hundo_shadows=hundo_shadows;
this.hundo_alolan=hundo_alolan;
this.hundo_other=hundo_other;
}
public static FilterDao fromEntity(FilterEntity filter) {
return new FilterDao(filter.getShiny_costumes(), filter.getShiny_shadows(), filter.getShiny_alolan(), filter.getShiny_other(),
filter.getLucky_costumes(), filter.getLucky_alolan(), filter.getLucky_other(),
filter.getHundo_costumes(), filter.getHundo_shadows(), filter.getHundo_alolan(), filter.getHundo_other());
}
} | UTF-8 | Java | 1,632 | java | FilterDao.java | Java | [] | null | [] | package com.clumsy.luckylister.data;
import com.clumsy.luckylister.entities.FilterEntity;
import lombok.Data;
@Data
public class FilterDao {
private Boolean shiny_costumes;
private Boolean shiny_shadows;
private Boolean shiny_alolan;
private Boolean shiny_other;
private Boolean lucky_costumes;
private Boolean lucky_alolan;
private Boolean lucky_other;
private Boolean hundo_costumes;
private Boolean hundo_shadows;
private Boolean hundo_alolan;
private Boolean hundo_other;
public FilterDao() {
}
public FilterDao(final boolean shiny_costumes, final boolean shiny_shadows, final boolean shiny_alolan, final boolean shiny_other,
final boolean lucky_costumes, final boolean lucky_alolan, final boolean lucky_other,
final boolean hundo_costumes, final boolean hundo_shadows, final boolean hundo_alolan, final boolean hundo_other) {
this.shiny_costumes=shiny_costumes;
this.shiny_shadows=shiny_shadows;
this.shiny_alolan=shiny_alolan;
this.shiny_other=shiny_other;
this.lucky_costumes=lucky_costumes;
this.lucky_alolan=lucky_alolan;
this.lucky_other=lucky_other;
this.hundo_costumes=hundo_costumes;
this.hundo_shadows=hundo_shadows;
this.hundo_alolan=hundo_alolan;
this.hundo_other=hundo_other;
}
public static FilterDao fromEntity(FilterEntity filter) {
return new FilterDao(filter.getShiny_costumes(), filter.getShiny_shadows(), filter.getShiny_alolan(), filter.getShiny_other(),
filter.getLucky_costumes(), filter.getLucky_alolan(), filter.getLucky_other(),
filter.getHundo_costumes(), filter.getHundo_shadows(), filter.getHundo_alolan(), filter.getHundo_other());
}
} | 1,632 | 0.780025 | 0.780025 | 46 | 34.5 | 33.236797 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.217391 | false | false | 6 |
e8392bc5a7ad01c823a34bb5331093522c167f7e | 1,855,425,872,248 | 994b038a15aa8e09fd501d3848b7c32d8bf24fd7 | /onlineBusBookingProject/src/main/java/com/app/controller/UserController.java | 29e8bc1df132bb199e6ca8d0dc650d6553ca91f4 | [] | no_license | mahajanmayur97/online_bus_reservation | https://github.com/mahajanmayur97/online_bus_reservation | 10d70acc43a51fa2a9a55ac5678bdac26c9dc631 | 50d82b91411046ab5480bc4116392c09a76cbed1 | refs/heads/master | 2023-03-23T04:52:00.714000 | 2021-03-21T10:45:35 | 2021-03-21T10:45:35 | 349,943,252 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.app.pojos.User;
import com.app.service.IUserService;
@RestController
@CrossOrigin("*")
public class UserController {
@Autowired
private IUserService userService;
public UserController() {
System.out.println("in home controller");
}
//-----------------------------Login------------------------------------------------------------------------------------------------------------------
@PostMapping("/login")
public ResponseEntity<?> validateUser(@RequestBody User u) {
System.out.println("in valditae user" + u.getEmail() + "," + u.getPassword());
try {
return new ResponseEntity<>(userService.authenticateUser(u.getEmail(), u.getPassword()), HttpStatus.OK);
} catch (RuntimeException e) {
return new ResponseEntity<>("Invalid Password or email...Please enter valid data", HttpStatus.OK);
}
}
//----------------------------Registration-------------------------------------------------------------------------------------------------------------------
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody User u) {
System.out.println("in register user");
try {
userService.registerUser(u);
return new ResponseEntity<>("Registeration Done Succssfully", HttpStatus.OK);
} catch (RuntimeException e) {
return new ResponseEntity<>("Registeration Fail....", HttpStatus.OK);
}
}
//------------------------------Edit Profile-----------------------------------------------------------------------------------------------------------------
@PutMapping("/update/{userId}")
public ResponseEntity<User> updateUser(@RequestBody User user, @PathVariable int userId) {
System.out.println("in update user" + user);
System.out.println("in update user" + userId);
try {
userService.updateUser(user, userId);
return ResponseEntity.ok().body(user);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
//-----------------------------Change Password------------------------------------------------------------------------------------------------------------------
@PutMapping("/changePassword")
public ResponseEntity<?> changePassword(@RequestBody User u) {
System.out.println("In change password");
try {
userService.updatePassword(u.getEmail(), u.getPassword());
return new ResponseEntity<String>("Password updated successfully", HttpStatus.OK);
} catch (RuntimeException e) {
e.printStackTrace();
return new ResponseEntity<String>("updation failed", HttpStatus.OK);
}
}
//-------------------------------------Get User by id----------------------------------------------------------------------------------------------------------
@GetMapping("/getUser/{userId}")
public ResponseEntity<?> getUserById(@PathVariable int userId) {
try {
return new ResponseEntity<>(userService.getUserById(userId), HttpStatus.OK);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
}
| UTF-8 | Java | 3,756 | java | UserController.java | Java | [] | null | [] | package com.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.app.pojos.User;
import com.app.service.IUserService;
@RestController
@CrossOrigin("*")
public class UserController {
@Autowired
private IUserService userService;
public UserController() {
System.out.println("in home controller");
}
//-----------------------------Login------------------------------------------------------------------------------------------------------------------
@PostMapping("/login")
public ResponseEntity<?> validateUser(@RequestBody User u) {
System.out.println("in valditae user" + u.getEmail() + "," + u.getPassword());
try {
return new ResponseEntity<>(userService.authenticateUser(u.getEmail(), u.getPassword()), HttpStatus.OK);
} catch (RuntimeException e) {
return new ResponseEntity<>("Invalid Password or email...Please enter valid data", HttpStatus.OK);
}
}
//----------------------------Registration-------------------------------------------------------------------------------------------------------------------
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody User u) {
System.out.println("in register user");
try {
userService.registerUser(u);
return new ResponseEntity<>("Registeration Done Succssfully", HttpStatus.OK);
} catch (RuntimeException e) {
return new ResponseEntity<>("Registeration Fail....", HttpStatus.OK);
}
}
//------------------------------Edit Profile-----------------------------------------------------------------------------------------------------------------
@PutMapping("/update/{userId}")
public ResponseEntity<User> updateUser(@RequestBody User user, @PathVariable int userId) {
System.out.println("in update user" + user);
System.out.println("in update user" + userId);
try {
userService.updateUser(user, userId);
return ResponseEntity.ok().body(user);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
//-----------------------------Change Password------------------------------------------------------------------------------------------------------------------
@PutMapping("/changePassword")
public ResponseEntity<?> changePassword(@RequestBody User u) {
System.out.println("In change password");
try {
userService.updatePassword(u.getEmail(), u.getPassword());
return new ResponseEntity<String>("Password updated successfully", HttpStatus.OK);
} catch (RuntimeException e) {
e.printStackTrace();
return new ResponseEntity<String>("updation failed", HttpStatus.OK);
}
}
//-------------------------------------Get User by id----------------------------------------------------------------------------------------------------------
@GetMapping("/getUser/{userId}")
public ResponseEntity<?> getUserById(@PathVariable int userId) {
try {
return new ResponseEntity<>(userService.getUserById(userId), HttpStatus.OK);
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
}
| 3,756 | 0.579872 | 0.579872 | 91 | 40.274727 | 41.355885 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.637363 | false | false | 6 |
cdec83ed2927af3f41b83195eaef3ac95e6d8530 | 12,695,923,390,249 | da19785e7c78967d56e22ba33ed96e1727925512 | /src/main/java/mojePierwszeZadanie/MathematicalOperation.java | 0face9518e35eba8db631484ac7f09efdb1dc680 | [] | no_license | surveybook3/JAVA | https://github.com/surveybook3/JAVA | 432bd48960c3c2119c569eb74d3ac975ac069573 | 11720879b4d8802cc22613c3976ff757b1ecdcfe | refs/heads/main | 2023-03-30T08:06:09.914000 | 2021-03-26T22:51:07 | 2021-03-26T22:51:07 | 349,532,625 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mojePierwszeZadanie;
public class MathematicalOperation {
public void add()
{
System.out.println("dodawania udało sie !!!!!!");
}
}
| UTF-8 | Java | 165 | java | MathematicalOperation.java | Java | [] | null | [] | package mojePierwszeZadanie;
public class MathematicalOperation {
public void add()
{
System.out.println("dodawania udało sie !!!!!!");
}
}
| 165 | 0.634146 | 0.634146 | 11 | 13.909091 | 18.322636 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 6 |
46b132cf68b6f056c684c086a89b5d6678452a83 | 4,587,025,135,196 | 8055e173be46d1b863e5441b9fbf099e872e8dcf | /batching-of-write-operations/src/test/java/io/costax/batching/BatchingUpdateTest.java | 357bf91b3e479d629fac325c172d65cb98e3fba0 | [
"MIT"
] | permissive | jlmc/hibernate-tunings | https://github.com/jlmc/hibernate-tunings | 5dbe03a32b88c34a8d8f32b23328501659971a3e | de9215b5b22fce8209ec951f49b87213ebb11cc5 | refs/heads/master | 2023-04-02T13:56:41.753000 | 2022-05-29T22:39:38 | 2022-06-20T08:59:32 | 149,929,972 | 7 | 1 | MIT | false | 2023-03-31T15:07:35 | 2018-09-22T23:19:19 | 2023-02-22T17:07:45 | 2023-03-31T15:07:33 | 9,183 | 6 | 1 | 10 | Java | false | false | package io.costax.batching;
import io.github.jlmc.jpa.test.annotation.JpaContext;
import io.github.jlmc.jpa.test.annotation.JpaTest;
import io.github.jlmc.jpa.test.junit.JpaProvider;
import org.junit.jupiter.api.Test;
import jakarta.persistence.EntityManager;
import java.util.List;
/**
* Test nº 3
*/
@JpaTest(persistenceUnit = "it")
public class BatchingUpdateTest {
@JpaContext
public JpaProvider provider;
@Test
public void testUpdateActorsBooks() {
EntityManager em = provider.em();
em.getTransaction().begin();
List<Author> authors = em
.createQuery("SELECT a FROM Author a JOIN FETCH a.books b", Author.class).getResultList();
for (Author a : authors) {
a.setFirstName(a.getFirstName() + " - updated");
a.getBooks().forEach(b -> b.setTitle(b.getTitle() + " - updated"));
}
em.getTransaction().commit();
em.close();
}
}
| UTF-8 | Java | 954 | java | BatchingUpdateTest.java | Java | [
{
"context": "package io.costax.batching;\n\nimport io.github.jlmc.jpa.test.annotation.JpaContext;\nimport io.github.",
"end": 50,
"score": 0.9937690496444702,
"start": 46,
"tag": "USERNAME",
"value": "jlmc"
},
{
"context": ".jpa.test.annotation.JpaContext;\nimport io.github.jlmc.jpa... | null | [] | package io.costax.batching;
import io.github.jlmc.jpa.test.annotation.JpaContext;
import io.github.jlmc.jpa.test.annotation.JpaTest;
import io.github.jlmc.jpa.test.junit.JpaProvider;
import org.junit.jupiter.api.Test;
import jakarta.persistence.EntityManager;
import java.util.List;
/**
* Test nº 3
*/
@JpaTest(persistenceUnit = "it")
public class BatchingUpdateTest {
@JpaContext
public JpaProvider provider;
@Test
public void testUpdateActorsBooks() {
EntityManager em = provider.em();
em.getTransaction().begin();
List<Author> authors = em
.createQuery("SELECT a FROM Author a JOIN FETCH a.books b", Author.class).getResultList();
for (Author a : authors) {
a.setFirstName(a.getFirstName() + " - updated");
a.getBooks().forEach(b -> b.setTitle(b.getTitle() + " - updated"));
}
em.getTransaction().commit();
em.close();
}
}
| 954 | 0.649528 | 0.648479 | 37 | 24.756756 | 24.662485 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432432 | false | false | 6 |
72b3290e925f915eaee34a49532745ded0c253f4 | 29,686,814,016,819 | 1277f622eb82586779a3d9414bd477077f7bede4 | /app/src/main/java/com/jxnugo/entity/user/registe/RegisteStates.java | bf4703e995cbfc4c5d9be3c2d9847856551337a9 | [] | no_license | zpauly/jxnugo-Android | https://github.com/zpauly/jxnugo-Android | 5d07fc874aa8daad2c3088e16881621a9462062a | b4c296787b9532138151a89f7090695bd98e09bc | refs/heads/master | 2021-01-16T22:30:52.207000 | 2016-07-23T06:27:28 | 2016-07-23T06:27:28 | 58,446,789 | 0 | 0 | null | true | 2016-05-10T09:16:34 | 2016-05-10T09:16:34 | 2016-05-10T09:14:34 | 2016-05-10T09:14:31 | 7,265 | 0 | 0 | 0 | null | null | null | package com.jxnugo.entity.user.registe;
/**
* Created by zpauly on 16-5-22.
*/
public class RegisteStates {
/**
* registerStatus : successful
*/
private String registerStatus;
public String getRegisterStatus() {
return registerStatus;
}
public void setRegisterStatus(String registerStatus) {
this.registerStatus = registerStatus;
}
}
| UTF-8 | Java | 390 | java | RegisteStates.java | Java | [
{
"context": "com.jxnugo.entity.user.registe;\n\n/**\n * Created by zpauly on 16-5-22.\n */\npublic class RegisteStates {\n ",
"end": 65,
"score": 0.9996333718299866,
"start": 59,
"tag": "USERNAME",
"value": "zpauly"
}
] | null | [] | package com.jxnugo.entity.user.registe;
/**
* Created by zpauly on 16-5-22.
*/
public class RegisteStates {
/**
* registerStatus : successful
*/
private String registerStatus;
public String getRegisterStatus() {
return registerStatus;
}
public void setRegisterStatus(String registerStatus) {
this.registerStatus = registerStatus;
}
}
| 390 | 0.661538 | 0.648718 | 20 | 18.5 | 18.402445 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 6 |
10d3cb019e7dab84f1dfe32005bf97f6770649b8 | 11,166,915,010,512 | 6e393cfade1dec4d84284bbacaa74a0f297fdeca | /corvus-ebms/src/test/java/hk/hku/cecid/ebms/spa/EbmsUtilityTest.java | 9e4d283f9273fbf850b601a70e7b0e2d1fe1b189 | [
"BSD-2-Clause"
] | permissive | iamhuwjones/hermes | https://github.com/iamhuwjones/hermes | 8faac6660ef5529740258acd1cd12d42398ba93b | 594b2849c4f3290955ee33d02574a1856be212f9 | refs/heads/master | 2020-03-28T15:46:17.435000 | 2018-09-04T04:42:56 | 2018-09-04T04:42:56 | 148,624,235 | 0 | 0 | BSD-2-Clause | true | 2018-09-13T10:51:35 | 2018-09-13T10:51:36 | 2018-09-06T10:52:46 | 2018-09-04T04:42:56 | 32,208 | 0 | 0 | 0 | null | false | null | package hk.hku.cecid.ebms.spa;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;
import junit.framework.TestCase;
import hk.hku.cecid.ebms.spa.EbmsUtility;
/**
* The <code>EbmsUtilityTest</code> is the testcase for <code>EbmsUtility</code>.
*
* @author Twinsen Tsang
* @since 1.0.0
* @version 1.0.0
*/
public class EbmsUtilityTest extends TestCase{
// Invoked for setup.
public void setUp() throws Exception {
System.out.println();
System.out.println("---------" + this.getName() + " Start -------");
}
// Invoked for finalized.
public void tearDown() throws Exception {
System.out.println("---------" + this.getName() + " End -------");
}
/**
* Get the local timezone represenetation from the UTC. The returned
* format is "GMT+hh:mm".
* <br/><br/>
* For example, if you are located in Asia/Hong Kong, the returned
* string should be "GMT+08:00".
*/
public String getLocalTimezone(){
// Get the default timezone.
TimeZone tz = TimeZone.getDefault();
// Get the offset from UTC.
int tzOffset = tz.getOffset(new Date().getTime());
// Formatter.
DecimalFormat twoDigits = new DecimalFormat("00");
String sign = "+";
if (tzOffset < 0){ sign = "-"; tzOffset = -tzOffset; }
// calculate the timezone offset.
int hours = (tzOffset / 3600000);
int minutes = (tzOffset % 3600000) / 60000;
// Return the local timezone.
return new StringBuffer("GMT")
.append(sign)
.append(twoDigits.format(hours))
.append(":")
.append(twoDigits.format(minutes)).toString();
}
/**
* A common method to validate cirtical field for specified <code>cal</code>
*
* @param cal The calendar to test against.
* @param expectedYear
* The expected year.
* @param expectedMonth
* The expected month.
* @param expectedDay
* The expected day.
* @param expectedHour
* The expected hour.
* @param expectedMins
* The expected mins.
* @param expectedSecond
* The expected second.
* @param expectedMillisecond
* The expected millisecond.
* @param expectedTz
* The expected timezone.
*/
public void validateCalendar(Calendar cal,
int expectedYear, int expectedMonth, int expectedDay, int expectedHour,
int expectedMins, int expectedSecond, int expectedMillisecond, String expectedTz)
{
// Null test
TestCase.assertNotNull(cal);
// Value test
TestCase.assertEquals(expectedYear , cal.get(Calendar.YEAR));
TestCase.assertEquals(expectedMonth , cal.get(Calendar.MONTH)); // Month is starting from zero.
TestCase.assertEquals(expectedDay , cal.get(Calendar.DAY_OF_MONTH));
TestCase.assertEquals(expectedHour , cal.get(Calendar.HOUR_OF_DAY));
TestCase.assertEquals(expectedMins , cal.get(Calendar.MINUTE));
TestCase.assertEquals(expectedSecond , cal.get(Calendar.SECOND));
TestCase.assertEquals(expectedMillisecond , cal.get(Calendar.MILLISECOND));
TestCase.assertEquals(expectedTz , cal.getTimeZone().getID());
// Now transform it to the local machine time.
Calendar transformedCal = Calendar.getInstance();
transformedCal.setTime(cal.getTime());
// Get the timezone offset from the testing calendar from UTC.
int clOffset = cal.getTimeZone().getOffset(new Date().getTime());
// Get the timezone offset of this local machine from UTC.
int tzOffset = TimeZone.getDefault().getOffset(cal.getTimeInMillis());
// Calculate the actual offset
tzOffset = tzOffset - clOffset;
System.out.println("TimeZone Offset: " + tzOffset);
int hours = expectedHour + tzOffset / 3600000;
int mins = expectedMins + (tzOffset % 3600000) / 60000;
int days = expectedDay;
// If the offset is greater than 24.
if (hours > 24){ hours -= 24; days += 1; }
else if (hours < 0) { hours += 24; days -= 1; }
TestCase.assertEquals(hours, transformedCal.get(Calendar.HOUR_OF_DAY));
TestCase.assertEquals(mins , transformedCal.get(Calendar.MINUTE));
TestCase.assertEquals(days , transformedCal.get(Calendar.DAY_OF_MONTH));
System.out.println(transformedCal.getTime());
// Done.
}
/**
* A common method to validate cirtical field for specified <code>target</code>
* by the value in the calendar <code>control</code>.
*
* @param target
* The target calendar to test for.
* @param control
* The reference calendar to test for.
*/
public void validateCalendar(Calendar target, Calendar control)
{
// Not Null test
TestCase.assertNotNull(target);
TestCase.assertNotNull(control);
// Assert whether they are representing same time.
System.out.println("Target Calendar (de): " + target.getTime());
System.out.println("Control Calendar (de): " + control.getTime());
System.out.println("Target Calendar (ms): " + target.getTimeInMillis());
System.out.println("Control Calendar (ms): " + control.getTimeInMillis());
TestCase.assertEquals (target.getTimeInMillis(), control.getTimeInMillis());
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone in UTC (GMT+00:00) using 'Z' designator.
*/
public void testUTC2Calendar_Pos0() throws Exception {
String dateTime = "2007-07-16T13:24:56.789Z";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "UTC");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone in UTC (GMT+00:00) using +00:00
*/
public void testUTC2Calendar_Pos1() throws Exception {
String dateTime = "2007-07-16T13:24:56.789+00:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "GMT+00:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone GMT+08:00 (non zero timezone)
*/
public void testUTC2Calendar_Pos2() throws Exception {
String dateTime = "2007-07-16T13:24:56.789+08:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "GMT+08:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone GMT+13:00 (boundary case)
*/
public void testUTC2Calendar_Pos3() throws Exception {
String dateTime = "2007-07-16T04:24:56.789+13:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// * We have used the hour 04 instead of 13 for testing the offset from previous day.
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 04, 24, 56, 789, "GMT+13:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone GMT-12:00 (boundary case)
*/
public void testUTC2Calendar_Pos4() throws Exception {
String dateTime = "2007-07-16T13:24:56.789-12:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "GMT-12:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC without millisecond
* and under the timezone UTC.
*/
public void testUTC2Calendar_Pos5() throws Exception {
String dateTime = "2007-07-16T13:24:56Z";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 0, "UTC");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC without millisecond
* and under any timezone other than UTC.
*/
public void testUTC2Calendar_Pos6() throws Exception {
String dateTime = "2007-07-16T13:24:56-08:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 0, "GMT-08:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC without millisecond and 'Z'
* and under any timezone other than UTC.
*/
public void testUTC2Calendar_Pos7() throws Exception {
String dateTime = "2007-07-16T13:24:56";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 0, "UTC");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC with 'Z'
* and under any timezone other than UTC.
*/
public void testUTC2Calendar_Pos8() throws Exception {
String dateTime = "2007-07-16T13:24:56.789";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "UTC");
}
/**
* Test the conversation from UTC to java calendar object negatively.<br/><br/>
*
* Testing for the scenario all invalid UTC format representation.
*/
public void testUTC2Calendar_Neg0() throws Exception {
// Invalid regex format between year and month
String dateTime0 = "2007**07-16T13:24:56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime0);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between year and month passed.");
}
// Invalid regex format between month and days
String dateTime1 = "2007-07!!16T13:24:56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime1);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between month and days passed.");
}
// Invalid regex format between days and hour
String dateTime2 = "2007-07-16@@@13:24:56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime2);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between days and hour passed.");
}
// Invalid regex format between hours and minutes
String dateTime3 = "2007-07-16@T13##24:56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime3);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between hours and minutes passed.");
}
// Invalid regex format between minutes and second
String dateTime4 = "2007-07-16@T13:24~~56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime4);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between minutes and second passed.");
}
// Invalid regex format between second and millisecond
String dateTime5 = "2007-07-16@T13:24:56~_~789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime5);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between second and millisecond passed.");
}
// Invalid regex format between millisecond and timezone
String dateTime6 = "2007-07-16@T13:24:56.78931212:00";
try{
EbmsUtility.UTC2Calendar(dateTime6);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between millisecond and timezone passed.");
}
// Invalid regex format for millisecond
String dateTime7 = "2007-07-16@T13:24:56.ddd-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime7);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format for millisecond");
}
}
/**
* Test for getting the current UTC data time.<br/><br/>
*/
/**
* @throws Exception
*/
public void testGetCurrentUTCDateTime_Pos0() throws Exception {
String utc = EbmsUtility.getCurrentUTCDateTime();
Calendar sysCal = Calendar.getInstance();
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
System.out.println("UTC converted: " + utc);
// For this testcase, we should tolerate the millisecond and second due to
// there is sightly time different between creating the sysCal and utcCal.
// So we set the millisecond part to 0 for this two cal.
sysCal.set(Calendar.SECOND, 0);
sysCal.set(Calendar.MILLISECOND, 0);
utcCal.set(Calendar.SECOND, 0);
utcCal.set(Calendar.MILLISECOND, 0);
// validate the calendar field
this.validateCalendar(utcCal,
sysCal.get(Calendar.YEAR),
sysCal.get(Calendar.MONTH),
sysCal.get(Calendar.DAY_OF_MONTH),
sysCal.get(Calendar.HOUR_OF_DAY),
sysCal.get(Calendar.MINUTE),
sysCal.get(Calendar.SECOND),
sysCal.get(Calendar.MILLISECOND),
this.getLocalTimezone());
}
/**
* Test for converting from a java date object to UTC conformed representation string.
*
* Testing for the scenario the dateTime is represented as java calendar and
* under the timezone same as the machine running.
*/
public void testDate2UTC_Pos0() throws Exception {
Calendar cal = Calendar.getInstance();
// 2007-07-16@T13:24:56.78931212:00
cal.set(2007, 06, 16, 13, 24, 56);
cal.set(Calendar.MILLISECOND, 0);
// Convert to UTC representation
String utc = EbmsUtility.date2UTC(cal.getTime(), cal.getTimeZone());
System.out.println("UTC converted: " + utc);
// Convert back to java calendar and validate the field.
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
// validate the calendar field
this.validateCalendar(utcCal, 2007, 6, 16, 13, 24, 56, 0, this.getLocalTimezone());
}
/**
* Test for converting from a java date object to UTC conformed representation string.
*
* Testing for the scenario the dateTime is represented as java calendar and
* under the timezone under UTC.
*/
public void testDate2UTC_Pos1() throws Exception {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// 2007-07-16@T13:24:56.000Z
cal.set(2007, 06, 16, 13, 24, 56);
cal.set(Calendar.MILLISECOND, 789);
// Convert to UTC representation
String utc = EbmsUtility.date2UTC(cal.getTime(), cal.getTimeZone());
System.out.println("UTC converted : " + utc);
// Convert back to java calendar and validate the field.
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
// validate whether the timezone is correctly converted.
String utcTz = utcCal.getTimeZone().getID();
TestCase.assertTrue(utcTz.equals("UTC") || utcTz.equals("GMT+00:00"));
// validate the calendar field based on cal.
this.validateCalendar(utcCal, cal);
}
/**
* Test for converting from a java date object to UTC conformed representation string.
*
* Testing for the scenario the dateTime is represented as java calendar and
* under the timezone under GMT-12:00 (boundary case)
*/
public void testDate2UTC_Pos2() throws Exception {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-12:00"));
// 2007-07-16@T13:24:56.000-12:00
cal.set(2007, 06, 16, 13, 24, 56);
cal.set(Calendar.MILLISECOND, 789);
// Convert to UTC representation
String utc = EbmsUtility.date2UTC(cal.getTime(), cal.getTimeZone());
System.out.println("UTC converted: " + utc);
// Convert back to java calendar and validate the field.
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
// validate whether the timezone is correctly converted.
TestCase.assertTrue(utcCal.getTimeZone().getID().equals("GMT-12:00"));
// validate the calendar field based on cal.
this.validateCalendar(utcCal, cal);
}
/**
* Test for converting from a java date object to UTC conformed representation string.
*
* Testing for the scenario the dateTime is represented as java calendar and
* under the timezone under GMT+13:00 (boundary case)
*/
public void testDate2UTC_Pos3() throws Exception {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+13:00"));
// 2007-07-16@T13:24:56.000-12:00
cal.set(2007, 06, 16, 13, 24, 56);
cal.set(Calendar.MILLISECOND, 789);
// Convert to UTC representation
String utc = EbmsUtility.date2UTC(cal.getTime(), cal.getTimeZone());
System.out.println("UTC converted: " + utc);
// Convert back to java calendar and validate the field.
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
// validate whether the timezone is correctly converted.
TestCase.assertTrue(utcCal.getTimeZone().getID().equals("GMT+13:00"));
// validate the calendar field based on cal.
this.validateCalendar(utcCal, cal);
}
/**
* Test for converting from GMT datetime representation to java date object.
*/
public void testGMT2Date_Pos0() throws Exception {
Date date = new Date();
String dateTime = date.toString();
Date convertedDate = EbmsUtility.GMT2Date(dateTime);
System.out.println("GMT converted: " + convertedDate);
// Since the millisecond pecision will be lost during conversion.
// we need to create a calendar and set the millisecond to zero.
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date.getTime());
cal.set(Calendar.MILLISECOND, 0);
// Check whether the time is equal or not.
TestCase.assertEquals(convertedDate.getTime(), cal.getTimeInMillis());
}
/**
* Test for the scenario issued by Martin Kalen from the google group.<br/><br/>
*
* QUOTED FROM martin said:
* <pre>
* Hermes sends ebMS ACK messages with a non-standard timezone part of
* the timestamp (timezone info is not according to ebXML-specification,
* see background below)
*
* Background on #1:
* The recent fix for Hermes UTC timestamps uses the Java
* SimpleDateFormat "Z"-pattern for timezone, which is unfortunately
* incompatible with the ebXML specification for time zone refering to
* the XML schema data-type "dateTime" specified here:
* http://www.w3.org/TR/xmlschema-2/#dateTime
*
* Snippets from the spec:
* "dateTime consists of finite-length sequences of characters of the
* form: '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)?
* (zzzzzz)?"
* "zzzzzz (if present) represents the timezone"
*
* From 3.2.7.3 Timezones The lexical representation of a timezone is a string of the form:
* (('+' | '-') hh ':' mm) | 'Z'"
* In Java the ':' character is missing between the "hh" and "mm" parts.
* More details on the Java SimpleDateFormat vs XSD dateTime
* incompatibility can be found here:
* </pre>
*
* Detail: http://groups.google.com/group/cecid-hermes2/browse_thread/thread/46cca8b51ca21524
*/
public void testMartinKalenIssue1() throws Exception {
// All UTC datetime should be generated through below methods
String utc = EbmsUtility.getCurrentUTCDateTime();
// if the last character is not 'Z', then the character preceding last two
// should be ":".
System.out.println(utc);
TestCase.assertTrue(
"The converted UTC string should have ':' character between the 'hh' and 'mm' parts",
(utc.charAt(utc.length() -1) != 'Z' && utc.charAt(utc.length() - 3) == ':'));
}
/**
* Test for the scenario issued by Martin Kalen from the google group.<br/><br/>
*
* <pre>
* I live in the UTC+02:00 timezone and today at 14:01 my time (=12:01
* UTC time) an incoming ebXML message with the following TTL timestamp
* was considered expired by Hermes: "2007-07-10T12:04:14Z".
* Without the change in EbmsUtility above, Hermes regards the incoming
* timestamp as 12:04 in my timezone which mutates the expected
* 12:04:14UTC to 10:04:14UTC = incorrect expiry notification to the
* sender.
* </pre>
*
* Detail: http://groups.google.com/group/cecid-hermes2/browse_thread/thread/46cca8b51ca21524
*/
public void testMartinKalenIssue2() throws Exception {
// Incoming ebMS message TTL.
String localTime = "2007-07-10T14:01:14+02:00";
String currentTime = "2007-07-10T12:01:14Z";
String timeToLive = "2007-07-10T12:04:14Z";
Calendar ttlCal = EbmsUtility.UTC2Calendar(timeToLive);
// Get the two calendar which they are representing same instant.
Calendar curCal = EbmsUtility.UTC2Calendar(currentTime);
Calendar locCal = EbmsUtility.UTC2Calendar(localTime);
// Check whether they are representing same instant.
this.validateCalendar(curCal, locCal);
// Create one more calendar for stimulating the expiration validation flow
// The timestamp created is 2007-07-10T12:01:14.
Calendar sysCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+02:00"));
sysCal.set(2007, 06, 10, 12, 01, 14);
System.out.println("System calendar : " + ttlCal.getTime());
System.out.println("System calendar : " + sysCal.getTime());
// The time to live timstamp is later than the system calendar, then it should
// return false.
TestCase.assertFalse(
"TimeToLive calendar should not eariler than system calendar",
ttlCal.getTime().before(sysCal.getTime()));
}
}
| UTF-8 | Java | 22,300 | java | EbmsUtilityTest.java | Java | [
{
"context": "e for <code>EbmsUtility</code>.\r\n * \r\n * @author \tTwinsen Tsang\r\n * @since\t1.0.0\r\n * @version\t1.0.0\r\n */\r\npublic ",
"end": 348,
"score": 0.9998598098754883,
"start": 335,
"tag": "NAME",
"value": "Twinsen Tsang"
},
{
"context": "\r\n\t}\r\n\t\r\n\t/**\r\n\... | null | [] | package hk.hku.cecid.ebms.spa;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;
import junit.framework.TestCase;
import hk.hku.cecid.ebms.spa.EbmsUtility;
/**
* The <code>EbmsUtilityTest</code> is the testcase for <code>EbmsUtility</code>.
*
* @author <NAME>
* @since 1.0.0
* @version 1.0.0
*/
public class EbmsUtilityTest extends TestCase{
// Invoked for setup.
public void setUp() throws Exception {
System.out.println();
System.out.println("---------" + this.getName() + " Start -------");
}
// Invoked for finalized.
public void tearDown() throws Exception {
System.out.println("---------" + this.getName() + " End -------");
}
/**
* Get the local timezone represenetation from the UTC. The returned
* format is "GMT+hh:mm".
* <br/><br/>
* For example, if you are located in Asia/Hong Kong, the returned
* string should be "GMT+08:00".
*/
public String getLocalTimezone(){
// Get the default timezone.
TimeZone tz = TimeZone.getDefault();
// Get the offset from UTC.
int tzOffset = tz.getOffset(new Date().getTime());
// Formatter.
DecimalFormat twoDigits = new DecimalFormat("00");
String sign = "+";
if (tzOffset < 0){ sign = "-"; tzOffset = -tzOffset; }
// calculate the timezone offset.
int hours = (tzOffset / 3600000);
int minutes = (tzOffset % 3600000) / 60000;
// Return the local timezone.
return new StringBuffer("GMT")
.append(sign)
.append(twoDigits.format(hours))
.append(":")
.append(twoDigits.format(minutes)).toString();
}
/**
* A common method to validate cirtical field for specified <code>cal</code>
*
* @param cal The calendar to test against.
* @param expectedYear
* The expected year.
* @param expectedMonth
* The expected month.
* @param expectedDay
* The expected day.
* @param expectedHour
* The expected hour.
* @param expectedMins
* The expected mins.
* @param expectedSecond
* The expected second.
* @param expectedMillisecond
* The expected millisecond.
* @param expectedTz
* The expected timezone.
*/
public void validateCalendar(Calendar cal,
int expectedYear, int expectedMonth, int expectedDay, int expectedHour,
int expectedMins, int expectedSecond, int expectedMillisecond, String expectedTz)
{
// Null test
TestCase.assertNotNull(cal);
// Value test
TestCase.assertEquals(expectedYear , cal.get(Calendar.YEAR));
TestCase.assertEquals(expectedMonth , cal.get(Calendar.MONTH)); // Month is starting from zero.
TestCase.assertEquals(expectedDay , cal.get(Calendar.DAY_OF_MONTH));
TestCase.assertEquals(expectedHour , cal.get(Calendar.HOUR_OF_DAY));
TestCase.assertEquals(expectedMins , cal.get(Calendar.MINUTE));
TestCase.assertEquals(expectedSecond , cal.get(Calendar.SECOND));
TestCase.assertEquals(expectedMillisecond , cal.get(Calendar.MILLISECOND));
TestCase.assertEquals(expectedTz , cal.getTimeZone().getID());
// Now transform it to the local machine time.
Calendar transformedCal = Calendar.getInstance();
transformedCal.setTime(cal.getTime());
// Get the timezone offset from the testing calendar from UTC.
int clOffset = cal.getTimeZone().getOffset(new Date().getTime());
// Get the timezone offset of this local machine from UTC.
int tzOffset = TimeZone.getDefault().getOffset(cal.getTimeInMillis());
// Calculate the actual offset
tzOffset = tzOffset - clOffset;
System.out.println("TimeZone Offset: " + tzOffset);
int hours = expectedHour + tzOffset / 3600000;
int mins = expectedMins + (tzOffset % 3600000) / 60000;
int days = expectedDay;
// If the offset is greater than 24.
if (hours > 24){ hours -= 24; days += 1; }
else if (hours < 0) { hours += 24; days -= 1; }
TestCase.assertEquals(hours, transformedCal.get(Calendar.HOUR_OF_DAY));
TestCase.assertEquals(mins , transformedCal.get(Calendar.MINUTE));
TestCase.assertEquals(days , transformedCal.get(Calendar.DAY_OF_MONTH));
System.out.println(transformedCal.getTime());
// Done.
}
/**
* A common method to validate cirtical field for specified <code>target</code>
* by the value in the calendar <code>control</code>.
*
* @param target
* The target calendar to test for.
* @param control
* The reference calendar to test for.
*/
public void validateCalendar(Calendar target, Calendar control)
{
// Not Null test
TestCase.assertNotNull(target);
TestCase.assertNotNull(control);
// Assert whether they are representing same time.
System.out.println("Target Calendar (de): " + target.getTime());
System.out.println("Control Calendar (de): " + control.getTime());
System.out.println("Target Calendar (ms): " + target.getTimeInMillis());
System.out.println("Control Calendar (ms): " + control.getTimeInMillis());
TestCase.assertEquals (target.getTimeInMillis(), control.getTimeInMillis());
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone in UTC (GMT+00:00) using 'Z' designator.
*/
public void testUTC2Calendar_Pos0() throws Exception {
String dateTime = "2007-07-16T13:24:56.789Z";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "UTC");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone in UTC (GMT+00:00) using +00:00
*/
public void testUTC2Calendar_Pos1() throws Exception {
String dateTime = "2007-07-16T13:24:56.789+00:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "GMT+00:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone GMT+08:00 (non zero timezone)
*/
public void testUTC2Calendar_Pos2() throws Exception {
String dateTime = "2007-07-16T13:24:56.789+08:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "GMT+08:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone GMT+13:00 (boundary case)
*/
public void testUTC2Calendar_Pos3() throws Exception {
String dateTime = "2007-07-16T04:24:56.789+13:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// * We have used the hour 04 instead of 13 for testing the offset from previous day.
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 04, 24, 56, 789, "GMT+13:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC and
* under the timezone GMT-12:00 (boundary case)
*/
public void testUTC2Calendar_Pos4() throws Exception {
String dateTime = "2007-07-16T13:24:56.789-12:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "GMT-12:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC without millisecond
* and under the timezone UTC.
*/
public void testUTC2Calendar_Pos5() throws Exception {
String dateTime = "2007-07-16T13:24:56Z";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 0, "UTC");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC without millisecond
* and under any timezone other than UTC.
*/
public void testUTC2Calendar_Pos6() throws Exception {
String dateTime = "2007-07-16T13:24:56-08:00";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 0, "GMT-08:00");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC without millisecond and 'Z'
* and under any timezone other than UTC.
*/
public void testUTC2Calendar_Pos7() throws Exception {
String dateTime = "2007-07-16T13:24:56";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 0, "UTC");
}
/**
* Test the conversation from UTC to java calendar object.<br/><br/>
*
* Testing for the scenario the dateTime is represented as UTC with 'Z'
* and under any timezone other than UTC.
*/
public void testUTC2Calendar_Pos8() throws Exception {
String dateTime = "2007-07-16T13:24:56.789";
Calendar cal = EbmsUtility.UTC2Calendar(dateTime);
// Validate all field.
this.validateCalendar(cal, 2007, 06, 16, 13, 24, 56, 789, "UTC");
}
/**
* Test the conversation from UTC to java calendar object negatively.<br/><br/>
*
* Testing for the scenario all invalid UTC format representation.
*/
public void testUTC2Calendar_Neg0() throws Exception {
// Invalid regex format between year and month
String dateTime0 = "2007**07-16T13:24:56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime0);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between year and month passed.");
}
// Invalid regex format between month and days
String dateTime1 = "2007-07!!16T13:24:56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime1);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between month and days passed.");
}
// Invalid regex format between days and hour
String dateTime2 = "2007-07-16@@@13:24:56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime2);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between days and hour passed.");
}
// Invalid regex format between hours and minutes
String dateTime3 = "2007-07-16@T13##24:56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime3);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between hours and minutes passed.");
}
// Invalid regex format between minutes and second
String dateTime4 = "2007-07-16@T13:24~~56.789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime4);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between minutes and second passed.");
}
// Invalid regex format between second and millisecond
String dateTime5 = "2007-07-16@T13:24:56~_~789-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime5);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between second and millisecond passed.");
}
// Invalid regex format between millisecond and timezone
String dateTime6 = "2007-07-16@T13:24:56.78931212:00";
try{
EbmsUtility.UTC2Calendar(dateTime6);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format between millisecond and timezone passed.");
}
// Invalid regex format for millisecond
String dateTime7 = "2007-07-16@T13:24:56.ddd-12:00";
try{
EbmsUtility.UTC2Calendar(dateTime7);
TestCase.fail("Invalid Format of UTC datetime has not throw parsing exception.");
} catch (Exception ex) {
System.out.println("Invalid regex format for millisecond");
}
}
/**
* Test for getting the current UTC data time.<br/><br/>
*/
/**
* @throws Exception
*/
public void testGetCurrentUTCDateTime_Pos0() throws Exception {
String utc = EbmsUtility.getCurrentUTCDateTime();
Calendar sysCal = Calendar.getInstance();
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
System.out.println("UTC converted: " + utc);
// For this testcase, we should tolerate the millisecond and second due to
// there is sightly time different between creating the sysCal and utcCal.
// So we set the millisecond part to 0 for this two cal.
sysCal.set(Calendar.SECOND, 0);
sysCal.set(Calendar.MILLISECOND, 0);
utcCal.set(Calendar.SECOND, 0);
utcCal.set(Calendar.MILLISECOND, 0);
// validate the calendar field
this.validateCalendar(utcCal,
sysCal.get(Calendar.YEAR),
sysCal.get(Calendar.MONTH),
sysCal.get(Calendar.DAY_OF_MONTH),
sysCal.get(Calendar.HOUR_OF_DAY),
sysCal.get(Calendar.MINUTE),
sysCal.get(Calendar.SECOND),
sysCal.get(Calendar.MILLISECOND),
this.getLocalTimezone());
}
/**
* Test for converting from a java date object to UTC conformed representation string.
*
* Testing for the scenario the dateTime is represented as java calendar and
* under the timezone same as the machine running.
*/
public void testDate2UTC_Pos0() throws Exception {
Calendar cal = Calendar.getInstance();
// 2007-07-16@T13:24:56.78931212:00
cal.set(2007, 06, 16, 13, 24, 56);
cal.set(Calendar.MILLISECOND, 0);
// Convert to UTC representation
String utc = EbmsUtility.date2UTC(cal.getTime(), cal.getTimeZone());
System.out.println("UTC converted: " + utc);
// Convert back to java calendar and validate the field.
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
// validate the calendar field
this.validateCalendar(utcCal, 2007, 6, 16, 13, 24, 56, 0, this.getLocalTimezone());
}
/**
* Test for converting from a java date object to UTC conformed representation string.
*
* Testing for the scenario the dateTime is represented as java calendar and
* under the timezone under UTC.
*/
public void testDate2UTC_Pos1() throws Exception {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// 2007-07-16@T13:24:56.000Z
cal.set(2007, 06, 16, 13, 24, 56);
cal.set(Calendar.MILLISECOND, 789);
// Convert to UTC representation
String utc = EbmsUtility.date2UTC(cal.getTime(), cal.getTimeZone());
System.out.println("UTC converted : " + utc);
// Convert back to java calendar and validate the field.
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
// validate whether the timezone is correctly converted.
String utcTz = utcCal.getTimeZone().getID();
TestCase.assertTrue(utcTz.equals("UTC") || utcTz.equals("GMT+00:00"));
// validate the calendar field based on cal.
this.validateCalendar(utcCal, cal);
}
/**
* Test for converting from a java date object to UTC conformed representation string.
*
* Testing for the scenario the dateTime is represented as java calendar and
* under the timezone under GMT-12:00 (boundary case)
*/
public void testDate2UTC_Pos2() throws Exception {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-12:00"));
// 2007-07-16@T13:24:56.000-12:00
cal.set(2007, 06, 16, 13, 24, 56);
cal.set(Calendar.MILLISECOND, 789);
// Convert to UTC representation
String utc = EbmsUtility.date2UTC(cal.getTime(), cal.getTimeZone());
System.out.println("UTC converted: " + utc);
// Convert back to java calendar and validate the field.
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
// validate whether the timezone is correctly converted.
TestCase.assertTrue(utcCal.getTimeZone().getID().equals("GMT-12:00"));
// validate the calendar field based on cal.
this.validateCalendar(utcCal, cal);
}
/**
* Test for converting from a java date object to UTC conformed representation string.
*
* Testing for the scenario the dateTime is represented as java calendar and
* under the timezone under GMT+13:00 (boundary case)
*/
public void testDate2UTC_Pos3() throws Exception {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+13:00"));
// 2007-07-16@T13:24:56.000-12:00
cal.set(2007, 06, 16, 13, 24, 56);
cal.set(Calendar.MILLISECOND, 789);
// Convert to UTC representation
String utc = EbmsUtility.date2UTC(cal.getTime(), cal.getTimeZone());
System.out.println("UTC converted: " + utc);
// Convert back to java calendar and validate the field.
Calendar utcCal = EbmsUtility.UTC2Calendar(utc);
// validate whether the timezone is correctly converted.
TestCase.assertTrue(utcCal.getTimeZone().getID().equals("GMT+13:00"));
// validate the calendar field based on cal.
this.validateCalendar(utcCal, cal);
}
/**
* Test for converting from GMT datetime representation to java date object.
*/
public void testGMT2Date_Pos0() throws Exception {
Date date = new Date();
String dateTime = date.toString();
Date convertedDate = EbmsUtility.GMT2Date(dateTime);
System.out.println("GMT converted: " + convertedDate);
// Since the millisecond pecision will be lost during conversion.
// we need to create a calendar and set the millisecond to zero.
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date.getTime());
cal.set(Calendar.MILLISECOND, 0);
// Check whether the time is equal or not.
TestCase.assertEquals(convertedDate.getTime(), cal.getTimeInMillis());
}
/**
* Test for the scenario issued by <NAME> from the google group.<br/><br/>
*
* QUOTED FROM martin said:
* <pre>
* Hermes sends ebMS ACK messages with a non-standard timezone part of
* the timestamp (timezone info is not according to ebXML-specification,
* see background below)
*
* Background on #1:
* The recent fix for Hermes UTC timestamps uses the Java
* SimpleDateFormat "Z"-pattern for timezone, which is unfortunately
* incompatible with the ebXML specification for time zone refering to
* the XML schema data-type "dateTime" specified here:
* http://www.w3.org/TR/xmlschema-2/#dateTime
*
* Snippets from the spec:
* "dateTime consists of finite-length sequences of characters of the
* form: '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)?
* (zzzzzz)?"
* "zzzzzz (if present) represents the timezone"
*
* From 3.2.7.3 Timezones The lexical representation of a timezone is a string of the form:
* (('+' | '-') hh ':' mm) | 'Z'"
* In Java the ':' character is missing between the "hh" and "mm" parts.
* More details on the Java SimpleDateFormat vs XSD dateTime
* incompatibility can be found here:
* </pre>
*
* Detail: http://groups.google.com/group/cecid-hermes2/browse_thread/thread/46cca8b51ca21524
*/
public void testMartinKalenIssue1() throws Exception {
// All UTC datetime should be generated through below methods
String utc = EbmsUtility.getCurrentUTCDateTime();
// if the last character is not 'Z', then the character preceding last two
// should be ":".
System.out.println(utc);
TestCase.assertTrue(
"The converted UTC string should have ':' character between the 'hh' and 'mm' parts",
(utc.charAt(utc.length() -1) != 'Z' && utc.charAt(utc.length() - 3) == ':'));
}
/**
* Test for the scenario issued by <NAME> from the google group.<br/><br/>
*
* <pre>
* I live in the UTC+02:00 timezone and today at 14:01 my time (=12:01
* UTC time) an incoming ebXML message with the following TTL timestamp
* was considered expired by Hermes: "2007-07-10T12:04:14Z".
* Without the change in EbmsUtility above, Hermes regards the incoming
* timestamp as 12:04 in my timezone which mutates the expected
* 12:04:14UTC to 10:04:14UTC = incorrect expiry notification to the
* sender.
* </pre>
*
* Detail: http://groups.google.com/group/cecid-hermes2/browse_thread/thread/46cca8b51ca21524
*/
public void testMartinKalenIssue2() throws Exception {
// Incoming ebMS message TTL.
String localTime = "2007-07-10T14:01:14+02:00";
String currentTime = "2007-07-10T12:01:14Z";
String timeToLive = "2007-07-10T12:04:14Z";
Calendar ttlCal = EbmsUtility.UTC2Calendar(timeToLive);
// Get the two calendar which they are representing same instant.
Calendar curCal = EbmsUtility.UTC2Calendar(currentTime);
Calendar locCal = EbmsUtility.UTC2Calendar(localTime);
// Check whether they are representing same instant.
this.validateCalendar(curCal, locCal);
// Create one more calendar for stimulating the expiration validation flow
// The timestamp created is 2007-07-10T12:01:14.
Calendar sysCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+02:00"));
sysCal.set(2007, 06, 10, 12, 01, 14);
System.out.println("System calendar : " + ttlCal.getTime());
System.out.println("System calendar : " + sysCal.getTime());
// The time to live timstamp is later than the system calendar, then it should
// return false.
TestCase.assertFalse(
"TimeToLive calendar should not eariler than system calendar",
ttlCal.getTime().before(sysCal.getTime()));
}
}
| 22,281 | 0.677444 | 0.631883 | 606 | 34.798679 | 27.89654 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.359736 | false | false | 6 |
8830815867c6dc73b1e95ccede9e7c2cc5574321 | 14,362,370,659,159 | 59e743806d6e411121b4e518d36203dac4a87c80 | /Kitaplik/src/Kitaplik/PDFViewer.java | b28a835e7fb8d39cf672ed59957bd6d6c3ef315f | [] | no_license | akadirdd/Ebook | https://github.com/akadirdd/Ebook | d889ded3f7d331ff6684f84e75d44f061275f6a8 | 4b5654ba0d74dd2a97884f9ba1f4db15a8e80c8b | refs/heads/master | 2020-04-14T09:00:35.041000 | 2019-01-01T16:15:06 | 2019-01-01T16:15:06 | 163,749,456 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Kitaplik;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
public class PDFViewer {
String filePath;
public PDFViewer(String filePath) {
this.filePath = filePath;
}
public void openPdf() {
// build a component controller
SwingController controller = new SwingController();
SwingViewBuilder factory = new SwingViewBuilder(controller);
JPanel viewerComponentPanel = factory.buildViewerPanel();
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
JFrame applicationFrame = new JFrame();
applicationFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
applicationFrame.getContentPane().add(viewerComponentPanel);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
applicationFrame.setLocation(dim.width / 2 - 500, dim.height / 2 - 500);
// Now that the GUI is all in place, we can try openning a PDF
controller.openDocument(filePath);
applicationFrame.pack();
applicationFrame.setVisible(true);
}
}
| UTF-8 | Java | 1,424 | java | PDFViewer.java | Java | [] | null | [] |
package Kitaplik;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
public class PDFViewer {
String filePath;
public PDFViewer(String filePath) {
this.filePath = filePath;
}
public void openPdf() {
// build a component controller
SwingController controller = new SwingController();
SwingViewBuilder factory = new SwingViewBuilder(controller);
JPanel viewerComponentPanel = factory.buildViewerPanel();
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
JFrame applicationFrame = new JFrame();
applicationFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
applicationFrame.getContentPane().add(viewerComponentPanel);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
applicationFrame.setLocation(dim.width / 2 - 500, dim.height / 2 - 500);
// Now that the GUI is all in place, we can try openning a PDF
controller.openDocument(filePath);
applicationFrame.pack();
applicationFrame.setVisible(true);
}
}
| 1,424 | 0.701545 | 0.695927 | 41 | 33.707317 | 26.601158 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.560976 | false | false | 6 |
3b447598b7ce2446fddc661ceca73ed9ad174da3 | 21,062,519,630,799 | bf812baa4cfd31d22d74ac7ec1a324641a991ede | /taxmanfk/src/main/java/kadryiplace/Ksiegapir.java | 8cbd931cbc87c9fab84b558f83a957315296dd5b | [] | no_license | brzaskun/NetBeansProjects | https://github.com/brzaskun/NetBeansProjects | f5d0abc95a29681fab87e6a039a7f925edab3dc6 | aa67838735901cc9171c49600348eaea8e35e523 | refs/heads/masterpozmianach | 2023-08-31T23:32:37.748000 | 2023-08-30T21:30:09 | 2023-08-30T21:30:09 | 40,359,654 | 0 | 0 | null | false | 2023-03-27T22:22:00 | 2015-08-07T12:35:43 | 2022-01-10T23:16:06 | 2023-03-27T22:21:58 | 221,533 | 0 | 0 | 15 | Java | false | false | /*
* 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 kadryiplace;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Osito
*/
@Entity
@Table(name = "ksiegapir", catalog = "kadryiplace", schema = "dbo")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Ksiegapir.findAll", query = "SELECT k FROM Ksiegapir k"),
@NamedQuery(name = "Ksiegapir.findByKsiSerial", query = "SELECT k FROM Ksiegapir k WHERE k.ksiSerial = :ksiSerial"),
@NamedQuery(name = "Ksiegapir.findByKsiDataZdarz", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDataZdarz = :ksiDataZdarz"),
@NamedQuery(name = "Ksiegapir.findByKsiNrDowodu", query = "SELECT k FROM Ksiegapir k WHERE k.ksiNrDowodu = :ksiNrDowodu"),
@NamedQuery(name = "Ksiegapir.findByKsiOpisZdarz", query = "SELECT k FROM Ksiegapir k WHERE k.ksiOpisZdarz = :ksiOpisZdarz"),
@NamedQuery(name = "Ksiegapir.findByKsiLp", query = "SELECT k FROM Ksiegapir k WHERE k.ksiLp = :ksiLp"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota7", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota7 = :ksiKwota7"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota8", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota8 = :ksiKwota8"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota10", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota10 = :ksiKwota10"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota11", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota11 = :ksiKwota11"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota12", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota12 = :ksiKwota12"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota13", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota13 = :ksiKwota13"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota14", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota14 = :ksiKwota14"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota16", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota16 = :ksiKwota16"),
@NamedQuery(name = "Ksiegapir.findByKsiUwagi", query = "SELECT k FROM Ksiegapir k WHERE k.ksiUwagi = :ksiUwagi"),
@NamedQuery(name = "Ksiegapir.findByKsiKonNazwa", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKonNazwa = :ksiKonNazwa"),
@NamedQuery(name = "Ksiegapir.findByKsiKonAdres", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKonAdres = :ksiKonAdres"),
@NamedQuery(name = "Ksiegapir.findByKsiKonNazwaSkr", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKonNazwaSkr = :ksiKonNazwaSkr"),
@NamedQuery(name = "Ksiegapir.findByKsiSkreslony", query = "SELECT k FROM Ksiegapir k WHERE k.ksiSkreslony = :ksiSkreslony"),
@NamedQuery(name = "Ksiegapir.findByKsiOrygTyp", query = "SELECT k FROM Ksiegapir k WHERE k.ksiOrygTyp = :ksiOrygTyp"),
@NamedQuery(name = "Ksiegapir.findByKsiOrygSerial", query = "SELECT k FROM Ksiegapir k WHERE k.ksiOrygSerial = :ksiOrygSerial"),
@NamedQuery(name = "Ksiegapir.findByKsiCzas", query = "SELECT k FROM Ksiegapir k WHERE k.ksiCzas = :ksiCzas"),
@NamedQuery(name = "Ksiegapir.findByKsiUsrUserid", query = "SELECT k FROM Ksiegapir k WHERE k.ksiUsrUserid = :ksiUsrUserid"),
@NamedQuery(name = "Ksiegapir.findByKsiCzasMod", query = "SELECT k FROM Ksiegapir k WHERE k.ksiCzasMod = :ksiCzasMod"),
@NamedQuery(name = "Ksiegapir.findByKsiUsrUseridMod", query = "SELECT k FROM Ksiegapir k WHERE k.ksiUsrUseridMod = :ksiUsrUseridMod"),
@NamedQuery(name = "Ksiegapir.findByKsiDodNum1", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodNum1 = :ksiDodNum1"),
@NamedQuery(name = "Ksiegapir.findByKsiDodNum2", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodNum2 = :ksiDodNum2"),
@NamedQuery(name = "Ksiegapir.findByKsiDodNum3", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodNum3 = :ksiDodNum3"),
@NamedQuery(name = "Ksiegapir.findByKsiDodNum4", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodNum4 = :ksiDodNum4"),
@NamedQuery(name = "Ksiegapir.findByKsiDodChar1", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodChar1 = :ksiDodChar1"),
@NamedQuery(name = "Ksiegapir.findByKsiDodChar2", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodChar2 = :ksiDodChar2"),
@NamedQuery(name = "Ksiegapir.findByKsiDodVchar1", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodVchar1 = :ksiDodVchar1"),
@NamedQuery(name = "Ksiegapir.findByKsiDodVchar2", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodVchar2 = :ksiDodVchar2")})
public class Ksiegapir implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "ksi_serial", nullable = false)
private Integer ksiSerial;
@Column(name = "ksi_data_zdarz")
@Temporal(TemporalType.TIMESTAMP)
private Date ksiDataZdarz;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 32)
@Column(name = "ksi_nr_dowodu", nullable = false, length = 32)
private String ksiNrDowodu;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 128)
@Column(name = "ksi_opis_zdarz", nullable = false, length = 128)
private String ksiOpisZdarz;
@Basic(optional = false)
@NotNull
@Column(name = "ksi_lp", nullable = false)
private int ksiLp;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "ksi_kwota_7", precision = 13, scale = 2)
private BigDecimal ksiKwota7;
@Column(name = "ksi_kwota_8", precision = 13, scale = 2)
private BigDecimal ksiKwota8;
@Column(name = "ksi_kwota_10", precision = 13, scale = 2)
private BigDecimal ksiKwota10;
@Column(name = "ksi_kwota_11", precision = 13, scale = 2)
private BigDecimal ksiKwota11;
@Column(name = "ksi_kwota_12", precision = 13, scale = 2)
private BigDecimal ksiKwota12;
@Column(name = "ksi_kwota_13", precision = 13, scale = 2)
private BigDecimal ksiKwota13;
@Column(name = "ksi_kwota_14", precision = 13, scale = 2)
private BigDecimal ksiKwota14;
@Column(name = "ksi_kwota_16", precision = 13, scale = 2)
private BigDecimal ksiKwota16;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 64)
@Column(name = "ksi_uwagi", nullable = false, length = 64)
private String ksiUwagi;
@Size(max = 64)
@Column(name = "ksi_kon_nazwa", length = 64)
private String ksiKonNazwa;
@Size(max = 128)
@Column(name = "ksi_kon_adres", length = 128)
private String ksiKonAdres;
@Size(max = 32)
@Column(name = "ksi_kon_nazwa_skr", length = 32)
private String ksiKonNazwaSkr;
@Column(name = "ksi_skreslony")
private Character ksiSkreslony;
@Column(name = "ksi_oryg_typ")
private Character ksiOrygTyp;
@Column(name = "ksi_oryg_serial")
private Integer ksiOrygSerial;
@Column(name = "ksi_czas")
@Temporal(TemporalType.TIMESTAMP)
private Date ksiCzas;
@Size(max = 32)
@Column(name = "ksi_usr_userid", length = 32)
private String ksiUsrUserid;
@Column(name = "ksi_czas_mod")
@Temporal(TemporalType.TIMESTAMP)
private Date ksiCzasMod;
@Size(max = 32)
@Column(name = "ksi_usr_userid_mod", length = 32)
private String ksiUsrUseridMod;
@Column(name = "ksi_dod_num_1", precision = 13, scale = 2)
private BigDecimal ksiDodNum1;
@Column(name = "ksi_dod_num_2", precision = 13, scale = 2)
private BigDecimal ksiDodNum2;
@Column(name = "ksi_dod_num_3", precision = 13, scale = 2)
private BigDecimal ksiDodNum3;
@Column(name = "ksi_dod_num_4", precision = 13, scale = 2)
private BigDecimal ksiDodNum4;
@Column(name = "ksi_dod_char_1")
private Character ksiDodChar1;
@Column(name = "ksi_dod_char_2")
private Character ksiDodChar2;
@Size(max = 64)
@Column(name = "ksi_dod_vchar_1", length = 64)
private String ksiDodVchar1;
@Size(max = 64)
@Column(name = "ksi_dod_vchar_2", length = 64)
private String ksiDodVchar2;
@JoinColumn(name = "ksi_fir_serial", referencedColumnName = "fir_serial", nullable = false)
@ManyToOne(optional = false)
private Firma ksiFirSerial;
@JoinColumn(name = "ksi_kon_serial", referencedColumnName = "kon_serial")
@ManyToOne
private Kontrahent ksiKonSerial;
@JoinColumn(name = "ksi_okr_serial", referencedColumnName = "okr_serial", nullable = false)
@ManyToOne(optional = false)
private Okres ksiOkrSerial;
@JoinColumn(name = "ksi_rok_serial", referencedColumnName = "rok_serial", nullable = false)
@ManyToOne(optional = false)
private Rok ksiRokSerial;
@OneToMany(mappedBy = "dsrKsiSerial")
private List<DaneStatR> daneStatRList;
public Ksiegapir() {
}
public Ksiegapir(Integer ksiSerial) {
this.ksiSerial = ksiSerial;
}
public Ksiegapir(Integer ksiSerial, String ksiNrDowodu, String ksiOpisZdarz, int ksiLp, String ksiUwagi) {
this.ksiSerial = ksiSerial;
this.ksiNrDowodu = ksiNrDowodu;
this.ksiOpisZdarz = ksiOpisZdarz;
this.ksiLp = ksiLp;
this.ksiUwagi = ksiUwagi;
}
public Integer getKsiSerial() {
return ksiSerial;
}
public void setKsiSerial(Integer ksiSerial) {
this.ksiSerial = ksiSerial;
}
public Date getKsiDataZdarz() {
return ksiDataZdarz;
}
public void setKsiDataZdarz(Date ksiDataZdarz) {
this.ksiDataZdarz = ksiDataZdarz;
}
public String getKsiNrDowodu() {
return ksiNrDowodu;
}
public void setKsiNrDowodu(String ksiNrDowodu) {
this.ksiNrDowodu = ksiNrDowodu;
}
public String getKsiOpisZdarz() {
return ksiOpisZdarz;
}
public void setKsiOpisZdarz(String ksiOpisZdarz) {
this.ksiOpisZdarz = ksiOpisZdarz;
}
public int getKsiLp() {
return ksiLp;
}
public void setKsiLp(int ksiLp) {
this.ksiLp = ksiLp;
}
public BigDecimal getKsiKwota7() {
return ksiKwota7;
}
public void setKsiKwota7(BigDecimal ksiKwota7) {
this.ksiKwota7 = ksiKwota7;
}
public BigDecimal getKsiKwota8() {
return ksiKwota8;
}
public void setKsiKwota8(BigDecimal ksiKwota8) {
this.ksiKwota8 = ksiKwota8;
}
public BigDecimal getKsiKwota10() {
return ksiKwota10;
}
public void setKsiKwota10(BigDecimal ksiKwota10) {
this.ksiKwota10 = ksiKwota10;
}
public BigDecimal getKsiKwota11() {
return ksiKwota11;
}
public void setKsiKwota11(BigDecimal ksiKwota11) {
this.ksiKwota11 = ksiKwota11;
}
public BigDecimal getKsiKwota12() {
return ksiKwota12;
}
public void setKsiKwota12(BigDecimal ksiKwota12) {
this.ksiKwota12 = ksiKwota12;
}
public BigDecimal getKsiKwota13() {
return ksiKwota13;
}
public void setKsiKwota13(BigDecimal ksiKwota13) {
this.ksiKwota13 = ksiKwota13;
}
public BigDecimal getKsiKwota14() {
return ksiKwota14;
}
public void setKsiKwota14(BigDecimal ksiKwota14) {
this.ksiKwota14 = ksiKwota14;
}
public BigDecimal getKsiKwota16() {
return ksiKwota16;
}
public void setKsiKwota16(BigDecimal ksiKwota16) {
this.ksiKwota16 = ksiKwota16;
}
public String getKsiUwagi() {
return ksiUwagi;
}
public void setKsiUwagi(String ksiUwagi) {
this.ksiUwagi = ksiUwagi;
}
public String getKsiKonNazwa() {
return ksiKonNazwa;
}
public void setKsiKonNazwa(String ksiKonNazwa) {
this.ksiKonNazwa = ksiKonNazwa;
}
public String getKsiKonAdres() {
return ksiKonAdres;
}
public void setKsiKonAdres(String ksiKonAdres) {
this.ksiKonAdres = ksiKonAdres;
}
public String getKsiKonNazwaSkr() {
return ksiKonNazwaSkr;
}
public void setKsiKonNazwaSkr(String ksiKonNazwaSkr) {
this.ksiKonNazwaSkr = ksiKonNazwaSkr;
}
public Character getKsiSkreslony() {
return ksiSkreslony;
}
public void setKsiSkreslony(Character ksiSkreslony) {
this.ksiSkreslony = ksiSkreslony;
}
public Character getKsiOrygTyp() {
return ksiOrygTyp;
}
public void setKsiOrygTyp(Character ksiOrygTyp) {
this.ksiOrygTyp = ksiOrygTyp;
}
public Integer getKsiOrygSerial() {
return ksiOrygSerial;
}
public void setKsiOrygSerial(Integer ksiOrygSerial) {
this.ksiOrygSerial = ksiOrygSerial;
}
public Date getKsiCzas() {
return ksiCzas;
}
public void setKsiCzas(Date ksiCzas) {
this.ksiCzas = ksiCzas;
}
public String getKsiUsrUserid() {
return ksiUsrUserid;
}
public void setKsiUsrUserid(String ksiUsrUserid) {
this.ksiUsrUserid = ksiUsrUserid;
}
public Date getKsiCzasMod() {
return ksiCzasMod;
}
public void setKsiCzasMod(Date ksiCzasMod) {
this.ksiCzasMod = ksiCzasMod;
}
public String getKsiUsrUseridMod() {
return ksiUsrUseridMod;
}
public void setKsiUsrUseridMod(String ksiUsrUseridMod) {
this.ksiUsrUseridMod = ksiUsrUseridMod;
}
public BigDecimal getKsiDodNum1() {
return ksiDodNum1;
}
public void setKsiDodNum1(BigDecimal ksiDodNum1) {
this.ksiDodNum1 = ksiDodNum1;
}
public BigDecimal getKsiDodNum2() {
return ksiDodNum2;
}
public void setKsiDodNum2(BigDecimal ksiDodNum2) {
this.ksiDodNum2 = ksiDodNum2;
}
public BigDecimal getKsiDodNum3() {
return ksiDodNum3;
}
public void setKsiDodNum3(BigDecimal ksiDodNum3) {
this.ksiDodNum3 = ksiDodNum3;
}
public BigDecimal getKsiDodNum4() {
return ksiDodNum4;
}
public void setKsiDodNum4(BigDecimal ksiDodNum4) {
this.ksiDodNum4 = ksiDodNum4;
}
public Character getKsiDodChar1() {
return ksiDodChar1;
}
public void setKsiDodChar1(Character ksiDodChar1) {
this.ksiDodChar1 = ksiDodChar1;
}
public Character getKsiDodChar2() {
return ksiDodChar2;
}
public void setKsiDodChar2(Character ksiDodChar2) {
this.ksiDodChar2 = ksiDodChar2;
}
public String getKsiDodVchar1() {
return ksiDodVchar1;
}
public void setKsiDodVchar1(String ksiDodVchar1) {
this.ksiDodVchar1 = ksiDodVchar1;
}
public String getKsiDodVchar2() {
return ksiDodVchar2;
}
public void setKsiDodVchar2(String ksiDodVchar2) {
this.ksiDodVchar2 = ksiDodVchar2;
}
public Firma getKsiFirSerial() {
return ksiFirSerial;
}
public void setKsiFirSerial(Firma ksiFirSerial) {
this.ksiFirSerial = ksiFirSerial;
}
public Kontrahent getKsiKonSerial() {
return ksiKonSerial;
}
public void setKsiKonSerial(Kontrahent ksiKonSerial) {
this.ksiKonSerial = ksiKonSerial;
}
public Okres getKsiOkrSerial() {
return ksiOkrSerial;
}
public void setKsiOkrSerial(Okres ksiOkrSerial) {
this.ksiOkrSerial = ksiOkrSerial;
}
public Rok getKsiRokSerial() {
return ksiRokSerial;
}
public void setKsiRokSerial(Rok ksiRokSerial) {
this.ksiRokSerial = ksiRokSerial;
}
@XmlTransient
public List<DaneStatR> getDaneStatRList() {
return daneStatRList;
}
public void setDaneStatRList(List<DaneStatR> daneStatRList) {
this.daneStatRList = daneStatRList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (ksiSerial != null ? ksiSerial.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Ksiegapir)) {
return false;
}
Ksiegapir other = (Ksiegapir) object;
if ((this.ksiSerial == null && other.ksiSerial != null) || (this.ksiSerial != null && !this.ksiSerial.equals(other.ksiSerial))) {
return false;
}
return true;
}
@Override
public String toString() {
return "kadryiplace.Ksiegapir[ ksiSerial=" + ksiSerial + " ]";
}
}
| UTF-8 | Java | 17,529 | java | Ksiegapir.java | Java | [
{
"context": "nd.annotation.XmlTransient;\r\n\r\n/**\r\n *\r\n * @author Osito\r\n */\r\n@Entity\r\n@Table(name = \"ksiegapir\", catalog",
"end": 966,
"score": 0.9995756149291992,
"start": 961,
"tag": "NAME",
"value": "Osito"
}
] | 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 kadryiplace;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Osito
*/
@Entity
@Table(name = "ksiegapir", catalog = "kadryiplace", schema = "dbo")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Ksiegapir.findAll", query = "SELECT k FROM Ksiegapir k"),
@NamedQuery(name = "Ksiegapir.findByKsiSerial", query = "SELECT k FROM Ksiegapir k WHERE k.ksiSerial = :ksiSerial"),
@NamedQuery(name = "Ksiegapir.findByKsiDataZdarz", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDataZdarz = :ksiDataZdarz"),
@NamedQuery(name = "Ksiegapir.findByKsiNrDowodu", query = "SELECT k FROM Ksiegapir k WHERE k.ksiNrDowodu = :ksiNrDowodu"),
@NamedQuery(name = "Ksiegapir.findByKsiOpisZdarz", query = "SELECT k FROM Ksiegapir k WHERE k.ksiOpisZdarz = :ksiOpisZdarz"),
@NamedQuery(name = "Ksiegapir.findByKsiLp", query = "SELECT k FROM Ksiegapir k WHERE k.ksiLp = :ksiLp"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota7", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota7 = :ksiKwota7"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota8", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota8 = :ksiKwota8"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota10", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota10 = :ksiKwota10"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota11", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota11 = :ksiKwota11"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota12", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota12 = :ksiKwota12"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota13", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota13 = :ksiKwota13"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota14", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota14 = :ksiKwota14"),
@NamedQuery(name = "Ksiegapir.findByKsiKwota16", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKwota16 = :ksiKwota16"),
@NamedQuery(name = "Ksiegapir.findByKsiUwagi", query = "SELECT k FROM Ksiegapir k WHERE k.ksiUwagi = :ksiUwagi"),
@NamedQuery(name = "Ksiegapir.findByKsiKonNazwa", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKonNazwa = :ksiKonNazwa"),
@NamedQuery(name = "Ksiegapir.findByKsiKonAdres", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKonAdres = :ksiKonAdres"),
@NamedQuery(name = "Ksiegapir.findByKsiKonNazwaSkr", query = "SELECT k FROM Ksiegapir k WHERE k.ksiKonNazwaSkr = :ksiKonNazwaSkr"),
@NamedQuery(name = "Ksiegapir.findByKsiSkreslony", query = "SELECT k FROM Ksiegapir k WHERE k.ksiSkreslony = :ksiSkreslony"),
@NamedQuery(name = "Ksiegapir.findByKsiOrygTyp", query = "SELECT k FROM Ksiegapir k WHERE k.ksiOrygTyp = :ksiOrygTyp"),
@NamedQuery(name = "Ksiegapir.findByKsiOrygSerial", query = "SELECT k FROM Ksiegapir k WHERE k.ksiOrygSerial = :ksiOrygSerial"),
@NamedQuery(name = "Ksiegapir.findByKsiCzas", query = "SELECT k FROM Ksiegapir k WHERE k.ksiCzas = :ksiCzas"),
@NamedQuery(name = "Ksiegapir.findByKsiUsrUserid", query = "SELECT k FROM Ksiegapir k WHERE k.ksiUsrUserid = :ksiUsrUserid"),
@NamedQuery(name = "Ksiegapir.findByKsiCzasMod", query = "SELECT k FROM Ksiegapir k WHERE k.ksiCzasMod = :ksiCzasMod"),
@NamedQuery(name = "Ksiegapir.findByKsiUsrUseridMod", query = "SELECT k FROM Ksiegapir k WHERE k.ksiUsrUseridMod = :ksiUsrUseridMod"),
@NamedQuery(name = "Ksiegapir.findByKsiDodNum1", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodNum1 = :ksiDodNum1"),
@NamedQuery(name = "Ksiegapir.findByKsiDodNum2", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodNum2 = :ksiDodNum2"),
@NamedQuery(name = "Ksiegapir.findByKsiDodNum3", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodNum3 = :ksiDodNum3"),
@NamedQuery(name = "Ksiegapir.findByKsiDodNum4", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodNum4 = :ksiDodNum4"),
@NamedQuery(name = "Ksiegapir.findByKsiDodChar1", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodChar1 = :ksiDodChar1"),
@NamedQuery(name = "Ksiegapir.findByKsiDodChar2", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodChar2 = :ksiDodChar2"),
@NamedQuery(name = "Ksiegapir.findByKsiDodVchar1", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodVchar1 = :ksiDodVchar1"),
@NamedQuery(name = "Ksiegapir.findByKsiDodVchar2", query = "SELECT k FROM Ksiegapir k WHERE k.ksiDodVchar2 = :ksiDodVchar2")})
public class Ksiegapir implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "ksi_serial", nullable = false)
private Integer ksiSerial;
@Column(name = "ksi_data_zdarz")
@Temporal(TemporalType.TIMESTAMP)
private Date ksiDataZdarz;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 32)
@Column(name = "ksi_nr_dowodu", nullable = false, length = 32)
private String ksiNrDowodu;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 128)
@Column(name = "ksi_opis_zdarz", nullable = false, length = 128)
private String ksiOpisZdarz;
@Basic(optional = false)
@NotNull
@Column(name = "ksi_lp", nullable = false)
private int ksiLp;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "ksi_kwota_7", precision = 13, scale = 2)
private BigDecimal ksiKwota7;
@Column(name = "ksi_kwota_8", precision = 13, scale = 2)
private BigDecimal ksiKwota8;
@Column(name = "ksi_kwota_10", precision = 13, scale = 2)
private BigDecimal ksiKwota10;
@Column(name = "ksi_kwota_11", precision = 13, scale = 2)
private BigDecimal ksiKwota11;
@Column(name = "ksi_kwota_12", precision = 13, scale = 2)
private BigDecimal ksiKwota12;
@Column(name = "ksi_kwota_13", precision = 13, scale = 2)
private BigDecimal ksiKwota13;
@Column(name = "ksi_kwota_14", precision = 13, scale = 2)
private BigDecimal ksiKwota14;
@Column(name = "ksi_kwota_16", precision = 13, scale = 2)
private BigDecimal ksiKwota16;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 64)
@Column(name = "ksi_uwagi", nullable = false, length = 64)
private String ksiUwagi;
@Size(max = 64)
@Column(name = "ksi_kon_nazwa", length = 64)
private String ksiKonNazwa;
@Size(max = 128)
@Column(name = "ksi_kon_adres", length = 128)
private String ksiKonAdres;
@Size(max = 32)
@Column(name = "ksi_kon_nazwa_skr", length = 32)
private String ksiKonNazwaSkr;
@Column(name = "ksi_skreslony")
private Character ksiSkreslony;
@Column(name = "ksi_oryg_typ")
private Character ksiOrygTyp;
@Column(name = "ksi_oryg_serial")
private Integer ksiOrygSerial;
@Column(name = "ksi_czas")
@Temporal(TemporalType.TIMESTAMP)
private Date ksiCzas;
@Size(max = 32)
@Column(name = "ksi_usr_userid", length = 32)
private String ksiUsrUserid;
@Column(name = "ksi_czas_mod")
@Temporal(TemporalType.TIMESTAMP)
private Date ksiCzasMod;
@Size(max = 32)
@Column(name = "ksi_usr_userid_mod", length = 32)
private String ksiUsrUseridMod;
@Column(name = "ksi_dod_num_1", precision = 13, scale = 2)
private BigDecimal ksiDodNum1;
@Column(name = "ksi_dod_num_2", precision = 13, scale = 2)
private BigDecimal ksiDodNum2;
@Column(name = "ksi_dod_num_3", precision = 13, scale = 2)
private BigDecimal ksiDodNum3;
@Column(name = "ksi_dod_num_4", precision = 13, scale = 2)
private BigDecimal ksiDodNum4;
@Column(name = "ksi_dod_char_1")
private Character ksiDodChar1;
@Column(name = "ksi_dod_char_2")
private Character ksiDodChar2;
@Size(max = 64)
@Column(name = "ksi_dod_vchar_1", length = 64)
private String ksiDodVchar1;
@Size(max = 64)
@Column(name = "ksi_dod_vchar_2", length = 64)
private String ksiDodVchar2;
@JoinColumn(name = "ksi_fir_serial", referencedColumnName = "fir_serial", nullable = false)
@ManyToOne(optional = false)
private Firma ksiFirSerial;
@JoinColumn(name = "ksi_kon_serial", referencedColumnName = "kon_serial")
@ManyToOne
private Kontrahent ksiKonSerial;
@JoinColumn(name = "ksi_okr_serial", referencedColumnName = "okr_serial", nullable = false)
@ManyToOne(optional = false)
private Okres ksiOkrSerial;
@JoinColumn(name = "ksi_rok_serial", referencedColumnName = "rok_serial", nullable = false)
@ManyToOne(optional = false)
private Rok ksiRokSerial;
@OneToMany(mappedBy = "dsrKsiSerial")
private List<DaneStatR> daneStatRList;
public Ksiegapir() {
}
public Ksiegapir(Integer ksiSerial) {
this.ksiSerial = ksiSerial;
}
public Ksiegapir(Integer ksiSerial, String ksiNrDowodu, String ksiOpisZdarz, int ksiLp, String ksiUwagi) {
this.ksiSerial = ksiSerial;
this.ksiNrDowodu = ksiNrDowodu;
this.ksiOpisZdarz = ksiOpisZdarz;
this.ksiLp = ksiLp;
this.ksiUwagi = ksiUwagi;
}
public Integer getKsiSerial() {
return ksiSerial;
}
public void setKsiSerial(Integer ksiSerial) {
this.ksiSerial = ksiSerial;
}
public Date getKsiDataZdarz() {
return ksiDataZdarz;
}
public void setKsiDataZdarz(Date ksiDataZdarz) {
this.ksiDataZdarz = ksiDataZdarz;
}
public String getKsiNrDowodu() {
return ksiNrDowodu;
}
public void setKsiNrDowodu(String ksiNrDowodu) {
this.ksiNrDowodu = ksiNrDowodu;
}
public String getKsiOpisZdarz() {
return ksiOpisZdarz;
}
public void setKsiOpisZdarz(String ksiOpisZdarz) {
this.ksiOpisZdarz = ksiOpisZdarz;
}
public int getKsiLp() {
return ksiLp;
}
public void setKsiLp(int ksiLp) {
this.ksiLp = ksiLp;
}
public BigDecimal getKsiKwota7() {
return ksiKwota7;
}
public void setKsiKwota7(BigDecimal ksiKwota7) {
this.ksiKwota7 = ksiKwota7;
}
public BigDecimal getKsiKwota8() {
return ksiKwota8;
}
public void setKsiKwota8(BigDecimal ksiKwota8) {
this.ksiKwota8 = ksiKwota8;
}
public BigDecimal getKsiKwota10() {
return ksiKwota10;
}
public void setKsiKwota10(BigDecimal ksiKwota10) {
this.ksiKwota10 = ksiKwota10;
}
public BigDecimal getKsiKwota11() {
return ksiKwota11;
}
public void setKsiKwota11(BigDecimal ksiKwota11) {
this.ksiKwota11 = ksiKwota11;
}
public BigDecimal getKsiKwota12() {
return ksiKwota12;
}
public void setKsiKwota12(BigDecimal ksiKwota12) {
this.ksiKwota12 = ksiKwota12;
}
public BigDecimal getKsiKwota13() {
return ksiKwota13;
}
public void setKsiKwota13(BigDecimal ksiKwota13) {
this.ksiKwota13 = ksiKwota13;
}
public BigDecimal getKsiKwota14() {
return ksiKwota14;
}
public void setKsiKwota14(BigDecimal ksiKwota14) {
this.ksiKwota14 = ksiKwota14;
}
public BigDecimal getKsiKwota16() {
return ksiKwota16;
}
public void setKsiKwota16(BigDecimal ksiKwota16) {
this.ksiKwota16 = ksiKwota16;
}
public String getKsiUwagi() {
return ksiUwagi;
}
public void setKsiUwagi(String ksiUwagi) {
this.ksiUwagi = ksiUwagi;
}
public String getKsiKonNazwa() {
return ksiKonNazwa;
}
public void setKsiKonNazwa(String ksiKonNazwa) {
this.ksiKonNazwa = ksiKonNazwa;
}
public String getKsiKonAdres() {
return ksiKonAdres;
}
public void setKsiKonAdres(String ksiKonAdres) {
this.ksiKonAdres = ksiKonAdres;
}
public String getKsiKonNazwaSkr() {
return ksiKonNazwaSkr;
}
public void setKsiKonNazwaSkr(String ksiKonNazwaSkr) {
this.ksiKonNazwaSkr = ksiKonNazwaSkr;
}
public Character getKsiSkreslony() {
return ksiSkreslony;
}
public void setKsiSkreslony(Character ksiSkreslony) {
this.ksiSkreslony = ksiSkreslony;
}
public Character getKsiOrygTyp() {
return ksiOrygTyp;
}
public void setKsiOrygTyp(Character ksiOrygTyp) {
this.ksiOrygTyp = ksiOrygTyp;
}
public Integer getKsiOrygSerial() {
return ksiOrygSerial;
}
public void setKsiOrygSerial(Integer ksiOrygSerial) {
this.ksiOrygSerial = ksiOrygSerial;
}
public Date getKsiCzas() {
return ksiCzas;
}
public void setKsiCzas(Date ksiCzas) {
this.ksiCzas = ksiCzas;
}
public String getKsiUsrUserid() {
return ksiUsrUserid;
}
public void setKsiUsrUserid(String ksiUsrUserid) {
this.ksiUsrUserid = ksiUsrUserid;
}
public Date getKsiCzasMod() {
return ksiCzasMod;
}
public void setKsiCzasMod(Date ksiCzasMod) {
this.ksiCzasMod = ksiCzasMod;
}
public String getKsiUsrUseridMod() {
return ksiUsrUseridMod;
}
public void setKsiUsrUseridMod(String ksiUsrUseridMod) {
this.ksiUsrUseridMod = ksiUsrUseridMod;
}
public BigDecimal getKsiDodNum1() {
return ksiDodNum1;
}
public void setKsiDodNum1(BigDecimal ksiDodNum1) {
this.ksiDodNum1 = ksiDodNum1;
}
public BigDecimal getKsiDodNum2() {
return ksiDodNum2;
}
public void setKsiDodNum2(BigDecimal ksiDodNum2) {
this.ksiDodNum2 = ksiDodNum2;
}
public BigDecimal getKsiDodNum3() {
return ksiDodNum3;
}
public void setKsiDodNum3(BigDecimal ksiDodNum3) {
this.ksiDodNum3 = ksiDodNum3;
}
public BigDecimal getKsiDodNum4() {
return ksiDodNum4;
}
public void setKsiDodNum4(BigDecimal ksiDodNum4) {
this.ksiDodNum4 = ksiDodNum4;
}
public Character getKsiDodChar1() {
return ksiDodChar1;
}
public void setKsiDodChar1(Character ksiDodChar1) {
this.ksiDodChar1 = ksiDodChar1;
}
public Character getKsiDodChar2() {
return ksiDodChar2;
}
public void setKsiDodChar2(Character ksiDodChar2) {
this.ksiDodChar2 = ksiDodChar2;
}
public String getKsiDodVchar1() {
return ksiDodVchar1;
}
public void setKsiDodVchar1(String ksiDodVchar1) {
this.ksiDodVchar1 = ksiDodVchar1;
}
public String getKsiDodVchar2() {
return ksiDodVchar2;
}
public void setKsiDodVchar2(String ksiDodVchar2) {
this.ksiDodVchar2 = ksiDodVchar2;
}
public Firma getKsiFirSerial() {
return ksiFirSerial;
}
public void setKsiFirSerial(Firma ksiFirSerial) {
this.ksiFirSerial = ksiFirSerial;
}
public Kontrahent getKsiKonSerial() {
return ksiKonSerial;
}
public void setKsiKonSerial(Kontrahent ksiKonSerial) {
this.ksiKonSerial = ksiKonSerial;
}
public Okres getKsiOkrSerial() {
return ksiOkrSerial;
}
public void setKsiOkrSerial(Okres ksiOkrSerial) {
this.ksiOkrSerial = ksiOkrSerial;
}
public Rok getKsiRokSerial() {
return ksiRokSerial;
}
public void setKsiRokSerial(Rok ksiRokSerial) {
this.ksiRokSerial = ksiRokSerial;
}
@XmlTransient
public List<DaneStatR> getDaneStatRList() {
return daneStatRList;
}
public void setDaneStatRList(List<DaneStatR> daneStatRList) {
this.daneStatRList = daneStatRList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (ksiSerial != null ? ksiSerial.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Ksiegapir)) {
return false;
}
Ksiegapir other = (Ksiegapir) object;
if ((this.ksiSerial == null && other.ksiSerial != null) || (this.ksiSerial != null && !this.ksiSerial.equals(other.ksiSerial))) {
return false;
}
return true;
}
@Override
public String toString() {
return "kadryiplace.Ksiegapir[ ksiSerial=" + ksiSerial + " ]";
}
}
| 17,529 | 0.65577 | 0.637059 | 514 | 32.103111 | 32.073769 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529183 | false | false | 12 |
0235669828ed33102826cc7ec0d30b2cb1cd1a67 | 26,654,567,083,837 | 3a8c29298a30f66335995d7d57c3ecf73dffb5ce | /app/src/main/java/com/example/replacefragments/adapters/RowItem.java | 0711fa531735f27fd6cce4ddb8a9ac459a5092a5 | [
"Apache-2.0",
"MIT"
] | permissive | emnrd-ito/ReplaceFragments | https://github.com/emnrd-ito/ReplaceFragments | 095afb92be6c8aee85070195da9852837e968828 | c2a164ba116e995f67de8fe090e704fd41bd808a | refs/heads/master | 2020-06-30T00:28:33.565000 | 2016-11-29T13:53:45 | 2016-11-29T13:53:45 | 74,402,287 | 0 | 1 | null | false | 2016-11-28T21:40:26 | 2016-11-21T20:19:01 | 2016-11-21T20:19:58 | 2016-11-28T21:40:26 | 717 | 0 | 1 | 0 | Java | null | null | package com.example.replacefragments.adapters;
public class RowItem {
public String row0;
public String row1;
public String row2;
public String row3;
public String row4;
public RowItem(String row0) {
this.row0 = row0;
this.row1 = "";
this.row2 = "";
this.row3 = "";
}
public RowItem(String row0, String row1) {
this.row0 = row0;
this.row1 = row1;
this.row2 = "";
this.row3 = "";
}
public RowItem(String row0, String row1, String row2) {
this.row0 = row0;
this.row1 = row1;
this.row2 = row2;
this.row3 = "";
}
public RowItem(String row0, String row1, String row2, String row3) {
this.row0 = row0;
this.row1 = row1;
this.row2 = row2;
this.row3 = row3;
this.row4 = "";
}
// row4 is used for the Divison of a Location.
// The text of the Division is not displayed in the Location list but rather the logo is.
public RowItem(String row0, String row1, String row2, String row3, String row4) {
this.row0 = row0;
this.row1 = row1;
this.row2 = row2;
this.row3 = row3;
this.row4 = row4;
}
}
| UTF-8 | Java | 1,231 | java | RowItem.java | Java | [] | null | [] | package com.example.replacefragments.adapters;
public class RowItem {
public String row0;
public String row1;
public String row2;
public String row3;
public String row4;
public RowItem(String row0) {
this.row0 = row0;
this.row1 = "";
this.row2 = "";
this.row3 = "";
}
public RowItem(String row0, String row1) {
this.row0 = row0;
this.row1 = row1;
this.row2 = "";
this.row3 = "";
}
public RowItem(String row0, String row1, String row2) {
this.row0 = row0;
this.row1 = row1;
this.row2 = row2;
this.row3 = "";
}
public RowItem(String row0, String row1, String row2, String row3) {
this.row0 = row0;
this.row1 = row1;
this.row2 = row2;
this.row3 = row3;
this.row4 = "";
}
// row4 is used for the Divison of a Location.
// The text of the Division is not displayed in the Location list but rather the logo is.
public RowItem(String row0, String row1, String row2, String row3, String row4) {
this.row0 = row0;
this.row1 = row1;
this.row2 = row2;
this.row3 = row3;
this.row4 = row4;
}
}
| 1,231 | 0.562957 | 0.515841 | 48 | 24.645834 | 20.174747 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.791667 | false | false | 12 |
a665245a4d18d0cb4eb6b653c81998a516c9a3d9 | 19,928,648,271,332 | 65627367a8c0a4587e23179d514674ec3d70e191 | /Currency/app/src/main/java/com/example/sophia/currency/MainActivity.java | c0d1ca75e9bef5d4e1b7d27c14eb3df221df6ebd | [] | no_license | sklocheva/Android | https://github.com/sklocheva/Android | 8bdeb4a3e0133d07e5b36e4cf99c02c5994bf94a | 52b11a6087db9ba13dc9ed9784e64d8ae5d60ff5 | refs/heads/master | 2021-01-19T07:22:21.713000 | 2017-04-26T16:45:09 | 2017-04-26T16:45:09 | 87,539,573 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.sophia.currency;
import android.app.AlertDialog;
import android.app.ApplicationErrorReport;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class MainActivity extends AppCompatActivity {
EditText textCurrencyInput;
EditText textInputCurrencyText;
EditText textAmountToConvert;
TextView textViewResult;
Button buttonCalculate;
Button buttonReset;
SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pref = getPreferences(Context.MODE_PRIVATE);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
textCurrencyInput = (EditText) findViewById(R.id.textCurrencyInput);
textInputCurrencyText = (EditText) findViewById(R.id.textnputCurrencyText);
textAmountToConvert = (EditText) findViewById(R.id.textAmountToConvert);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonCalculate = (Button) findViewById(R.id.buttonCalculate);
buttonReset = (Button) findViewById(R.id.buttonReset);
buttonCalculate.setOnClickListener(onButtonClick);
buttonReset.setOnClickListener(onButtonClick);
textInputCurrencyText.setText(pref.getString("CYRRENCYSYMBOL", ""));
textCurrencyInput.setText(pref.getString("CURRENCY", ""));
textAmountToConvert.setText(pref.getString("VALUELEV", ""));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void resetCalculator(){
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
textCurrencyInput.setText("");
editor.putString("CURRENCY", "");
textInputCurrencyText.setText("");
editor.putString("CYRRENCYSYMBOL", "");
textAmountToConvert.setText("");
editor.putString("VALUELEV", "");
textViewResult.setText("");
editor.commit();
}
View.OnClickListener onButtonClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.buttonReset: {
resetCalculator();
}break;
case R.id.buttonCalculate: {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
String currencySymbol = textInputCurrencyText.getText().toString();
editor.putString("CYRRENCYSYMBOL", currencySymbol);
Float currency = Float.parseFloat(textCurrencyInput.getText().toString());
editor.putString("CURRENCY", String.valueOf(currency));
Float valueLev = Float.parseFloat(textAmountToConvert.getText().toString());
editor.putString("VALUELEV", String.valueOf(valueLev));
if((!Float.isNaN(currency) && !Float.isNaN(valueLev))&&!currencySymbol.isEmpty()) {
NumberFormat nformat = new DecimalFormat("#.00");
String result = nformat.format(valueLev * currency);
textViewResult.setText(result + " " + currencySymbol);
}
editor.commit();
}break;
}
}
};
}
| UTF-8 | Java | 5,000 | java | MainActivity.java | Java | [] | null | [] | package com.example.sophia.currency;
import android.app.AlertDialog;
import android.app.ApplicationErrorReport;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class MainActivity extends AppCompatActivity {
EditText textCurrencyInput;
EditText textInputCurrencyText;
EditText textAmountToConvert;
TextView textViewResult;
Button buttonCalculate;
Button buttonReset;
SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pref = getPreferences(Context.MODE_PRIVATE);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
textCurrencyInput = (EditText) findViewById(R.id.textCurrencyInput);
textInputCurrencyText = (EditText) findViewById(R.id.textnputCurrencyText);
textAmountToConvert = (EditText) findViewById(R.id.textAmountToConvert);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonCalculate = (Button) findViewById(R.id.buttonCalculate);
buttonReset = (Button) findViewById(R.id.buttonReset);
buttonCalculate.setOnClickListener(onButtonClick);
buttonReset.setOnClickListener(onButtonClick);
textInputCurrencyText.setText(pref.getString("CYRRENCYSYMBOL", ""));
textCurrencyInput.setText(pref.getString("CURRENCY", ""));
textAmountToConvert.setText(pref.getString("VALUELEV", ""));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void resetCalculator(){
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
textCurrencyInput.setText("");
editor.putString("CURRENCY", "");
textInputCurrencyText.setText("");
editor.putString("CYRRENCYSYMBOL", "");
textAmountToConvert.setText("");
editor.putString("VALUELEV", "");
textViewResult.setText("");
editor.commit();
}
View.OnClickListener onButtonClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.buttonReset: {
resetCalculator();
}break;
case R.id.buttonCalculate: {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
String currencySymbol = textInputCurrencyText.getText().toString();
editor.putString("CYRRENCYSYMBOL", currencySymbol);
Float currency = Float.parseFloat(textCurrencyInput.getText().toString());
editor.putString("CURRENCY", String.valueOf(currency));
Float valueLev = Float.parseFloat(textAmountToConvert.getText().toString());
editor.putString("VALUELEV", String.valueOf(valueLev));
if((!Float.isNaN(currency) && !Float.isNaN(valueLev))&&!currencySymbol.isEmpty()) {
NumberFormat nformat = new DecimalFormat("#.00");
String result = nformat.format(valueLev * currency);
textViewResult.setText(result + " " + currencySymbol);
}
editor.commit();
}break;
}
}
};
}
| 5,000 | 0.6466 | 0.6458 | 146 | 33.246574 | 28.343916 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.609589 | false | false | 12 |
8db8e06ab71c79b67d33c87b31ede38aa06d04ab | 34,531,537,073,650 | 4a4d6ff3709cfe764f89a09ddebe384d595a7283 | /ArrayDemo/src/DemoArrayOperations.java | 2beb20447b7685a164f4bfb88d103a3d770e8f71 | [] | no_license | shivamsingh20449/CitiTraining | https://github.com/shivamsingh20449/CitiTraining | e335fdcb3e59bdd68560fb2b8213d2e451f6375f | bf8fbbe8d67824ccc72814524aa1ec3c551660b6 | refs/heads/master | 2020-03-27T04:33:54.065000 | 2018-08-24T05:29:54 | 2018-08-24T05:29:54 | 145,950,453 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Arrays;
public class DemoArrayOperations {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] numbers = {123, 34,55, 65, 43,55, 6,89,90};
///////////////////////////////////////////////////////////////////////////
//Arrays.fill(numbers, 0);
/*for(int num: numbers)
{
System.out.println(num);
}*/
//////////////////////////////////////////////////////////////////////////
/*
Arrays.fill(numbers, 1, 3, 100);
for(int num: numbers)
{
System.out.println(num);
}
*/
int[] arr_copy=Arrays.copyOf(numbers, 5);
for(int num: arr_copy)
{
System.out.println(num);
}
//double[] arr_copy2= Arrays.copyOfRange(numbares, 3, 5);
//------------------------------COMPARISION----------------------------------------------//
String [] names= {"ABC","XYZ","LMN","ASDF"};
String [] names1= {"ABC","XYZ","LMN","ASDF"};
boolean data = Arrays.equals(names, names1);
if(data)
{
System.out.println("Equal");
}
System.out.println("--------------------------Sorting---------------------");
Arrays.sort(numbers);
for(int num: numbers)
{
System.out.println(num);
}
System.out.println("--------------------------Binary Search---------------------");
int index=Arrays.binarySearch(numbers, 1243);
System.out.println(index);
}
}
| UTF-8 | Java | 1,379 | java | DemoArrayOperations.java | Java | [] | null | [] | import java.util.Arrays;
public class DemoArrayOperations {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] numbers = {123, 34,55, 65, 43,55, 6,89,90};
///////////////////////////////////////////////////////////////////////////
//Arrays.fill(numbers, 0);
/*for(int num: numbers)
{
System.out.println(num);
}*/
//////////////////////////////////////////////////////////////////////////
/*
Arrays.fill(numbers, 1, 3, 100);
for(int num: numbers)
{
System.out.println(num);
}
*/
int[] arr_copy=Arrays.copyOf(numbers, 5);
for(int num: arr_copy)
{
System.out.println(num);
}
//double[] arr_copy2= Arrays.copyOfRange(numbares, 3, 5);
//------------------------------COMPARISION----------------------------------------------//
String [] names= {"ABC","XYZ","LMN","ASDF"};
String [] names1= {"ABC","XYZ","LMN","ASDF"};
boolean data = Arrays.equals(names, names1);
if(data)
{
System.out.println("Equal");
}
System.out.println("--------------------------Sorting---------------------");
Arrays.sort(numbers);
for(int num: numbers)
{
System.out.println(num);
}
System.out.println("--------------------------Binary Search---------------------");
int index=Arrays.binarySearch(numbers, 1243);
System.out.println(index);
}
}
| 1,379 | 0.459028 | 0.434373 | 63 | 20.888889 | 24.337645 | 93 | false | false | 0 | 0 | 0 | 0 | 76 | 0.1095 | 2.523809 | false | false | 12 |
a1cb5271972d5f62cb5414560acd669385aa63c1 | 34,531,537,074,018 | 9effd97fee10c6597e0eb80dfe4370fd9657f83c | /src/main/java/com/z/springboot_thymeleaf/service/UserService.java | ae0827a1279e81cbf2b59e50b1a19c7c69afaf04 | [] | no_license | zhang9960/springboot_th | https://github.com/zhang9960/springboot_th | f531c47762e0004af5b0a5cd599e2706f5a15788 | 062753e8ee6b3b8c4976726b71b5ede16151f6f9 | refs/heads/master | 2023-03-21T22:17:28.690000 | 2021-03-19T02:42:47 | 2021-03-19T02:42:47 | 342,428,503 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.z.springboot_thymeleaf.service;
import com.z.springboot_thymeleaf.entity.User;
/**
* @author zhang
* @version 1.0
* @date 2021/2/1 9:36
*/
public interface UserService {
User login(String username, String password);
}
| UTF-8 | Java | 240 | java | UserService.java | Java | [
{
"context": ".springboot_thymeleaf.entity.User;\n\n/**\n * @author zhang\n * @version 1.0\n * @date 2021/2/1 9:36\n */\npublic",
"end": 113,
"score": 0.5696253776550293,
"start": 108,
"tag": "USERNAME",
"value": "zhang"
}
] | null | [] | package com.z.springboot_thymeleaf.service;
import com.z.springboot_thymeleaf.entity.User;
/**
* @author zhang
* @version 1.0
* @date 2021/2/1 9:36
*/
public interface UserService {
User login(String username, String password);
}
| 240 | 0.716667 | 0.670833 | 12 | 19 | 18.069311 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 12 |
359bee12f20ec914030db57b4b2ac208eba7ed9d | 30,648,886,692,359 | 4024ef041798a3d4a5a475c0c0cd85ad3fe4a75a | /app/controllers/Common.java | a82b87b8fb04383fe23c65e1b686cc99cb59c620 | [] | no_license | aaberg/Tic-tec-toe-demo | https://github.com/aaberg/Tic-tec-toe-demo | edb703a2e3078678b487153eacf0d3b0bf2ab4c1 | b69f9f73856209e77cf324bd087104847fa8aa6c | refs/heads/master | 2021-01-19T08:31:24.542000 | 2011-10-21T10:29:26 | 2011-10-21T10:29:26 | 2,618,715 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controllers;
import play.i18n.Lang;
import play.mvc.Controller;
/**
* Created by IntelliJ IDEA.
* User: lars
* Date: 10/20/11
* Time: 6:59 PM
* To change this template use File | Settings | File Templates.
*/
public class Common extends Controller {
public static void changeLang(String lang, String redirectUrl){
Lang.change(lang);
if (redirectUrl == null){
redirectUrl = "/";
}
redirect(redirectUrl);
}
}
| UTF-8 | Java | 478 | java | Common.java | Java | [
{
"context": "roller;\n\n/**\n * Created by IntelliJ IDEA.\n * User: lars\n * Date: 10/20/11\n * Time: 6:59 PM\n * To change t",
"end": 120,
"score": 0.9845306873321533,
"start": 116,
"tag": "USERNAME",
"value": "lars"
}
] | null | [] | package controllers;
import play.i18n.Lang;
import play.mvc.Controller;
/**
* Created by IntelliJ IDEA.
* User: lars
* Date: 10/20/11
* Time: 6:59 PM
* To change this template use File | Settings | File Templates.
*/
public class Common extends Controller {
public static void changeLang(String lang, String redirectUrl){
Lang.change(lang);
if (redirectUrl == null){
redirectUrl = "/";
}
redirect(redirectUrl);
}
}
| 478 | 0.633891 | 0.610879 | 24 | 18.916666 | 18.705873 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 12 |
3765c52a2fc45dd867aa14afb51ec1a7b0bd5386 | 30,648,886,692,393 | 8c08435f16b62fbd3f7da9757571b1410c2a9647 | /src/main/java/com/hs/YuanXing/Circle.java | 01907da6db2bf97041b128570074d6e37e6443c8 | [] | no_license | h15353662578/Factory | https://github.com/h15353662578/Factory | 3e9ef8913c09350c3d5624125ad2ffd4c29a5c68 | c1792db0c0dd17eed37de99891537801dfaf213a | refs/heads/master | 2023-05-02T11:48:28.370000 | 2021-05-18T08:51:57 | 2021-05-18T08:51:57 | 365,411,928 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hs.YuanXing;
import java.util.Objects;
/**
* @author Huasheng
* @Date 2021/05/10/14:53
* 简单形状 圆形
* @Description
*/
public class Circle extends Shapes{
public int radius;
public Circle(){}
public Circle(Circle target){
super(target);
if (target != null){
this.radius = target.radius;
}
}
@Override
public Shapes clone(){
return new Circle(this);
}
@Override
public boolean equals(Object object2){
if (!(object2 instanceof Circle) || !super.equals(object2))
return false;
Circle shapes2 = (Circle) object2;
return shapes2.radius == radius;
}
}
| UTF-8 | Java | 697 | java | Circle.java | Java | [
{
"context": "anXing;\n\nimport java.util.Objects;\n\n/**\n * @author Huasheng\n * @Date 2021/05/10/14:53\n * 简单形状 圆形\n * @Descript",
"end": 76,
"score": 0.9997913241386414,
"start": 68,
"tag": "NAME",
"value": "Huasheng"
}
] | null | [] | package com.hs.YuanXing;
import java.util.Objects;
/**
* @author Huasheng
* @Date 2021/05/10/14:53
* 简单形状 圆形
* @Description
*/
public class Circle extends Shapes{
public int radius;
public Circle(){}
public Circle(Circle target){
super(target);
if (target != null){
this.radius = target.radius;
}
}
@Override
public Shapes clone(){
return new Circle(this);
}
@Override
public boolean equals(Object object2){
if (!(object2 instanceof Circle) || !super.equals(object2))
return false;
Circle shapes2 = (Circle) object2;
return shapes2.radius == radius;
}
}
| 697 | 0.588321 | 0.562044 | 35 | 18.571428 | 16.037966 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.314286 | false | false | 12 |
c44497a1b92acab97cf0123254cc1c3af6e32634 | 37,022,618,116,629 | 3603bedbcdf740a500c7f80e1ce8e893b79ad14a | /src/main/java/com/edu/security/rest/AuthController.java | c9d92b3ce34a2dbd5ab3a8247e5983942cbe0235 | [] | no_license | kizazu/mobile-shop | https://github.com/kizazu/mobile-shop | 4d204f47a79d9724e49b698ecf50632c3f379182 | fb670c044c9b04ee4a4d808a5c7968a3b1a7515b | refs/heads/master | 2023-01-21T16:24:32.447000 | 2020-11-29T18:28:32 | 2020-11-29T18:28:32 | 315,668,111 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.edu.security.rest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import com.edu.security.dto.JwtResponse;
import com.edu.security.dto.LoginRequest;
import com.edu.security.dto.SignupRequest;
import com.edu.security.entities.ERole;
import com.edu.security.entities.Role;
import com.edu.security.entities.User;
import com.edu.security.jwt.JwtUtils;
import com.edu.security.repositories.RoleRepository;
import com.edu.security.repositories.UserRepository;
import com.edu.security.services.impl.UserDetailsImpl;
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping(value = "/api/auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/signin")
public String authenticateUser(@ModelAttribute LoginRequest loginRequest, Model model) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
/*
* List<String> roles = userDetails.getAuthorities().stream().map(item ->
* item.getAuthority()) .collect(Collectors.toList());
*
* return ResponseEntity.ok( new JwtResponse(jwt, userDetails.getId(),
* userDetails.getUsername(), userDetails.getEmail(), roles));
*
*/
model.addAttribute("name", userDetails.getUsername());
return "homepage";
}
@PostMapping("/signup")
public String registerUser(@ModelAttribute SignupRequest signUpRequest, Model model) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
model.addAttribute("message", "Username is used");
return "index";
}
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
model.addAttribute("message", "Email is used");
return "index";
}
if (!signUpRequest.getPassword().equals(signUpRequest.getRepassword())) {
return "index";
}
String strRoles = signUpRequest.getRole();
if(strRoles.equals("")) {
model.addAttribute("message", "Please check role");
return "index";
}
// Create new user's account
User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()), 1);
Set<Role> roles = new HashSet<Role>();
switch (strRoles) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
}
user.setRoles(roles);
userRepository.save(user);
return "redirect:/login";
}
} | UTF-8 | Java | 4,274 | java | AuthController.java | Java | [] | null | [] | package com.edu.security.rest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import com.edu.security.dto.JwtResponse;
import com.edu.security.dto.LoginRequest;
import com.edu.security.dto.SignupRequest;
import com.edu.security.entities.ERole;
import com.edu.security.entities.Role;
import com.edu.security.entities.User;
import com.edu.security.jwt.JwtUtils;
import com.edu.security.repositories.RoleRepository;
import com.edu.security.repositories.UserRepository;
import com.edu.security.services.impl.UserDetailsImpl;
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping(value = "/api/auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/signin")
public String authenticateUser(@ModelAttribute LoginRequest loginRequest, Model model) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
/*
* List<String> roles = userDetails.getAuthorities().stream().map(item ->
* item.getAuthority()) .collect(Collectors.toList());
*
* return ResponseEntity.ok( new JwtResponse(jwt, userDetails.getId(),
* userDetails.getUsername(), userDetails.getEmail(), roles));
*
*/
model.addAttribute("name", userDetails.getUsername());
return "homepage";
}
@PostMapping("/signup")
public String registerUser(@ModelAttribute SignupRequest signUpRequest, Model model) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
model.addAttribute("message", "Username is used");
return "index";
}
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
model.addAttribute("message", "Email is used");
return "index";
}
if (!signUpRequest.getPassword().equals(signUpRequest.getRepassword())) {
return "index";
}
String strRoles = signUpRequest.getRole();
if(strRoles.equals("")) {
model.addAttribute("message", "Please check role");
return "index";
}
// Create new user's account
User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()), 1);
Set<Role> roles = new HashSet<Role>();
switch (strRoles) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
}
user.setRoles(roles);
userRepository.save(user);
return "redirect:/login";
}
} | 4,274 | 0.77211 | 0.770941 | 127 | 32.661419 | 26.968988 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.889764 | false | false | 12 |
45b6d84a4e04a3e58e728780b8599c318d307aea | 35,442,070,162,686 | f9c3675ad5fc568106bb94091dbbd57f5a5eb8b2 | /android/src/main/java/com/genexus/db/driver/DataSource.java | d6787c153e69ae45e93b696e38044cff5af77d2d | [
"Apache-2.0"
] | permissive | genexuslabs/JavaClasses | https://github.com/genexuslabs/JavaClasses | 58c87090f5e0f69fa226823f20abd2e5918fa231 | 07164c96b4069cb23d57998089dd17b51a9fad0a | refs/heads/master | 2023-08-16T19:51:57.001000 | 2023-08-15T19:12:17 | 2023-08-15T19:12:17 | 171,533,715 | 30 | 20 | Apache-2.0 | false | 2023-09-14T18:50:28 | 2019-02-19T19:12:51 | 2023-08-20T20:59:32 | 2023-09-14T18:50:27 | 8,524 | 21 | 14 | 17 | Java | false | false | /**
* Representa un DataSource GeneXus. Tiene asociado un connection pool.
*
*/
package com.genexus.db.driver;
import java.sql.SQLException;
import com.genexus.common.classes.AbstractDataSource;
public class DataSource extends AbstractDataSource
{
public static String INFORMIX_DB_ANSI = "ANSI";
public static String INFORMIX_DB_LOGGED = "Logged";
public static String INFORMIX_DB_NOTLOGGED = "NotLogged";
private GXDBDebug debugLog;
public String defaultUser;
public String defaultPassword;
public String jdbcDriver;
public String jdbcUrl;
public String jdbcAS400Lib;
public String jdbcDBName;
public boolean jdbcLogEnabled;
public int jdbcIsolationLevel;
public boolean jdbcIntegrity;
public String informixDB;
public int maxCursors;
public String schema;
public boolean initializeNew;
public GXDBMSsqlite dbms;
public int rwPoolSize;
public boolean rwPoolSizeUnlimited;
public boolean forceAutocommit;
public int roPoolSize;
public boolean roPoolSizeUnlimited;
public int roPoolUsers;
public boolean createPoolStartup;
public boolean connectStartup;
public boolean roPoolEnabled;
private boolean rwPoolEnabled;
private boolean roPoolRecycle;
private int roPoolRecycleMins;
private boolean rwPoolRecycle;
private int rwPoolRecycleMins;
private int rwPoolRecycleType;
public int waitRecord;
public int lockRetryCount;
public boolean loginInServer;
private JDBCLogConfig jdbcLogCfg;
private boolean dataSourceLog = false;
private String as400Package = "";
private String as400DateType = "";
public boolean useJdbcDataSource;
private boolean useMultiJdbcDataSource;
public String MultiJdbcDataSourceProc;
public String jdbcDataSource;
private String namespace;
public DataSource(
String name,
String jdbcDriver,
String jdbcUrl,
String jdbcUser,
String jdbcPassword,
JDBCLogConfig jdbcLogCfg,
boolean useJdbcDataSource,
boolean useMultiJdbcDataSource,
String MultiJdbcDataSourceProc,
String jdbcDataSource,
int maxCursors,
int jdbcIsolationLevel,
boolean jdbcIntegrity,
String dbmsName,
String schema,
boolean initializeNew,
String jdbcAS400Lib,
String jdbcDBName,
int waitRecord,
int lockRetryCount,
boolean loginInServer,
int rwPoolSize,
boolean rwPoolSizeUnlimited,
boolean roPoolEnabled,
int roPoolSize,
boolean roPoolSizeUnlimited,
int roPoolUsers,
boolean createPoolStartup,
boolean forceAutocommit,
boolean connectStartup,
boolean rwPoolEnabled,
boolean roPoolRecycle,
int roPoolRecycleMins,
boolean rwPoolRecycle,
int rwPoolRecycleMins,
int rwPoolRecycleType)
{
this.name = name;
this.jdbcDriver = jdbcDriver;
this.jdbcUrl = jdbcUrl;
this.defaultUser = jdbcUser;
this.defaultPassword = jdbcPassword;
this.jdbcLogCfg = jdbcLogCfg;
this.useJdbcDataSource = useJdbcDataSource;
this.useMultiJdbcDataSource = useMultiJdbcDataSource;
this.MultiJdbcDataSourceProc = MultiJdbcDataSourceProc;
this.jdbcDataSource = jdbcDataSource;
this.jdbcIsolationLevel = jdbcIsolationLevel;
this.jdbcIntegrity = jdbcIntegrity;
this.maxCursors = maxCursors;
this.schema = schema;
this.initializeNew = initializeNew;
this.jdbcAS400Lib = jdbcAS400Lib;
this.jdbcDBName = jdbcDBName;
this.rwPoolSize = rwPoolSize;
this.rwPoolEnabled = rwPoolSize == 0?false:rwPoolEnabled;
this.rwPoolSizeUnlimited = this.rwPoolEnabled?rwPoolSizeUnlimited:true;
this.roPoolEnabled = roPoolSize == 0?false:roPoolEnabled;
this.roPoolSize = roPoolSize;
this.roPoolSizeUnlimited = roPoolEnabled?roPoolSizeUnlimited:true;
this.roPoolUsers = roPoolUsers;
this.createPoolStartup = createPoolStartup ;
this.forceAutocommit = forceAutocommit;
this.connectStartup = connectStartup;
this.roPoolRecycle = roPoolRecycle;
this.roPoolRecycleMins = roPoolRecycleMins;
this.rwPoolRecycle = rwPoolRecycle;
this.rwPoolRecycleMins = rwPoolRecycleMins;
this.rwPoolRecycleType = rwPoolRecycleType;
this.waitRecord = waitRecord;
this.loginInServer = loginInServer;
setDBMS(dbmsName);
this.lockRetryCount = lockRetryCount;
dbms.setDatabaseName(this.jdbcDBName);
if (forceAutocommit) dbms.setInReorg();
if (maxCursors <= 0)
{
throw new InternalError("The preference Maximum open cursors per connection has an invalid value (0)");
}
}
public void initialize()
{
}
public void cleanup() throws SQLException
{
if (getLog() != null)
{
if (jdbcLogCfg.getLevel() == JDBCLogConfig.LEVEL_CONNECTION)
getLog().close(JDBCLogConfig.LEVEL_CONNECTION);
else
getLog().close(JDBCLogConfig.LEVEL_DATASOURCE);
}
}
void setConnectionLog(GXConnection con)
{
if (jdbcLogCfg.getLevel() == JDBCLogConfig.LEVEL_CONNECTION)
{
jdbcLogCfg.setConnectionName(Integer.toString(con.hashCode()));
con.setLog(new GXDBDebug(jdbcLogCfg));
}
else
{
con.setLog(getLog());
}
}
public int getLockRetryCount(){
return dbms.getLockRetryCount(lockRetryCount, waitRecord);
}
public GXDBDebug getLog()
{
return debugLog;
}
public void setLog(GXDBDebug debugLog)
{
this.debugLog = debugLog;
}
private void setDBMS(String dbmsName)
{
dbms = new GXDBMSsqlite();
}
public void disconnect(int handle) throws SQLException
{
}
public void disconnectOnException(int handle) throws SQLException
{
}
public String getName()
{
return name;
}
public String getNamespace()
{
return namespace;
}
public void setNamespace(String namespace)
{
this.namespace = namespace;
}
public String[] concatOp()
{
return new String[]{"", " || ", ""};
}
}
| UTF-8 | Java | 6,113 | java | DataSource.java | Java | [
{
"context": "User\t = jdbcUser;\n\t\tthis.defaultPassword = jdbcPassword;\n\t\tthis.jdbcLogCfg\t\t\t = jdbcLogCfg;\n\n\t\tthis.useJd",
"end": 3149,
"score": 0.9947587847709656,
"start": 3137,
"tag": "PASSWORD",
"value": "jdbcPassword"
}
] | null | [] | /**
* Representa un DataSource GeneXus. Tiene asociado un connection pool.
*
*/
package com.genexus.db.driver;
import java.sql.SQLException;
import com.genexus.common.classes.AbstractDataSource;
public class DataSource extends AbstractDataSource
{
public static String INFORMIX_DB_ANSI = "ANSI";
public static String INFORMIX_DB_LOGGED = "Logged";
public static String INFORMIX_DB_NOTLOGGED = "NotLogged";
private GXDBDebug debugLog;
public String defaultUser;
public String defaultPassword;
public String jdbcDriver;
public String jdbcUrl;
public String jdbcAS400Lib;
public String jdbcDBName;
public boolean jdbcLogEnabled;
public int jdbcIsolationLevel;
public boolean jdbcIntegrity;
public String informixDB;
public int maxCursors;
public String schema;
public boolean initializeNew;
public GXDBMSsqlite dbms;
public int rwPoolSize;
public boolean rwPoolSizeUnlimited;
public boolean forceAutocommit;
public int roPoolSize;
public boolean roPoolSizeUnlimited;
public int roPoolUsers;
public boolean createPoolStartup;
public boolean connectStartup;
public boolean roPoolEnabled;
private boolean rwPoolEnabled;
private boolean roPoolRecycle;
private int roPoolRecycleMins;
private boolean rwPoolRecycle;
private int rwPoolRecycleMins;
private int rwPoolRecycleType;
public int waitRecord;
public int lockRetryCount;
public boolean loginInServer;
private JDBCLogConfig jdbcLogCfg;
private boolean dataSourceLog = false;
private String as400Package = "";
private String as400DateType = "";
public boolean useJdbcDataSource;
private boolean useMultiJdbcDataSource;
public String MultiJdbcDataSourceProc;
public String jdbcDataSource;
private String namespace;
public DataSource(
String name,
String jdbcDriver,
String jdbcUrl,
String jdbcUser,
String jdbcPassword,
JDBCLogConfig jdbcLogCfg,
boolean useJdbcDataSource,
boolean useMultiJdbcDataSource,
String MultiJdbcDataSourceProc,
String jdbcDataSource,
int maxCursors,
int jdbcIsolationLevel,
boolean jdbcIntegrity,
String dbmsName,
String schema,
boolean initializeNew,
String jdbcAS400Lib,
String jdbcDBName,
int waitRecord,
int lockRetryCount,
boolean loginInServer,
int rwPoolSize,
boolean rwPoolSizeUnlimited,
boolean roPoolEnabled,
int roPoolSize,
boolean roPoolSizeUnlimited,
int roPoolUsers,
boolean createPoolStartup,
boolean forceAutocommit,
boolean connectStartup,
boolean rwPoolEnabled,
boolean roPoolRecycle,
int roPoolRecycleMins,
boolean rwPoolRecycle,
int rwPoolRecycleMins,
int rwPoolRecycleType)
{
this.name = name;
this.jdbcDriver = jdbcDriver;
this.jdbcUrl = jdbcUrl;
this.defaultUser = jdbcUser;
this.defaultPassword = <PASSWORD>;
this.jdbcLogCfg = jdbcLogCfg;
this.useJdbcDataSource = useJdbcDataSource;
this.useMultiJdbcDataSource = useMultiJdbcDataSource;
this.MultiJdbcDataSourceProc = MultiJdbcDataSourceProc;
this.jdbcDataSource = jdbcDataSource;
this.jdbcIsolationLevel = jdbcIsolationLevel;
this.jdbcIntegrity = jdbcIntegrity;
this.maxCursors = maxCursors;
this.schema = schema;
this.initializeNew = initializeNew;
this.jdbcAS400Lib = jdbcAS400Lib;
this.jdbcDBName = jdbcDBName;
this.rwPoolSize = rwPoolSize;
this.rwPoolEnabled = rwPoolSize == 0?false:rwPoolEnabled;
this.rwPoolSizeUnlimited = this.rwPoolEnabled?rwPoolSizeUnlimited:true;
this.roPoolEnabled = roPoolSize == 0?false:roPoolEnabled;
this.roPoolSize = roPoolSize;
this.roPoolSizeUnlimited = roPoolEnabled?roPoolSizeUnlimited:true;
this.roPoolUsers = roPoolUsers;
this.createPoolStartup = createPoolStartup ;
this.forceAutocommit = forceAutocommit;
this.connectStartup = connectStartup;
this.roPoolRecycle = roPoolRecycle;
this.roPoolRecycleMins = roPoolRecycleMins;
this.rwPoolRecycle = rwPoolRecycle;
this.rwPoolRecycleMins = rwPoolRecycleMins;
this.rwPoolRecycleType = rwPoolRecycleType;
this.waitRecord = waitRecord;
this.loginInServer = loginInServer;
setDBMS(dbmsName);
this.lockRetryCount = lockRetryCount;
dbms.setDatabaseName(this.jdbcDBName);
if (forceAutocommit) dbms.setInReorg();
if (maxCursors <= 0)
{
throw new InternalError("The preference Maximum open cursors per connection has an invalid value (0)");
}
}
public void initialize()
{
}
public void cleanup() throws SQLException
{
if (getLog() != null)
{
if (jdbcLogCfg.getLevel() == JDBCLogConfig.LEVEL_CONNECTION)
getLog().close(JDBCLogConfig.LEVEL_CONNECTION);
else
getLog().close(JDBCLogConfig.LEVEL_DATASOURCE);
}
}
void setConnectionLog(GXConnection con)
{
if (jdbcLogCfg.getLevel() == JDBCLogConfig.LEVEL_CONNECTION)
{
jdbcLogCfg.setConnectionName(Integer.toString(con.hashCode()));
con.setLog(new GXDBDebug(jdbcLogCfg));
}
else
{
con.setLog(getLog());
}
}
public int getLockRetryCount(){
return dbms.getLockRetryCount(lockRetryCount, waitRecord);
}
public GXDBDebug getLog()
{
return debugLog;
}
public void setLog(GXDBDebug debugLog)
{
this.debugLog = debugLog;
}
private void setDBMS(String dbmsName)
{
dbms = new GXDBMSsqlite();
}
public void disconnect(int handle) throws SQLException
{
}
public void disconnectOnException(int handle) throws SQLException
{
}
public String getName()
{
return name;
}
public String getNamespace()
{
return namespace;
}
public void setNamespace(String namespace)
{
this.namespace = namespace;
}
public String[] concatOp()
{
return new String[]{"", " || ", ""};
}
}
| 6,111 | 0.699493 | 0.695894 | 235 | 25.008511 | 20.764124 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.668085 | false | false | 12 |
951b6f420a8a10cf6a961fe0e05bbcb6e4f58836 | 37,589,553,796,622 | df418e1f6cf47b27f24493bd3e30c2b953dc0dd8 | /app/src/main/java/fr/rogerleoen/edeip_extranet/objet/CarnetLiaison.java | 3b557870606b6ac30e87fe205321cc73447333bb | [] | no_license | roger-jb/Edeip-Extranet | https://github.com/roger-jb/Edeip-Extranet | 51677c49ba0b9c80cf2e9c43186f07b92177b17d | a42554a960e9d35735529630ccde773b5f9870e1 | refs/heads/master | 2021-01-20T20:05:14.744000 | 2016-06-14T13:14:08 | 2016-06-14T13:14:08 | 60,001,555 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.rogerleoen.edeip_extranet.objet;
import com.google.gson.annotations.SerializedName;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import fr.rogerleoen.edeip_extranet.EdeipExtranet;
/**
* Application Edeip-Extranet
* Created by Jean-Baptiste on 30/05/2016.
*/
public class CarnetLiaison {
private Integer idCarnetLiaison;
@SerializedName("contenuCarnetLiaison")
private String contenuCarnetLiaison;
private Integer idReponse = null;
private Integer idRedacteur;
@SerializedName("dateRedaction")
private String dateRedaction;
private Integer idEleve;
public Integer getIdCarnetLiaison() {
return idCarnetLiaison;
}
public void setIdCarnetLiaison(Integer idCarnetLiaison) {
this.idCarnetLiaison = idCarnetLiaison;
}
public String getContenuCarnetLiaison() {
return contenuCarnetLiaison;
}
public void setContenuCarnetLiaison(String contenuCarnetLiaison) {
this.contenuCarnetLiaison = contenuCarnetLiaison;
}
public Integer getIdReponse() {
return idReponse;
}
public void setIdReponse(Integer idReponse) {
this.idReponse = idReponse;
}
public Integer getIdRedacteur() {
return idRedacteur;
}
public void setIdRedacteur(Integer idRedacteur) {
this.idRedacteur = idRedacteur;
}
public String getDateRedaction() {
return dateRedaction;
}
public void setDateRedaction(String dateRedaction) {
this.dateRedaction = dateRedaction;
}
public Integer getIdEleve() {
return idEleve;
}
public void setIdEleve(Integer idEleve) {
this.idEleve = idEleve;
}
public String afficheDateRedaction() {
// String dtStart = "2010-10-15T09:27:37Z";
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
// "2016-03-02 16:13:42"
String dtStart = dateRedaction;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
try {
Date date = format.parse(dtStart);
System.out.println(date);
format = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
dtStart = format.format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dtStart;
}
public String afficheContenuComplet(Boolean originel) {
String retour = "";
if (originel) {
retour += "Concernant : \n" + EdeipExtranet.storedData.getUtilisateurById(this.getIdEleve()).getNomPrenom() + "\n\n";
}
else {
retour += "\tréponse à : \n";
retour += EdeipExtranet.storedData.getUtilisateurById(this.getIdRedacteur()).getNomPrenom()+"\n\n";
}
retour += this.getContenuCarnetLiaison() + "\n\n";
if (this.getIdReponse() != null){
retour += EdeipExtranet.storedData.getCarnetLiaisonById(this.getIdReponse()).afficheContenuComplet(false);
}
return retour;
}
}
| UTF-8 | Java | 3,136 | java | CarnetLiaison.java | Java | [
{
"context": ";\n\n/**\n * Application Edeip-Extranet\n * Created by Jean-Baptiste on 30/05/2016.\n */\npublic class CarnetLiaison {\n ",
"end": 302,
"score": 0.9996819496154785,
"start": 289,
"tag": "NAME",
"value": "Jean-Baptiste"
}
] | null | [] | package fr.rogerleoen.edeip_extranet.objet;
import com.google.gson.annotations.SerializedName;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import fr.rogerleoen.edeip_extranet.EdeipExtranet;
/**
* Application Edeip-Extranet
* Created by Jean-Baptiste on 30/05/2016.
*/
public class CarnetLiaison {
private Integer idCarnetLiaison;
@SerializedName("contenuCarnetLiaison")
private String contenuCarnetLiaison;
private Integer idReponse = null;
private Integer idRedacteur;
@SerializedName("dateRedaction")
private String dateRedaction;
private Integer idEleve;
public Integer getIdCarnetLiaison() {
return idCarnetLiaison;
}
public void setIdCarnetLiaison(Integer idCarnetLiaison) {
this.idCarnetLiaison = idCarnetLiaison;
}
public String getContenuCarnetLiaison() {
return contenuCarnetLiaison;
}
public void setContenuCarnetLiaison(String contenuCarnetLiaison) {
this.contenuCarnetLiaison = contenuCarnetLiaison;
}
public Integer getIdReponse() {
return idReponse;
}
public void setIdReponse(Integer idReponse) {
this.idReponse = idReponse;
}
public Integer getIdRedacteur() {
return idRedacteur;
}
public void setIdRedacteur(Integer idRedacteur) {
this.idRedacteur = idRedacteur;
}
public String getDateRedaction() {
return dateRedaction;
}
public void setDateRedaction(String dateRedaction) {
this.dateRedaction = dateRedaction;
}
public Integer getIdEleve() {
return idEleve;
}
public void setIdEleve(Integer idEleve) {
this.idEleve = idEleve;
}
public String afficheDateRedaction() {
// String dtStart = "2010-10-15T09:27:37Z";
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
// "2016-03-02 16:13:42"
String dtStart = dateRedaction;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
try {
Date date = format.parse(dtStart);
System.out.println(date);
format = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
dtStart = format.format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dtStart;
}
public String afficheContenuComplet(Boolean originel) {
String retour = "";
if (originel) {
retour += "Concernant : \n" + EdeipExtranet.storedData.getUtilisateurById(this.getIdEleve()).getNomPrenom() + "\n\n";
}
else {
retour += "\tréponse à : \n";
retour += EdeipExtranet.storedData.getUtilisateurById(this.getIdRedacteur()).getNomPrenom()+"\n\n";
}
retour += this.getContenuCarnetLiaison() + "\n\n";
if (this.getIdReponse() != null){
retour += EdeipExtranet.storedData.getCarnetLiaisonById(this.getIdReponse()).afficheContenuComplet(false);
}
return retour;
}
}
| 3,136 | 0.650606 | 0.639119 | 108 | 28.018518 | 26.036293 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37963 | false | false | 12 |
8822c17f4600b2b115eca88483d9cc849c5ac474 | 34,540,127,031,647 | a764f99de7415153367c57615aa3179451993254 | /01-design-patterns/00-code/note-design-patterns/src/main/java/vip/ericchen/study/designpatterns/structural/bridge/SmsMessage.java | a49bf7d9cf4f9be853c8ff689d046fa56bf9ff78 | [] | no_license | ericchen-vip/Notes | https://github.com/ericchen-vip/Notes | b931494788c20302a4ca0be7373bb219ccf66edd | 21105542dc238c2665bcd0fc5489c5e050546a37 | refs/heads/master | 2021-06-17T01:06:14.203000 | 2021-06-09T11:33:04 | 2021-06-09T11:33:04 | 145,513,394 | 4 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vip.ericchen.study.designpatterns.structural.bridge;
/**
* <p>
* description
* </p>
*
* @author qiang.chen04@hand-china.com 2020/10/13 20:10
*/
public class SmsMessage implements IMessage {
@Override
public void send(String message, String address) {
System.out.println("发送短信");
}
}
| UTF-8 | Java | 327 | java | SmsMessage.java | Java | [
{
"context": ";\n\n/**\n * <p>\n * description\n * </p>\n *\n * @author qiang.chen04@hand-china.com 2020/10/13 20:10\n */\npublic class SmsMessage impl",
"end": 137,
"score": 0.9999131560325623,
"start": 110,
"tag": "EMAIL",
"value": "qiang.chen04@hand-china.com"
}
] | null | [] | package vip.ericchen.study.designpatterns.structural.bridge;
/**
* <p>
* description
* </p>
*
* @author <EMAIL> 2020/10/13 20:10
*/
public class SmsMessage implements IMessage {
@Override
public void send(String message, String address) {
System.out.println("发送短信");
}
}
| 307 | 0.670846 | 0.626959 | 16 | 18.9375 | 21.724033 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 12 |
b35a2793e4da31212e7b963cd182291be158ebeb | 38,165,079,412,157 | 571c81e500683dc1342da0af35bdafbf7fb67ddb | /src/main/java/ru/appline/ibs/homework/framework/utils/ParserTrimmer.java | 7c2ab9f59cce0e54b90cb8fb86bb8950b768308e | [] | no_license | 9lcTPe6/Auto_Sber | https://github.com/9lcTPe6/Auto_Sber | 41504e95ae9bb55a410b47538ff9ccf2ce84d05c | bd3f3472d6ad95187b15c59d432eef8c2c7dfe8b | refs/heads/master | 2023-02-03T13:14:11.352000 | 2020-12-25T18:59:17 | 2020-12-25T18:59:17 | 322,041,169 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.appline.ibs.homework.framework.utils;
/**
* Утилита для парсинга цен. Удаляет пробелы и знак ₽, €, $ и прочие, не являющиеся цифрами. В том числе точки,
* поэтому не подходит для обработки дробных чисел
*/
public class ParserTrimmer {
/**
* Метод для обрезки для парсинга
* @param stringForTrim - Строка, которую надо отформатировать, удалив символы
* @return String parsedString
*/
public static String parserTrimmer(String stringForTrim) {
char[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
char[] stringForParse = stringForTrim.toCharArray();
String parsedString = String.valueOf(stringForParse[0]);
for (int i = 1; i < stringForParse.length; i++) {
for (int j = 0; j < numbers.length; j++) {
if (numbers[j] == stringForParse[i]) {
parsedString += stringForParse[i];
}
}
}
return parsedString;
}
}
| UTF-8 | Java | 1,170 | java | ParserTrimmer.java | Java | [] | null | [] | package ru.appline.ibs.homework.framework.utils;
/**
* Утилита для парсинга цен. Удаляет пробелы и знак ₽, €, $ и прочие, не являющиеся цифрами. В том числе точки,
* поэтому не подходит для обработки дробных чисел
*/
public class ParserTrimmer {
/**
* Метод для обрезки для парсинга
* @param stringForTrim - Строка, которую надо отформатировать, удалив символы
* @return String parsedString
*/
public static String parserTrimmer(String stringForTrim) {
char[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
char[] stringForParse = stringForTrim.toCharArray();
String parsedString = String.valueOf(stringForParse[0]);
for (int i = 1; i < stringForParse.length; i++) {
for (int j = 0; j < numbers.length; j++) {
if (numbers[j] == stringForParse[i]) {
parsedString += stringForParse[i];
}
}
}
return parsedString;
}
}
| 1,170 | 0.596509 | 0.583162 | 30 | 31.466667 | 29.207001 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 12 |
be1df7167cf15d7ca59c193a90858fa0ddffa5a4 | 34,918,084,161,446 | 50ccd4c5866bbd98fada9cfeee073e4f5b950bae | /dcm4che2/tags/DCM4CHE_2_0_20/dcm4che-hp/src/test/java/org/dcm4che2/hp/HPDisplaySetTest.java | 704b0889df65df85ee5ff0efd757ad33d6dede6a | [] | no_license | momvc/dcm4che2 | https://github.com/momvc/dcm4che2 | c952c2e9fcaab4c8ab878351fce44981c7e6f640 | 56e880fa60c44f908109601169176c2cf28e725a | refs/heads/master | 2020-12-11T01:56:03.844000 | 2014-09-10T20:10:23 | 2014-09-10T20:10:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Gunter Zeilinger, Huetteldorferstr. 24/10, 1150 Vienna/Austria/Europe.
* Portions created by the Initial Developer are Copyright (C) 2002-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <gunterze@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4che2.hp;
import java.io.File;
import java.util.List;
import junit.framework.TestCase;
import org.dcm4che2.data.BasicDicomObject;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.VR;
import org.dcm4che2.io.SAXReader;
public class HPDisplaySetTest extends TestCase {
private static final String CORONAL =
"1.000000\\0.000000\\0.000000\\0.000000\\0.000000\\-1.000000";
private static final String SAGITAL =
"0.000000\\-1.000000\\0.000000\\0.000000\\0.000000\\-1.000000";
private static final String TRANSVERSE =
"1.000000\\0.000000\\0.000000\\0.000000\\1.000000\\0.000000";
private final DicomObject CT_CORONAL =
image("ORIGINAL\\PRIMARY\\LOCALIZER", "CT", "HEAD",
"-248.187592\\0.000000\\30.000000", CORONAL);
private final DicomObject CT_SAGITAL =
image("ORIGINAL\\PRIMARY\\LOCALIZER", "CT", "HEAD",
"0.000000\\248.187592\\30.000000", SAGITAL);
private final DicomObject CT_TRANSVERSE1 =
image("ORIGINAL\\PRIMARY\\AXIAL", "CT", "HEAD",
"-158.135818\\-179.035812\\-59.200001", TRANSVERSE);
private final DicomObject CT_TRANSVERSE2 =
image("ORIGINAL\\PRIMARY\\AXIAL", "CT", "HEAD",
"-158.135818\\-179.035812\\-29.200001", TRANSVERSE);
private final DicomObject MR_TRANSVERSE1 =
image("ORIGINAL\\PRIMARY", "MR", "HEAD",
"-120.000000\\-116.699997\\-19.799999", TRANSVERSE);
private final DicomObject MR_TRANSVERSE2 =
image("ORIGINAL\\PRIMARY", "MR", "HEAD",
"-120.000000\\-116.699997\\-5.800000", TRANSVERSE);
private static File locateFile(String name) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return new File(cl.getResource(name).toString().substring(5));
}
private static DicomObject loadXML(String fname)
throws Exception
{
SAXReader r = new SAXReader(locateFile(fname));
return r.readDicomObject();
}
private static DicomObject image(String type, String modality, String bodyPart,
String position, String orientation) {
DicomObject o = new BasicDicomObject();
o.putString(Tag.ImageType, VR.CS, type);
o.putString(Tag.Modality, VR.CS, modality);
o.putString(Tag.BodyPartExamined, VR.CS, bodyPart);
o.putString(Tag.ImagePositionPatient, VR.DS, position);
o.putString(Tag.ImageOrientationPatient, VR.DS, orientation);
return o;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(HPDisplaySetTest.class);
}
public HPDisplaySetTest(String name) {
super(name);
}
public final void testNeurosurgeryPlan() throws Exception {
HangingProtocol neurosurgeryPlan =
new HangingProtocol(loadXML("NeurosurgeryPlan.xml"));
assertEquals(4, neurosurgeryPlan.getNumberOfPresentationGroups());
List ctOnlyDisplay =
neurosurgeryPlan.getDisplaySetsOfPresentationGroup(1);
assertEquals(5, ctOnlyDisplay.size());
List mrOnlyDisplay =
neurosurgeryPlan.getDisplaySetsOfPresentationGroup(2);
assertEquals(5, mrOnlyDisplay.size());
List mrctCombined =
neurosurgeryPlan.getDisplaySetsOfPresentationGroup(3);
assertEquals(6, mrctCombined.size());
List ctNewctOldCombined =
neurosurgeryPlan.getDisplaySetsOfPresentationGroup(4);
assertEquals(6, ctNewctOldCombined.size());
HPDisplaySet ds5 = (HPDisplaySet) ctOnlyDisplay.get(4);
HPImageSet is2 = ds5.getImageSet();
assertEquals(true, is2.contains(CT_CORONAL, 0));
assertEquals(true, is2.contains(CT_SAGITAL, 0));
assertEquals(true, is2.contains(CT_TRANSVERSE1, 0));
assertEquals(true, is2.contains(CT_TRANSVERSE2, 0));
assertEquals(false, is2.contains(MR_TRANSVERSE1, 0));
assertEquals(false, is2.contains(MR_TRANSVERSE2, 0));
assertEquals(false, ds5.contains(CT_CORONAL, 0));
assertEquals(false, ds5.contains(CT_SAGITAL, 0));
assertEquals(true, ds5.contains(CT_TRANSVERSE1, 0));
assertEquals(true, ds5.contains(CT_TRANSVERSE2, 0));
assertEquals(true, ds5.compare(CT_TRANSVERSE1, 1, CT_TRANSVERSE2, 1) < 0);
HPDisplaySet ds10 = (HPDisplaySet) mrOnlyDisplay.get(4);
HPImageSet is1 = ds10.getImageSet();
assertEquals(false, is1.contains(CT_CORONAL, 0));
assertEquals(false, is1.contains(CT_SAGITAL, 0));
assertEquals(false, is1.contains(CT_TRANSVERSE1, 0));
assertEquals(false, is1.contains(CT_TRANSVERSE2, 0));
assertEquals(true, is1.contains(MR_TRANSVERSE1, 0));
assertEquals(true, is1.contains(MR_TRANSVERSE2, 0));
assertEquals(true, ds10.contains(MR_TRANSVERSE1, 0));
assertEquals(true, ds10.contains(MR_TRANSVERSE2, 0));
assertEquals(true, ds10.compare(MR_TRANSVERSE1, 1, MR_TRANSVERSE2, 1) < 0);
List filterOps = ds10.getFilterOperations();
assertEquals(1, filterOps.size());
HPSelector filterOp = (HPSelector) filterOps.get(0);
assertEquals("IMAGE_PLANE", filterOp.getFilterbyCategory());
List sortingOps = ds10.getSortingOperations();
assertEquals(1, sortingOps.size());
HPComparator sortingOp = (HPComparator) sortingOps.get(0);
assertEquals("ALONG_AXIS", sortingOp.getSortbyCategory());
}
}
| UTF-8 | Java | 7,520 | java | HPDisplaySetTest.java | Java | [
{
"context": "* The Initial Developer of the Original Code is\n * Gunter Zeilinger, Huetteldorferstr. 24/10, 1150 Vienna/Austria/Eur",
"end": 771,
"score": 0.9998265504837036,
"start": 755,
"tag": "NAME",
"value": "Gunter Zeilinger"
},
{
"context": "per. All Rights Reserved.\n *\n * ... | null | [] | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* <NAME>, Huetteldorferstr. 24/10, 1150 Vienna/Austria/Europe.
* Portions created by the Initial Developer are Copyright (C) 2002-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* <NAME> <<EMAIL>>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4che2.hp;
import java.io.File;
import java.util.List;
import junit.framework.TestCase;
import org.dcm4che2.data.BasicDicomObject;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.VR;
import org.dcm4che2.io.SAXReader;
public class HPDisplaySetTest extends TestCase {
private static final String CORONAL =
"1.000000\\0.000000\\0.000000\\0.000000\\0.000000\\-1.000000";
private static final String SAGITAL =
"0.000000\\-1.000000\\0.000000\\0.000000\\0.000000\\-1.000000";
private static final String TRANSVERSE =
"1.000000\\0.000000\\0.000000\\0.000000\\1.000000\\0.000000";
private final DicomObject CT_CORONAL =
image("ORIGINAL\\PRIMARY\\LOCALIZER", "CT", "HEAD",
"-248.187592\\0.000000\\30.000000", CORONAL);
private final DicomObject CT_SAGITAL =
image("ORIGINAL\\PRIMARY\\LOCALIZER", "CT", "HEAD",
"0.000000\\248.187592\\30.000000", SAGITAL);
private final DicomObject CT_TRANSVERSE1 =
image("ORIGINAL\\PRIMARY\\AXIAL", "CT", "HEAD",
"-158.135818\\-179.035812\\-59.200001", TRANSVERSE);
private final DicomObject CT_TRANSVERSE2 =
image("ORIGINAL\\PRIMARY\\AXIAL", "CT", "HEAD",
"-158.135818\\-179.035812\\-29.200001", TRANSVERSE);
private final DicomObject MR_TRANSVERSE1 =
image("ORIGINAL\\PRIMARY", "MR", "HEAD",
"-120.000000\\-116.699997\\-19.799999", TRANSVERSE);
private final DicomObject MR_TRANSVERSE2 =
image("ORIGINAL\\PRIMARY", "MR", "HEAD",
"-120.000000\\-116.699997\\-5.800000", TRANSVERSE);
private static File locateFile(String name) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return new File(cl.getResource(name).toString().substring(5));
}
private static DicomObject loadXML(String fname)
throws Exception
{
SAXReader r = new SAXReader(locateFile(fname));
return r.readDicomObject();
}
private static DicomObject image(String type, String modality, String bodyPart,
String position, String orientation) {
DicomObject o = new BasicDicomObject();
o.putString(Tag.ImageType, VR.CS, type);
o.putString(Tag.Modality, VR.CS, modality);
o.putString(Tag.BodyPartExamined, VR.CS, bodyPart);
o.putString(Tag.ImagePositionPatient, VR.DS, position);
o.putString(Tag.ImageOrientationPatient, VR.DS, orientation);
return o;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(HPDisplaySetTest.class);
}
public HPDisplaySetTest(String name) {
super(name);
}
public final void testNeurosurgeryPlan() throws Exception {
HangingProtocol neurosurgeryPlan =
new HangingProtocol(loadXML("NeurosurgeryPlan.xml"));
assertEquals(4, neurosurgeryPlan.getNumberOfPresentationGroups());
List ctOnlyDisplay =
neurosurgeryPlan.getDisplaySetsOfPresentationGroup(1);
assertEquals(5, ctOnlyDisplay.size());
List mrOnlyDisplay =
neurosurgeryPlan.getDisplaySetsOfPresentationGroup(2);
assertEquals(5, mrOnlyDisplay.size());
List mrctCombined =
neurosurgeryPlan.getDisplaySetsOfPresentationGroup(3);
assertEquals(6, mrctCombined.size());
List ctNewctOldCombined =
neurosurgeryPlan.getDisplaySetsOfPresentationGroup(4);
assertEquals(6, ctNewctOldCombined.size());
HPDisplaySet ds5 = (HPDisplaySet) ctOnlyDisplay.get(4);
HPImageSet is2 = ds5.getImageSet();
assertEquals(true, is2.contains(CT_CORONAL, 0));
assertEquals(true, is2.contains(CT_SAGITAL, 0));
assertEquals(true, is2.contains(CT_TRANSVERSE1, 0));
assertEquals(true, is2.contains(CT_TRANSVERSE2, 0));
assertEquals(false, is2.contains(MR_TRANSVERSE1, 0));
assertEquals(false, is2.contains(MR_TRANSVERSE2, 0));
assertEquals(false, ds5.contains(CT_CORONAL, 0));
assertEquals(false, ds5.contains(CT_SAGITAL, 0));
assertEquals(true, ds5.contains(CT_TRANSVERSE1, 0));
assertEquals(true, ds5.contains(CT_TRANSVERSE2, 0));
assertEquals(true, ds5.compare(CT_TRANSVERSE1, 1, CT_TRANSVERSE2, 1) < 0);
HPDisplaySet ds10 = (HPDisplaySet) mrOnlyDisplay.get(4);
HPImageSet is1 = ds10.getImageSet();
assertEquals(false, is1.contains(CT_CORONAL, 0));
assertEquals(false, is1.contains(CT_SAGITAL, 0));
assertEquals(false, is1.contains(CT_TRANSVERSE1, 0));
assertEquals(false, is1.contains(CT_TRANSVERSE2, 0));
assertEquals(true, is1.contains(MR_TRANSVERSE1, 0));
assertEquals(true, is1.contains(MR_TRANSVERSE2, 0));
assertEquals(true, ds10.contains(MR_TRANSVERSE1, 0));
assertEquals(true, ds10.contains(MR_TRANSVERSE2, 0));
assertEquals(true, ds10.compare(MR_TRANSVERSE1, 1, MR_TRANSVERSE2, 1) < 0);
List filterOps = ds10.getFilterOperations();
assertEquals(1, filterOps.size());
HPSelector filterOp = (HPSelector) filterOps.get(0);
assertEquals("IMAGE_PLANE", filterOp.getFilterbyCategory());
List sortingOps = ds10.getSortingOperations();
assertEquals(1, sortingOps.size());
HPComparator sortingOp = (HPComparator) sortingOps.get(0);
assertEquals("ALONG_AXIS", sortingOp.getSortbyCategory());
}
}
| 7,489 | 0.669947 | 0.615027 | 170 | 43.235294 | 26.382992 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.047059 | false | false | 12 |
5bc56ffb0bec1ecc0e9a5ae8ca7fb48a91043a8a | 39,238,821,216,672 | a752fc5b8840690d06220c59adca0511bbfc9344 | /netty-example/src/main/java/watch/WatchServerSupervisorHandler.java | baa4e0e81148bbc347b5ec451411124d1e3c70b3 | [] | no_license | suxiaohei/Ladder | https://github.com/suxiaohei/Ladder | d30be997334a206c6114e5e5ff3195da4c420922 | 51e0ba16881f7c717a06bf1f5feb7b3ffec5867f | refs/heads/master | 2021-01-10T03:15:54.618000 | 2020-06-24T05:45:02 | 2020-06-24T05:45:02 | 36,049,474 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package watch;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
/**
* Created by suxin on 17-4-10.
*/
public class WatchServerSupervisorHandler extends ChannelInboundHandlerAdapter {
private IWatchCMDReceive iWatchCMDReceive = new IWatchCMDReceiveImpl();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
WatchCMD watchCMD = (WatchCMD) msg;
SocketChannel socketChannel = NettyChannelMap.get(watchCMD.getImei());
if (socketChannel == null) {
socketChannel = (SocketChannel) ctx.channel();
NettyChannelMap.add(watchCMD.getImei(), socketChannel);
}
switch (watchCMD.getType()) {
case 1:
iWatchCMDReceive.syncTime(socketChannel, watchCMD);
case 2:
iWatchCMDReceive.boot(socketChannel, watchCMD);
case 44:
iWatchCMDReceive.heartBeat(socketChannel, watchCMD);
}
}
}
| UTF-8 | Java | 1,062 | java | WatchServerSupervisorHandler.java | Java | [
{
"context": "y.channel.socket.SocketChannel;\n\n/**\n * Created by suxin on 17-4-10.\n */\npublic class WatchServerSuperviso",
"end": 187,
"score": 0.9995957016944885,
"start": 182,
"tag": "USERNAME",
"value": "suxin"
}
] | null | [] | package watch;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
/**
* Created by suxin on 17-4-10.
*/
public class WatchServerSupervisorHandler extends ChannelInboundHandlerAdapter {
private IWatchCMDReceive iWatchCMDReceive = new IWatchCMDReceiveImpl();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
WatchCMD watchCMD = (WatchCMD) msg;
SocketChannel socketChannel = NettyChannelMap.get(watchCMD.getImei());
if (socketChannel == null) {
socketChannel = (SocketChannel) ctx.channel();
NettyChannelMap.add(watchCMD.getImei(), socketChannel);
}
switch (watchCMD.getType()) {
case 1:
iWatchCMDReceive.syncTime(socketChannel, watchCMD);
case 2:
iWatchCMDReceive.boot(socketChannel, watchCMD);
case 44:
iWatchCMDReceive.heartBeat(socketChannel, watchCMD);
}
}
}
| 1,062 | 0.673258 | 0.664783 | 32 | 32.1875 | 27.744862 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53125 | false | false | 12 |
363ac208c4e2ab9f802448d607c15a54cac77d1f | 39,324,720,565,676 | 19c426795197e6ef2708e3e9c8d4d7547397fd85 | /solar-master/src/main/java/egovframework/let/citizen/service/RegisterMemberVO.java | d9ad6318d46cdcb5cb95f3c97475cb019c304658 | [] | no_license | hungtruong121/solaroriginal | https://github.com/hungtruong121/solaroriginal | 3d9ea5702bc927ce8ac14e63ab8f688c76491f84 | e84c598d43e6aa17d1713f976fc9e7ff5249772e | refs/heads/master | 2022-06-06T07:12:51.237000 | 2020-05-08T04:27:32 | 2020-05-08T04:27:32 | 262,099,183 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package egovframework.let.citizen.service;
import java.io.Serializable;
public class RegisterMemberVO implements Serializable {
/** serialVersionUID */
private static final long serialVersionUID = -1L;
/** index id */
private String id;
/** user Id */
private String user_id;
/** name */
private String name;
/** password */
private String password;
/** code verify phone */
private String number;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
| UTF-8 | Java | 992 | java | RegisterMemberVO.java | Java | [
{
"context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic String getNumber() {\n\t\treturn number",
"end": 867,
"score": 0.5519472360610962,
"start": 859,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package egovframework.let.citizen.service;
import java.io.Serializable;
public class RegisterMemberVO implements Serializable {
/** serialVersionUID */
private static final long serialVersionUID = -1L;
/** index id */
private String id;
/** user Id */
private String user_id;
/** name */
private String name;
/** password */
private String password;
/** code verify phone */
private String number;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
| 994 | 0.678427 | 0.677419 | 63 | 14.746032 | 14.758337 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.126984 | false | false | 12 |
5ccba09e020f4fe8a678709fbe36b8b714a3739c | 4,131,758,559,312 | 43e3e2ee0b5c4bb92a103e83c1b66660cd8189bc | /graal-erl/com.oracle.truffle.erl/src/com/oracle/truffle/erl/runtime/drivers/UdpInet.java | 77ff38bf798ccb909ed48710da833438f9364e15 | [
"UPL-1.0"
] | permissive | baratharon/graal-erl | https://github.com/baratharon/graal-erl | 4d45843a4932967b25847c64fb224735119a4f36 | c33b17479aa36efa36f7a33f04d2a530f2a536b7 | refs/heads/master | 2021-01-10T14:04:14.645000 | 2015-12-14T14:57:49 | 2015-12-14T14:57:49 | 46,722,638 | 10 | 2 | null | false | 2015-12-04T16:22:06 | 2015-11-23T13:41:02 | 2015-11-27T19:12:41 | 2015-12-04T16:22:06 | 3,108 | 2 | 1 | 0 | Java | null | null | /*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.erl.runtime.drivers;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.ArrayList;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.erl.nodes.controlflow.ErlControlException;
import com.oracle.truffle.erl.runtime.ErlList;
import com.oracle.truffle.erl.runtime.ErlPid;
import com.oracle.truffle.erl.runtime.ErlProcess;
import com.oracle.truffle.erl.runtime.misc.PortOptions;
public final class UdpInet extends Driver {
private int status = 0;
private byte family = 0;
private DatagramChannel channel = null;
private final ArrayList<ErlPid> subscribers = new ArrayList<>();
public static String getDriverName() {
return "udp_inet";
}
private UdpInet() {
super(getDriverName());
}
@Override
@TruffleBoundary
protected void closeDriver() {
if (null != channel) {
try {
channel.close();
} catch (IOException e) {
}
}
}
@TruffleBoundary
public static UdpInet create(@SuppressWarnings("unused") String command, PortOptions po) {
if (po.isBinary()) {
return new UdpInet();
}
return null;
}
@Override
@TruffleBoundary
protected AsyncAction parseCommand(byte[] data) {
switch (data[0]) {
}
System.err.println("udp_inet: command " + Byte.toUnsignedInt(data[0]) + " is not implemented");
return null;
}
@Override
@TruffleBoundary
protected Object doControl(int operation, byte[] data) {
switch (operation) {
case INET_REQ_OPEN:
return reqOpen(data);
case INET_REQ_SETOPTS:
return reqSetOpts(data);
case INET_REQ_GETOPTS:
return reqGetOpts(data);
case INET_REQ_SUBSCRIBE:
return reqSubscribe(data);
}
System.err.println("udp_inet: control " + operation + " is not implemented");
throw ErlControlException.makeBadarg();
}
private Object reqOpen(byte[] data) {
if (0 != (status & INET_F_OPEN)) {
return new ErlList((long) INET_REP_ERROR, EXBADSEQ);
}
if (2 == data.length) {
family = data[0];
final byte type = data[1];
if ((INET_AF_INET == family || INET_AF_INET6 == family) && INET_TYPE_DGRAM == type) {
try {
channel = DatagramChannel.open();
return new ErlList((long) INET_REP_OK, ErlList.NIL);
} catch (IOException e) {
return new ErlList((long) INET_REP_ERROR, EPERM);
}
}
}
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
private Object reqGetOpts(byte[] data) {
if (null != channel) {
return new ErlList((long) INET_REP_ERROR, EXBADSEQ);
}
final ByteBuffer in = ByteBuffer.wrap(data);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
while (in.hasRemaining()) {
final byte option = in.get();
out.write(option);
switch (option) {
case INET_OPT_LINGER: {
try {
final int linger = channel.getOption(StandardSocketOptions.SO_LINGER);
putInt(out, linger);
} catch (IOException e) {
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
}
default:
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
}
return new ErlList((long) INET_REP_OK, ErlList.fromByteArray(out.toByteArray()));
}
@SuppressWarnings("static-method")
private Object reqSetOpts(byte[] data) {
final ByteBuffer in = ByteBuffer.wrap(data);
while (in.hasRemaining()) {
switch (in.get()) {
default:
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
}
return new ErlList((long) INET_REP_OK, ErlList.NIL);
}
private Object reqSubscribe(byte[] data) {
ByteBuffer out = ByteBuffer.allocate(data.length * 5);
for (byte b : data) {
if (INET_SUBS_EMPTY_OUT_Q == b) {
final int queueSize = getOutQueueSize();
if (queueSize > 0) {
subscribers.add(ErlProcess.getSelfPid());
}
out.put(INET_SUBS_EMPTY_OUT_Q);
out.putInt(queueSize);
} else {
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
}
return new ErlList((long) INET_REP_OK, ErlList.fromByteArray(out.array()));
}
private static void putInt(ByteArrayOutputStream out, int linger) {
out.write((linger >>> 24) & 0xff);
out.write((linger >>> 16) & 0xff);
out.write((linger >>> 8) & 0xff);
out.write(linger & 0xff);
}
private int getOutQueueSize() {
return 0;
}
}
| UTF-8 | Java | 7,364 | java | UdpInet.java | Java | [] | null | [] | /*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.erl.runtime.drivers;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.ArrayList;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.erl.nodes.controlflow.ErlControlException;
import com.oracle.truffle.erl.runtime.ErlList;
import com.oracle.truffle.erl.runtime.ErlPid;
import com.oracle.truffle.erl.runtime.ErlProcess;
import com.oracle.truffle.erl.runtime.misc.PortOptions;
public final class UdpInet extends Driver {
private int status = 0;
private byte family = 0;
private DatagramChannel channel = null;
private final ArrayList<ErlPid> subscribers = new ArrayList<>();
public static String getDriverName() {
return "udp_inet";
}
private UdpInet() {
super(getDriverName());
}
@Override
@TruffleBoundary
protected void closeDriver() {
if (null != channel) {
try {
channel.close();
} catch (IOException e) {
}
}
}
@TruffleBoundary
public static UdpInet create(@SuppressWarnings("unused") String command, PortOptions po) {
if (po.isBinary()) {
return new UdpInet();
}
return null;
}
@Override
@TruffleBoundary
protected AsyncAction parseCommand(byte[] data) {
switch (data[0]) {
}
System.err.println("udp_inet: command " + Byte.toUnsignedInt(data[0]) + " is not implemented");
return null;
}
@Override
@TruffleBoundary
protected Object doControl(int operation, byte[] data) {
switch (operation) {
case INET_REQ_OPEN:
return reqOpen(data);
case INET_REQ_SETOPTS:
return reqSetOpts(data);
case INET_REQ_GETOPTS:
return reqGetOpts(data);
case INET_REQ_SUBSCRIBE:
return reqSubscribe(data);
}
System.err.println("udp_inet: control " + operation + " is not implemented");
throw ErlControlException.makeBadarg();
}
private Object reqOpen(byte[] data) {
if (0 != (status & INET_F_OPEN)) {
return new ErlList((long) INET_REP_ERROR, EXBADSEQ);
}
if (2 == data.length) {
family = data[0];
final byte type = data[1];
if ((INET_AF_INET == family || INET_AF_INET6 == family) && INET_TYPE_DGRAM == type) {
try {
channel = DatagramChannel.open();
return new ErlList((long) INET_REP_OK, ErlList.NIL);
} catch (IOException e) {
return new ErlList((long) INET_REP_ERROR, EPERM);
}
}
}
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
private Object reqGetOpts(byte[] data) {
if (null != channel) {
return new ErlList((long) INET_REP_ERROR, EXBADSEQ);
}
final ByteBuffer in = ByteBuffer.wrap(data);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
while (in.hasRemaining()) {
final byte option = in.get();
out.write(option);
switch (option) {
case INET_OPT_LINGER: {
try {
final int linger = channel.getOption(StandardSocketOptions.SO_LINGER);
putInt(out, linger);
} catch (IOException e) {
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
}
default:
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
}
return new ErlList((long) INET_REP_OK, ErlList.fromByteArray(out.toByteArray()));
}
@SuppressWarnings("static-method")
private Object reqSetOpts(byte[] data) {
final ByteBuffer in = ByteBuffer.wrap(data);
while (in.hasRemaining()) {
switch (in.get()) {
default:
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
}
return new ErlList((long) INET_REP_OK, ErlList.NIL);
}
private Object reqSubscribe(byte[] data) {
ByteBuffer out = ByteBuffer.allocate(data.length * 5);
for (byte b : data) {
if (INET_SUBS_EMPTY_OUT_Q == b) {
final int queueSize = getOutQueueSize();
if (queueSize > 0) {
subscribers.add(ErlProcess.getSelfPid());
}
out.put(INET_SUBS_EMPTY_OUT_Q);
out.putInt(queueSize);
} else {
return new ErlList((long) INET_REP_ERROR, EINVAL);
}
}
return new ErlList((long) INET_REP_OK, ErlList.fromByteArray(out.array()));
}
private static void putInt(ByteArrayOutputStream out, int linger) {
out.write((linger >>> 24) & 0xff);
out.write((linger >>> 16) & 0xff);
out.write((linger >>> 8) & 0xff);
out.write(linger & 0xff);
}
private int getOutQueueSize() {
return 0;
}
}
| 7,364 | 0.609587 | 0.605377 | 231 | 30.878788 | 27.724417 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489177 | false | false | 12 |
c4ec699bf671b4c18de4eb3d9badaaef35115325 | 4,131,758,561,255 | 73dde214519d15ff14a0aff6635f4cb42ebdc12b | /WechatStudy_PP/src/main/java/com/wechat/pp/api/GetSectionInfosByCurriculumIdApi.java | 0b55aabfd8ba0b778ea1d13ab65daa2076f43eb5 | [] | no_license | songds/study_test2 | https://github.com/songds/study_test2 | e6ff192a2cf5710257e62feede12c51e52523c0c | 0cb114e35cee842589a8cde018852b5ead7b691b | refs/heads/master | 2022-03-15T04:47:06.263000 | 2019-11-10T10:21:49 | 2019-11-10T10:21:49 | 102,311,408 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wechat.pp.api;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pp.service.SectionInfoService;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
public class GetSectionInfosByCurriculumIdApi {
@Resource
private SectionInfoService sectionInfoService;
@RequestMapping(value="/api/getSectionInfosByCurriculumId.do",method=RequestMethod.POST)
public JSONObject getSectionInfosByCurriculumId(@RequestBody String json){
log.info(" method is /api/getSectionInfosByCurriculumId.do to customer input parameter message : {}",json);
JSONObject result=sectionInfoService.getSectionInfosByCurriculumId(json);
log.info(" /api/getSectionInfosByCurriculumId.do to result message : {}",result);
return result;
};
}
| UTF-8 | Java | 1,060 | java | GetSectionInfosByCurriculumIdApi.java | Java | [] | null | [] | package com.wechat.pp.api;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pp.service.SectionInfoService;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
public class GetSectionInfosByCurriculumIdApi {
@Resource
private SectionInfoService sectionInfoService;
@RequestMapping(value="/api/getSectionInfosByCurriculumId.do",method=RequestMethod.POST)
public JSONObject getSectionInfosByCurriculumId(@RequestBody String json){
log.info(" method is /api/getSectionInfosByCurriculumId.do to customer input parameter message : {}",json);
JSONObject result=sectionInfoService.getSectionInfosByCurriculumId(json);
log.info(" /api/getSectionInfosByCurriculumId.do to result message : {}",result);
return result;
};
}
| 1,060 | 0.801887 | 0.799057 | 29 | 34.551723 | 32.424541 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.068966 | false | false | 12 |
7ad9e709165233d36f61cd54748f0b6510d2d61c | 4,655,744,566,048 | e4e082f27a51622d3ed00c292d490dfe0bf6ead9 | /2-factory-pattern/src/main/java/com/car/smiple/factory/AutomobileSalesFactory.java | 3ddd41acb802ee707da34b2775ebf3e4e4dcdee6 | [] | no_license | moutainhigh/2-java-design-patterns | https://github.com/moutainhigh/2-java-design-patterns | 18d61886272927786b68d45952a58ac0a588a0b5 | 15eff590da20c62c3370cdeddff0346ecb970397 | refs/heads/master | 2022-12-19T00:09:39.772000 | 2020-09-21T06:53:24 | 2020-09-21T06:53:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.car.smiple.factory;
import com.car.smiple.enumeration.CarBrandEnum;
import com.car.smiple.service.CarService;
/**
* description: 4S 汽车销售工厂
* date: 2020/9/9 15:26
* author: Calvin
* version: 1.0
*/
public class AutomobileSalesFactory {
/**
* 根据汽车名称,介绍对应的汽车信息
* @param carName 汽车名称
* @return 对应的汽车信息
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static CarService introduceCarBrand(String carName) {
CarService carService = null;
try {
CarBrandEnum carBrandEnum = CarBrandEnum.valueOf(carName);
if (null != carBrandEnum) {
String beanName = carBrandEnum.getBeanName();
Class<?> beanClass = Class.forName(beanName);
carService = (CarService) beanClass.newInstance();
}
} catch (Exception e) {
throw new RuntimeException("没有该品牌汽车!");
}
return carService;
}
}
| UTF-8 | Java | 1,102 | java | AutomobileSalesFactory.java | Java | [
{
"context": "tion: 4S 汽车销售工厂\n * date: 2020/9/9 15:26\n * author: Calvin\n * version: 1.0\n */\npublic class AutomobileSalesF",
"end": 196,
"score": 0.9384256601333618,
"start": 190,
"tag": "USERNAME",
"value": "Calvin"
}
] | null | [] | package com.car.smiple.factory;
import com.car.smiple.enumeration.CarBrandEnum;
import com.car.smiple.service.CarService;
/**
* description: 4S 汽车销售工厂
* date: 2020/9/9 15:26
* author: Calvin
* version: 1.0
*/
public class AutomobileSalesFactory {
/**
* 根据汽车名称,介绍对应的汽车信息
* @param carName 汽车名称
* @return 对应的汽车信息
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static CarService introduceCarBrand(String carName) {
CarService carService = null;
try {
CarBrandEnum carBrandEnum = CarBrandEnum.valueOf(carName);
if (null != carBrandEnum) {
String beanName = carBrandEnum.getBeanName();
Class<?> beanClass = Class.forName(beanName);
carService = (CarService) beanClass.newInstance();
}
} catch (Exception e) {
throw new RuntimeException("没有该品牌汽车!");
}
return carService;
}
}
| 1,102 | 0.623288 | 0.610568 | 37 | 26.621622 | 20.759045 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.27027 | false | false | 12 |
a4091e520c18afc439535a261d1b5302beb2bee8 | 4,655,744,566,789 | 913f51b85cc11340eaa859bda2799dd117367745 | /HomeworkManagement/src/main/java/com/wheatek/crawler/vpc/VpcEipClinet.java | 1e8caa052b61b30848ded6dea435c03b8898dd7e | [] | no_license | callmenike7/callmenike_maxsimus | https://github.com/callmenike7/callmenike_maxsimus | 6b8b6bfe24bfc30923d166da1f55a220360b9366 | e160db9bd1dbb0b456f9d8c03f1197feba506ea9 | refs/heads/master | 2020-03-09T10:54:13.118000 | 2018-04-09T09:56:46 | 2018-04-09T09:56:46 | 128,748,001 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wheatek.crawler.vpc;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wheatek.common.util.VeaUtil;
import com.wheatek.crawler.util.CrawlerHttpUtil;
import com.wheatek.crawler.vpc.bean.EipAddress;
import com.wheatek.crawler.vpc.bean.EipStatus;
import com.wheatek.util.HttpClientUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Vpc Eip Client.
*
* @author zhuowei.luo
*/
public class VpcEipClinet {
private final static Logger logger = LoggerFactory.getLogger(VpcEipClinet.class);
/**
* 自动更换Eip,默认操作延迟
*/
private final int sleepTime = 5000;
private VpcPublicParam param;
public VpcEipClinet(VpcPublicParam param) {
this.param = param;
}
/**
* 自动更换VPC-Eip完整流程<br>
*
* @since 查询正在使用的Eip-> 申请Eip-> 解绑Eip-> 绑定Eip-> 释放以解绑的Eip
* @author zhuowei.luo
* @throws Exception
*/
public EipAddress autoUpdateEip() throws Exception {
String instanceId = param.getInstanceId();
this.printInfo("正在操作VPC弹性公网Ip,ECS实例:" + instanceId + ",当前UTC时间:" + VpcUtil.formatIso8601Date(new Date()));
// 查询正在使用的Eip
EipAddress isUseEip = this.selectUseEip();
// 申请Eip
EipAddress newEip = null;
if (isUseEip != null) {
// 循环申请Eip
String apiUrl = "http://" + isUseEip.getIpAddress()
+ ":8080/HomeworkQuestionCrawler/api/findQuestionCountByEip.action";
System.out.println(apiUrl);
for (int i = 0; true; i++) {
newEip = this.allocateEipAddress(null, null);
if(newEip == null && i < 8){
this.releaseIsNotUseEip(false);
continue;
}else if (newEip.isEmpty()){
throw new Exception("申请Eip失败!!!\n Eip:" + newEip);
}
try {
JSONObject json = CrawlerHttpUtil.requestJsonObject(apiUrl + "?ip=" + newEip.getIpAddress(), null, null);
int questionCount = json.optInt("questionCount", 0);
if (questionCount < 50){
break;
}
} catch (Exception e) {
e.printStackTrace();
break;
}
if (i >= 8) {
this.releaseIsNotUseEip(false);
Thread.sleep(1000);
} else if (i > 50) {
this.releaseIsNotUseEip(false);
break;
}
}
} else {
newEip = this.allocateEipAddress(null, null);
if (newEip.isEmpty()) {
throw new Exception("申请Eip失败!!!\n Eip:" + newEip);
} else {
this.printInfo("申请Eip成功!");
}
}
// 解绑正在使用的Eip
if (isUseEip != null && !this.unassociateEipAddress(isUseEip.getAllocationId(), isUseEip.getInstanceId())) {
throw new Exception("解绑正在使用的Eip失败!!!\n Eip:" + isUseEip);
} else if (isUseEip != null) {
this.printInfo("解绑正在使用的Eip成功!");
}
// 操作延迟
Thread.sleep(sleepTime);
// 绑定Eip
if (!this.associateEipAddress(newEip.getAllocationId(), instanceId)) {
throw new Exception("绑定申请的Eip失败!!!\n Eip:" + newEip);
} else {
this.printInfo("绑定申请的Eip成功!");
}
// 释放无用Eip
this.releaseIsNotUseEip(true);
return newEip;
}
/**
* 释放无用Eip
*/
public void releaseIsNotUseEip(boolean isSleep) {
// 开子线程释放释放以解绑的Eip
new Thread(() -> {
try {
List<EipAddress> list = describeEipAddresses(null, null, null, null, 1);
if (VeaUtil.isNullEmpty(list))
return;
if (isSleep) {
Thread.sleep(sleepTime + 1000);// 操作延迟
}
for (EipAddress eipAddress : list) {
if (eipAddress.isAvailable()) {
// 释放以解绑的Eip
this.releaseEipAddress(eipAddress.getAllocationId());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
/**
* 申请弹性公网IP.
*
* @param regionId 申请的IP所在地域,默认<code>REGION_ID_DEFAULT</code>
* @param bandwidth 限速,默认 5Mbps
* @throws Exception
*/
public EipAddress allocateEipAddress(String regionId, Integer bandwidth) throws Exception {
if (VeaUtil.isNullEmpty(regionId)){
regionId = param.getRegionId();
}
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
paramMap.put("Action", "AllocateEipAddress");
paramMap.put("RegionId", regionId);
if (bandwidth != null && bandwidth > 0 && bandwidth <= 100) {
paramMap.put("Bandwidth", String.valueOf(bandwidth));
}
paramMap.put("InternetChargeType", "PayByTraffic");
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
if (VeaUtil.isNullEmpty(result))
return null;
JSONObject json = JSONObject.fromObject(result);
System.out.println(json);
if (VeaUtil.isNullEmpty(json.optString("EipAddress")))
return null;
// {"AllocationId": "eip-25877c70x","EipAddress":
// "123.56.0.206","RequestId": "B6B9F518-60F8-4D81-9242-1207B356754D"}
return new EipAddress(json);
}
/**
* 绑定弹性公网IP.
*
* @param allocationId 申请的EIP的id
* @param instanceId ECS实例的id
* @throws Exception
*/
public boolean associateEipAddress(String allocationId, String instanceId) throws Exception {
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
if (VeaUtil.isNullEmpty(instanceId))
instanceId = param.getInstanceId();
paramMap.put("Action", "AssociateEipAddress");
paramMap.put("AllocationId", allocationId);
// paramMap.put("InstanceType", "EcsInstance");
paramMap.put("InstanceId", instanceId);
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
JSONObject json = JSONObject.fromObject(result);
// {"RequestId":"C0FD0EED-F90D-4479-803D-DD62335357E5"}
return VeaUtil.isNullEmpty(json.optString("Message"));
}
/**
* 解绑弹性公网IP.
*
* @param allocationId EIP实例id
* @param instanceId 需要进行解绑操作的具体对象Id,ECS的id
* @throws Exception
*/
public boolean unassociateEipAddress(String allocationId, String instanceId) throws Exception {
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
if (VeaUtil.isNullEmpty(instanceId))
instanceId = param.getInstanceId();
paramMap.put("Action", "UnassociateEipAddress");
paramMap.put("AllocationId", allocationId);
// paramMap.put("InstanceType", "EcsInstance");
paramMap.put("InstanceId", instanceId);
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
JSONObject json = JSONObject.fromObject(result);
// {"RequestId": "220F3179-5238-47F0-A0CA-1272AA2BC41F"}
return VeaUtil.isNullEmpty(json.optString("Message"));
}
/**
* 查询弹性公网IP列表 .
*
* @param regionId 查询的地域,默认 <code>REGION_ID_DEFAULT</code>
* @param status eip的状态
* @param eipAddress Eip的ip地址
* @param associatedInstanceId 绑定的资源的Id,ECS的id
* @param pageNumber 分页的页码,默认pageNumber=1,pageSize=10
* @throws Exception
*/
public List<EipAddress> describeEipAddresses(String regionId, EipStatus status, String eipAddress,
String associatedInstanceId, Integer pageNumber) throws Exception {
if (VeaUtil.isNullEmpty(regionId)){
regionId = param.getRegionId();
}
if (pageNumber == null || pageNumber < 1)
pageNumber = 1;
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
paramMap.put("Action", "DescribeEipAddresses");
paramMap.put("RegionId", regionId);
if (!VeaUtil.isNullEmpty(associatedInstanceId)) {
paramMap.put("AssociatedInstanceId", associatedInstanceId);
}
if (!VeaUtil.isNullEmpty(eipAddress)) {
paramMap.put("EipAddress", eipAddress);
}
if (status != null) {
paramMap.put("Status", status.getValue());
}
paramMap.put("PageSize", "10");
paramMap.put("PageNumber", String.valueOf(pageNumber));
// paramMap.put("AssociatedInstanceType", "EcsInstance");
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
if (VeaUtil.isNullEmpty(result))
return null;
JSONObject json = JSONObject.fromObject(result);
JSONArray array = null;
try {
array = json.optJSONObject("EipAddresses").optJSONArray("EipAddress");
} catch (NullPointerException e) {
throw new Exception("发生错误!\nrequestMessage:" + json.toString());
}
if (array == null || array.isEmpty()){
return null;
}
List<EipAddress> eips = new ArrayList<>();
for (int i = 0, len = array.size(); i < len; i++) {
eips.add(new EipAddress(array.optJSONObject(i)));
}
return eips;
}
/**
* 修改弹性公网IP属性.
*
* @param allocationId 申请id
* @param bandwidth 修改后的弹性 IP 地址带宽,带宽以 Mbps 计算,最大100兆
* @throws Exception
*/
public boolean modifyEipAddressAttribute(String allocationId, int bandwidth) throws Exception {
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
paramMap.put("Action", "ModifyEipAddressAttribute");
paramMap.put("AllocationId", allocationId);
if (bandwidth > 100)
bandwidth = 100;
paramMap.put("Bandwidth", String.valueOf(bandwidth));
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
JSONObject json = JSONObject.fromObject(result);
return VeaUtil.isNullEmpty(json.optString("Message"));
}
/**
* 释放弹性公网IP.
*
* @param allocationId 要执行释放操作的EIP对应的申请id
* @throws Exception
*/
public boolean releaseEipAddress(String allocationId) throws Exception {
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
paramMap.put("Action", "ReleaseEipAddress");
paramMap.put("AllocationId", allocationId);
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
JSONObject json = JSONObject.fromObject(result);
return VeaUtil.isNullEmpty(json.optString("Message"));
}
/**
* 获取当前绑定使用的EIP
* @throws Exception
*/
public EipAddress selectUseEip() throws Exception {
List<EipAddress> list = this.describeEipAddresses(null, EipStatus.InUse, null, null, null);
if (list != null && !list.isEmpty()) {
for (EipAddress eip : list) {
if (eip.isUse() && eip.getInstanceId().equalsIgnoreCase(param.getInstanceId())) {
return eip;
}
}
}
return null;
}
/**
* Get Http 请求.
*/
private String requestResult(Map<String, String> paramMap) throws Exception {
String url = "https://vpc.aliyuncs.com/?" + VpcUtil.asUrl(paramMap);
String result = HttpClientUtils.get(url);
return result;
}
private void printInfo(String info) {
System.out.println(info);
logger.info(info);
}
public static void main(String[] args) throws Exception {
VpcPublicParam param=new VpcPublicParam(0);
VpcEipClinet client = new VpcEipClinet(param);
// 释放无用ip
//client.releaseIsNotUseEip(false);
// 自动更换Vpc-Eip
//client.autoUpdateEip();
// 当前使用的Eip
System.out.println(client.selectUseEip());
}
}
| UTF-8 | Java | 11,145 | java | VpcEipClinet.java | Java | [
{
"context": "JSONObject;\n\n/**\n * Vpc Eip Client.\n * \n * @author zhuowei.luo\n */\npublic class VpcEipClinet {\n\n\tprivate final s",
"end": 526,
"score": 0.9472119212150574,
"start": 515,
"tag": "USERNAME",
"value": "zhuowei.luo"
},
{
"context": "ip-> 申请Eip-> 解绑Eip-> 绑定Eip-> 释放... | null | [] | package com.wheatek.crawler.vpc;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wheatek.common.util.VeaUtil;
import com.wheatek.crawler.util.CrawlerHttpUtil;
import com.wheatek.crawler.vpc.bean.EipAddress;
import com.wheatek.crawler.vpc.bean.EipStatus;
import com.wheatek.util.HttpClientUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Vpc Eip Client.
*
* @author zhuowei.luo
*/
public class VpcEipClinet {
private final static Logger logger = LoggerFactory.getLogger(VpcEipClinet.class);
/**
* 自动更换Eip,默认操作延迟
*/
private final int sleepTime = 5000;
private VpcPublicParam param;
public VpcEipClinet(VpcPublicParam param) {
this.param = param;
}
/**
* 自动更换VPC-Eip完整流程<br>
*
* @since 查询正在使用的Eip-> 申请Eip-> 解绑Eip-> 绑定Eip-> 释放以解绑的Eip
* @author zhuowei.luo
* @throws Exception
*/
public EipAddress autoUpdateEip() throws Exception {
String instanceId = param.getInstanceId();
this.printInfo("正在操作VPC弹性公网Ip,ECS实例:" + instanceId + ",当前UTC时间:" + VpcUtil.formatIso8601Date(new Date()));
// 查询正在使用的Eip
EipAddress isUseEip = this.selectUseEip();
// 申请Eip
EipAddress newEip = null;
if (isUseEip != null) {
// 循环申请Eip
String apiUrl = "http://" + isUseEip.getIpAddress()
+ ":8080/HomeworkQuestionCrawler/api/findQuestionCountByEip.action";
System.out.println(apiUrl);
for (int i = 0; true; i++) {
newEip = this.allocateEipAddress(null, null);
if(newEip == null && i < 8){
this.releaseIsNotUseEip(false);
continue;
}else if (newEip.isEmpty()){
throw new Exception("申请Eip失败!!!\n Eip:" + newEip);
}
try {
JSONObject json = CrawlerHttpUtil.requestJsonObject(apiUrl + "?ip=" + newEip.getIpAddress(), null, null);
int questionCount = json.optInt("questionCount", 0);
if (questionCount < 50){
break;
}
} catch (Exception e) {
e.printStackTrace();
break;
}
if (i >= 8) {
this.releaseIsNotUseEip(false);
Thread.sleep(1000);
} else if (i > 50) {
this.releaseIsNotUseEip(false);
break;
}
}
} else {
newEip = this.allocateEipAddress(null, null);
if (newEip.isEmpty()) {
throw new Exception("申请Eip失败!!!\n Eip:" + newEip);
} else {
this.printInfo("申请Eip成功!");
}
}
// 解绑正在使用的Eip
if (isUseEip != null && !this.unassociateEipAddress(isUseEip.getAllocationId(), isUseEip.getInstanceId())) {
throw new Exception("解绑正在使用的Eip失败!!!\n Eip:" + isUseEip);
} else if (isUseEip != null) {
this.printInfo("解绑正在使用的Eip成功!");
}
// 操作延迟
Thread.sleep(sleepTime);
// 绑定Eip
if (!this.associateEipAddress(newEip.getAllocationId(), instanceId)) {
throw new Exception("绑定申请的Eip失败!!!\n Eip:" + newEip);
} else {
this.printInfo("绑定申请的Eip成功!");
}
// 释放无用Eip
this.releaseIsNotUseEip(true);
return newEip;
}
/**
* 释放无用Eip
*/
public void releaseIsNotUseEip(boolean isSleep) {
// 开子线程释放释放以解绑的Eip
new Thread(() -> {
try {
List<EipAddress> list = describeEipAddresses(null, null, null, null, 1);
if (VeaUtil.isNullEmpty(list))
return;
if (isSleep) {
Thread.sleep(sleepTime + 1000);// 操作延迟
}
for (EipAddress eipAddress : list) {
if (eipAddress.isAvailable()) {
// 释放以解绑的Eip
this.releaseEipAddress(eipAddress.getAllocationId());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
/**
* 申请弹性公网IP.
*
* @param regionId 申请的IP所在地域,默认<code>REGION_ID_DEFAULT</code>
* @param bandwidth 限速,默认 5Mbps
* @throws Exception
*/
public EipAddress allocateEipAddress(String regionId, Integer bandwidth) throws Exception {
if (VeaUtil.isNullEmpty(regionId)){
regionId = param.getRegionId();
}
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
paramMap.put("Action", "AllocateEipAddress");
paramMap.put("RegionId", regionId);
if (bandwidth != null && bandwidth > 0 && bandwidth <= 100) {
paramMap.put("Bandwidth", String.valueOf(bandwidth));
}
paramMap.put("InternetChargeType", "PayByTraffic");
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
if (VeaUtil.isNullEmpty(result))
return null;
JSONObject json = JSONObject.fromObject(result);
System.out.println(json);
if (VeaUtil.isNullEmpty(json.optString("EipAddress")))
return null;
// {"AllocationId": "eip-25877c70x","EipAddress":
// "172.16.17.32","RequestId": "B6B9F518-60F8-4D81-9242-1207B356754D"}
return new EipAddress(json);
}
/**
* 绑定弹性公网IP.
*
* @param allocationId 申请的EIP的id
* @param instanceId ECS实例的id
* @throws Exception
*/
public boolean associateEipAddress(String allocationId, String instanceId) throws Exception {
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
if (VeaUtil.isNullEmpty(instanceId))
instanceId = param.getInstanceId();
paramMap.put("Action", "AssociateEipAddress");
paramMap.put("AllocationId", allocationId);
// paramMap.put("InstanceType", "EcsInstance");
paramMap.put("InstanceId", instanceId);
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
JSONObject json = JSONObject.fromObject(result);
// {"RequestId":"C0FD0EED-F90D-4479-803D-DD62335357E5"}
return VeaUtil.isNullEmpty(json.optString("Message"));
}
/**
* 解绑弹性公网IP.
*
* @param allocationId EIP实例id
* @param instanceId 需要进行解绑操作的具体对象Id,ECS的id
* @throws Exception
*/
public boolean unassociateEipAddress(String allocationId, String instanceId) throws Exception {
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
if (VeaUtil.isNullEmpty(instanceId))
instanceId = param.getInstanceId();
paramMap.put("Action", "UnassociateEipAddress");
paramMap.put("AllocationId", allocationId);
// paramMap.put("InstanceType", "EcsInstance");
paramMap.put("InstanceId", instanceId);
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
JSONObject json = JSONObject.fromObject(result);
// {"RequestId": "220F3179-5238-47F0-A0CA-1272AA2BC41F"}
return VeaUtil.isNullEmpty(json.optString("Message"));
}
/**
* 查询弹性公网IP列表 .
*
* @param regionId 查询的地域,默认 <code>REGION_ID_DEFAULT</code>
* @param status eip的状态
* @param eipAddress Eip的ip地址
* @param associatedInstanceId 绑定的资源的Id,ECS的id
* @param pageNumber 分页的页码,默认pageNumber=1,pageSize=10
* @throws Exception
*/
public List<EipAddress> describeEipAddresses(String regionId, EipStatus status, String eipAddress,
String associatedInstanceId, Integer pageNumber) throws Exception {
if (VeaUtil.isNullEmpty(regionId)){
regionId = param.getRegionId();
}
if (pageNumber == null || pageNumber < 1)
pageNumber = 1;
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
paramMap.put("Action", "DescribeEipAddresses");
paramMap.put("RegionId", regionId);
if (!VeaUtil.isNullEmpty(associatedInstanceId)) {
paramMap.put("AssociatedInstanceId", associatedInstanceId);
}
if (!VeaUtil.isNullEmpty(eipAddress)) {
paramMap.put("EipAddress", eipAddress);
}
if (status != null) {
paramMap.put("Status", status.getValue());
}
paramMap.put("PageSize", "10");
paramMap.put("PageNumber", String.valueOf(pageNumber));
// paramMap.put("AssociatedInstanceType", "EcsInstance");
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
if (VeaUtil.isNullEmpty(result))
return null;
JSONObject json = JSONObject.fromObject(result);
JSONArray array = null;
try {
array = json.optJSONObject("EipAddresses").optJSONArray("EipAddress");
} catch (NullPointerException e) {
throw new Exception("发生错误!\nrequestMessage:" + json.toString());
}
if (array == null || array.isEmpty()){
return null;
}
List<EipAddress> eips = new ArrayList<>();
for (int i = 0, len = array.size(); i < len; i++) {
eips.add(new EipAddress(array.optJSONObject(i)));
}
return eips;
}
/**
* 修改弹性公网IP属性.
*
* @param allocationId 申请id
* @param bandwidth 修改后的弹性 IP 地址带宽,带宽以 Mbps 计算,最大100兆
* @throws Exception
*/
public boolean modifyEipAddressAttribute(String allocationId, int bandwidth) throws Exception {
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
paramMap.put("Action", "ModifyEipAddressAttribute");
paramMap.put("AllocationId", allocationId);
if (bandwidth > 100)
bandwidth = 100;
paramMap.put("Bandwidth", String.valueOf(bandwidth));
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
JSONObject json = JSONObject.fromObject(result);
return VeaUtil.isNullEmpty(json.optString("Message"));
}
/**
* 释放弹性公网IP.
*
* @param allocationId 要执行释放操作的EIP对应的申请id
* @throws Exception
*/
public boolean releaseEipAddress(String allocationId) throws Exception {
Map<String, String> paramMap = VpcUtil.paramMapByPublicParam(param);
paramMap.put("Action", "ReleaseEipAddress");
paramMap.put("AllocationId", allocationId);
VpcUtil.signature(paramMap, param.getAccessKeySecret());
String result = requestResult(paramMap);
JSONObject json = JSONObject.fromObject(result);
return VeaUtil.isNullEmpty(json.optString("Message"));
}
/**
* 获取当前绑定使用的EIP
* @throws Exception
*/
public EipAddress selectUseEip() throws Exception {
List<EipAddress> list = this.describeEipAddresses(null, EipStatus.InUse, null, null, null);
if (list != null && !list.isEmpty()) {
for (EipAddress eip : list) {
if (eip.isUse() && eip.getInstanceId().equalsIgnoreCase(param.getInstanceId())) {
return eip;
}
}
}
return null;
}
/**
* Get Http 请求.
*/
private String requestResult(Map<String, String> paramMap) throws Exception {
String url = "https://vpc.aliyuncs.com/?" + VpcUtil.asUrl(paramMap);
String result = HttpClientUtils.get(url);
return result;
}
private void printInfo(String info) {
System.out.println(info);
logger.info(info);
}
public static void main(String[] args) throws Exception {
VpcPublicParam param=new VpcPublicParam(0);
VpcEipClinet client = new VpcEipClinet(param);
// 释放无用ip
//client.releaseIsNotUseEip(false);
// 自动更换Vpc-Eip
//client.autoUpdateEip();
// 当前使用的Eip
System.out.println(client.selectUseEip());
}
}
| 11,145 | 0.698631 | 0.68552 | 350 | 28.854286 | 24.492422 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.48 | false | false | 12 |
e384d170b5410c4d14d48fa11de0305f2c30f2a0 | 20,435,454,445,471 | 54344fb9cd5a26ec56e074b8188cda7eedde7a39 | /src/main/java/CalculateVolumeSolution.java | 2d36dd0b164cb4744cbc9f6f388fe3a5573f375f | [] | no_license | MichaelBathon/HackerRank | https://github.com/MichaelBathon/HackerRank | b0bd98a89858ceb1b3bca7e925322378d98198d8 | 6ec53889a3c5786d29b55b8b55342218b1308077 | refs/heads/master | 2021-01-10T16:23:28.335000 | 2016-04-01T14:17:36 | 2016-04-01T14:17:36 | 55,237,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import java.security.Permission;
import java.util.Scanner;
/**
* Created by michaelbathon on 2/20/16.
*/
class Volume {
double volume;
public double main(int a){
return Math.pow(a,3);
}
public double main(int l, int b, int h){
return l * b * h;
}
public double main(double radius){
double pie = Math.PI;
double rCubed = Math.pow(radius,3);
double twoThirds = (2d/3d);
volume = twoThirds*pie*rCubed;
return volume;
}
public double main(double radius, double height){
return (Math.PI)*(Math.pow(radius, 2))*height;
}
}
class Display {
public void display(double volume){
System.out.printf("%.3f\n", volume);
}
}
class Calculate{
Scanner scan;
Display output;
Calculate() throws IOException{
scan = new Scanner(System.in);
output = new Display();
if(scan==null)
throw new IOException("Exception thrown");
}
public int getINTVal() throws java.lang.NumberFormatException {
int num = scan.nextInt();
if(num <= 0){
throw new java.lang.NumberFormatException("All the values must be positive");
}
else
return num;
}
public double getDoubleVal() throws java.lang.NumberFormatException {
double num = scan.nextDouble();
if(num <= 0){
throw new java.lang.NumberFormatException("All the values must be positive");
}
else
return num;
}
public static Volume get_Vol() {
return new Volume();
}
}
public class CalculateVolumeSolution {
public static void main(String[] args){
Do_Not_Terminate.forbidExit();
try{
Calculate cal=new Calculate();
int T=cal.getINTVal();
while(T-->0){
double volume = 0.0d;
int ch=cal.getINTVal();
if(ch==1){
int a=cal.getINTVal();
volume=Calculate.get_Vol().main(a);
}else if(ch==2){
int l=cal.getINTVal();
int b=cal.getINTVal();
int h=cal.getINTVal();
volume=Calculate.get_Vol().main(l,b,h);
}else if(ch==3){
double r=cal.getDoubleVal();
volume=Calculate.get_Vol().main(r);
}else if(ch==4){
double r=cal.getDoubleVal();
double h=cal.getDoubleVal();
volume=Calculate.get_Vol().main(r,h);
}
cal.output.display(volume);
}
}
catch (NumberFormatException e) {
System.out.print(e);
} catch (IOException e) {
e.printStackTrace();
}
catch (Do_Not_Terminate.ExitTrappedException e) {
System.out.println("Unsuccessful Termination!!");
}
}
}
/**
*This class prevents the user from using System.exit(0)
* from terminating the program abnormally.
*/
class Do_Not_Terminate {
public static class ExitTrappedException extends SecurityException {}
public static void forbidExit() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
}
| UTF-8 | Java | 3,632 | java | CalculateVolumeSolution.java | Java | [
{
"context": "sion;\nimport java.util.Scanner;\n\n/**\n * Created by michaelbathon on 2/20/16.\n */\n\nclass Volume {\n double volume",
"end": 119,
"score": 0.9812538623809814,
"start": 106,
"tag": "USERNAME",
"value": "michaelbathon"
}
] | null | [] | import java.io.IOException;
import java.security.Permission;
import java.util.Scanner;
/**
* Created by michaelbathon on 2/20/16.
*/
class Volume {
double volume;
public double main(int a){
return Math.pow(a,3);
}
public double main(int l, int b, int h){
return l * b * h;
}
public double main(double radius){
double pie = Math.PI;
double rCubed = Math.pow(radius,3);
double twoThirds = (2d/3d);
volume = twoThirds*pie*rCubed;
return volume;
}
public double main(double radius, double height){
return (Math.PI)*(Math.pow(radius, 2))*height;
}
}
class Display {
public void display(double volume){
System.out.printf("%.3f\n", volume);
}
}
class Calculate{
Scanner scan;
Display output;
Calculate() throws IOException{
scan = new Scanner(System.in);
output = new Display();
if(scan==null)
throw new IOException("Exception thrown");
}
public int getINTVal() throws java.lang.NumberFormatException {
int num = scan.nextInt();
if(num <= 0){
throw new java.lang.NumberFormatException("All the values must be positive");
}
else
return num;
}
public double getDoubleVal() throws java.lang.NumberFormatException {
double num = scan.nextDouble();
if(num <= 0){
throw new java.lang.NumberFormatException("All the values must be positive");
}
else
return num;
}
public static Volume get_Vol() {
return new Volume();
}
}
public class CalculateVolumeSolution {
public static void main(String[] args){
Do_Not_Terminate.forbidExit();
try{
Calculate cal=new Calculate();
int T=cal.getINTVal();
while(T-->0){
double volume = 0.0d;
int ch=cal.getINTVal();
if(ch==1){
int a=cal.getINTVal();
volume=Calculate.get_Vol().main(a);
}else if(ch==2){
int l=cal.getINTVal();
int b=cal.getINTVal();
int h=cal.getINTVal();
volume=Calculate.get_Vol().main(l,b,h);
}else if(ch==3){
double r=cal.getDoubleVal();
volume=Calculate.get_Vol().main(r);
}else if(ch==4){
double r=cal.getDoubleVal();
double h=cal.getDoubleVal();
volume=Calculate.get_Vol().main(r,h);
}
cal.output.display(volume);
}
}
catch (NumberFormatException e) {
System.out.print(e);
} catch (IOException e) {
e.printStackTrace();
}
catch (Do_Not_Terminate.ExitTrappedException e) {
System.out.println("Unsuccessful Termination!!");
}
}
}
/**
*This class prevents the user from using System.exit(0)
* from terminating the program abnormally.
*/
class Do_Not_Terminate {
public static class ExitTrappedException extends SecurityException {}
public static void forbidExit() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
}
| 3,632 | 0.540749 | 0.534967 | 139 | 25.122303 | 21.813948 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.417266 | false | false | 12 |
f1f16903f0f173dafeb9c323dd2cae31bf09f0e2 | 22,900,765,661,774 | 303e506eccd44aab87e33e287c5b0d6626ac05e0 | /service-device/src/main/java/pro/dengyi/myhome/servicedevice/controller/DeviceCategoryController.java | bfef8c60693902c2fcf0c42c036d9b2392038a35 | [] | no_license | BearLaboratory/myhome-backend | https://github.com/BearLaboratory/myhome-backend | a63678fadbe573ae8244551065c1f97aaf32513a | 08c0663f5b81fa3e5383dc9d1069584e621c8947 | refs/heads/master | 2023-05-15T19:24:46.629000 | 2021-06-11T06:11:45 | 2021-06-11T06:11:45 | 372,220,284 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pro.dengyi.myhome.servicedevice.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pro.dengyi.myhome.common.response.BaseResponse;
import pro.dengyi.myhome.common.response.DataResponse;
import pro.dengyi.myhome.common.response.ResponseEnum;
import pro.dengyi.myhome.myhomemodel.business.device.DeviceCategory;
import pro.dengyi.myhome.servicedevice.service.DeviceCategoryService;
import pro.dengyi.myhome.servicedevice.vo.CategoryPageVo;
/**
* 设备类型管理controller
*
* @author DengYi
* @version v1.0
*/
@RestController
@RequestMapping("/deviceCategory")
@Api(tags = "设备类型接口")
public class DeviceCategoryController {
@Autowired
private DeviceCategoryService deviceCategoryService;
@ApiOperation("条件分页查询")
@PostMapping("/page")
public DataResponse<Page<DeviceCategory>> page(@RequestBody CategoryPageVo vo) {
Page<DeviceCategory> page = deviceCategoryService.page(vo);
return new DataResponse<>(ResponseEnum.SUCCESS, page);
}
@ApiOperation("新增或修改")
@PostMapping("/addOrUpdate")
public BaseResponse addOrUpdate(@RequestBody DeviceCategory deviceCategory) {
deviceCategoryService.addOrUpdate(deviceCategory);
return new BaseResponse(ResponseEnum.SUCCESS);
}
@ApiOperation("删除分类")
@PostMapping("/delCategory")
public BaseResponse delCategory(@RequestBody DeviceCategory deviceCategory) {
deviceCategoryService.delCategory(deviceCategory);
return new BaseResponse(ResponseEnum.SUCCESS);
}
}
| UTF-8 | Java | 1,983 | java | DeviceCategoryController.java | Java | [
{
"context": "oryPageVo;\n\n\n/**\n * 设备类型管理controller\n *\n * @author DengYi\n * @version v1.0\n */\n@RestController\n@RequestMapp",
"end": 916,
"score": 0.9996314644813538,
"start": 910,
"tag": "NAME",
"value": "DengYi"
}
] | null | [] | package pro.dengyi.myhome.servicedevice.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pro.dengyi.myhome.common.response.BaseResponse;
import pro.dengyi.myhome.common.response.DataResponse;
import pro.dengyi.myhome.common.response.ResponseEnum;
import pro.dengyi.myhome.myhomemodel.business.device.DeviceCategory;
import pro.dengyi.myhome.servicedevice.service.DeviceCategoryService;
import pro.dengyi.myhome.servicedevice.vo.CategoryPageVo;
/**
* 设备类型管理controller
*
* @author DengYi
* @version v1.0
*/
@RestController
@RequestMapping("/deviceCategory")
@Api(tags = "设备类型接口")
public class DeviceCategoryController {
@Autowired
private DeviceCategoryService deviceCategoryService;
@ApiOperation("条件分页查询")
@PostMapping("/page")
public DataResponse<Page<DeviceCategory>> page(@RequestBody CategoryPageVo vo) {
Page<DeviceCategory> page = deviceCategoryService.page(vo);
return new DataResponse<>(ResponseEnum.SUCCESS, page);
}
@ApiOperation("新增或修改")
@PostMapping("/addOrUpdate")
public BaseResponse addOrUpdate(@RequestBody DeviceCategory deviceCategory) {
deviceCategoryService.addOrUpdate(deviceCategory);
return new BaseResponse(ResponseEnum.SUCCESS);
}
@ApiOperation("删除分类")
@PostMapping("/delCategory")
public BaseResponse delCategory(@RequestBody DeviceCategory deviceCategory) {
deviceCategoryService.delCategory(deviceCategory);
return new BaseResponse(ResponseEnum.SUCCESS);
}
}
| 1,983 | 0.785899 | 0.784863 | 54 | 34.722221 | 26.592548 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.425926 | false | false | 12 |
3c2a9436b61fd80dd3ed0717daff0667f4fc6ff7 | 37,331,855,749,752 | 70d3465495623dc0555c474aee1cdfc520c1206b | /ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/BlinkinLedTest.java | 094936a643c4e32aef5dd7a1e070836eec33b00c | [
"BSD-3-Clause"
] | permissive | formula-r-ftc/ftcapp-skystone | https://github.com/formula-r-ftc/ftcapp-skystone | 531d1012aec18b71246f84cf9c27a5aba0e2f57c | 3632c078a664290b4f0559ed920b5bb3728a53f3 | refs/heads/master | 2021-07-14T10:24:02.866000 | 2020-08-14T19:32:28 | 2020-08-14T19:32:28 | 189,764,755 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.rev.RevBlinkinLedDriver;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
@TeleOp
public class BlinkinLedTest extends LinearOpMode {
private DcMotor IntakeR;
private DcMotor IntakeL;
private RevBlinkinLedDriver blinkin;
private RevBlinkinLedDriver.BlinkinPattern IntakeOn;
private RevBlinkinLedDriver.BlinkinPattern SlowIntakeOn;
private RevBlinkinLedDriver.BlinkinPattern OutakeOn;
private RevBlinkinLedDriver.BlinkinPattern IntakeNOutakeOff;
private ElapsedTime t1 = new ElapsedTime();
private boolean toggleIntakeBoolean = false;
private boolean toggleOutakeBoolean = false;
private void IntakeToggle(){
if (gamepad2.left_trigger > 0.5 && t1.seconds() > 0.5 ){
t1.reset();
toggleIntakeBoolean = true;
toggleOutakeBoolean = false;
}
}
private void IntakeButtons(){
if (gamepad1.a && t1.seconds() > 0.5 ){
toggleIntakeBoolean = true;
toggleOutakeBoolean = false;
}
else if (gamepad1.b){
toggleIntakeBoolean = false;
toggleOutakeBoolean = true;
}
else if (gamepad1.x){
toggleIntakeBoolean = false;
toggleOutakeBoolean = false;
}
}
private void intakeControl(){
if (!gamepad1.right_bumper) {
if (toggleIntakeBoolean) {
blinkin.setPattern(IntakeOn);
IntakeL.setPower(0.5);
IntakeR.setPower(-0.5);
} else if (toggleOutakeBoolean) {
blinkin.setPattern(OutakeOn);
IntakeL.setPower(-0.5);
IntakeR.setPower(0.5);
} else if (!toggleIntakeBoolean && !toggleOutakeBoolean) {
blinkin.setPattern(IntakeNOutakeOff);
IntakeL.setPower(0.0);
IntakeR.setPower(0.0);
}
}
else{
if (toggleIntakeBoolean) {
blinkin.setPattern(SlowIntakeOn);
IntakeL.setPower(0.3);
IntakeR.setPower(-0.3);
} else if (toggleOutakeBoolean) {
blinkin.setPattern(OutakeOn);
IntakeL.setPower(-0.5);
IntakeR.setPower(0.5);
} else if (!toggleIntakeBoolean && !toggleOutakeBoolean) {
blinkin.setPattern(IntakeNOutakeOff);
IntakeL.setPower(0.0);
IntakeR.setPower(0.0);
}
}
}
private void OutakeToggle(){
if (gamepad2.right_trigger > 0.5 && t1.seconds() > 0.5 ){
t1.reset();
toggleOutakeBoolean=true;
toggleIntakeBoolean=false;
}
}
@Override
public void runOpMode() {
blinkin = hardwareMap.get(RevBlinkinLedDriver.class, "blinky");
IntakeR = hardwareMap.get(DcMotor.class, "IntakeR");
IntakeL = hardwareMap.get(DcMotor.class, "IntakeL");
IntakeNOutakeOff = RevBlinkinLedDriver.BlinkinPattern.WHITE;
IntakeOn = RevBlinkinLedDriver.BlinkinPattern.RED;
OutakeOn = RevBlinkinLedDriver.BlinkinPattern.GOLD;
SlowIntakeOn = RevBlinkinLedDriver.BlinkinPattern.STROBE_RED;
waitForStart();
while (opModeIsActive()) {
IntakeToggle();
OutakeToggle();
IntakeButtons();
intakeControl();
}
}
}
| UTF-8 | Java | 3,624 | java | BlinkinLedTest.java | Java | [] | null | [] | package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.rev.RevBlinkinLedDriver;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
@TeleOp
public class BlinkinLedTest extends LinearOpMode {
private DcMotor IntakeR;
private DcMotor IntakeL;
private RevBlinkinLedDriver blinkin;
private RevBlinkinLedDriver.BlinkinPattern IntakeOn;
private RevBlinkinLedDriver.BlinkinPattern SlowIntakeOn;
private RevBlinkinLedDriver.BlinkinPattern OutakeOn;
private RevBlinkinLedDriver.BlinkinPattern IntakeNOutakeOff;
private ElapsedTime t1 = new ElapsedTime();
private boolean toggleIntakeBoolean = false;
private boolean toggleOutakeBoolean = false;
private void IntakeToggle(){
if (gamepad2.left_trigger > 0.5 && t1.seconds() > 0.5 ){
t1.reset();
toggleIntakeBoolean = true;
toggleOutakeBoolean = false;
}
}
private void IntakeButtons(){
if (gamepad1.a && t1.seconds() > 0.5 ){
toggleIntakeBoolean = true;
toggleOutakeBoolean = false;
}
else if (gamepad1.b){
toggleIntakeBoolean = false;
toggleOutakeBoolean = true;
}
else if (gamepad1.x){
toggleIntakeBoolean = false;
toggleOutakeBoolean = false;
}
}
private void intakeControl(){
if (!gamepad1.right_bumper) {
if (toggleIntakeBoolean) {
blinkin.setPattern(IntakeOn);
IntakeL.setPower(0.5);
IntakeR.setPower(-0.5);
} else if (toggleOutakeBoolean) {
blinkin.setPattern(OutakeOn);
IntakeL.setPower(-0.5);
IntakeR.setPower(0.5);
} else if (!toggleIntakeBoolean && !toggleOutakeBoolean) {
blinkin.setPattern(IntakeNOutakeOff);
IntakeL.setPower(0.0);
IntakeR.setPower(0.0);
}
}
else{
if (toggleIntakeBoolean) {
blinkin.setPattern(SlowIntakeOn);
IntakeL.setPower(0.3);
IntakeR.setPower(-0.3);
} else if (toggleOutakeBoolean) {
blinkin.setPattern(OutakeOn);
IntakeL.setPower(-0.5);
IntakeR.setPower(0.5);
} else if (!toggleIntakeBoolean && !toggleOutakeBoolean) {
blinkin.setPattern(IntakeNOutakeOff);
IntakeL.setPower(0.0);
IntakeR.setPower(0.0);
}
}
}
private void OutakeToggle(){
if (gamepad2.right_trigger > 0.5 && t1.seconds() > 0.5 ){
t1.reset();
toggleOutakeBoolean=true;
toggleIntakeBoolean=false;
}
}
@Override
public void runOpMode() {
blinkin = hardwareMap.get(RevBlinkinLedDriver.class, "blinky");
IntakeR = hardwareMap.get(DcMotor.class, "IntakeR");
IntakeL = hardwareMap.get(DcMotor.class, "IntakeL");
IntakeNOutakeOff = RevBlinkinLedDriver.BlinkinPattern.WHITE;
IntakeOn = RevBlinkinLedDriver.BlinkinPattern.RED;
OutakeOn = RevBlinkinLedDriver.BlinkinPattern.GOLD;
SlowIntakeOn = RevBlinkinLedDriver.BlinkinPattern.STROBE_RED;
waitForStart();
while (opModeIsActive()) {
IntakeToggle();
OutakeToggle();
IntakeButtons();
intakeControl();
}
}
}
| 3,624 | 0.602097 | 0.589404 | 105 | 33.504761 | 20.018621 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580952 | false | false | 12 |
b38101ea344fbdb53dac5e63268fc5b65e74df2d | 6,700,149,046,379 | f663a0d8c153bb77869ff7fb50d4b4c5c209b027 | /src/main/java/org/sonar/plugins/modelbus/smmparser/impl/SoftwareMetricsMetamodel2FactoryImpl.java | 58797ccdc8c4941a69972407937612aa2fc69bdf | [] | no_license | arsenij-solovjev/sonar-modelbus-plugin | https://github.com/arsenij-solovjev/sonar-modelbus-plugin | 3301f710dd8383072c441195ffa6f87bb3aa80e5 | c4b6166e07eedd3ef79d7b8f51bdaea0e2ba5030 | refs/heads/master | 2020-09-21T14:18:41.548000 | 2013-02-20T10:03:45 | 2013-02-20T10:03:45 | 6,535,088 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*/
package org.sonar.plugins.modelbus.smmparser.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.sonar.plugins.modelbus.smmparser.*;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class SoftwareMetricsMetamodel2FactoryImpl extends EFactoryImpl implements SoftwareMetricsMetamodel2Factory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static SoftwareMetricsMetamodel2Factory init() {
try {
SoftwareMetricsMetamodel2Factory theSoftwareMetricsMetamodel2Factory = (SoftwareMetricsMetamodel2Factory)EPackage.Registry.INSTANCE.getEFactory("http://www.omg.org/ADM/SMM2");
if (theSoftwareMetricsMetamodel2Factory != null) {
return theSoftwareMetricsMetamodel2Factory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new SoftwareMetricsMetamodel2FactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SoftwareMetricsMetamodel2FactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case SoftwareMetricsMetamodel2Package.AGGREGATED_MEASUREMENT: return createAggregatedMeasurement();
case SoftwareMetricsMetamodel2Package.BINARY_MEASURE: return createBinaryMeasure();
case SoftwareMetricsMetamodel2Package.BINARY_MEASUREMENT: return createBinaryMeasurement();
case SoftwareMetricsMetamodel2Package.CATEGORY_RELATIONSHIP: return createCategoryRelationship();
case SoftwareMetricsMetamodel2Package.CHARACTERISTIC: return createCharacteristic();
case SoftwareMetricsMetamodel2Package.COLLECTIVE_MEASURE: return createCollectiveMeasure();
case SoftwareMetricsMetamodel2Package.COLLECTIVE_MEASUREMENT: return createCollectiveMeasurement();
case SoftwareMetricsMetamodel2Package.COUNT: return createCount();
case SoftwareMetricsMetamodel2Package.COUNTING: return createCounting();
case SoftwareMetricsMetamodel2Package.DATE: return createDate();
case SoftwareMetricsMetamodel2Package.DIMENSIONAL_MEASURE: return createDimensionalMeasure();
case SoftwareMetricsMetamodel2Package.DIRECT_MEASURE: return createDirectMeasure();
case SoftwareMetricsMetamodel2Package.DIRECT_MEASUREMENT: return createDirectMeasurement();
case SoftwareMetricsMetamodel2Package.DOCUMENT_ROOT: return createDocumentRoot();
case SoftwareMetricsMetamodel2Package.GRADE: return createGrade();
case SoftwareMetricsMetamodel2Package.NAMED_MEASURE: return createNamedMeasure();
case SoftwareMetricsMetamodel2Package.NAMED_MEASUREMENT: return createNamedMeasurement();
case SoftwareMetricsMetamodel2Package.OBSERVATION: return createObservation();
case SoftwareMetricsMetamodel2Package.RANKING: return createRanking();
case SoftwareMetricsMetamodel2Package.RANKING_INTERVAL: return createRankingInterval();
case SoftwareMetricsMetamodel2Package.RATIO_MEASURE: return createRatioMeasure();
case SoftwareMetricsMetamodel2Package.RATIO_MEASUREMENT: return createRatioMeasurement();
case SoftwareMetricsMetamodel2Package.RESCALED_MEASURE: return createRescaledMeasure();
case SoftwareMetricsMetamodel2Package.RE_SCALED_MEASUREMENT: return createReScaledMeasurement();
case SoftwareMetricsMetamodel2Package.SCOPE: return createScope();
case SoftwareMetricsMetamodel2Package.SMM_CATEGORY: return createSMMCategory();
case SoftwareMetricsMetamodel2Package.SMM_MODEL: return createSMMModel();
case SoftwareMetricsMetamodel2Package.TIMESTAMP: return createTimestamp();
case SoftwareMetricsMetamodel2Package.SMM_NAMED_ELEMENT: return createSMMNamedElement();
case SoftwareMetricsMetamodel2Package.MEASURE_UTIL: return createMeasureUtil();
case SoftwareMetricsMetamodel2Package.AUDIT: return createAudit();
case SoftwareMetricsMetamodel2Package.MEASURE_AGGREGATION: return createMeasureAggregation();
case SoftwareMetricsMetamodel2Package.MEASUREMENT_AGGREGATION: return createMeasurementAggregation();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case SoftwareMetricsMetamodel2Package.ACCUMULATOR:
return createAccumulatorFromString(eDataType, initialValue);
case SoftwareMetricsMetamodel2Package.ACCUMULATOR_OBJECT:
return createAccumulatorObjectFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case SoftwareMetricsMetamodel2Package.ACCUMULATOR:
return convertAccumulatorToString(eDataType, instanceValue);
case SoftwareMetricsMetamodel2Package.ACCUMULATOR_OBJECT:
return convertAccumulatorObjectToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AggregatedMeasurement createAggregatedMeasurement() {
AggregatedMeasurementImpl aggregatedMeasurement = new AggregatedMeasurementImpl();
return aggregatedMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BinaryMeasure createBinaryMeasure() {
BinaryMeasureImpl binaryMeasure = new BinaryMeasureImpl();
return binaryMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BinaryMeasurement createBinaryMeasurement() {
BinaryMeasurementImpl binaryMeasurement = new BinaryMeasurementImpl();
return binaryMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CategoryRelationship createCategoryRelationship() {
CategoryRelationshipImpl categoryRelationship = new CategoryRelationshipImpl();
return categoryRelationship;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Characteristic createCharacteristic() {
CharacteristicImpl characteristic = new CharacteristicImpl();
return characteristic;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CollectiveMeasure createCollectiveMeasure() {
CollectiveMeasureImpl collectiveMeasure = new CollectiveMeasureImpl();
return collectiveMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CollectiveMeasurement createCollectiveMeasurement() {
CollectiveMeasurementImpl collectiveMeasurement = new CollectiveMeasurementImpl();
return collectiveMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Count createCount() {
CountImpl count = new CountImpl();
return count;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Counting createCounting() {
CountingImpl counting = new CountingImpl();
return counting;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Date createDate() {
DateImpl date = new DateImpl();
return date;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DimensionalMeasure createDimensionalMeasure() {
DimensionalMeasureImpl dimensionalMeasure = new DimensionalMeasureImpl();
return dimensionalMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DirectMeasure createDirectMeasure() {
DirectMeasureImpl directMeasure = new DirectMeasureImpl();
return directMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DirectMeasurement createDirectMeasurement() {
DirectMeasurementImpl directMeasurement = new DirectMeasurementImpl();
return directMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Grade createGrade() {
GradeImpl grade = new GradeImpl();
return grade;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamedMeasure createNamedMeasure() {
NamedMeasureImpl namedMeasure = new NamedMeasureImpl();
return namedMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamedMeasurement createNamedMeasurement() {
NamedMeasurementImpl namedMeasurement = new NamedMeasurementImpl();
return namedMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Observation createObservation() {
ObservationImpl observation = new ObservationImpl();
return observation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Ranking createRanking() {
RankingImpl ranking = new RankingImpl();
return ranking;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RankingInterval createRankingInterval() {
RankingIntervalImpl rankingInterval = new RankingIntervalImpl();
return rankingInterval;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RatioMeasure createRatioMeasure() {
RatioMeasureImpl ratioMeasure = new RatioMeasureImpl();
return ratioMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RatioMeasurement createRatioMeasurement() {
RatioMeasurementImpl ratioMeasurement = new RatioMeasurementImpl();
return ratioMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RescaledMeasure createRescaledMeasure() {
RescaledMeasureImpl rescaledMeasure = new RescaledMeasureImpl();
return rescaledMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ReScaledMeasurement createReScaledMeasurement() {
ReScaledMeasurementImpl reScaledMeasurement = new ReScaledMeasurementImpl();
return reScaledMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Scope createScope() {
ScopeImpl scope = new ScopeImpl();
return scope;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SMMCategory createSMMCategory() {
SMMCategoryImpl smmCategory = new SMMCategoryImpl();
return smmCategory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SMMModel createSMMModel() {
SMMModelImpl smmModel = new SMMModelImpl();
return smmModel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Timestamp createTimestamp() {
TimestampImpl timestamp = new TimestampImpl();
return timestamp;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SMMNamedElement createSMMNamedElement() {
SMMNamedElementImpl smmNamedElement = new SMMNamedElementImpl();
return smmNamedElement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeasureUtil createMeasureUtil() {
MeasureUtilImpl measureUtil = new MeasureUtilImpl();
return measureUtil;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Audit createAudit() {
AuditImpl audit = new AuditImpl();
return audit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeasureAggregation createMeasureAggregation() {
MeasureAggregationImpl measureAggregation = new MeasureAggregationImpl();
return measureAggregation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeasurementAggregation createMeasurementAggregation() {
MeasurementAggregationImpl measurementAggregation = new MeasurementAggregationImpl();
return measurementAggregation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Accumulator createAccumulatorFromString(EDataType eDataType, String initialValue) {
Accumulator result = Accumulator.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertAccumulatorToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Accumulator createAccumulatorObjectFromString(EDataType eDataType, String initialValue) {
return createAccumulatorFromString(org.sonar.plugins.modelbus.smmparser.SoftwareMetricsMetamodel2Package.Literals.ACCUMULATOR, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertAccumulatorObjectToString(EDataType eDataType, Object instanceValue) {
return convertAccumulatorToString(org.sonar.plugins.modelbus.smmparser.SoftwareMetricsMetamodel2Package.Literals.ACCUMULATOR, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SoftwareMetricsMetamodel2Package getSoftwareMetricsMetamodel2Package() {
return (SoftwareMetricsMetamodel2Package)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static SoftwareMetricsMetamodel2Package getPackage() {
return SoftwareMetricsMetamodel2Package.eINSTANCE;
}
} //SoftwareMetricsMetamodel2FactoryImpl
| UTF-8 | Java | 15,352 | java | SoftwareMetricsMetamodel2FactoryImpl.java | Java | [] | null | [] | /**
*/
package org.sonar.plugins.modelbus.smmparser.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.sonar.plugins.modelbus.smmparser.*;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class SoftwareMetricsMetamodel2FactoryImpl extends EFactoryImpl implements SoftwareMetricsMetamodel2Factory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static SoftwareMetricsMetamodel2Factory init() {
try {
SoftwareMetricsMetamodel2Factory theSoftwareMetricsMetamodel2Factory = (SoftwareMetricsMetamodel2Factory)EPackage.Registry.INSTANCE.getEFactory("http://www.omg.org/ADM/SMM2");
if (theSoftwareMetricsMetamodel2Factory != null) {
return theSoftwareMetricsMetamodel2Factory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new SoftwareMetricsMetamodel2FactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SoftwareMetricsMetamodel2FactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case SoftwareMetricsMetamodel2Package.AGGREGATED_MEASUREMENT: return createAggregatedMeasurement();
case SoftwareMetricsMetamodel2Package.BINARY_MEASURE: return createBinaryMeasure();
case SoftwareMetricsMetamodel2Package.BINARY_MEASUREMENT: return createBinaryMeasurement();
case SoftwareMetricsMetamodel2Package.CATEGORY_RELATIONSHIP: return createCategoryRelationship();
case SoftwareMetricsMetamodel2Package.CHARACTERISTIC: return createCharacteristic();
case SoftwareMetricsMetamodel2Package.COLLECTIVE_MEASURE: return createCollectiveMeasure();
case SoftwareMetricsMetamodel2Package.COLLECTIVE_MEASUREMENT: return createCollectiveMeasurement();
case SoftwareMetricsMetamodel2Package.COUNT: return createCount();
case SoftwareMetricsMetamodel2Package.COUNTING: return createCounting();
case SoftwareMetricsMetamodel2Package.DATE: return createDate();
case SoftwareMetricsMetamodel2Package.DIMENSIONAL_MEASURE: return createDimensionalMeasure();
case SoftwareMetricsMetamodel2Package.DIRECT_MEASURE: return createDirectMeasure();
case SoftwareMetricsMetamodel2Package.DIRECT_MEASUREMENT: return createDirectMeasurement();
case SoftwareMetricsMetamodel2Package.DOCUMENT_ROOT: return createDocumentRoot();
case SoftwareMetricsMetamodel2Package.GRADE: return createGrade();
case SoftwareMetricsMetamodel2Package.NAMED_MEASURE: return createNamedMeasure();
case SoftwareMetricsMetamodel2Package.NAMED_MEASUREMENT: return createNamedMeasurement();
case SoftwareMetricsMetamodel2Package.OBSERVATION: return createObservation();
case SoftwareMetricsMetamodel2Package.RANKING: return createRanking();
case SoftwareMetricsMetamodel2Package.RANKING_INTERVAL: return createRankingInterval();
case SoftwareMetricsMetamodel2Package.RATIO_MEASURE: return createRatioMeasure();
case SoftwareMetricsMetamodel2Package.RATIO_MEASUREMENT: return createRatioMeasurement();
case SoftwareMetricsMetamodel2Package.RESCALED_MEASURE: return createRescaledMeasure();
case SoftwareMetricsMetamodel2Package.RE_SCALED_MEASUREMENT: return createReScaledMeasurement();
case SoftwareMetricsMetamodel2Package.SCOPE: return createScope();
case SoftwareMetricsMetamodel2Package.SMM_CATEGORY: return createSMMCategory();
case SoftwareMetricsMetamodel2Package.SMM_MODEL: return createSMMModel();
case SoftwareMetricsMetamodel2Package.TIMESTAMP: return createTimestamp();
case SoftwareMetricsMetamodel2Package.SMM_NAMED_ELEMENT: return createSMMNamedElement();
case SoftwareMetricsMetamodel2Package.MEASURE_UTIL: return createMeasureUtil();
case SoftwareMetricsMetamodel2Package.AUDIT: return createAudit();
case SoftwareMetricsMetamodel2Package.MEASURE_AGGREGATION: return createMeasureAggregation();
case SoftwareMetricsMetamodel2Package.MEASUREMENT_AGGREGATION: return createMeasurementAggregation();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case SoftwareMetricsMetamodel2Package.ACCUMULATOR:
return createAccumulatorFromString(eDataType, initialValue);
case SoftwareMetricsMetamodel2Package.ACCUMULATOR_OBJECT:
return createAccumulatorObjectFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case SoftwareMetricsMetamodel2Package.ACCUMULATOR:
return convertAccumulatorToString(eDataType, instanceValue);
case SoftwareMetricsMetamodel2Package.ACCUMULATOR_OBJECT:
return convertAccumulatorObjectToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AggregatedMeasurement createAggregatedMeasurement() {
AggregatedMeasurementImpl aggregatedMeasurement = new AggregatedMeasurementImpl();
return aggregatedMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BinaryMeasure createBinaryMeasure() {
BinaryMeasureImpl binaryMeasure = new BinaryMeasureImpl();
return binaryMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BinaryMeasurement createBinaryMeasurement() {
BinaryMeasurementImpl binaryMeasurement = new BinaryMeasurementImpl();
return binaryMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CategoryRelationship createCategoryRelationship() {
CategoryRelationshipImpl categoryRelationship = new CategoryRelationshipImpl();
return categoryRelationship;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Characteristic createCharacteristic() {
CharacteristicImpl characteristic = new CharacteristicImpl();
return characteristic;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CollectiveMeasure createCollectiveMeasure() {
CollectiveMeasureImpl collectiveMeasure = new CollectiveMeasureImpl();
return collectiveMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CollectiveMeasurement createCollectiveMeasurement() {
CollectiveMeasurementImpl collectiveMeasurement = new CollectiveMeasurementImpl();
return collectiveMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Count createCount() {
CountImpl count = new CountImpl();
return count;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Counting createCounting() {
CountingImpl counting = new CountingImpl();
return counting;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Date createDate() {
DateImpl date = new DateImpl();
return date;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DimensionalMeasure createDimensionalMeasure() {
DimensionalMeasureImpl dimensionalMeasure = new DimensionalMeasureImpl();
return dimensionalMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DirectMeasure createDirectMeasure() {
DirectMeasureImpl directMeasure = new DirectMeasureImpl();
return directMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DirectMeasurement createDirectMeasurement() {
DirectMeasurementImpl directMeasurement = new DirectMeasurementImpl();
return directMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Grade createGrade() {
GradeImpl grade = new GradeImpl();
return grade;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamedMeasure createNamedMeasure() {
NamedMeasureImpl namedMeasure = new NamedMeasureImpl();
return namedMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamedMeasurement createNamedMeasurement() {
NamedMeasurementImpl namedMeasurement = new NamedMeasurementImpl();
return namedMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Observation createObservation() {
ObservationImpl observation = new ObservationImpl();
return observation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Ranking createRanking() {
RankingImpl ranking = new RankingImpl();
return ranking;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RankingInterval createRankingInterval() {
RankingIntervalImpl rankingInterval = new RankingIntervalImpl();
return rankingInterval;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RatioMeasure createRatioMeasure() {
RatioMeasureImpl ratioMeasure = new RatioMeasureImpl();
return ratioMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RatioMeasurement createRatioMeasurement() {
RatioMeasurementImpl ratioMeasurement = new RatioMeasurementImpl();
return ratioMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RescaledMeasure createRescaledMeasure() {
RescaledMeasureImpl rescaledMeasure = new RescaledMeasureImpl();
return rescaledMeasure;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ReScaledMeasurement createReScaledMeasurement() {
ReScaledMeasurementImpl reScaledMeasurement = new ReScaledMeasurementImpl();
return reScaledMeasurement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Scope createScope() {
ScopeImpl scope = new ScopeImpl();
return scope;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SMMCategory createSMMCategory() {
SMMCategoryImpl smmCategory = new SMMCategoryImpl();
return smmCategory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SMMModel createSMMModel() {
SMMModelImpl smmModel = new SMMModelImpl();
return smmModel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Timestamp createTimestamp() {
TimestampImpl timestamp = new TimestampImpl();
return timestamp;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SMMNamedElement createSMMNamedElement() {
SMMNamedElementImpl smmNamedElement = new SMMNamedElementImpl();
return smmNamedElement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeasureUtil createMeasureUtil() {
MeasureUtilImpl measureUtil = new MeasureUtilImpl();
return measureUtil;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Audit createAudit() {
AuditImpl audit = new AuditImpl();
return audit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeasureAggregation createMeasureAggregation() {
MeasureAggregationImpl measureAggregation = new MeasureAggregationImpl();
return measureAggregation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeasurementAggregation createMeasurementAggregation() {
MeasurementAggregationImpl measurementAggregation = new MeasurementAggregationImpl();
return measurementAggregation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Accumulator createAccumulatorFromString(EDataType eDataType, String initialValue) {
Accumulator result = Accumulator.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertAccumulatorToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Accumulator createAccumulatorObjectFromString(EDataType eDataType, String initialValue) {
return createAccumulatorFromString(org.sonar.plugins.modelbus.smmparser.SoftwareMetricsMetamodel2Package.Literals.ACCUMULATOR, initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertAccumulatorObjectToString(EDataType eDataType, Object instanceValue) {
return convertAccumulatorToString(org.sonar.plugins.modelbus.smmparser.SoftwareMetricsMetamodel2Package.Literals.ACCUMULATOR, instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SoftwareMetricsMetamodel2Package getSoftwareMetricsMetamodel2Package() {
return (SoftwareMetricsMetamodel2Package)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static SoftwareMetricsMetamodel2Package getPackage() {
return SoftwareMetricsMetamodel2Package.eINSTANCE;
}
} //SoftwareMetricsMetamodel2FactoryImpl
| 15,352 | 0.673463 | 0.669815 | 519 | 28.107901 | 29.80547 | 182 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529865 | false | false | 12 |
182f81e49bd8f6bdfb470f0103446f48f82300fd | 34,548,716,961,495 | 4815691a93095c3b52013b6ced025f2fba495154 | /core-customize/hybris/bin/modules/sap-customer/sapcustomerb2b/testsrc/com/sap/hybris/sapcustomerb2b/outbound/B2BCustomerExportServiceTest.java | 4acf99c908d73de53e88e6ea773e3a63ec029926 | [
"Apache-2.0"
] | permissive | karthik-git-user/SAP-Stage | https://github.com/karthik-git-user/SAP-Stage | fd6fd0b7a2436b690eee08a2c2b8d4e086665c80 | 72487ab521e7e2411f1b081615817d099edf9744 | refs/heads/master | 2022-12-20T04:50:04.840000 | 2020-10-05T21:10:28 | 2020-10-05T21:10:28 | 301,515,436 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
*/
package com.sap.hybris.sapcustomerb2b.outbound;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_B2BUNIT;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_EMAIL;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_FIRST_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_LAST_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_SESSION_LANGUAGE;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_TITLE_CODE;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.CUSTOMER_ID;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_CUSTOMER_ID;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_EMAIL;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_FIRST_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_LAST_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_SESSION_LANGUAGE;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_TITLE;
import static com.sap.hybris.sapcustomerb2b.constants.Sapcustomerb2bConstants.RAW_HYBRIS_B2B_CUSTOMER;
import static com.sap.hybris.sapcustomerb2b.constants.Sapcustomerb2bConstants.SAPCONTACT_OUTBOUND_FEED;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.sap.hybris.sapcustomerb2c.outbound.CustomerAddressReplicationUtilityService;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.b2b.model.B2BCustomerModel;
import de.hybris.platform.b2b.model.B2BUnitModel;
import de.hybris.platform.commerceservices.strategies.CustomerNameStrategy;
import de.hybris.platform.core.model.c2l.LanguageModel;
import de.hybris.platform.core.model.user.TitleModel;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import com.hybris.datahub.core.rest.DataHubCommunicationException;
import com.hybris.datahub.core.rest.DataHubOutboundException;
import com.hybris.datahub.core.services.DataHubOutboundService;
import org.mockito.MockitoAnnotations;
@UnitTest
public class B2BCustomerExportServiceTest {
@InjectMocks
private final B2BCustomerExportService b2BCustomerExportService = new B2BCustomerExportService();
@Mock
private final CustomerNameStrategy customerNameStrategy = mock(CustomerNameStrategy.class);
@Mock
private final B2BCustomerModel b2bCustomerModel = mock(B2BCustomerModel.class);
@Mock
private final DataHubOutboundService dataHubOutboundService = mock(DataHubOutboundService.class);
@Mock
private CustomerAddressReplicationUtilityService customerAddressReplicationUtilityService = mock(CustomerAddressReplicationUtilityService.class);
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSendB2BContactData() throws InterceptorException {
// given
mockBaseCustomerData();
Map<String, String> batchIdAttributes = new HashMap<String, String>();
batchIdAttributes.put("dh_batchId", "000001");
batchIdAttributes.put("dh_sourceId", "HYBRIS");
batchIdAttributes.put("dh_type", "DH_TYPE");
b2BCustomerExportService.setBatchIdAttributes(batchIdAttributes);
final List<Map<String, Object>> b2bContactData = new ArrayList<>();
b2bContactData.add(b2BCustomerExportService.prepareB2BCustomerData(b2bCustomerModel, "de"));
b2BCustomerExportService.setFeed(SAPCONTACT_OUTBOUND_FEED);
b2BCustomerExportService.setDataHubOutboundService(dataHubOutboundService);
b2BCustomerExportService.sendRawItemsToDataHub(RAW_HYBRIS_B2B_CUSTOMER, b2bContactData);
try {
verify(dataHubOutboundService, times(1)).sendToDataHub(SAPCONTACT_OUTBOUND_FEED, RAW_HYBRIS_B2B_CUSTOMER,
b2bContactData);
} catch (final DataHubCommunicationException e) {
fail("Error processing sending data to Data Hub. DataHubCommunicationException: " + e.getMessage());
} catch (final DataHubOutboundException e) {
fail("Error processing sending data to Data Hub. DataHubOutboundException: " + e.getMessage());
}
}
@Test
public void testNotSendEmptyB2BContactDataNull() throws InterceptorException {
// given
final List<Map<String, Object>> b2bContactData = null;
b2BCustomerExportService.sendRawItemsToDataHub(RAW_HYBRIS_B2B_CUSTOMER, b2bContactData);
try {
verify(dataHubOutboundService, times(0)).sendToDataHub("DEFAULT_FEED", RAW_HYBRIS_B2B_CUSTOMER, b2bContactData);
} catch (final DataHubCommunicationException e) {
fail("Error processing sending data to Data Hub. DataHubCommunicationException: " + e.getMessage());
} catch (final DataHubOutboundException e) {
fail("Error processing sending data to Data Hub. DataHubOutboundException: " + e.getMessage());
}
}
@Test
public void testPrepareB2BContactDataNoLnaguage() throws InterceptorException {
mockBaseCustomerData();
Map<String, String> batchIdAttributes = new HashMap<String, String>();
batchIdAttributes.put("dh_batchId", "000001");
batchIdAttributes.put("dh_sourceId", "HYBRIS");
batchIdAttributes.put("dh_type", "DH_TYPE");
b2BCustomerExportService.setBatchIdAttributes(batchIdAttributes);
final TitleModel title = mock(TitleModel.class);
given(title.getCode()).willReturn(B2BCUSTOMER_TITLE_CODE);
given(b2bCustomerModel.getTitle()).willReturn(title);
final Map<String, Object> b2bCustomerData = b2BCustomerExportService.prepareB2BCustomerData(b2bCustomerModel, "de");
checkBaseCustomerData(b2bCustomerData);
Assert.assertEquals(b2bCustomerData.get(KEY_TITLE), B2BCUSTOMER_TITLE_CODE);
Assert.assertEquals(b2bCustomerData.get(KEY_SESSION_LANGUAGE), "de");
}
@Test
public void testPrepareB2BCustomerDataNoLanguageNoTitleCode() throws InterceptorException {
// given
mockBaseCustomerData();
Map<String, String> batchIdAttributes = new HashMap<String, String>();
batchIdAttributes.put("dh_batchId", "000001");
batchIdAttributes.put("dh_sourceId", "HYBRIS");
batchIdAttributes.put("dh_type", "DH_TYPE");
b2BCustomerExportService.setBatchIdAttributes(batchIdAttributes);
final Map<String, Object> b2bCustomerData = b2BCustomerExportService.prepareB2BCustomerData(b2bCustomerModel, "de");
checkBaseCustomerData(b2bCustomerData);
Assert.assertEquals(b2bCustomerData.get(KEY_TITLE), null);
Assert.assertEquals(b2bCustomerData.get(KEY_SESSION_LANGUAGE), "de");
}
@Test
public void testPrepareB2BContactData() throws InterceptorException {
// given
mockBaseCustomerData();
Map<String, String> batchIdAttributes = new HashMap<String, String>();
batchIdAttributes.put("dh_batchId", "000001");
batchIdAttributes.put("dh_sourceId", "HYBRIS");
batchIdAttributes.put("dh_type", "DH_TYPE");
b2BCustomerExportService.setBatchIdAttributes(batchIdAttributes);
final TitleModel title = mock(TitleModel.class);
given(title.getCode()).willReturn(B2BCUSTOMER_TITLE_CODE);
given(b2bCustomerModel.getTitle()).willReturn(title);
final LanguageModel languageModel = mock(LanguageModel.class);
given(languageModel.getIsocode()).willReturn(B2BCUSTOMER_SESSION_LANGUAGE);
given(b2bCustomerModel.getSessionLanguage()).willReturn(languageModel);
final Map<String, Object> b2bCustomerData = b2BCustomerExportService.prepareB2BCustomerData(b2bCustomerModel, "de");
checkBaseCustomerData(b2bCustomerData);
Assert.assertEquals(b2bCustomerData.get(KEY_SESSION_LANGUAGE), B2BCUSTOMER_SESSION_LANGUAGE);
Assert.assertEquals(b2bCustomerData.get(KEY_TITLE), B2BCUSTOMER_TITLE_CODE);
}
protected void mockBaseCustomerData() {
final B2BUnitModel b2bUnit = mock(B2BUnitModel.class);
given(b2bCustomerModel.getDefaultB2BUnit()).willReturn(b2bUnit);
given(b2bCustomerModel.getDefaultB2BUnit().getUid()).willReturn(B2BCUSTOMER_B2BUNIT);
given(b2bCustomerModel.getEmail()).willReturn(B2BCUSTOMER_EMAIL);
given(b2bCustomerModel.getName()).willReturn(B2BCUSTOMER_NAME);
final String[] names = new String[]
{B2BCUSTOMER_FIRST_NAME, B2BCUSTOMER_LAST_NAME};
given(customerNameStrategy.splitName(b2bCustomerModel.getName())).willReturn(names);
b2BCustomerExportService.setCustomerNameStrategy(customerNameStrategy);
given(b2bCustomerModel.getCustomerID()).willReturn(CUSTOMER_ID);
given(customerAddressReplicationUtilityService.findDefaultAddress(b2bCustomerModel, null)).willReturn(null);
}
protected void checkBaseCustomerData(final Map<String, Object> b2bContactData) {
Assert.assertFalse(b2bContactData.isEmpty());
Assert.assertEquals(b2bContactData.get(KEY_EMAIL), B2BCUSTOMER_EMAIL);
Assert.assertEquals(b2bContactData.get(KEY_CUSTOMER_ID), CUSTOMER_ID);
Assert.assertEquals(b2bContactData.get(KEY_FIRST_NAME), B2BCUSTOMER_FIRST_NAME);
Assert.assertEquals(b2bContactData.get(KEY_LAST_NAME), B2BCUSTOMER_LAST_NAME);
}
} | UTF-8 | Java | 9,634 | java | B2BCustomerExportServiceTest.java | Java | [] | null | [] | /*
* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
*/
package com.sap.hybris.sapcustomerb2b.outbound;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_B2BUNIT;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_EMAIL;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_FIRST_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_LAST_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_SESSION_LANGUAGE;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.B2BCUSTOMER_TITLE_CODE;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.CUSTOMER_ID;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_CUSTOMER_ID;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_EMAIL;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_FIRST_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_LAST_NAME;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_SESSION_LANGUAGE;
import static com.sap.hybris.sapcustomerb2b.CustomerB2BConstantsUtils.KEY_TITLE;
import static com.sap.hybris.sapcustomerb2b.constants.Sapcustomerb2bConstants.RAW_HYBRIS_B2B_CUSTOMER;
import static com.sap.hybris.sapcustomerb2b.constants.Sapcustomerb2bConstants.SAPCONTACT_OUTBOUND_FEED;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.sap.hybris.sapcustomerb2c.outbound.CustomerAddressReplicationUtilityService;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.b2b.model.B2BCustomerModel;
import de.hybris.platform.b2b.model.B2BUnitModel;
import de.hybris.platform.commerceservices.strategies.CustomerNameStrategy;
import de.hybris.platform.core.model.c2l.LanguageModel;
import de.hybris.platform.core.model.user.TitleModel;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import com.hybris.datahub.core.rest.DataHubCommunicationException;
import com.hybris.datahub.core.rest.DataHubOutboundException;
import com.hybris.datahub.core.services.DataHubOutboundService;
import org.mockito.MockitoAnnotations;
@UnitTest
public class B2BCustomerExportServiceTest {
@InjectMocks
private final B2BCustomerExportService b2BCustomerExportService = new B2BCustomerExportService();
@Mock
private final CustomerNameStrategy customerNameStrategy = mock(CustomerNameStrategy.class);
@Mock
private final B2BCustomerModel b2bCustomerModel = mock(B2BCustomerModel.class);
@Mock
private final DataHubOutboundService dataHubOutboundService = mock(DataHubOutboundService.class);
@Mock
private CustomerAddressReplicationUtilityService customerAddressReplicationUtilityService = mock(CustomerAddressReplicationUtilityService.class);
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSendB2BContactData() throws InterceptorException {
// given
mockBaseCustomerData();
Map<String, String> batchIdAttributes = new HashMap<String, String>();
batchIdAttributes.put("dh_batchId", "000001");
batchIdAttributes.put("dh_sourceId", "HYBRIS");
batchIdAttributes.put("dh_type", "DH_TYPE");
b2BCustomerExportService.setBatchIdAttributes(batchIdAttributes);
final List<Map<String, Object>> b2bContactData = new ArrayList<>();
b2bContactData.add(b2BCustomerExportService.prepareB2BCustomerData(b2bCustomerModel, "de"));
b2BCustomerExportService.setFeed(SAPCONTACT_OUTBOUND_FEED);
b2BCustomerExportService.setDataHubOutboundService(dataHubOutboundService);
b2BCustomerExportService.sendRawItemsToDataHub(RAW_HYBRIS_B2B_CUSTOMER, b2bContactData);
try {
verify(dataHubOutboundService, times(1)).sendToDataHub(SAPCONTACT_OUTBOUND_FEED, RAW_HYBRIS_B2B_CUSTOMER,
b2bContactData);
} catch (final DataHubCommunicationException e) {
fail("Error processing sending data to Data Hub. DataHubCommunicationException: " + e.getMessage());
} catch (final DataHubOutboundException e) {
fail("Error processing sending data to Data Hub. DataHubOutboundException: " + e.getMessage());
}
}
@Test
public void testNotSendEmptyB2BContactDataNull() throws InterceptorException {
// given
final List<Map<String, Object>> b2bContactData = null;
b2BCustomerExportService.sendRawItemsToDataHub(RAW_HYBRIS_B2B_CUSTOMER, b2bContactData);
try {
verify(dataHubOutboundService, times(0)).sendToDataHub("DEFAULT_FEED", RAW_HYBRIS_B2B_CUSTOMER, b2bContactData);
} catch (final DataHubCommunicationException e) {
fail("Error processing sending data to Data Hub. DataHubCommunicationException: " + e.getMessage());
} catch (final DataHubOutboundException e) {
fail("Error processing sending data to Data Hub. DataHubOutboundException: " + e.getMessage());
}
}
@Test
public void testPrepareB2BContactDataNoLnaguage() throws InterceptorException {
mockBaseCustomerData();
Map<String, String> batchIdAttributes = new HashMap<String, String>();
batchIdAttributes.put("dh_batchId", "000001");
batchIdAttributes.put("dh_sourceId", "HYBRIS");
batchIdAttributes.put("dh_type", "DH_TYPE");
b2BCustomerExportService.setBatchIdAttributes(batchIdAttributes);
final TitleModel title = mock(TitleModel.class);
given(title.getCode()).willReturn(B2BCUSTOMER_TITLE_CODE);
given(b2bCustomerModel.getTitle()).willReturn(title);
final Map<String, Object> b2bCustomerData = b2BCustomerExportService.prepareB2BCustomerData(b2bCustomerModel, "de");
checkBaseCustomerData(b2bCustomerData);
Assert.assertEquals(b2bCustomerData.get(KEY_TITLE), B2BCUSTOMER_TITLE_CODE);
Assert.assertEquals(b2bCustomerData.get(KEY_SESSION_LANGUAGE), "de");
}
@Test
public void testPrepareB2BCustomerDataNoLanguageNoTitleCode() throws InterceptorException {
// given
mockBaseCustomerData();
Map<String, String> batchIdAttributes = new HashMap<String, String>();
batchIdAttributes.put("dh_batchId", "000001");
batchIdAttributes.put("dh_sourceId", "HYBRIS");
batchIdAttributes.put("dh_type", "DH_TYPE");
b2BCustomerExportService.setBatchIdAttributes(batchIdAttributes);
final Map<String, Object> b2bCustomerData = b2BCustomerExportService.prepareB2BCustomerData(b2bCustomerModel, "de");
checkBaseCustomerData(b2bCustomerData);
Assert.assertEquals(b2bCustomerData.get(KEY_TITLE), null);
Assert.assertEquals(b2bCustomerData.get(KEY_SESSION_LANGUAGE), "de");
}
@Test
public void testPrepareB2BContactData() throws InterceptorException {
// given
mockBaseCustomerData();
Map<String, String> batchIdAttributes = new HashMap<String, String>();
batchIdAttributes.put("dh_batchId", "000001");
batchIdAttributes.put("dh_sourceId", "HYBRIS");
batchIdAttributes.put("dh_type", "DH_TYPE");
b2BCustomerExportService.setBatchIdAttributes(batchIdAttributes);
final TitleModel title = mock(TitleModel.class);
given(title.getCode()).willReturn(B2BCUSTOMER_TITLE_CODE);
given(b2bCustomerModel.getTitle()).willReturn(title);
final LanguageModel languageModel = mock(LanguageModel.class);
given(languageModel.getIsocode()).willReturn(B2BCUSTOMER_SESSION_LANGUAGE);
given(b2bCustomerModel.getSessionLanguage()).willReturn(languageModel);
final Map<String, Object> b2bCustomerData = b2BCustomerExportService.prepareB2BCustomerData(b2bCustomerModel, "de");
checkBaseCustomerData(b2bCustomerData);
Assert.assertEquals(b2bCustomerData.get(KEY_SESSION_LANGUAGE), B2BCUSTOMER_SESSION_LANGUAGE);
Assert.assertEquals(b2bCustomerData.get(KEY_TITLE), B2BCUSTOMER_TITLE_CODE);
}
protected void mockBaseCustomerData() {
final B2BUnitModel b2bUnit = mock(B2BUnitModel.class);
given(b2bCustomerModel.getDefaultB2BUnit()).willReturn(b2bUnit);
given(b2bCustomerModel.getDefaultB2BUnit().getUid()).willReturn(B2BCUSTOMER_B2BUNIT);
given(b2bCustomerModel.getEmail()).willReturn(B2BCUSTOMER_EMAIL);
given(b2bCustomerModel.getName()).willReturn(B2BCUSTOMER_NAME);
final String[] names = new String[]
{B2BCUSTOMER_FIRST_NAME, B2BCUSTOMER_LAST_NAME};
given(customerNameStrategy.splitName(b2bCustomerModel.getName())).willReturn(names);
b2BCustomerExportService.setCustomerNameStrategy(customerNameStrategy);
given(b2bCustomerModel.getCustomerID()).willReturn(CUSTOMER_ID);
given(customerAddressReplicationUtilityService.findDefaultAddress(b2bCustomerModel, null)).willReturn(null);
}
protected void checkBaseCustomerData(final Map<String, Object> b2bContactData) {
Assert.assertFalse(b2bContactData.isEmpty());
Assert.assertEquals(b2bContactData.get(KEY_EMAIL), B2BCUSTOMER_EMAIL);
Assert.assertEquals(b2bContactData.get(KEY_CUSTOMER_ID), CUSTOMER_ID);
Assert.assertEquals(b2bContactData.get(KEY_FIRST_NAME), B2BCUSTOMER_FIRST_NAME);
Assert.assertEquals(b2bContactData.get(KEY_LAST_NAME), B2BCUSTOMER_LAST_NAME);
}
} | 9,634 | 0.794167 | 0.776417 | 204 | 46.230392 | 36.436634 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.843137 | false | false | 12 |
4796b1824186012b32e3242dce87519b0ed0ae65 | 22,222,160,843,796 | 02413387bdb0311dd363f4114f6e509794e4eadf | /android/TestProject/app/src/main/java/com/example/tanermetin/testproject/TestProjectApplication.java | d7fa7ac1924bd5c9a89ac2116fa5e9226c2956cd | [] | no_license | sheepsdream/1stone | https://github.com/sheepsdream/1stone | f1fe4ec2b96179f42e1caf53b5ef2e21de884869 | ee0f32005ec69e2f1505bb8fb09bbba5a914aaaa | refs/heads/master | 2021-10-16T14:59:25.824000 | 2019-02-11T17:54:31 | 2019-02-11T17:54:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.tanermetin.testproject;
import android.app.Application;
import android.content.res.Configuration;
//Singleton Activity
//https://stackoverflow.com/questions/18002227/why-extend-an-application-class
public class TestProjectApplication extends Application {
static UdpClient udpClient;
@Override
public void onCreate() {
super.onCreate();
// Required initialization logic here
udpClient = UdpClient.getInstance("");
}
// Called by the system when the device configuration changes while the component is running.
// Overriding the method is totally optional.
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
// Called when the overall system is low on memory. To limit actively running processes.
@Override
public void onLowMemory(){
super.onLowMemory();
}
}
class Singleton {}
| UTF-8 | Java | 979 | java | TestProjectApplication.java | Java | [
{
"context": "package com.example.tanermetin.testproject;\n\nimport android.app.Application;\nimp",
"end": 30,
"score": 0.9549797773361206,
"start": 20,
"tag": "USERNAME",
"value": "tanermetin"
}
] | null | [] | package com.example.tanermetin.testproject;
import android.app.Application;
import android.content.res.Configuration;
//Singleton Activity
//https://stackoverflow.com/questions/18002227/why-extend-an-application-class
public class TestProjectApplication extends Application {
static UdpClient udpClient;
@Override
public void onCreate() {
super.onCreate();
// Required initialization logic here
udpClient = UdpClient.getInstance("");
}
// Called by the system when the device configuration changes while the component is running.
// Overriding the method is totally optional.
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
// Called when the overall system is low on memory. To limit actively running processes.
@Override
public void onLowMemory(){
super.onLowMemory();
}
}
class Singleton {}
| 979 | 0.71093 | 0.702758 | 38 | 24.473684 | 27.077604 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.210526 | false | false | 12 |
fbc96b93d7b87c282d6a49eae592f76bf5de008c | 6,425,271,134,857 | a10b817e6d7f94d96ca522e65603a7c24b226848 | /src/org/order/service/UserService.java | fb4c0fb12033529d77df8665f41ed07fc908c7ae | [] | no_license | WhoNoName/MyGraduationProject | https://github.com/WhoNoName/MyGraduationProject | 9f46f65a0b5bc211789dc7664ac7a55ff1cde285 | f557ad22e46d19d37730f6a90ed17fadff58c1d0 | refs/heads/master | 2021-01-01T04:00:28.381000 | 2016-06-07T03:45:55 | 2016-06-07T03:53:32 | 57,769,954 | 0 | 0 | null | false | 2016-06-07T04:06:04 | 2016-05-01T19:34:25 | 2016-05-01T19:34:25 | 2016-06-07T04:06:04 | 3 | 0 | 0 | 0 | null | null | null | package org.order.service;
import org.order.util.OrderResult;
public interface UserService {
public OrderResult saveUser(String user_name,
String password, String dishes_address, String phone_num);
public OrderResult checkRegistUserPhone(String userPhone);
public OrderResult checkRegistUserName(String userName);
public OrderResult userLogin(String name, String password);
public OrderResult checkIndexUserLoad(String userId);
}
| UTF-8 | Java | 465 | java | UserService.java | Java | [] | null | [] | package org.order.service;
import org.order.util.OrderResult;
public interface UserService {
public OrderResult saveUser(String user_name,
String password, String dishes_address, String phone_num);
public OrderResult checkRegistUserPhone(String userPhone);
public OrderResult checkRegistUserName(String userName);
public OrderResult userLogin(String name, String password);
public OrderResult checkIndexUserLoad(String userId);
}
| 465 | 0.778495 | 0.778495 | 18 | 23.833334 | 25.377703 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.111111 | false | false | 12 |
1d1c9f8e84f784e9ba99bcbc89d8a743a9fb7c78 | 12,678,743,491,435 | bff72afaf5f0dea7f6ba4c592d4e2dc343615bc7 | /Scramble2/src/org/housey/Sprite.java | 4f5bd78421db36c593538e515e65f5e766222668 | [] | no_license | badgerchops/Scramble | https://github.com/badgerchops/Scramble | f8a1cf241aa85d2300a92daab612cc3d555c4c56 | e13e6c786bad99f0acdf60492d6daf9f04cee566 | refs/heads/master | 2021-07-11T03:01:38.684000 | 2017-10-10T08:16:17 | 2017-10-10T08:16:17 | 106,271,180 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.housey;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
//import java.util.Arrays;
/**
* This is the base class for all Sprites in the game.<br>
* Contains all code and variables common to all Sprites (Alien, Craft, Missile, Map tiles, etc.)<br>
* Extended by all the sprites in the game.
*
* @author Paul House
* @version 1.0
*/
public class Sprite implements Common {
// Instance Variables / Fields
/** The x coordinate of the sprite on the game panel */
protected int x;
/** The y coordinate of the sprite on the game panel */
protected int y;
/** The width in pixels of the sprite */
protected int width;
/** The height in pixels of the sprite */
protected int height;
/** Is the sprite visible or not. Sprites are made invisible before being removed in the next game cycle */
protected boolean vis;
/** The image representing the sprite in the game panel */
protected Image image;
/** Is the sprite destroyable when involved in a collision */
protected boolean destroyable;
/**
* 2D integer array representing the solid and empty parts of the sprite.
* Zeroes represent empty (transparent) pixels which cannot be involved in a
* collision with another sprite. Ones represent solid (non-transparent)
* pixels which can be involved in a collision with another sprite.
*/
protected int[][] transparencyArr;
/**
* Current animation frame being displayed - animated sprites only
*/
protected int currentFrame = 0;
/**
* Creates a new visible Sprite object at the coordinates passed in. Default
* visibility of the sprite is true. Default destroyable of the sprite is
* true.
*
* @param x
* the int initial x coordinate of the craft
* @param y
* the int initial y coordinate of the craft
*
*/
public Sprite(int x, int y) {
this.x = x;
this.y = y;
vis = true;
destroyable = true;
}
/**
* Get image and calculate the transparency array for pixel level collision
* calculations.
*
* @param imageName
* the String representing the image location
*/
protected void loadImage(String imageName) {
ImageIcon ii = new ImageIcon(imageName);
image = ii.getImage();
setTransparencyArr(image); // determine non transparent pixels for collision calcs
}
/**
* Get image from sprite sheet that corresponds to the frame passed in.<br>
* We don't recalculate the transparency array for pixel level collision
* calculations as it was generating an error and is unnecessary overhead
* anyway (done in loadImage).
* Assumes all frames are the same size (TILE_WIDTH = 32 pixels)
*
* @param imageName
* the String representing the image location
* @param frame
* the int representing the frame to retrieve
*/
protected void loadSubImage(String imageName, int frame) {
ImageIcon ii = new ImageIcon(imageName);
image = ii.getImage();
// Convert to buffered image so we can use getSubimage to retrieve frame of interest
BufferedImage bufferedImg = toBufferedImage(image);
// Calculate x,y co-ords of rectangle containing required sprite image
int srcX = frame * TILE_WIDTH;
int srcY = 0;
image = bufferedImg.getSubimage(srcX, srcY, TILE_WIDTH, TILE_HEIGHT);
// setTransparencyArr(image);
}
/**
* Get image from sprite sheet that corresponds to the frame passed in.<br>
* We don't recalculate the transparency array for pixel level collision
* calculations as it was generating an error and is unnecessary overhead
* anyway (done in loadImage). Supports frames that aren't the standard size
* (TILE_WIDTH = 32 pixels)
*
* @param imageName
* the String representing the image location
* @param frame
* the int representing the frame to retrieve
* @param frameWidth
* the int representing the width of the frames in pixels
*/
protected void loadSubImage(String imageName, int frame, int frameWidth) {
ImageIcon ii = new ImageIcon(imageName);
image = ii.getImage();
// Convert to buffered image so we can use getSubimage to retrieve frame
// of interest
BufferedImage bufferedImg = toBufferedImage(image);
// Calculate x,y co-ords of rectangle containing required sprite image
int srcX = frame * frameWidth;
int srcY = 0;
image = bufferedImg.getSubimage(srcX, srcY, frameWidth, frameWidth);
// setTransparencyArr(image);
}
/** Retrieve the dimensions of the image */
protected void getImageDimensions() {
width = image.getWidth(null);
height = image.getHeight(null);
}
public Image getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getCurrentFrame(){
return currentFrame;
}
public void setCurrentFrame(int frame){
currentFrame = frame;
}
public boolean isVisible() {
return vis;
}
public void setVisible(Boolean visible) {
vis = visible;
}
public boolean isDestroyable() {
return destroyable;
}
public void setDestroyable(Boolean destroy) {
destroyable = destroy;
}
/**
* Returns the bounding rectangle of the sprite image to allow collision
* detection.
*
* @return Rectangle
*/
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
/**
* Create integer array to identify all non transparent pixels in the sprite
* Rule is Sprites can't collide with transparent pixels
* Assumption - all sprites used will have an alpha (transparency) channel
* Adapted from: https://stackoverflow.com/questions/6524196/java-get-pixel-array-from-image
*
* @param img Image to analyse
*
*/
public void setTransparencyArr(Image img) {
// Get buffered image
BufferedImage bufferedImg = toBufferedImage(img);
final int pixelLength;
boolean hasAlphaChannel = bufferedImg.getAlphaRaster() != null;
if (hasAlphaChannel){
pixelLength = 4; //number of bytes used to represent a pixel if alpha value present
} else {
pixelLength = 3; //number of bytes used to represent a pixel if alpha value not present
}
int height = bufferedImg.getHeight();
int width = bufferedImg.getWidth();
final byte[] imgPixels = ((DataBufferByte) bufferedImg.getRaster().getDataBuffer()).getData();
int[][] imgArr = new int[height][width];
for (int pixel = 0, row = 0, col = 0; pixel < imgPixels.length; pixel = pixel + pixelLength) {
int alpha = 0;
alpha = (((int) imgPixels[pixel] & 0xff) << 24); //getting the alpha channel only for the pixel
// some images giving me more than 32 rows!
if (alpha==0){
// imgArr[row][col] = 0;
if (row < 32) imgArr[row][col] = 0;
} else{
// imgArr[row][col] = 1;
if (row < 32) imgArr[row][col] = 1;
}
col++;
if (col == width) {
col = 0;
row++;
}
}
// for( int i = 0; i < width; i++ ) {
// for( int j = 0; j < height; j++ ){
// int alpha = -16777216; // 255 alpha
// if (hasAlphaChannel)
// {
// int pixel = bufferedImg.getRGB(i, j);
// alpha = (pixel >> 24) & 0xff;
// }
// if (alpha==0){
// imgArr[i][j] = 0;
// } else {
// imgArr[i][j] = 1;
// }
// }
// }
transparencyArr = imgArr;
// System.out.println(Arrays.deepToString(imgArr));
}
public int[][] getTransparencyArr(){
return transparencyArr;
}
/**
* Converts a given Image into a BufferedImage
*
* @param img
* The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
} | UTF-8 | Java | 8,793 | java | Sprite.java | Java | [
{
"context": "d by all the sprites in the game.\r\n * \r\n * @author Paul House\r\n * @version 1.0 \r\n */\r\npublic class Sprite impl",
"end": 485,
"score": 0.9997378587722778,
"start": 475,
"tag": "NAME",
"value": "Paul House"
}
] | null | [] | package org.housey;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
//import java.util.Arrays;
/**
* This is the base class for all Sprites in the game.<br>
* Contains all code and variables common to all Sprites (Alien, Craft, Missile, Map tiles, etc.)<br>
* Extended by all the sprites in the game.
*
* @author <NAME>
* @version 1.0
*/
public class Sprite implements Common {
// Instance Variables / Fields
/** The x coordinate of the sprite on the game panel */
protected int x;
/** The y coordinate of the sprite on the game panel */
protected int y;
/** The width in pixels of the sprite */
protected int width;
/** The height in pixels of the sprite */
protected int height;
/** Is the sprite visible or not. Sprites are made invisible before being removed in the next game cycle */
protected boolean vis;
/** The image representing the sprite in the game panel */
protected Image image;
/** Is the sprite destroyable when involved in a collision */
protected boolean destroyable;
/**
* 2D integer array representing the solid and empty parts of the sprite.
* Zeroes represent empty (transparent) pixels which cannot be involved in a
* collision with another sprite. Ones represent solid (non-transparent)
* pixels which can be involved in a collision with another sprite.
*/
protected int[][] transparencyArr;
/**
* Current animation frame being displayed - animated sprites only
*/
protected int currentFrame = 0;
/**
* Creates a new visible Sprite object at the coordinates passed in. Default
* visibility of the sprite is true. Default destroyable of the sprite is
* true.
*
* @param x
* the int initial x coordinate of the craft
* @param y
* the int initial y coordinate of the craft
*
*/
public Sprite(int x, int y) {
this.x = x;
this.y = y;
vis = true;
destroyable = true;
}
/**
* Get image and calculate the transparency array for pixel level collision
* calculations.
*
* @param imageName
* the String representing the image location
*/
protected void loadImage(String imageName) {
ImageIcon ii = new ImageIcon(imageName);
image = ii.getImage();
setTransparencyArr(image); // determine non transparent pixels for collision calcs
}
/**
* Get image from sprite sheet that corresponds to the frame passed in.<br>
* We don't recalculate the transparency array for pixel level collision
* calculations as it was generating an error and is unnecessary overhead
* anyway (done in loadImage).
* Assumes all frames are the same size (TILE_WIDTH = 32 pixels)
*
* @param imageName
* the String representing the image location
* @param frame
* the int representing the frame to retrieve
*/
protected void loadSubImage(String imageName, int frame) {
ImageIcon ii = new ImageIcon(imageName);
image = ii.getImage();
// Convert to buffered image so we can use getSubimage to retrieve frame of interest
BufferedImage bufferedImg = toBufferedImage(image);
// Calculate x,y co-ords of rectangle containing required sprite image
int srcX = frame * TILE_WIDTH;
int srcY = 0;
image = bufferedImg.getSubimage(srcX, srcY, TILE_WIDTH, TILE_HEIGHT);
// setTransparencyArr(image);
}
/**
* Get image from sprite sheet that corresponds to the frame passed in.<br>
* We don't recalculate the transparency array for pixel level collision
* calculations as it was generating an error and is unnecessary overhead
* anyway (done in loadImage). Supports frames that aren't the standard size
* (TILE_WIDTH = 32 pixels)
*
* @param imageName
* the String representing the image location
* @param frame
* the int representing the frame to retrieve
* @param frameWidth
* the int representing the width of the frames in pixels
*/
protected void loadSubImage(String imageName, int frame, int frameWidth) {
ImageIcon ii = new ImageIcon(imageName);
image = ii.getImage();
// Convert to buffered image so we can use getSubimage to retrieve frame
// of interest
BufferedImage bufferedImg = toBufferedImage(image);
// Calculate x,y co-ords of rectangle containing required sprite image
int srcX = frame * frameWidth;
int srcY = 0;
image = bufferedImg.getSubimage(srcX, srcY, frameWidth, frameWidth);
// setTransparencyArr(image);
}
/** Retrieve the dimensions of the image */
protected void getImageDimensions() {
width = image.getWidth(null);
height = image.getHeight(null);
}
public Image getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getCurrentFrame(){
return currentFrame;
}
public void setCurrentFrame(int frame){
currentFrame = frame;
}
public boolean isVisible() {
return vis;
}
public void setVisible(Boolean visible) {
vis = visible;
}
public boolean isDestroyable() {
return destroyable;
}
public void setDestroyable(Boolean destroy) {
destroyable = destroy;
}
/**
* Returns the bounding rectangle of the sprite image to allow collision
* detection.
*
* @return Rectangle
*/
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
/**
* Create integer array to identify all non transparent pixels in the sprite
* Rule is Sprites can't collide with transparent pixels
* Assumption - all sprites used will have an alpha (transparency) channel
* Adapted from: https://stackoverflow.com/questions/6524196/java-get-pixel-array-from-image
*
* @param img Image to analyse
*
*/
public void setTransparencyArr(Image img) {
// Get buffered image
BufferedImage bufferedImg = toBufferedImage(img);
final int pixelLength;
boolean hasAlphaChannel = bufferedImg.getAlphaRaster() != null;
if (hasAlphaChannel){
pixelLength = 4; //number of bytes used to represent a pixel if alpha value present
} else {
pixelLength = 3; //number of bytes used to represent a pixel if alpha value not present
}
int height = bufferedImg.getHeight();
int width = bufferedImg.getWidth();
final byte[] imgPixels = ((DataBufferByte) bufferedImg.getRaster().getDataBuffer()).getData();
int[][] imgArr = new int[height][width];
for (int pixel = 0, row = 0, col = 0; pixel < imgPixels.length; pixel = pixel + pixelLength) {
int alpha = 0;
alpha = (((int) imgPixels[pixel] & 0xff) << 24); //getting the alpha channel only for the pixel
// some images giving me more than 32 rows!
if (alpha==0){
// imgArr[row][col] = 0;
if (row < 32) imgArr[row][col] = 0;
} else{
// imgArr[row][col] = 1;
if (row < 32) imgArr[row][col] = 1;
}
col++;
if (col == width) {
col = 0;
row++;
}
}
// for( int i = 0; i < width; i++ ) {
// for( int j = 0; j < height; j++ ){
// int alpha = -16777216; // 255 alpha
// if (hasAlphaChannel)
// {
// int pixel = bufferedImg.getRGB(i, j);
// alpha = (pixel >> 24) & 0xff;
// }
// if (alpha==0){
// imgArr[i][j] = 0;
// } else {
// imgArr[i][j] = 1;
// }
// }
// }
transparencyArr = imgArr;
// System.out.println(Arrays.deepToString(imgArr));
}
public int[][] getTransparencyArr(){
return transparencyArr;
}
/**
* Converts a given Image into a BufferedImage
*
* @param img
* The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
} | 8,789 | 0.626749 | 0.619698 | 298 | 27.513422 | 26.411715 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.563758 | false | false | 12 |
8a6db8ce562b708f9668dd6fc7038e6fab26eafc | 38,826,504,362,206 | e5b4702fd259d2a5f7a6c23216dd26dd1ba7f34a | /app/src/main/java/com/hongri/animation/ViewWrapper.java | e4d3fbb53cec3887ba84e3951c3437ce4c0ac82c | [] | no_license | zhongyao/PropertyAnimation | https://github.com/zhongyao/PropertyAnimation | 24e045513ed4c567f179e656d4174f7adea1b697 | f0620fbce343587515a3cedeb41a182d773468fe | refs/heads/master | 2020-03-24T00:11:42.020000 | 2018-07-28T01:51:30 | 2018-07-28T01:51:30 | 142,278,402 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hongri.animation;
import android.view.View;
/**
* @author zhongyao
* @date 2018/7/28
*/
public class ViewWrapper {
public View mTarget;
public ViewWrapper(View mTarget) {
this.mTarget = mTarget;
}
public int getWidth() {
return mTarget.getLayoutParams().width;
}
public void setWidth(int width) {
mTarget.getLayoutParams().width = width;
mTarget.requestLayout();
}
}
| UTF-8 | Java | 449 | java | ViewWrapper.java | Java | [
{
"context": "mation;\n\nimport android.view.View;\n\n/**\n * @author zhongyao\n * @date 2018/7/28\n */\n\npublic class ViewWrapper ",
"end": 81,
"score": 0.9994325637817383,
"start": 73,
"tag": "USERNAME",
"value": "zhongyao"
}
] | null | [] | package com.hongri.animation;
import android.view.View;
/**
* @author zhongyao
* @date 2018/7/28
*/
public class ViewWrapper {
public View mTarget;
public ViewWrapper(View mTarget) {
this.mTarget = mTarget;
}
public int getWidth() {
return mTarget.getLayoutParams().width;
}
public void setWidth(int width) {
mTarget.getLayoutParams().width = width;
mTarget.requestLayout();
}
}
| 449 | 0.632517 | 0.616926 | 26 | 16.26923 | 15.998937 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | false | false | 12 |
25c193e3fac357f7f275eaf713cae3802237e01b | 21,157,008,962,501 | b1ccd37282ac08adf3a78d9cb06424d62c3c802c | /src/main/java/org/sql2mongo/parse/SQL2MongoBaseVisitor.java | 147e96aca81b15be8aee90c0424e393403d08142 | [] | no_license | shadim/sql2mongo | https://github.com/shadim/sql2mongo | ebd827686153dc182ccfda0650e5cbaf788cc767 | 70535a8e8186dc972be70bf0db1f2b23f6189da8 | refs/heads/master | 2015-08-08T18:45:15.634000 | 2013-11-04T18:20:27 | 2013-11-04T18:20:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Generated from SQL2Mongo.g4 by ANTLR 4.0
package org.sql2mongo.parse;
import org.antlr.v4.runtime.tree.*;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.ParserRuleContext;
public class SQL2MongoBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements SQL2MongoVisitor<T> {
public T visitNot(SQL2MongoParser.NotContext ctx) { return visitChildren(ctx); }
public T visitExpression(SQL2MongoParser.ExpressionContext ctx) { return visitChildren(ctx); }
public T visitAtom(SQL2MongoParser.AtomContext ctx) { return visitChildren(ctx); }
public T visitOp(SQL2MongoParser.OpContext ctx) { return visitChildren(ctx); }
public T visitOr(SQL2MongoParser.OrContext ctx) { return visitChildren(ctx); }
public T visitValue(SQL2MongoParser.ValueContext ctx) { return visitChildren(ctx); }
public T visitParse(SQL2MongoParser.ParseContext ctx) { return visitChildren(ctx); }
public T visitAnd(SQL2MongoParser.AndContext ctx) { return visitChildren(ctx); }
} | UTF-8 | Java | 1,014 | java | SQL2MongoBaseVisitor.java | Java | [] | null | [] | // Generated from SQL2Mongo.g4 by ANTLR 4.0
package org.sql2mongo.parse;
import org.antlr.v4.runtime.tree.*;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.ParserRuleContext;
public class SQL2MongoBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements SQL2MongoVisitor<T> {
public T visitNot(SQL2MongoParser.NotContext ctx) { return visitChildren(ctx); }
public T visitExpression(SQL2MongoParser.ExpressionContext ctx) { return visitChildren(ctx); }
public T visitAtom(SQL2MongoParser.AtomContext ctx) { return visitChildren(ctx); }
public T visitOp(SQL2MongoParser.OpContext ctx) { return visitChildren(ctx); }
public T visitOr(SQL2MongoParser.OrContext ctx) { return visitChildren(ctx); }
public T visitValue(SQL2MongoParser.ValueContext ctx) { return visitChildren(ctx); }
public T visitParse(SQL2MongoParser.ParseContext ctx) { return visitChildren(ctx); }
public T visitAnd(SQL2MongoParser.AndContext ctx) { return visitChildren(ctx); }
} | 1,014 | 0.772189 | 0.754438 | 23 | 42.173912 | 38.828106 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.869565 | false | false | 12 |
050e75f182e446ff5944e472b82ed545b29129fe | 36,816,459,681,451 | 0c281b5f31b7e2e205faa8c97c8f3ab93199466f | /ReformYourCountry/src/reformyourcountry/service/UserService.java | 7a6a74bf8a7cf35d479880178d5022d8559c972c | [] | no_license | PibaMutanda/reform-your-country | https://github.com/PibaMutanda/reform-your-country | 9dcd7fe561ae45c71975350f61d46b97cbc348db | b5d493ef9275aee2608d252acd36f84293fd02a9 | refs/heads/master | 2021-01-10T21:16:58.333000 | 2015-03-31T11:47:39 | 2015-03-31T11:47:39 | 33,181,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package reformyourcountry.service;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.ImageType;
import org.springframework.social.google.api.Google;
import org.springframework.social.twitter.api.ImageSize;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.WebRequest;
import reformyourcountry.exception.InvalidPasswordException;
import reformyourcountry.exception.UserAlreadyExistsException;
import reformyourcountry.exception.UserAlreadyExistsException.IdentifierType;
import reformyourcountry.exception.UserLockedException;
import reformyourcountry.exception.UserNotFoundException;
import reformyourcountry.exception.UserNotValidatedException;
import reformyourcountry.mail.MailCategory;
import reformyourcountry.mail.MailType;
import reformyourcountry.model.Badge;
import reformyourcountry.model.BadgeType;
import reformyourcountry.model.User;
import reformyourcountry.model.User.AccountConnectedType;
import reformyourcountry.model.User.AccountStatus;
import reformyourcountry.model.User.Role;
import reformyourcountry.model.User.SpecialType;
import reformyourcountry.repository.UserRepository;
import reformyourcountry.security.SecurityContext;
import reformyourcountry.service.LoginService.WaitDelayNotReachedException;
import reformyourcountry.util.CurrentEnvironment;
import reformyourcountry.util.DateUtil;
import reformyourcountry.util.FileUtil;
import reformyourcountry.util.HTMLUtil;
import reformyourcountry.util.ImageUtil;
import reformyourcountry.util.Logger;
import reformyourcountry.util.NotificationUtil;
import reformyourcountry.util.SecurityUtils;
import reformyourcountry.web.ContextUtil;
import reformyourcountry.web.UrlUtil;
import reformyourcountry.web.UrlUtil.Mode;
@Transactional
@Service(value="userService")
@Scope("singleton")
public class UserService {
// Constant values used in the automatic calculation of the influence factor
public static final int INFLUENCE_PERCENTAGE_OF_RELEASED_QUESTIONS_WITH_NO_CONCERNS = 90;
public static final int INFLUENCE_AMOUNT_OF_RELEASED_QUESTIONS_WITH_NO_CONCERNS = 20;
public static final int INFLUENCE_AMOUNT_OF_RELEASED_QUESTIONS = 50;
// private TemplateService templateService;
// private String registrationTemplate;
// private String passwordRecoveryTemplate;
@Logger Log log;
@Autowired private UserRepository userRepository;
@Autowired private MailService mailService;
@Autowired private LoginService loginService;
@Autowired private UsersConnectionRepository usersConnectionRepository;
@Autowired private CurrentEnvironment currentEnvironment;
@Autowired IndexManagerService indexManagerService;
/**
* Register a user and sends a validation mail.
*
* @param directValidation
* : validate an account directly without send a mail
*/
public User registerUser(boolean directValidation, String username, String passwordInClear, String mail, boolean isSocial) throws UserAlreadyExistsException {
//exception if html is dangerous
//TODO review
if(!HTMLUtil.isHtmlSecure(username)) {
throw new RuntimeException("String used for register a user is dangerous : " + username);
}
if (userRepository.getUserByUserName(username) != null) {
throw new UserAlreadyExistsException(IdentifierType.USERNAME, username);
}
if (userRepository.getUserByEmail(mail) != null){
throw new UserAlreadyExistsException(IdentifierType.MAIL, mail);
}
User newUser = new User();
newUser.setUserName(username);
newUser.setPassword(SecurityUtils.md5Encode(passwordInClear));
newUser.setMail(mail);
newUser.setSpecialType(SpecialType.PRIVATE);
newUser.setAskedGroup(false);
//// Validation mail.
String base = newUser.getMail() + newUser.getPassword() + Math.random(); // Could be pure random.
newUser.setValidationCode(SecurityUtils.md5Encode(base.toString()));
if (directValidation) {
newUser.setAccountStatus(AccountStatus.ACTIVE);
} else {
newUser.setAccountStatus(AccountStatus.NOTVALIDATED);
}
newUser.setPasswordKnownByTheUser(!isSocial);
//// Save the user in the db
userRepository.persist(newUser);
// All is ok lets eventually send a validation email
if (!directValidation) {
sendRegistrationValidationMail(newUser);
}
///// update index
indexManagerService.add(newUser);
return newUser;
}
public void sendRegistrationValidationMail(User user) {
String validationUrl = UrlUtil.getAbsoluteUrl( "validationsubmit?code=" + user.getValidationCode());
String htmlMessage = "Bienvenue sur "+ currentEnvironment.getSiteName()+", " + user.getUserName() + "." +
"<br/>Il reste une dernière étape pour créer votre compte : " +
"veuillez s'il vous plait cliquer sur le lien ci-dessous pour valider votre e-mail !" +
"<br/><a href='"+ validationUrl + "'>" + validationUrl + "</a>" +
"<br/><br/>Si vous rencontrez un problème, essayez de copier/coller l'URL dans votre navigateur (au lieu de cliquer sur le lien), ou en dernier recours " +
"<a href='" + UrlUtil.getAbsoluteUrl("contact") + "'>nous contacter</a>" +
"<br/><br/>merci de vous être inscrit sur "+currentEnvironment.getSiteName()+".";
mailService.sendMail(user, "Votre nouveau compte", htmlMessage, MailType.IMMEDIATE, MailCategory.USER);
log.debug("mail sent: " + htmlMessage);
}
public void generateNewPasswordForUserAndSendEmail(User user) {
// We generate a password
String newPassword = SecurityUtils.generateRandomPassword(8, 12);
// we set the new password to the user
user.setPassword(SecurityUtils.md5Encode(newPassword));
user.setPasswordKnownByTheUser(true); // it's a random pwd, but the user knows it.
userRepository.merge(user);
mailService.sendMail(user.getMail(), "Recupération de mot de passe",
"Vous avez demandé un nouveau mot de passe pour votre compte '"+ user.getUserName()+"' sur "+ContextUtil.servletContext.getAttribute("p_website_name")+"<br/>" +
"Nous ne pouvons pas vous transmettre votre ancien mot de passe parce que nous ne l'enregistrons pas directement, pour des raisons de sécurité et de protection de votre vie privée, il est crypté de mannière irréverssible.<br/><br/>"+
"Voici votre nouveau mot de passe : "+ newPassword +
"<ol>" +
"<li>le mot de passe respecte la casse des caractères,</li>" +
"<li>Il s'agit d'un mot de passe auto-généré, libre à vous de le changer sur votre <a href='"+UrlUtil.getAbsoluteUrl("user/"+user.getUserName(),Mode.DEV)+"'>page de profile</a>.</li>" +
"</ol>",
MailType.IMMEDIATE, MailCategory.USER);
}
/** Change the name of the user and note it in the log */
public void changeUserName(User user, String newUserName, String newFirstName, String newLastName) {
if (user.getNameChangeLog() == null) {
user.addNameChangeLog("Previous name: " + user.getFirstName()
+ " - " + user.getLastName() + " - " + user.getUserName());
}
user.addNameChangeLog("\n"+ DateUtil.formatyyyyMMdd(new Date()) + ": "
+ newFirstName + " - " + newLastName + " - " + newUserName);
user.setFirstName(newFirstName);
user.setLastName(newLastName);
user.setUserName(newUserName);
userRepository.merge(user);
}
public void addOrUpdateUserImage(User user, BufferedImage image){
try {
ImageUtil.saveImageToFileAsJPEG(image,
FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER + FileUtil.USER_ORIGINAL_SUB_FOLDER, user.getId() + ".jpg", 0.9f);
BufferedImage resizedImage = ImageUtil.scale(ImageUtil.convertIntoByteArrayInputStream(image),120 * 200, 200, 200);
ImageUtil.saveImageToFileAsJPEG(resizedImage,
FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER +FileUtil.USER_RESIZED_SUB_FOLDER+ FileUtil.USER_RESIZED_LARGE_SUB_FOLDER, user.getId() + ".jpg", 0.9f);
user.setPicture(true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void addOrUpdateUserImageFromSocialProvider(User user ,Connection<?> connection){
AccountConnectedType type = AccountConnectedType.getProviderType(connection.getKey().getProviderId());
byte[] userImage =null;
switch(type){
case FACEBOOK :
Facebook facebook = (Facebook) connection.getApi();
userImage = facebook.userOperations().getUserProfileImage(ImageType.NORMAL);
if(userImage != null){
try {
addOrUpdateUserImage(user, ImageIO.read(new ByteArrayInputStream(userImage)));
} catch (IOException e) {
throw new RuntimeException(e);
}}else{
NotificationUtil.addNotificationMessage("Aucune image n'est disponnible depuis votre compte "+connection.getKey().getProviderId());
}
break;
case TWITTER:
Twitter twitter = (Twitter) connection.getApi();
// At 30/11/2012 the method getUserProfileImage() seem not work on twitter so we get the image by its url.
// userImage = twitter.userOperations().getUserProfileImage(twitter.userOperations().getScreenName(),ImageSize.ORIGINAL);
String urlImage = twitter.userOperations().getUserProfile().getProfileImageUrl();
urlImage = urlImage.replace("_normal", "");
if(urlImage != null){
BufferedImage image = ImageUtil.readImage(urlImage);
// addOrUpdateUserImage(user, ImageIO.read(new ByteArrayInputStream(userImage)));
addOrUpdateUserImage(user, image);
}else{
NotificationUtil.addNotificationMessage("Aucune image n'est disponnible depuis votre compte "+connection.getKey().getProviderId());
}
break;
case GOOGLE :
Google google = (Google) connection.getApi();
String urlProfil = google.userOperations().getUserProfile().getProfilePictureUrl();
if (urlProfil != null) { // Null if Google has no image.
BufferedImage image = ImageUtil.readImage(urlProfil);
addOrUpdateUserImage(user,image);
}else{
NotificationUtil.addNotificationMessage("Aucune image n'est disponnible depuis votre compte "+connection.getKey().getProviderId());
}
break;
default : throw new RuntimeException("invalid social provider name submitted");
}
}
public void unsocialiseUser(User user, String newPassword){
// We remove all uer's social connections.
ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(user.getId()+"");
MultiValueMap<String,Connection<?>> connectionsByProvider = connectionRepository.findAllConnections();
for(List<Connection<?>> collection : connectionsByProvider.values()) {
for(Connection<?> con : collection){
connectionRepository.removeConnection(con.getKey());
}
}
// We make this user a "normal" (not a "through-facebook" user).
user.setPassword(SecurityUtils.md5Encode(newPassword));
user.setPasswordKnownByTheUser(true);
user.setAccountStatus(AccountStatus.ACTIVE);
user.setAccountConnectedType(AccountConnectedType.LOCAL);
userRepository.merge(user);
loginService.resetLoginData(user, new ArrayList<Connection<?>>());
}
public void removeSocialConnection(User user, Connection<?> connection){
ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(user.getId()+"");
connectionRepository.removeConnection(connection.getKey());
// If the removed connection was the preferred of the user
if (connection.getKey().getProviderId().equals( user.getAccountConnectedType().getProviderId() )) {
// then change that preferred to the first of the remaining connections
Connection<?> firstRemainingConnection = getAllConnections(user).get(0);
user.setAccountConnectedType(User.AccountConnectedType.getProviderType(firstRemainingConnection.getKey().getProviderId()));
}
loginService.resetLoginData(user, getAllConnections(user));
}
public List<Connection<?>> getAllConnections(User user){
ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(user.getId()+"");
MultiValueMap<String,Connection<?>> connectionsByProvider = connectionRepository.findAllConnections();
// We build a list that is usable in the <c:foreach> of the jsp (not the case of the map).
List<Connection<?>> connections = new ArrayList<Connection<?>>();
for(List<Connection<?>> collection : connectionsByProvider.values()) {
connections.addAll(collection);
}
return connections;
}
public User tryToAttachSocialLoginToAnExistingUser(Connection<?> connection) throws UserLockedException{
if (SecurityContext.getUser() != null) {
User user = SecurityContext.getUser();
completUserFromSocialProviderData(connection,user);
// User already logged in.
return user;
} else {
String mail = connection.fetchUserProfile().getEmail();
if (mail != null) { // Some providers, such as Twitter, don't give the e-mail.
User userfound = userRepository.getUserByEmail(mail);
if (userfound != null) { // That visitor already has a user on RYC
completUserFromSocialProviderData(connection, userfound);
if(userfound.getAccountStatus().equals(AccountStatus.LOCKED)) { // Cannot login...
throw new UserLockedException(userfound);
} else if (userfound.getAccountStatus().equals(AccountStatus.NOTVALIDATED)) { // We have the mail from the social provider (which we trust) => no need to click the mail link to finish the registration.
userfound.setAccountStatus(AccountStatus.ACTIVE);
}
try {
if((userfound.getAccountStatus().equals(AccountStatus.ACTIVE))){
loginService.login(null,null,false,userfound.getId(),AccountConnectedType.getProviderType(connection.getKey().getProviderId()));
// we place the provider name in the session , will be used by header.jsp
}
} catch (UserNotFoundException | InvalidPasswordException
| UserNotValidatedException | UserLockedException
| WaitDelayNotReachedException e) {
throw new RuntimeException(e);
}
userRepository.merge(userfound);
return userfound;
}
}
}
return null; // Cannot attach the visitor to an existing RYC user.
}
public void completUserFromSocialProviderData(Connection<?> connection,User user){
if(StringUtils.isBlank(user.getLastName())) {
user.setLastName(connection.fetchUserProfile().getLastName());
}
if(StringUtils.isBlank(user.getFirstName())) {
user.setFirstName(connection.fetchUserProfile().getFirstName());
}
////// Image
if (!user.isPicture()) { // No picture yet => try to fetch one from the social provider.
addOrUpdateUserImageFromSocialProvider(user,connection);
}
userRepository.merge(user);
}
public User registerSocialUser(WebRequest request,String mail,boolean mailIsValid) throws UserAlreadyExistsException {
Connection<?> connection = ProviderSignInUtils.getConnection(request);
User user = null;
try {
Date date = new Date();
// 1. Username based on Time stamp (temporary name until we persist it and have it's id)
String username = date.getTime()+"";
int begin = username.length()-12;
username= "tmp"+username.substring(begin);
Random random = new Random();
if (mailIsValid) { // Ok, we directly register that user.
user = registerUser(true,
username, // This name will change at the next line, as soon as we have the id.
random.nextLong()+"", // Nobody should never use this password (because the user logs in through it's social network).
mail,true);
} else { // is there another user having the same mail?
user = userRepository.getUserByEmail(mail);
if(user == null){
//we need to verify the mail before registering so we pass false for directValidation
user = registerUser(false,
username,
random.nextLong()+"",
mail,true);
} else { //case where the user is already registered in local and try to register with twitter
throw new UserAlreadyExistsException(IdentifierType.MAIL, user.getUserName());
}
}
// 2. Now we have the ID and can assign a better username.
user.setUserName("user"+user.getId());
userRepository.merge(user);
//When the user is created in local , add a new Connection to userconnection table
ProviderSignInUtils.handlePostSignUp(user.getId()+"", request);
} catch (Exception e) {
if(e instanceof UserAlreadyExistsException){
throw new UserAlreadyExistsException(IdentifierType.MAIL,user.getUserName());
} else {
throw new RuntimeException("Problem while registering "+mail+" account through "+ connection.getKey().getProviderId(), e);
}
}
return user;
}
public List<User> getUserLstWithRoleOrPrivilege(){
List<User> list1 = userRepository.getUserWithRoleNotNull();
List<User> list2 = userRepository.getUserWithPrivilegeNotEmpty();
// Add to list1, the users of list2 which are not already in list1.
for(User u : list2){
if(!(list1.contains(u))){
list1.add(u);
}
}
return list1;
}
/** Encoding user's nickname and registration date to have a parameter sent to a page.
* Used in urls (from mails, for example), to directly authentify a user. */
public String getUserSecurityString(User user){
return SecurityUtils.md5Encode(user.getUserName()+user.getCreatedOn().toString()).substring(0, 6);
}
public void setUser(User user){
changeUserName(user, "Anonymous"+user.getId(), "", "");
user.setTitle("");
user.setCertificationDate(null);
user.setBirthDate(null);
user.setGender(null);
user.setAccountStatus(AccountStatus.LOCKED);
user.setRole(Role.USER);
}
public void userImageDelete(User user){
FileUtil.deleteFilesWithPattern(FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER + FileUtil.USER_ORIGINAL_SUB_FOLDER, user.getId()+".*");
FileUtil.deleteFilesWithPattern(FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER + FileUtil.USER_RESIZED_SUB_FOLDER + FileUtil.USER_RESIZED_LARGE_SUB_FOLDER, user.getId()+".*");
FileUtil.deleteFilesWithPattern(FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER + FileUtil.USER_RESIZED_SUB_FOLDER + FileUtil.USER_RESIZED_SMALL_SUB_FOLDER, user.getId()+".*");
user.setPicture(false);
}
} | UTF-8 | Java | 21,751 | java | UserService.java | Java | [
{
"context": "newUser = new User();\n newUser.setUserName(username);\n newUser.setPassword(SecurityUtils.md5En",
"end": 4550,
"score": 0.9989479184150696,
"start": 4542,
"tag": "USERNAME",
"value": "username"
},
{
"context": "etLastName(newLastName);\n user.setUs... | null | [] | package reformyourcountry.service;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.ImageType;
import org.springframework.social.google.api.Google;
import org.springframework.social.twitter.api.ImageSize;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.WebRequest;
import reformyourcountry.exception.InvalidPasswordException;
import reformyourcountry.exception.UserAlreadyExistsException;
import reformyourcountry.exception.UserAlreadyExistsException.IdentifierType;
import reformyourcountry.exception.UserLockedException;
import reformyourcountry.exception.UserNotFoundException;
import reformyourcountry.exception.UserNotValidatedException;
import reformyourcountry.mail.MailCategory;
import reformyourcountry.mail.MailType;
import reformyourcountry.model.Badge;
import reformyourcountry.model.BadgeType;
import reformyourcountry.model.User;
import reformyourcountry.model.User.AccountConnectedType;
import reformyourcountry.model.User.AccountStatus;
import reformyourcountry.model.User.Role;
import reformyourcountry.model.User.SpecialType;
import reformyourcountry.repository.UserRepository;
import reformyourcountry.security.SecurityContext;
import reformyourcountry.service.LoginService.WaitDelayNotReachedException;
import reformyourcountry.util.CurrentEnvironment;
import reformyourcountry.util.DateUtil;
import reformyourcountry.util.FileUtil;
import reformyourcountry.util.HTMLUtil;
import reformyourcountry.util.ImageUtil;
import reformyourcountry.util.Logger;
import reformyourcountry.util.NotificationUtil;
import reformyourcountry.util.SecurityUtils;
import reformyourcountry.web.ContextUtil;
import reformyourcountry.web.UrlUtil;
import reformyourcountry.web.UrlUtil.Mode;
@Transactional
@Service(value="userService")
@Scope("singleton")
public class UserService {
// Constant values used in the automatic calculation of the influence factor
public static final int INFLUENCE_PERCENTAGE_OF_RELEASED_QUESTIONS_WITH_NO_CONCERNS = 90;
public static final int INFLUENCE_AMOUNT_OF_RELEASED_QUESTIONS_WITH_NO_CONCERNS = 20;
public static final int INFLUENCE_AMOUNT_OF_RELEASED_QUESTIONS = 50;
// private TemplateService templateService;
// private String registrationTemplate;
// private String passwordRecoveryTemplate;
@Logger Log log;
@Autowired private UserRepository userRepository;
@Autowired private MailService mailService;
@Autowired private LoginService loginService;
@Autowired private UsersConnectionRepository usersConnectionRepository;
@Autowired private CurrentEnvironment currentEnvironment;
@Autowired IndexManagerService indexManagerService;
/**
* Register a user and sends a validation mail.
*
* @param directValidation
* : validate an account directly without send a mail
*/
public User registerUser(boolean directValidation, String username, String passwordInClear, String mail, boolean isSocial) throws UserAlreadyExistsException {
//exception if html is dangerous
//TODO review
if(!HTMLUtil.isHtmlSecure(username)) {
throw new RuntimeException("String used for register a user is dangerous : " + username);
}
if (userRepository.getUserByUserName(username) != null) {
throw new UserAlreadyExistsException(IdentifierType.USERNAME, username);
}
if (userRepository.getUserByEmail(mail) != null){
throw new UserAlreadyExistsException(IdentifierType.MAIL, mail);
}
User newUser = new User();
newUser.setUserName(username);
newUser.setPassword(SecurityUtils.md5Encode(passwordInClear));
newUser.setMail(mail);
newUser.setSpecialType(SpecialType.PRIVATE);
newUser.setAskedGroup(false);
//// Validation mail.
String base = newUser.getMail() + newUser.getPassword() + Math.random(); // Could be pure random.
newUser.setValidationCode(SecurityUtils.md5Encode(base.toString()));
if (directValidation) {
newUser.setAccountStatus(AccountStatus.ACTIVE);
} else {
newUser.setAccountStatus(AccountStatus.NOTVALIDATED);
}
newUser.setPasswordKnownByTheUser(!isSocial);
//// Save the user in the db
userRepository.persist(newUser);
// All is ok lets eventually send a validation email
if (!directValidation) {
sendRegistrationValidationMail(newUser);
}
///// update index
indexManagerService.add(newUser);
return newUser;
}
public void sendRegistrationValidationMail(User user) {
String validationUrl = UrlUtil.getAbsoluteUrl( "validationsubmit?code=" + user.getValidationCode());
String htmlMessage = "Bienvenue sur "+ currentEnvironment.getSiteName()+", " + user.getUserName() + "." +
"<br/>Il reste une dernière étape pour créer votre compte : " +
"veuillez s'il vous plait cliquer sur le lien ci-dessous pour valider votre e-mail !" +
"<br/><a href='"+ validationUrl + "'>" + validationUrl + "</a>" +
"<br/><br/>Si vous rencontrez un problème, essayez de copier/coller l'URL dans votre navigateur (au lieu de cliquer sur le lien), ou en dernier recours " +
"<a href='" + UrlUtil.getAbsoluteUrl("contact") + "'>nous contacter</a>" +
"<br/><br/>merci de vous être inscrit sur "+currentEnvironment.getSiteName()+".";
mailService.sendMail(user, "Votre nouveau compte", htmlMessage, MailType.IMMEDIATE, MailCategory.USER);
log.debug("mail sent: " + htmlMessage);
}
public void generateNewPasswordForUserAndSendEmail(User user) {
// We generate a password
String newPassword = SecurityUtils.generateRandomPassword(8, 12);
// we set the new password to the user
user.setPassword(SecurityUtils.md5Encode(newPassword));
user.setPasswordKnownByTheUser(true); // it's a random pwd, but the user knows it.
userRepository.merge(user);
mailService.sendMail(user.getMail(), "Recupération de mot de passe",
"Vous avez demandé un nouveau mot de passe pour votre compte '"+ user.getUserName()+"' sur "+ContextUtil.servletContext.getAttribute("p_website_name")+"<br/>" +
"Nous ne pouvons pas vous transmettre votre ancien mot de passe parce que nous ne l'enregistrons pas directement, pour des raisons de sécurité et de protection de votre vie privée, il est crypté de mannière irréverssible.<br/><br/>"+
"Voici votre nouveau mot de passe : "+ newPassword +
"<ol>" +
"<li>le mot de passe respecte la casse des caractères,</li>" +
"<li>Il s'agit d'un mot de passe auto-généré, libre à vous de le changer sur votre <a href='"+UrlUtil.getAbsoluteUrl("user/"+user.getUserName(),Mode.DEV)+"'>page de profile</a>.</li>" +
"</ol>",
MailType.IMMEDIATE, MailCategory.USER);
}
/** Change the name of the user and note it in the log */
public void changeUserName(User user, String newUserName, String newFirstName, String newLastName) {
if (user.getNameChangeLog() == null) {
user.addNameChangeLog("Previous name: " + user.getFirstName()
+ " - " + user.getLastName() + " - " + user.getUserName());
}
user.addNameChangeLog("\n"+ DateUtil.formatyyyyMMdd(new Date()) + ": "
+ newFirstName + " - " + newLastName + " - " + newUserName);
user.setFirstName(newFirstName);
user.setLastName(newLastName);
user.setUserName(newUserName);
userRepository.merge(user);
}
public void addOrUpdateUserImage(User user, BufferedImage image){
try {
ImageUtil.saveImageToFileAsJPEG(image,
FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER + FileUtil.USER_ORIGINAL_SUB_FOLDER, user.getId() + ".jpg", 0.9f);
BufferedImage resizedImage = ImageUtil.scale(ImageUtil.convertIntoByteArrayInputStream(image),120 * 200, 200, 200);
ImageUtil.saveImageToFileAsJPEG(resizedImage,
FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER +FileUtil.USER_RESIZED_SUB_FOLDER+ FileUtil.USER_RESIZED_LARGE_SUB_FOLDER, user.getId() + ".jpg", 0.9f);
user.setPicture(true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void addOrUpdateUserImageFromSocialProvider(User user ,Connection<?> connection){
AccountConnectedType type = AccountConnectedType.getProviderType(connection.getKey().getProviderId());
byte[] userImage =null;
switch(type){
case FACEBOOK :
Facebook facebook = (Facebook) connection.getApi();
userImage = facebook.userOperations().getUserProfileImage(ImageType.NORMAL);
if(userImage != null){
try {
addOrUpdateUserImage(user, ImageIO.read(new ByteArrayInputStream(userImage)));
} catch (IOException e) {
throw new RuntimeException(e);
}}else{
NotificationUtil.addNotificationMessage("Aucune image n'est disponnible depuis votre compte "+connection.getKey().getProviderId());
}
break;
case TWITTER:
Twitter twitter = (Twitter) connection.getApi();
// At 30/11/2012 the method getUserProfileImage() seem not work on twitter so we get the image by its url.
// userImage = twitter.userOperations().getUserProfileImage(twitter.userOperations().getScreenName(),ImageSize.ORIGINAL);
String urlImage = twitter.userOperations().getUserProfile().getProfileImageUrl();
urlImage = urlImage.replace("_normal", "");
if(urlImage != null){
BufferedImage image = ImageUtil.readImage(urlImage);
// addOrUpdateUserImage(user, ImageIO.read(new ByteArrayInputStream(userImage)));
addOrUpdateUserImage(user, image);
}else{
NotificationUtil.addNotificationMessage("Aucune image n'est disponnible depuis votre compte "+connection.getKey().getProviderId());
}
break;
case GOOGLE :
Google google = (Google) connection.getApi();
String urlProfil = google.userOperations().getUserProfile().getProfilePictureUrl();
if (urlProfil != null) { // Null if Google has no image.
BufferedImage image = ImageUtil.readImage(urlProfil);
addOrUpdateUserImage(user,image);
}else{
NotificationUtil.addNotificationMessage("Aucune image n'est disponnible depuis votre compte "+connection.getKey().getProviderId());
}
break;
default : throw new RuntimeException("invalid social provider name submitted");
}
}
public void unsocialiseUser(User user, String newPassword){
// We remove all uer's social connections.
ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(user.getId()+"");
MultiValueMap<String,Connection<?>> connectionsByProvider = connectionRepository.findAllConnections();
for(List<Connection<?>> collection : connectionsByProvider.values()) {
for(Connection<?> con : collection){
connectionRepository.removeConnection(con.getKey());
}
}
// We make this user a "normal" (not a "through-facebook" user).
user.setPassword(SecurityUtils.md5Encode(newPassword));
user.setPasswordKnownByTheUser(true);
user.setAccountStatus(AccountStatus.ACTIVE);
user.setAccountConnectedType(AccountConnectedType.LOCAL);
userRepository.merge(user);
loginService.resetLoginData(user, new ArrayList<Connection<?>>());
}
public void removeSocialConnection(User user, Connection<?> connection){
ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(user.getId()+"");
connectionRepository.removeConnection(connection.getKey());
// If the removed connection was the preferred of the user
if (connection.getKey().getProviderId().equals( user.getAccountConnectedType().getProviderId() )) {
// then change that preferred to the first of the remaining connections
Connection<?> firstRemainingConnection = getAllConnections(user).get(0);
user.setAccountConnectedType(User.AccountConnectedType.getProviderType(firstRemainingConnection.getKey().getProviderId()));
}
loginService.resetLoginData(user, getAllConnections(user));
}
public List<Connection<?>> getAllConnections(User user){
ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(user.getId()+"");
MultiValueMap<String,Connection<?>> connectionsByProvider = connectionRepository.findAllConnections();
// We build a list that is usable in the <c:foreach> of the jsp (not the case of the map).
List<Connection<?>> connections = new ArrayList<Connection<?>>();
for(List<Connection<?>> collection : connectionsByProvider.values()) {
connections.addAll(collection);
}
return connections;
}
public User tryToAttachSocialLoginToAnExistingUser(Connection<?> connection) throws UserLockedException{
if (SecurityContext.getUser() != null) {
User user = SecurityContext.getUser();
completUserFromSocialProviderData(connection,user);
// User already logged in.
return user;
} else {
String mail = connection.fetchUserProfile().getEmail();
if (mail != null) { // Some providers, such as Twitter, don't give the e-mail.
User userfound = userRepository.getUserByEmail(mail);
if (userfound != null) { // That visitor already has a user on RYC
completUserFromSocialProviderData(connection, userfound);
if(userfound.getAccountStatus().equals(AccountStatus.LOCKED)) { // Cannot login...
throw new UserLockedException(userfound);
} else if (userfound.getAccountStatus().equals(AccountStatus.NOTVALIDATED)) { // We have the mail from the social provider (which we trust) => no need to click the mail link to finish the registration.
userfound.setAccountStatus(AccountStatus.ACTIVE);
}
try {
if((userfound.getAccountStatus().equals(AccountStatus.ACTIVE))){
loginService.login(null,null,false,userfound.getId(),AccountConnectedType.getProviderType(connection.getKey().getProviderId()));
// we place the provider name in the session , will be used by header.jsp
}
} catch (UserNotFoundException | InvalidPasswordException
| UserNotValidatedException | UserLockedException
| WaitDelayNotReachedException e) {
throw new RuntimeException(e);
}
userRepository.merge(userfound);
return userfound;
}
}
}
return null; // Cannot attach the visitor to an existing RYC user.
}
public void completUserFromSocialProviderData(Connection<?> connection,User user){
if(StringUtils.isBlank(user.getLastName())) {
user.setLastName(connection.fetchUserProfile().getLastName());
}
if(StringUtils.isBlank(user.getFirstName())) {
user.setFirstName(connection.fetchUserProfile().getFirstName());
}
////// Image
if (!user.isPicture()) { // No picture yet => try to fetch one from the social provider.
addOrUpdateUserImageFromSocialProvider(user,connection);
}
userRepository.merge(user);
}
public User registerSocialUser(WebRequest request,String mail,boolean mailIsValid) throws UserAlreadyExistsException {
Connection<?> connection = ProviderSignInUtils.getConnection(request);
User user = null;
try {
Date date = new Date();
// 1. Username based on Time stamp (temporary name until we persist it and have it's id)
String username = date.getTime()+"";
int begin = username.length()-12;
username= "tmp"+username.substring(begin);
Random random = new Random();
if (mailIsValid) { // Ok, we directly register that user.
user = registerUser(true,
username, // This name will change at the next line, as soon as we have the id.
random.nextLong()+"", // Nobody should never use this password (because the user logs in through it's social network).
mail,true);
} else { // is there another user having the same mail?
user = userRepository.getUserByEmail(mail);
if(user == null){
//we need to verify the mail before registering so we pass false for directValidation
user = registerUser(false,
username,
random.nextLong()+"",
mail,true);
} else { //case where the user is already registered in local and try to register with twitter
throw new UserAlreadyExistsException(IdentifierType.MAIL, user.getUserName());
}
}
// 2. Now we have the ID and can assign a better username.
user.setUserName("user"+user.getId());
userRepository.merge(user);
//When the user is created in local , add a new Connection to userconnection table
ProviderSignInUtils.handlePostSignUp(user.getId()+"", request);
} catch (Exception e) {
if(e instanceof UserAlreadyExistsException){
throw new UserAlreadyExistsException(IdentifierType.MAIL,user.getUserName());
} else {
throw new RuntimeException("Problem while registering "+mail+" account through "+ connection.getKey().getProviderId(), e);
}
}
return user;
}
public List<User> getUserLstWithRoleOrPrivilege(){
List<User> list1 = userRepository.getUserWithRoleNotNull();
List<User> list2 = userRepository.getUserWithPrivilegeNotEmpty();
// Add to list1, the users of list2 which are not already in list1.
for(User u : list2){
if(!(list1.contains(u))){
list1.add(u);
}
}
return list1;
}
/** Encoding user's nickname and registration date to have a parameter sent to a page.
* Used in urls (from mails, for example), to directly authentify a user. */
public String getUserSecurityString(User user){
return SecurityUtils.md5Encode(user.getUserName()+user.getCreatedOn().toString()).substring(0, 6);
}
public void setUser(User user){
changeUserName(user, "Anonymous"+user.getId(), "", "");
user.setTitle("");
user.setCertificationDate(null);
user.setBirthDate(null);
user.setGender(null);
user.setAccountStatus(AccountStatus.LOCKED);
user.setRole(Role.USER);
}
public void userImageDelete(User user){
FileUtil.deleteFilesWithPattern(FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER + FileUtil.USER_ORIGINAL_SUB_FOLDER, user.getId()+".*");
FileUtil.deleteFilesWithPattern(FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER + FileUtil.USER_RESIZED_SUB_FOLDER + FileUtil.USER_RESIZED_LARGE_SUB_FOLDER, user.getId()+".*");
FileUtil.deleteFilesWithPattern(FileUtil.getGenFolderPath(currentEnvironment) + FileUtil.USER_SUB_FOLDER + FileUtil.USER_RESIZED_SUB_FOLDER + FileUtil.USER_RESIZED_SMALL_SUB_FOLDER, user.getId()+".*");
user.setPicture(false);
}
} | 21,751 | 0.658078 | 0.655547 | 463 | 45.941685 | 41.499107 | 257 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684665 | false | false | 12 |
43682203576e5acc317189e06d70874d46c60787 | 7,584,912,309,045 | 9e72719165ee759b824de697788fa058043b573f | /src/learnityasmtserver/assessmentadmin/standaloneasmt/AsmtDefiAddVadation.java | 9a7119c3988e3fb0bbdbf977eb424b8d28424dd5 | [] | no_license | elearn123/LMS | https://github.com/elearn123/LMS | 79de45d9ae9f08193c1c77c8b7d1d15196e54db6 | 79e57031c52bdcbc67320c2382bfa33e3ff7fd76 | refs/heads/master | 2020-05-21T20:32:45.319000 | 2017-07-05T12:58:59 | 2017-07-05T12:58:59 | 61,017,923 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package learnityasmtserver.assessmentadmin.standaloneasmt;
import interfaceenginev2.*;
import org.grlea.log.*;
import comv2.aunwesha.lfutil.Pair;
import javax.servlet.http.*;
import learnityasmtserver.assessmentadmin.dbconnection.*;
import java.util.*;
public class AsmtDefiAddVadation implements ValidatorFunction
{
public static final SimpleLogger log;
public Pair<Boolean,String> validateadd(final HttpServletRequest request) {
Boolean b = false;
String message = "";
//final String AssessTitleSelect = request.getParameter("assessment_id");
//final int assessment_id = Integer.parseInt(AssessTitleSelect);
final String no_questions = request.getParameter("no_of_questions");
final int no_ques_per_topic = Integer.parseInt(no_questions);
final String select_topic = request.getParameter("topic_id");
final String idlebel = request.getParameter("degree_of_difficulty");
final String question_type = request.getParameter("question_type");
//final String admin = request.getParameter("current_login_user_id");
final Vector<String> vQB_id = DataBaseLayer.getQuesBankId(select_topic);
final int qbsize = vQB_id.size();
if (qbsize != 0) {
final Vector<String> vIList = new Vector<String>();
for (int kk = 0; kk < vQB_id.size(); ++kk) {
final String quesbankid = vQB_id.elementAt(kk);
final Vector<String> vIList2 = DataBaseLayer.getItemList(quesbankid);
for (int ii = 0; ii < vIList2.size(); ++ii) {
final String id = vIList2.elementAt(ii);
vIList.addElement(id);
}
}
final int itemNo = vIList.size();
if (itemNo >= no_ques_per_topic) {
if (!question_type.equals("Any")) {
final Vector<String> vIList3 = new Vector<String>();
for (int k = 0; k < vIList.size(); ++k) {
final String id2 = vIList.elementAt(k);
int t = 0;
t = DataBaseLayer.getIteIDmsType(id2, question_type);
if (t != 0) {
vIList3.addElement(id2);
}
}
if (vIList3.size() >= no_ques_per_topic) {
if (!idlebel.equals("Any")) {
final Vector<String> vIList4 = new Vector<String>();
for (int k2 = 0; k2 < vIList3.size(); ++k2) {
final String id3 = vIList3.elementAt(k2);
int d = 0;
d = DataBaseLayer.getIteIDmslevel(id3, idlebel);
if (d != 0) {
vIList4.addElement(id3);
}
}
if (vIList4.size() >= no_ques_per_topic) {
b = true;
message = "Successful";
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is " + question_type + " and Difficulty level is " + idlebel + " is " + vIList4.size();
}
}
else {
b = true;
message = "Successful";
}
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is " + question_type + " is " + vIList3.size();
}
}
else if (!idlebel.equals("Any")) {
final Vector<String> vIList5 = new Vector<String>();
for (int k3 = 0; k3 < vIList.size(); ++k3) {
final String id4 = vIList.elementAt(k3);
int d2 = 0;
d2 = DataBaseLayer.getIteIDmslevel(id4, idlebel);
if (d2 != 0) {
vIList5.addElement(id4);
}
}
if (vIList5.size() >= no_ques_per_topic) {
b = true;
message = "Successful";
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is Any and Difficulty level is " + idlebel + " is " + vIList5.size();
}
}
else {
b = true;
message = "Successful";
}
}
else {
b = false;
message = "Total no.of questions available in selected topic is " + itemNo;
}
}
else {
b = false;
message = "First Associates Selected topic with Question Bank";
}
System.out.println("b==add==" + b);
return new Pair<Boolean,String>(b, message);
}
public Pair<Boolean,String> validateedit(final HttpServletRequest request) {
Boolean b = false;
String message = "";
//final String AssessTitleSelect = request.getParameter("assessment_id");
//final int assessment_id = Integer.parseInt(AssessTitleSelect);
final String no_questions = request.getParameter("no_of_questions");
final int no_ques_per_topic = Integer.parseInt(no_questions);
final String select_topic = request.getParameter("topic_id");
final String idlebel = request.getParameter("degree_of_difficulty");
final String question_type = request.getParameter("question_type");
//final String admin = request.getParameter("current_login_user_id");
final Vector<String> vQB_id = DataBaseLayer.getQuesBankId(select_topic);
final int qbsize = vQB_id.size();
if (qbsize != 0) {
final Vector<String> vIList = new Vector<String>();
for (int kk = 0; kk < vQB_id.size(); ++kk) {
final String quesbankid = vQB_id.elementAt(kk);
final Vector<String> vIList2 = DataBaseLayer.getItemList(quesbankid);
for (int ii = 0; ii < vIList2.size(); ++ii) {
final String id = vIList2.elementAt(ii);
vIList.addElement(id);
}
}
final int itemNo = vIList.size();
if (itemNo >= no_ques_per_topic) {
if (!question_type.equals("Any")) {
final Vector<String> vIList3 = new Vector<String>();
for (int k = 0; k < vIList.size(); ++k) {
final String id2 = vIList.elementAt(k);
int t = 0;
t = DataBaseLayer.getIteIDmsType(id2, question_type);
if (t != 0) {
vIList3.addElement(id2);
}
}
if (vIList3.size() >= no_ques_per_topic) {
if (!idlebel.equals("Any")) {
final Vector<String> vIList4 = new Vector<String>();
for (int k2 = 0; k2 < vIList3.size(); ++k2) {
final String id3 = vIList3.elementAt(k2);
int d = 0;
d = DataBaseLayer.getIteIDmslevel(id3, idlebel);
if (d != 0) {
vIList4.addElement(id3);
}
}
if (vIList4.size() >= no_ques_per_topic) {
b = true;
message = "Successful";
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is " + question_type + " and Difficulty level is " + idlebel + " is " + vIList4.size();
}
}
else {
b = true;
message = "Successful";
}
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is " + question_type + " is " + vIList3.size();
}
}
else if (!idlebel.equals("Any")) {
final Vector<String> vIList5 = new Vector<String>();
for (int k3 = 0; k3 < vIList.size(); ++k3) {
final String id4 = vIList.elementAt(k3);
int d2 = 0;
d2 = DataBaseLayer.getIteIDmslevel(id4, idlebel);
if (d2 != 0) {
vIList5.addElement(id4);
}
}
if (vIList5.size() >= no_ques_per_topic) {
b = true;
message = "Successful";
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is Any and Difficulty level is " + idlebel + " is " + vIList5.size();
}
}
else {
b = true;
message = "Successful";
}
}
else {
b = false;
message = "Total no.of questions available in selected topic is " + itemNo;
}
}
else {
b = false;
message = "First Associates Selected topic with Question Bank";
}
System.out.println("b===edit=" + b);
return new Pair<Boolean,String>(b, message);
}
public Pair<Boolean,String> validatedelete(HttpServletRequest request)
{return new Pair<Boolean,String>(false, "");}
static {
log = new SimpleLogger((Class)AsmtDefiAddVadation.class, true);
}
}
| UTF-8 | Java | 10,627 | java | AsmtDefiAddVadation.java | Java | [] | null | [] | package learnityasmtserver.assessmentadmin.standaloneasmt;
import interfaceenginev2.*;
import org.grlea.log.*;
import comv2.aunwesha.lfutil.Pair;
import javax.servlet.http.*;
import learnityasmtserver.assessmentadmin.dbconnection.*;
import java.util.*;
public class AsmtDefiAddVadation implements ValidatorFunction
{
public static final SimpleLogger log;
public Pair<Boolean,String> validateadd(final HttpServletRequest request) {
Boolean b = false;
String message = "";
//final String AssessTitleSelect = request.getParameter("assessment_id");
//final int assessment_id = Integer.parseInt(AssessTitleSelect);
final String no_questions = request.getParameter("no_of_questions");
final int no_ques_per_topic = Integer.parseInt(no_questions);
final String select_topic = request.getParameter("topic_id");
final String idlebel = request.getParameter("degree_of_difficulty");
final String question_type = request.getParameter("question_type");
//final String admin = request.getParameter("current_login_user_id");
final Vector<String> vQB_id = DataBaseLayer.getQuesBankId(select_topic);
final int qbsize = vQB_id.size();
if (qbsize != 0) {
final Vector<String> vIList = new Vector<String>();
for (int kk = 0; kk < vQB_id.size(); ++kk) {
final String quesbankid = vQB_id.elementAt(kk);
final Vector<String> vIList2 = DataBaseLayer.getItemList(quesbankid);
for (int ii = 0; ii < vIList2.size(); ++ii) {
final String id = vIList2.elementAt(ii);
vIList.addElement(id);
}
}
final int itemNo = vIList.size();
if (itemNo >= no_ques_per_topic) {
if (!question_type.equals("Any")) {
final Vector<String> vIList3 = new Vector<String>();
for (int k = 0; k < vIList.size(); ++k) {
final String id2 = vIList.elementAt(k);
int t = 0;
t = DataBaseLayer.getIteIDmsType(id2, question_type);
if (t != 0) {
vIList3.addElement(id2);
}
}
if (vIList3.size() >= no_ques_per_topic) {
if (!idlebel.equals("Any")) {
final Vector<String> vIList4 = new Vector<String>();
for (int k2 = 0; k2 < vIList3.size(); ++k2) {
final String id3 = vIList3.elementAt(k2);
int d = 0;
d = DataBaseLayer.getIteIDmslevel(id3, idlebel);
if (d != 0) {
vIList4.addElement(id3);
}
}
if (vIList4.size() >= no_ques_per_topic) {
b = true;
message = "Successful";
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is " + question_type + " and Difficulty level is " + idlebel + " is " + vIList4.size();
}
}
else {
b = true;
message = "Successful";
}
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is " + question_type + " is " + vIList3.size();
}
}
else if (!idlebel.equals("Any")) {
final Vector<String> vIList5 = new Vector<String>();
for (int k3 = 0; k3 < vIList.size(); ++k3) {
final String id4 = vIList.elementAt(k3);
int d2 = 0;
d2 = DataBaseLayer.getIteIDmslevel(id4, idlebel);
if (d2 != 0) {
vIList5.addElement(id4);
}
}
if (vIList5.size() >= no_ques_per_topic) {
b = true;
message = "Successful";
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is Any and Difficulty level is " + idlebel + " is " + vIList5.size();
}
}
else {
b = true;
message = "Successful";
}
}
else {
b = false;
message = "Total no.of questions available in selected topic is " + itemNo;
}
}
else {
b = false;
message = "First Associates Selected topic with Question Bank";
}
System.out.println("b==add==" + b);
return new Pair<Boolean,String>(b, message);
}
public Pair<Boolean,String> validateedit(final HttpServletRequest request) {
Boolean b = false;
String message = "";
//final String AssessTitleSelect = request.getParameter("assessment_id");
//final int assessment_id = Integer.parseInt(AssessTitleSelect);
final String no_questions = request.getParameter("no_of_questions");
final int no_ques_per_topic = Integer.parseInt(no_questions);
final String select_topic = request.getParameter("topic_id");
final String idlebel = request.getParameter("degree_of_difficulty");
final String question_type = request.getParameter("question_type");
//final String admin = request.getParameter("current_login_user_id");
final Vector<String> vQB_id = DataBaseLayer.getQuesBankId(select_topic);
final int qbsize = vQB_id.size();
if (qbsize != 0) {
final Vector<String> vIList = new Vector<String>();
for (int kk = 0; kk < vQB_id.size(); ++kk) {
final String quesbankid = vQB_id.elementAt(kk);
final Vector<String> vIList2 = DataBaseLayer.getItemList(quesbankid);
for (int ii = 0; ii < vIList2.size(); ++ii) {
final String id = vIList2.elementAt(ii);
vIList.addElement(id);
}
}
final int itemNo = vIList.size();
if (itemNo >= no_ques_per_topic) {
if (!question_type.equals("Any")) {
final Vector<String> vIList3 = new Vector<String>();
for (int k = 0; k < vIList.size(); ++k) {
final String id2 = vIList.elementAt(k);
int t = 0;
t = DataBaseLayer.getIteIDmsType(id2, question_type);
if (t != 0) {
vIList3.addElement(id2);
}
}
if (vIList3.size() >= no_ques_per_topic) {
if (!idlebel.equals("Any")) {
final Vector<String> vIList4 = new Vector<String>();
for (int k2 = 0; k2 < vIList3.size(); ++k2) {
final String id3 = vIList3.elementAt(k2);
int d = 0;
d = DataBaseLayer.getIteIDmslevel(id3, idlebel);
if (d != 0) {
vIList4.addElement(id3);
}
}
if (vIList4.size() >= no_ques_per_topic) {
b = true;
message = "Successful";
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is " + question_type + " and Difficulty level is " + idlebel + " is " + vIList4.size();
}
}
else {
b = true;
message = "Successful";
}
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is " + question_type + " is " + vIList3.size();
}
}
else if (!idlebel.equals("Any")) {
final Vector<String> vIList5 = new Vector<String>();
for (int k3 = 0; k3 < vIList.size(); ++k3) {
final String id4 = vIList.elementAt(k3);
int d2 = 0;
d2 = DataBaseLayer.getIteIDmslevel(id4, idlebel);
if (d2 != 0) {
vIList5.addElement(id4);
}
}
if (vIList5.size() >= no_ques_per_topic) {
b = true;
message = "Successful";
}
else {
b = false;
message = "Total no.of questions available in selected topic when Question Type is Any and Difficulty level is " + idlebel + " is " + vIList5.size();
}
}
else {
b = true;
message = "Successful";
}
}
else {
b = false;
message = "Total no.of questions available in selected topic is " + itemNo;
}
}
else {
b = false;
message = "First Associates Selected topic with Question Bank";
}
System.out.println("b===edit=" + b);
return new Pair<Boolean,String>(b, message);
}
public Pair<Boolean,String> validatedelete(HttpServletRequest request)
{return new Pair<Boolean,String>(false, "");}
static {
log = new SimpleLogger((Class)AsmtDefiAddVadation.class, true);
}
}
| 10,627 | 0.445187 | 0.435777 | 226 | 46.022125 | 31.549574 | 199 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681416 | false | false | 12 |
6e24df3fd4f0e51dbc7f29ce4d6f5c454aa2e902 | 7,026,566,553,038 | 091d917cd46770a5989df4ad627d2fb2d3562556 | /src/com/insideperu/map/MapLocation.java | 68f720b4cf9b5bf50ce632d0b88aea8c9a550bc5 | [] | no_license | ujwaltrivedi/Event-Locations-Tablet | https://github.com/ujwaltrivedi/Event-Locations-Tablet | 7eadb724e6b548345c45a8d7c99d01b2d8af04c7 | 20e0b3bf433613843b3854f605d89080a56fdd8d | refs/heads/master | 2016-05-22T20:19:34.593000 | 2012-04-24T09:17:45 | 2012-04-24T09:17:45 | 4,122,866 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.insideperu.map;
import us.eventlocations.androidtab.R;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.Point;
import android.graphics.RectF;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
/** Class to hold our location information */
public class MapLocation {
public static final int PADDING_X = 10;
public static final int PADDING_Y = 8;
public static final int RADIUS_BUBBLES = 5;
public static final int DISTANCE_BUBBLE = 15;
public static final int SIZE_SELECTOR_BUBBLE = 10;
private GeoPoint point;
private String name;
private MapLocationViewer mapLocationView;
private int type ;
public int getType() {
return type;
}
private Bitmap drawIcon, shadowIcon;
public MapLocation(MapLocationViewer mapView, String name, double latitude, double longitude, int type) {
this.name = name;
mapLocationView = mapView;
point = new GeoPoint((int)(latitude*1e6),(int)(longitude*1e6));
setType(type);
}
public MapLocation(MapLocationViewer mapView, String name, GeoPoint point, int type) {
this.name = name;
mapLocationView = mapView;
this.point = point;
setType(type);
}
private void setType(int type) {
this.type = type;
switch (type) {
case R.drawable.bubble:
drawIcon = BitmapFactory.decodeResource(mapLocationView.getResources(),R.drawable.bubble);
shadowIcon = BitmapFactory.decodeResource(mapLocationView.getResources(),R.drawable.bubble_shadow);
break;
default:
drawIcon = BitmapFactory.decodeResource(mapLocationView.getResources(),R.drawable.blank);
shadowIcon = BitmapFactory.decodeResource(mapLocationView.getResources(),R.drawable.bubble_shadow);
break;
}
}
public Bitmap getDrawIcon() {
return drawIcon;
}
public Bitmap getShadowIcon() {
return shadowIcon;
}
public GeoPoint getPoint() {
return point;
}
public String getName() {
return name;
}
public int getWidthIcon() {
return drawIcon.getWidth();
}
public int getHeightIcon() {
return drawIcon.getHeight();
}
public int getWidthText() {
return (int)MapLocationsManager.textPaint.measureText(this.getName());
}
public int getHeightText() {
return (int)MapLocationsManager.textPaint.descent()-(int)MapLocationsManager.textPaint.ascent();
}
public RectF getHRectFIcon() {
return getHRectFIcon(0, 0);
}
public RectF getHRectFIcon(int offsetx, int offsety) {
RectF rectf = new RectF();
rectf.set(-drawIcon.getWidth()/2,-drawIcon.getHeight(),drawIcon.getWidth()/2,0);
rectf.offset(offsetx, offsety);
return rectf;
}
public boolean getHit(int offsetx, int offsety, float event_x, float event_y) {
if ( getHRectFIcon(offsetx, offsety).contains(event_x,event_y) ) {
return true;
}
return false;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Point p = new Point();
mapView.getProjection().toPixels(this.getPoint(), p);
if (shadow) {
canvas.drawBitmap(this.getShadowIcon(), p.x, p.y - this.getShadowIcon().getHeight(),null);
} else {
canvas.drawBitmap(this.getDrawIcon(), p.x -this.getDrawIcon().getWidth()/2, p.y -this.getDrawIcon().getHeight(),null);
}
}
public void drawBubble(Canvas canvas, MapView mapView, boolean shadow) {
Point p = new Point();
mapView.getProjection().toPixels(this.getPoint(), p);
int wBox = getWidthText() + (PADDING_X*2);
int hBox = getHeightText() + (PADDING_Y*2);
RectF boxRect = new RectF(0, 0, wBox, hBox);
int offsetX = p.x - wBox/2;
int offsetY = p.y - hBox - this.getHeightIcon() - DISTANCE_BUBBLE;
boxRect.offset(offsetX, offsetY);
Path pathBubble = new Path();
pathBubble.addRoundRect(boxRect, RADIUS_BUBBLES, RADIUS_BUBBLES, Direction.CCW);
pathBubble.moveTo(offsetX+(wBox/2)-(SIZE_SELECTOR_BUBBLE/2), offsetY+hBox);
pathBubble.lineTo(offsetX+(wBox/2), offsetY+hBox+SIZE_SELECTOR_BUBBLE);
pathBubble.lineTo(offsetX+(wBox/2)+(SIZE_SELECTOR_BUBBLE/2), offsetY+hBox);
canvas.drawPath(pathBubble, MapLocationsManager.borderPaint);
canvas.drawPath(pathBubble, MapLocationsManager.innerPaint);
canvas.drawText(this.getName(), p.x-(getWidthText()/2),
p.y-MapLocationsManager.textPaint.ascent()-this.getHeightIcon()-hBox+PADDING_Y - DISTANCE_BUBBLE, MapLocationsManager.textPaint);
}
}
| UTF-8 | Java | 4,527 | java | MapLocation.java | Java | [] | null | [] | package com.insideperu.map;
import us.eventlocations.androidtab.R;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.Point;
import android.graphics.RectF;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
/** Class to hold our location information */
public class MapLocation {
public static final int PADDING_X = 10;
public static final int PADDING_Y = 8;
public static final int RADIUS_BUBBLES = 5;
public static final int DISTANCE_BUBBLE = 15;
public static final int SIZE_SELECTOR_BUBBLE = 10;
private GeoPoint point;
private String name;
private MapLocationViewer mapLocationView;
private int type ;
public int getType() {
return type;
}
private Bitmap drawIcon, shadowIcon;
public MapLocation(MapLocationViewer mapView, String name, double latitude, double longitude, int type) {
this.name = name;
mapLocationView = mapView;
point = new GeoPoint((int)(latitude*1e6),(int)(longitude*1e6));
setType(type);
}
public MapLocation(MapLocationViewer mapView, String name, GeoPoint point, int type) {
this.name = name;
mapLocationView = mapView;
this.point = point;
setType(type);
}
private void setType(int type) {
this.type = type;
switch (type) {
case R.drawable.bubble:
drawIcon = BitmapFactory.decodeResource(mapLocationView.getResources(),R.drawable.bubble);
shadowIcon = BitmapFactory.decodeResource(mapLocationView.getResources(),R.drawable.bubble_shadow);
break;
default:
drawIcon = BitmapFactory.decodeResource(mapLocationView.getResources(),R.drawable.blank);
shadowIcon = BitmapFactory.decodeResource(mapLocationView.getResources(),R.drawable.bubble_shadow);
break;
}
}
public Bitmap getDrawIcon() {
return drawIcon;
}
public Bitmap getShadowIcon() {
return shadowIcon;
}
public GeoPoint getPoint() {
return point;
}
public String getName() {
return name;
}
public int getWidthIcon() {
return drawIcon.getWidth();
}
public int getHeightIcon() {
return drawIcon.getHeight();
}
public int getWidthText() {
return (int)MapLocationsManager.textPaint.measureText(this.getName());
}
public int getHeightText() {
return (int)MapLocationsManager.textPaint.descent()-(int)MapLocationsManager.textPaint.ascent();
}
public RectF getHRectFIcon() {
return getHRectFIcon(0, 0);
}
public RectF getHRectFIcon(int offsetx, int offsety) {
RectF rectf = new RectF();
rectf.set(-drawIcon.getWidth()/2,-drawIcon.getHeight(),drawIcon.getWidth()/2,0);
rectf.offset(offsetx, offsety);
return rectf;
}
public boolean getHit(int offsetx, int offsety, float event_x, float event_y) {
if ( getHRectFIcon(offsetx, offsety).contains(event_x,event_y) ) {
return true;
}
return false;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Point p = new Point();
mapView.getProjection().toPixels(this.getPoint(), p);
if (shadow) {
canvas.drawBitmap(this.getShadowIcon(), p.x, p.y - this.getShadowIcon().getHeight(),null);
} else {
canvas.drawBitmap(this.getDrawIcon(), p.x -this.getDrawIcon().getWidth()/2, p.y -this.getDrawIcon().getHeight(),null);
}
}
public void drawBubble(Canvas canvas, MapView mapView, boolean shadow) {
Point p = new Point();
mapView.getProjection().toPixels(this.getPoint(), p);
int wBox = getWidthText() + (PADDING_X*2);
int hBox = getHeightText() + (PADDING_Y*2);
RectF boxRect = new RectF(0, 0, wBox, hBox);
int offsetX = p.x - wBox/2;
int offsetY = p.y - hBox - this.getHeightIcon() - DISTANCE_BUBBLE;
boxRect.offset(offsetX, offsetY);
Path pathBubble = new Path();
pathBubble.addRoundRect(boxRect, RADIUS_BUBBLES, RADIUS_BUBBLES, Direction.CCW);
pathBubble.moveTo(offsetX+(wBox/2)-(SIZE_SELECTOR_BUBBLE/2), offsetY+hBox);
pathBubble.lineTo(offsetX+(wBox/2), offsetY+hBox+SIZE_SELECTOR_BUBBLE);
pathBubble.lineTo(offsetX+(wBox/2)+(SIZE_SELECTOR_BUBBLE/2), offsetY+hBox);
canvas.drawPath(pathBubble, MapLocationsManager.borderPaint);
canvas.drawPath(pathBubble, MapLocationsManager.innerPaint);
canvas.drawText(this.getName(), p.x-(getWidthText()/2),
p.y-MapLocationsManager.textPaint.ascent()-this.getHeightIcon()-hBox+PADDING_Y - DISTANCE_BUBBLE, MapLocationsManager.textPaint);
}
}
| 4,527 | 0.713939 | 0.707533 | 152 | 28.782894 | 29.952576 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.032895 | false | false | 12 |
ddb9709986574b23ab1f5564effd6eaa022340a5 | 17,910,013,680,953 | 9edbf8fb9711eec531ebb40ba0b8402ae3e4ee26 | /PoP/src/entities/Pillar.java | e393ddd6fbda39cd1a973ddb70aacd7e7952ea98 | [
"MIT"
] | permissive | InformaticAA/PrinceOfPersia | https://github.com/InformaticAA/PrinceOfPersia | 37caf8eb8eb2da1d3ff0c9a522a63296d1c5c1d4 | b2ab16717ed0c064c865c9a9cb44a53c46859fed | refs/heads/master | 2020-04-05T14:08:52.194000 | 2019-05-19T21:56:53 | 2019-05-19T21:56:53 | 51,510,514 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package entities;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import framework.Loader;
public class Pillar extends Entity{
public Pillar(int x, int y, int x_offset, int y_offset, Loader loader, String type) {
super("Pillar_" + type, x + x_offset, y + y_offset, loader);
animations = loader.getAnimations("pillar");
currentAnimation = animations.get(type);
/* Sets the bounding box */
if(type.equals("pillar_left")){
boundingBoxColor = Color.YELLOW;
enableBoundingBox(this.x + 25, this.y + currentAnimation.getImage().getHeight() - 14,
currentAnimation.getImage().getWidth() - 25,
13);
} else if(type.equals("pillar_right_main")){
boundingBoxColor = Color.WHITE;
enableBoundingBox(this.x, this.y + currentAnimation.getImage().getHeight() - 18,
currentAnimation.getImage().getWidth() -27,
17);
}
}
/**
*
* @return the center coords of the entity
*/
@Override
public int[] getCenter() {
int width2 = currentAnimation.getImage().getWidth()/2;
int height2 = (int) (this.getBoundingBox().getMaxY() - this.getBoundingBox().getMinY()) / 2;
int xx = x - width2;
int yy = y - height2;
return new int[]{xx,yy};
}
@Override
public Entity copy() {
return null;
}
// @Override
// public void drawSelf(Graphics g) {
//
// /* Draws the entity */
// BufferedImage img = currentAnimation.getImage();
// g.drawImage(img, x - currentAnimation.getImage().getWidth(),
// y - currentAnimation.getImage().getHeight(), null);
//
// /* Draws the entity's bounding box */
// if (boundingBox != null) {
// g.setColor(boundingBoxColor);
// g.drawRect((int) boundingBox.getX(),
// (int) boundingBox.getY(),
// (int) boundingBox.getWidth(),
// (int) boundingBox.getHeight());
// g.setColor(Color.BLACK);
// }
// }
}
| UTF-8 | Java | 1,851 | java | Pillar.java | Java | [] | null | [] | package entities;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import framework.Loader;
public class Pillar extends Entity{
public Pillar(int x, int y, int x_offset, int y_offset, Loader loader, String type) {
super("Pillar_" + type, x + x_offset, y + y_offset, loader);
animations = loader.getAnimations("pillar");
currentAnimation = animations.get(type);
/* Sets the bounding box */
if(type.equals("pillar_left")){
boundingBoxColor = Color.YELLOW;
enableBoundingBox(this.x + 25, this.y + currentAnimation.getImage().getHeight() - 14,
currentAnimation.getImage().getWidth() - 25,
13);
} else if(type.equals("pillar_right_main")){
boundingBoxColor = Color.WHITE;
enableBoundingBox(this.x, this.y + currentAnimation.getImage().getHeight() - 18,
currentAnimation.getImage().getWidth() -27,
17);
}
}
/**
*
* @return the center coords of the entity
*/
@Override
public int[] getCenter() {
int width2 = currentAnimation.getImage().getWidth()/2;
int height2 = (int) (this.getBoundingBox().getMaxY() - this.getBoundingBox().getMinY()) / 2;
int xx = x - width2;
int yy = y - height2;
return new int[]{xx,yy};
}
@Override
public Entity copy() {
return null;
}
// @Override
// public void drawSelf(Graphics g) {
//
// /* Draws the entity */
// BufferedImage img = currentAnimation.getImage();
// g.drawImage(img, x - currentAnimation.getImage().getWidth(),
// y - currentAnimation.getImage().getHeight(), null);
//
// /* Draws the entity's bounding box */
// if (boundingBox != null) {
// g.setColor(boundingBoxColor);
// g.drawRect((int) boundingBox.getX(),
// (int) boundingBox.getY(),
// (int) boundingBox.getWidth(),
// (int) boundingBox.getHeight());
// g.setColor(Color.BLACK);
// }
// }
}
| 1,851 | 0.655862 | 0.645057 | 67 | 26.626865 | 23.742924 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.552239 | false | false | 12 |
56af048da35ae61d2d7bf0a6298f29f150f5be25 | 23,682,449,722,845 | a691e1a89f6b9b6b3577898e321d987db21cba5d | /src/main/java/kakao/pay/test/invest/impl/jpa/InternalInvestRepository.java | fa53f9e634a11886e8f1b4b0955ff1eb3bdc55b6 | [] | no_license | JeHuiPark/kakao-pay-test | https://github.com/JeHuiPark/kakao-pay-test | 1208b0cd4fb2ce9e6126f10523ec1af18e5325b4 | c17901a3252b2ed5819970dbaa7849b9d9953c59 | refs/heads/master | 2023-04-05T13:34:13.178000 | 2021-04-19T00:53:35 | 2021-04-19T00:53:35 | 359,054,288 | 0 | 0 | null | false | 2021-04-18T23:26:37 | 2021-04-18T05:36:16 | 2021-04-18T20:09:35 | 2021-04-18T23:26:37 | 170 | 0 | 0 | 0 | Java | false | false | package kakao.pay.test.invest.impl.jpa;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
class InternalInvestRepository {
private final InvestmentProductRepository investmentProductRepository;
private final InvestmentReceiptRepository investmentReceiptRepository;
private final ProductInvestmentLogRepository productInvestmentLogRepository;
public Optional<InvestmentProduct> findById(long productId) {
return investmentProductRepository.findById(productId);
}
public void saveInvestProductReceipt(InvestmentReceipt investProductReceipt) {
investmentReceiptRepository.saveAndFlush(investProductReceipt);
if (productInvestmentLogRepository.logging(investProductReceipt)) {
investmentProductRepository.accumulateInvestmentAmountWithInvestor(
investProductReceipt.productId(), investProductReceipt.investingAmount());
} else {
investmentProductRepository.accumulateInvestmentAmount(
investProductReceipt.productId(), investProductReceipt.investingAmount());
}
}
}
| UTF-8 | Java | 1,130 | java | InternalInvestRepository.java | Java | [] | null | [] | package kakao.pay.test.invest.impl.jpa;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
class InternalInvestRepository {
private final InvestmentProductRepository investmentProductRepository;
private final InvestmentReceiptRepository investmentReceiptRepository;
private final ProductInvestmentLogRepository productInvestmentLogRepository;
public Optional<InvestmentProduct> findById(long productId) {
return investmentProductRepository.findById(productId);
}
public void saveInvestProductReceipt(InvestmentReceipt investProductReceipt) {
investmentReceiptRepository.saveAndFlush(investProductReceipt);
if (productInvestmentLogRepository.logging(investProductReceipt)) {
investmentProductRepository.accumulateInvestmentAmountWithInvestor(
investProductReceipt.productId(), investProductReceipt.investingAmount());
} else {
investmentProductRepository.accumulateInvestmentAmount(
investProductReceipt.productId(), investProductReceipt.investingAmount());
}
}
}
| 1,130 | 0.826549 | 0.826549 | 29 | 37.965519 | 31.515167 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.448276 | false | false | 12 |
b13ddad46f9c0468c97e95a1713a125f44ada489 | 8,538,394,989,648 | 79a6cf43828280dde4a8957ab2878def495cde95 | /platform/platform-api/src/main/java/com/asiainfo/rms/alm/demand/web/AlmReqtmpFunctionController.java | 110e41f6036fc9b1232654f4c39f8187de6eca2a | [] | no_license | zostudy/cb | https://github.com/zostudy/cb | aeee90afde5f83fc8fecb02073c724963cf3c44f | c18b3d6fb078d66bd45f446707e67d918ca57ae0 | refs/heads/master | 2020-05-17T22:24:44.910000 | 2019-05-07T09:29:39 | 2019-05-07T09:29:39 | 183,999,895 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asiainfo.rms.alm.demand.web;
import com.asiainfo.rms.alm.demand.dto.AlmReqtmpFunctionDTO;
import com.asiainfo.rms.alm.demand.dto.FunctionDTO;
import com.asiainfo.rms.core.api.Page;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/alm")
public interface AlmReqtmpFunctionController {
/**
* 新增功能需求模板信息
*
* @param functionDTO
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function", method = RequestMethod.POST)
String saveAlmReqtmpFunction(@RequestBody FunctionDTO functionDTO);
/**
* 修改功能需求模板信息
*
* @param functionDTO
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function", method = RequestMethod.PUT)
String updateAlmReqtmpFunction(@RequestBody FunctionDTO functionDTO);
/**
* 删除功能需求模板信息
*
* @param arfId
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function/{arf_id}", method = RequestMethod.DELETE)
String deleteAlmReqtmpFunction(@PathVariable("arf_id") Integer arfId);
/**
* 根据ID查询功能需求模板信息
*
* @param arfId
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function/{arf_id}", method = RequestMethod.GET)
FunctionDTO selectAlmReqtmpFunction(@PathVariable("arf_id") Integer arfId);
/**
* 根据artId查询资费需求模板信息
*
* @param artId
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function/function/{art_id}", method = RequestMethod.GET)
FunctionDTO selectFunction(@PathVariable("art_id") Integer artId);
/**
* 查询所有功能需求模板信息
*
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function/all", method = RequestMethod.GET)
Page<AlmReqtmpFunctionDTO> selectAllAlmReqtmpFunction(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "art_type", required = false) Integer artType,
@RequestParam(value = "art_name", required = false) String artName,
@RequestParam(value = "art_tag", required = false) String artTag,
@RequestParam(value = "art_region", required = false) Integer artRegion,
@RequestParam(value = "urgent_level", required = false) Integer urgentLevel,
@RequestParam(value = "submit_staff_name", required = false) String submitStaffName,
@RequestParam(value = "page_no") Integer pageNo,
@RequestParam(value = "page_size") Integer pageSize);
}
| UTF-8 | Java | 2,943 | java | AlmReqtmpFunctionController.java | Java | [] | null | [] | package com.asiainfo.rms.alm.demand.web;
import com.asiainfo.rms.alm.demand.dto.AlmReqtmpFunctionDTO;
import com.asiainfo.rms.alm.demand.dto.FunctionDTO;
import com.asiainfo.rms.core.api.Page;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/alm")
public interface AlmReqtmpFunctionController {
/**
* 新增功能需求模板信息
*
* @param functionDTO
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function", method = RequestMethod.POST)
String saveAlmReqtmpFunction(@RequestBody FunctionDTO functionDTO);
/**
* 修改功能需求模板信息
*
* @param functionDTO
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function", method = RequestMethod.PUT)
String updateAlmReqtmpFunction(@RequestBody FunctionDTO functionDTO);
/**
* 删除功能需求模板信息
*
* @param arfId
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function/{arf_id}", method = RequestMethod.DELETE)
String deleteAlmReqtmpFunction(@PathVariable("arf_id") Integer arfId);
/**
* 根据ID查询功能需求模板信息
*
* @param arfId
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function/{arf_id}", method = RequestMethod.GET)
FunctionDTO selectAlmReqtmpFunction(@PathVariable("arf_id") Integer arfId);
/**
* 根据artId查询资费需求模板信息
*
* @param artId
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function/function/{art_id}", method = RequestMethod.GET)
FunctionDTO selectFunction(@PathVariable("art_id") Integer artId);
/**
* 查询所有功能需求模板信息
*
* @return
*/
@RequestMapping(value = "/alm_reqtmp_function/all", method = RequestMethod.GET)
Page<AlmReqtmpFunctionDTO> selectAllAlmReqtmpFunction(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "art_type", required = false) Integer artType,
@RequestParam(value = "art_name", required = false) String artName,
@RequestParam(value = "art_tag", required = false) String artTag,
@RequestParam(value = "art_region", required = false) Integer artRegion,
@RequestParam(value = "urgent_level", required = false) Integer urgentLevel,
@RequestParam(value = "submit_staff_name", required = false) String submitStaffName,
@RequestParam(value = "page_no") Integer pageNo,
@RequestParam(value = "page_size") Integer pageSize);
}
| 2,943 | 0.57275 | 0.57275 | 71 | 38.591549 | 42.400364 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.450704 | false | false | 12 |
c9858434d9f33be61dc269745625f44d43c4a9a8 | 32,280,974,235,334 | 1ec7a10af1b1819f6682019239e08925ea62c3e8 | /app/src/main/java/com/futureskyltd/trackingmate/Model/AddMerchant/PhoneNo.java | ed40213e81c13d86addd11a6c99e1d07ea171906 | [] | no_license | SadakatulShakil/TrackingMate | https://github.com/SadakatulShakil/TrackingMate | 6b8da8a41e4b0ec8d3114d8784adb8633919afa5 | 9e72f8daebb7695e5e070421aa963d10f807973a | refs/heads/master | 2023-03-08T19:25:36.386000 | 2021-02-16T10:15:20 | 2021-02-16T10:15:20 | 336,779,121 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.futureskyltd.trackingmate.Model.AddMerchant;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class PhoneNo implements Serializable {
@SerializedName("numeric")
@Expose
private String numeric;
public String getNumeric() {
return numeric;
}
public void setNumeric(String numeric) {
this.numeric = numeric;
}
@Override
public String toString() {
return "PhoneNo{" +
"numeric='" + numeric + '\'' +
'}';
}
}
| UTF-8 | Java | 601 | java | PhoneNo.java | Java | [] | null | [] |
package com.futureskyltd.trackingmate.Model.AddMerchant;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class PhoneNo implements Serializable {
@SerializedName("numeric")
@Expose
private String numeric;
public String getNumeric() {
return numeric;
}
public void setNumeric(String numeric) {
this.numeric = numeric;
}
@Override
public String toString() {
return "PhoneNo{" +
"numeric='" + numeric + '\'' +
'}';
}
}
| 601 | 0.635607 | 0.635607 | 28 | 20.428572 | 18.131323 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 12 |
00686a8e16d3106d8fbf50829af6cdecf16cbd1c | 14,809,047,237,096 | 3e62a69d33c3fd94b410cd140ec5bf7f75b7e523 | /Ejercicio17/src/main/java/com/mycompany/ejercicio17/Ejercicio17.java | 68be4963d0ecb2cf8919141e4719157c0722c5a1 | [] | no_license | XXnikoDarkXX/1Trimestre | https://github.com/XXnikoDarkXX/1Trimestre | f7125415ef1c1f3814b90eb1b39224f40157e235 | d814b2ad45cf83c3ecc17746ca8224efcf92c35f | refs/heads/master | 2020-12-30T06:38:06.960000 | 2020-02-07T10:19:51 | 2020-02-07T10:19:51 | 238,895,239 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.ejercicio17;
import java.util.Scanner;
/**
*
* @author nicoc
*/
public class Ejercicio17 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc=new Scanner (System.in);
int numeroPersonas=cuantasPersonas();
String [] nombrePersona =new String [numeroPersonas];
String informeFinal="";
String [] apellidoPersona=new String [numeroPersonas];
byte[] edadPersona=new byte [numeroPersonas];
String [] nacionalidadPersona=new String [numeroPersonas];
String[] gen=new String [numeroPersonas];
for ( int i = 0; i < numeroPersonas; i++) {
System.out.println("Voy a pedir datos de una persona (pedir nombre, nacionalidad)");
nombrePersona [i] = pideNombre ("Dime tu nombre");
apellidoPersona [i]=pideNombre ("Dime tu 1º apellido");
System.out.println("Dime tu edad");
nacionalidadPersona[i]=pideNombre("Dime tu nacionalidad");
System.out.println("Dime tu edad");
edadPersona [i]=pideedad();
gen [i]=generos("Eres hombre/mujero/Bigenero/Cross–Dresser/Femme");
}
for (int i = 0; i < numeroPersonas; i++) {
System.out.print("los nombres son "+nombrePersona [i]);
System.out.print(" Los apellidos son "+apellidoPersona[i]);
System.out.print(" Las edades son "+edadPersona[i]);
System.out.println("La nacionalidad es "+nacionalidadPersona[i]);
System.out.println("Tu genero es "+gen[i]);
System.out.println("\n");
}
}
//Aquí para que funcione y no me haga bucle infinito tengo que crear una nueva variables
//como la String gen; y a esa compararla "Hombre" y "Mujer"
//Si comparo pregunta no me vale porque esta comparando "Eres Hombre/Mujer" y lo que yo ponga por el scan.nexline
public static String informe(String nombre, String apellido, byte edad, String nacionalidad,boolean genero) {
return nombre +" "+ apellido +", de "+ edad + " años , y nacionalidad " + nacionalidad + " Su género es" + genero;
}
/**
* Este metodo nos compara 5 tipos de generos y nos devuelve uno
* @param pregunta Para mandar el mensaje a preguntar
* @return Devuelve el genero que hayas escrito
*/
public static String generos (String pregunta){
Scanner scan = new Scanner(System.in);
String gen;
do {
System.out.println(pregunta);
gen=scan.nextLine();
}while (!gen.equalsIgnoreCase("Hombre")&&!gen.equalsIgnoreCase("Mujer")&&
!gen.equalsIgnoreCase("Bigenero")&&!gen.equalsIgnoreCase("Cross–Dresser")&&!gen.equalsIgnoreCase("Femme"));
if(gen.equalsIgnoreCase("Hombre")){
return "Eres Hombre";
}else if(gen.equalsIgnoreCase("Mujer")){
return "Eres Mujer";
}else if(gen.equalsIgnoreCase("BiGenero")){
return "Eres Bigenero";
}else if (gen.equalsIgnoreCase("Cross–Dresser")){
return "Eres Cross–Dresser";
}else if (gen.equalsIgnoreCase("Femme")) {
return "Eres Femme";
}
return "";
}
/**Esta funcion sirve para pedir los nombres y los apellidos
*
* @param mensaje el mensaje que vas a pedir
* @return devuelve dicho mensaje
*/
public static String pideNombre(String mensaje) {
Scanner scan = new Scanner(System.in);
System.out.println(mensaje);
return scan.nextLine();
}
/**
* Sirve para pedir el total de personas que vamos a pedir los datos
* @param personas Cantidad de personas que vamos a pedir los datos
* @return el numero de personas que vamos a pedir los datos
*/
public static int cuantasPersonas ( ){
Scanner scan=new Scanner (System.in);
int personas;
do{
System.out.println("Cuantas personas quieres pedir los datos, debe de ser entre 1 y 3");
personas=Integer.parseInt(scan.nextLine());
} while (personas>=4||personas<1);
return personas;
}
/**
* Este metodo sirve para pedir la edad de las personas
* @return la edad de la persona en byte
*/
public static Byte pideedad() {
Scanner scan = new Scanner(System.in);
return Byte.parseByte(scan.nextLine());
}
}
| UTF-8 | Java | 4,827 | java | Ejercicio17.java | Java | [
{
"context": "o17;\n\nimport java.util.Scanner;\n\n/**\n *\n * @author nicoc\n */\npublic class Ejercicio17 {\n\n /**\n * @p",
"end": 271,
"score": 0.9996408820152283,
"start": 266,
"tag": "USERNAME",
"value": "nicoc"
}
] | 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.mycompany.ejercicio17;
import java.util.Scanner;
/**
*
* @author nicoc
*/
public class Ejercicio17 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc=new Scanner (System.in);
int numeroPersonas=cuantasPersonas();
String [] nombrePersona =new String [numeroPersonas];
String informeFinal="";
String [] apellidoPersona=new String [numeroPersonas];
byte[] edadPersona=new byte [numeroPersonas];
String [] nacionalidadPersona=new String [numeroPersonas];
String[] gen=new String [numeroPersonas];
for ( int i = 0; i < numeroPersonas; i++) {
System.out.println("Voy a pedir datos de una persona (pedir nombre, nacionalidad)");
nombrePersona [i] = pideNombre ("Dime tu nombre");
apellidoPersona [i]=pideNombre ("Dime tu 1º apellido");
System.out.println("Dime tu edad");
nacionalidadPersona[i]=pideNombre("Dime tu nacionalidad");
System.out.println("Dime tu edad");
edadPersona [i]=pideedad();
gen [i]=generos("Eres hombre/mujero/Bigenero/Cross–Dresser/Femme");
}
for (int i = 0; i < numeroPersonas; i++) {
System.out.print("los nombres son "+nombrePersona [i]);
System.out.print(" Los apellidos son "+apellidoPersona[i]);
System.out.print(" Las edades son "+edadPersona[i]);
System.out.println("La nacionalidad es "+nacionalidadPersona[i]);
System.out.println("Tu genero es "+gen[i]);
System.out.println("\n");
}
}
//Aquí para que funcione y no me haga bucle infinito tengo que crear una nueva variables
//como la String gen; y a esa compararla "Hombre" y "Mujer"
//Si comparo pregunta no me vale porque esta comparando "Eres Hombre/Mujer" y lo que yo ponga por el scan.nexline
public static String informe(String nombre, String apellido, byte edad, String nacionalidad,boolean genero) {
return nombre +" "+ apellido +", de "+ edad + " años , y nacionalidad " + nacionalidad + " Su género es" + genero;
}
/**
* Este metodo nos compara 5 tipos de generos y nos devuelve uno
* @param pregunta Para mandar el mensaje a preguntar
* @return Devuelve el genero que hayas escrito
*/
public static String generos (String pregunta){
Scanner scan = new Scanner(System.in);
String gen;
do {
System.out.println(pregunta);
gen=scan.nextLine();
}while (!gen.equalsIgnoreCase("Hombre")&&!gen.equalsIgnoreCase("Mujer")&&
!gen.equalsIgnoreCase("Bigenero")&&!gen.equalsIgnoreCase("Cross–Dresser")&&!gen.equalsIgnoreCase("Femme"));
if(gen.equalsIgnoreCase("Hombre")){
return "Eres Hombre";
}else if(gen.equalsIgnoreCase("Mujer")){
return "Eres Mujer";
}else if(gen.equalsIgnoreCase("BiGenero")){
return "Eres Bigenero";
}else if (gen.equalsIgnoreCase("Cross–Dresser")){
return "Eres Cross–Dresser";
}else if (gen.equalsIgnoreCase("Femme")) {
return "Eres Femme";
}
return "";
}
/**Esta funcion sirve para pedir los nombres y los apellidos
*
* @param mensaje el mensaje que vas a pedir
* @return devuelve dicho mensaje
*/
public static String pideNombre(String mensaje) {
Scanner scan = new Scanner(System.in);
System.out.println(mensaje);
return scan.nextLine();
}
/**
* Sirve para pedir el total de personas que vamos a pedir los datos
* @param personas Cantidad de personas que vamos a pedir los datos
* @return el numero de personas que vamos a pedir los datos
*/
public static int cuantasPersonas ( ){
Scanner scan=new Scanner (System.in);
int personas;
do{
System.out.println("Cuantas personas quieres pedir los datos, debe de ser entre 1 y 3");
personas=Integer.parseInt(scan.nextLine());
} while (personas>=4||personas<1);
return personas;
}
/**
* Este metodo sirve para pedir la edad de las personas
* @return la edad de la persona en byte
*/
public static Byte pideedad() {
Scanner scan = new Scanner(System.in);
return Byte.parseByte(scan.nextLine());
}
}
| 4,827 | 0.604154 | 0.601662 | 124 | 37.830647 | 29.139465 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.524194 | false | false | 12 |
cb4e2b85e25f3b184eee9c6218a168612de388f7 | 25,305,947,358,677 | d1abe9f256e6232e54edcb3e4a86caaffa9bd5cc | /Shopping-Mall Demo/jt-cart/src/main/java/com/jt/cart/mapper/CartMapper.java | 7e394e400896790a2856b7607d11cf9330db955d | [
"MIT"
] | permissive | chncx/Shopping-Mall | https://github.com/chncx/Shopping-Mall | 03c82818992c4037eae8df3381de0b0ae8d3490f | 12487d1d51cf5692119989c8a5114ff323747667 | refs/heads/master | 2022-09-17T08:27:05.762000 | 2019-10-14T07:05:36 | 2019-10-14T07:05:36 | 147,501,639 | 3 | 0 | MIT | false | 2022-09-01T22:48:54 | 2018-09-05T10:35:51 | 2019-10-14T07:05:42 | 2022-09-01T22:48:51 | 57,543 | 1 | 0 | 15 | JavaScript | false | false | package com.jt.cart.mapper;
import com.jt.cart.pojo.Cart;
import com.jt.common.mapper.SysMapper;
public interface CartMapper extends SysMapper<Cart>{
Cart findCartByUI(Cart cart);
void updateCartNum(Cart cart);
}
| UTF-8 | Java | 220 | java | CartMapper.java | Java | [] | null | [] | package com.jt.cart.mapper;
import com.jt.cart.pojo.Cart;
import com.jt.common.mapper.SysMapper;
public interface CartMapper extends SysMapper<Cart>{
Cart findCartByUI(Cart cart);
void updateCartNum(Cart cart);
}
| 220 | 0.777273 | 0.777273 | 12 | 17.333334 | 18.199512 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 12 |
22bdeef424a6e181d282a92369c86aaca9cc8d4e | 16,183,436,804,776 | 20e817526bfe38af4b05445d88a11332a5345843 | /cdqj_app/src/main/java/com/cdqj/cdqjpatrolandroid/view/i/IPersonMapView.java | bb35abcc6fe46a20fbfb06f91dcbb57815c6480c | [] | no_license | tinggu/CdqjPatrolModel | https://github.com/tinggu/CdqjPatrolModel | a653436da4132b25bda3f8ba278544b81256eabd | e62a8136286357caedd893d8c4bc09e4356cb5d7 | refs/heads/master | 2022-07-05T14:00:32.368000 | 2020-05-12T13:23:59 | 2020-05-12T13:23:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cdqj.cdqjpatrolandroid.view.i;
import com.cdqj.cdqjpatrolandroid.base.BaseView;
import com.cdqj.cdqjpatrolandroid.bean.LocationBean;
import com.cdqj.cdqjpatrolandroid.http.BasePostResponse;
import java.util.List;
/**
* Created by lyf on 2018/9/10 14:48
*
* @author lyf
* desc:人员轨迹
*/
public interface IPersonMapView extends BaseView{
/**
* 获取人员轨迹列表结果
* @param body body
*/
void onGetPersonTrajectorySuccess(BasePostResponse<List<LocationBean>> body);
}
| UTF-8 | Java | 526 | java | IPersonMapView.java | Java | [
{
"context": "sponse;\n\nimport java.util.List;\n\n/**\n * Created by lyf on 2018/9/10 14:48\n *\n * @author lyf\n * desc:人员轨迹",
"end": 249,
"score": 0.9993857145309448,
"start": 246,
"tag": "USERNAME",
"value": "lyf"
},
{
"context": " * Created by lyf on 2018/9/10 14:48\n *\n * @aut... | null | [] | package com.cdqj.cdqjpatrolandroid.view.i;
import com.cdqj.cdqjpatrolandroid.base.BaseView;
import com.cdqj.cdqjpatrolandroid.bean.LocationBean;
import com.cdqj.cdqjpatrolandroid.http.BasePostResponse;
import java.util.List;
/**
* Created by lyf on 2018/9/10 14:48
*
* @author lyf
* desc:人员轨迹
*/
public interface IPersonMapView extends BaseView{
/**
* 获取人员轨迹列表结果
* @param body body
*/
void onGetPersonTrajectorySuccess(BasePostResponse<List<LocationBean>> body);
}
| 526 | 0.743952 | 0.721774 | 21 | 22.619047 | 23.078491 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 12 |
c7362a96044687484ed143ba209485daed6c937f | 9,028,021,256,687 | 6e8e4b91982dd6597974e324b66407644dc6e502 | /src/Calculator.java | 0feea195374515ffb6f78908c7468bf3b32371b6 | [] | no_license | ARGutierrez/Java-GUI-Applications | https://github.com/ARGutierrez/Java-GUI-Applications | 4d5edcecc9a32fc3907cbcc2cd0cf56e6e9dc2b3 | 458e66efcc33292e44856324f4aa82db53532a35 | refs/heads/master | 2021-01-22T09:27:35.149000 | 2014-03-10T02:33:22 | 2014-03-10T02:33:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Simple Calculator
*/
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
public class Calculator extends JFrame {
private static final long serialVersionUID = 1L;
Calculator() {
setTitle("Calculator");
setSize(400, 350);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
JPanel panel = new CalcPanel();
add(panel);
setVisible(true);
}
public class CalcPanel extends JPanel {
Dimension buttonSize = new Dimension(60, 60);
Boolean add = false, sub = false, divide = false, multiply = false;
private JButton oneBtn, twoBtn, threeBtn, fourBtn, fiveBtn, sixBtn,
svnBtn, eightBtn, nineBtn, tenBtn, eqlBtn, addBtn, subBtn,
multBtn, divBtn, solvBtn, decBtn;
private double temp, tempCalc;
private JTextField result;
String display = "";
public CalcPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 3));
panel.add(svnBtn = new JButton("7"));
panel.add(eightBtn = new JButton("8"));
panel.add(nineBtn = new JButton("9"));
panel.add(divBtn = new JButton("/"));
panel.add(fourBtn = new JButton("4"));
panel.add(fiveBtn = new JButton("5"));
panel.add(sixBtn = new JButton("6"));
panel.add(multBtn = new JButton("*"));
panel.add(oneBtn = new JButton("1"));
panel.add(twoBtn = new JButton("2"));
panel.add(threeBtn = new JButton("3"));
panel.add(subBtn = new JButton("-"));
panel.add(tenBtn = new JButton("0"));
panel.add(decBtn = new JButton("."));
panel.add(addBtn = new JButton("+"));
panel.add(solvBtn = new JButton("="));
JPanel panelTwo = new JPanel();
panelTwo.setLayout(new FlowLayout());
panelTwo.add(result = new JTextField(20));
result.setHorizontalAlignment(JTextField.RIGHT);
result.setEditable(false);
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(panelTwo);
p.add(panel);
add(p);
oneBtn.addActionListener(new OneListener());
oneBtn.setPreferredSize(buttonSize);
twoBtn.addActionListener(new TwoListener());
threeBtn.addActionListener(new ThreeListener());
fourBtn.addActionListener(new FourListener());
fiveBtn.addActionListener(new FiveListener());
sixBtn.addActionListener(new SixListener());
svnBtn.addActionListener(new SevenListener());
eightBtn.addActionListener(new EightListener());
nineBtn.addActionListener(new NineListener());
tenBtn.addActionListener(new ZeroListener());
addBtn.addActionListener(new AddListener());
subBtn.addActionListener(new SubListener());
multBtn.addActionListener(new MultListener());
divBtn.addActionListener(new DivListener());
solvBtn.addActionListener(new SolveListener());
decBtn.addActionListener(new DecimalListener());
}
class DecimalListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + ".");
}
}
class OneListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "1");
}
}
class TwoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "2");
}
}
class ThreeListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "3");
}
}
class FourListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "4");
}
}
class FiveListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "5");
}
}
class SixListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "6");
}
}
class SevenListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "7");
}
}
class EightListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "8");
}
}
class NineListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "9");
}
}
class ZeroListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "0");
}
}
class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
temp = Double.parseDouble(result.getText());
result.setText("");
add = true;
}
}
class SubListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
temp = Double.parseDouble(result.getText());
result.setText("");
sub = true;
}
}
class MultListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
temp = Double.parseDouble(result.getText());
result.setText("");
multiply = true;
}
}
class DivListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
temp = Double.parseDouble(result.getText());
result.setText("");
divide = true;
}
}
class SolveListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
tempCalc = Double.parseDouble(result.getText());
if (add == true)
tempCalc = tempCalc + temp;
else if (sub == true)
tempCalc = temp - tempCalc;
else if (multiply == true)
tempCalc = tempCalc * temp;
else if (divide == true)
tempCalc = temp / tempCalc;
result.setText(Double.toString(tempCalc));
add = false;
sub = false;
multiply = false;
divide = false;
}
}
}
public static void main(String[] args) {
JFrame frame = new Calculator();
}
} | UTF-8 | Java | 6,284 | java | Calculator.java | Java | [] | null | [] | /*
* Simple Calculator
*/
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
public class Calculator extends JFrame {
private static final long serialVersionUID = 1L;
Calculator() {
setTitle("Calculator");
setSize(400, 350);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
JPanel panel = new CalcPanel();
add(panel);
setVisible(true);
}
public class CalcPanel extends JPanel {
Dimension buttonSize = new Dimension(60, 60);
Boolean add = false, sub = false, divide = false, multiply = false;
private JButton oneBtn, twoBtn, threeBtn, fourBtn, fiveBtn, sixBtn,
svnBtn, eightBtn, nineBtn, tenBtn, eqlBtn, addBtn, subBtn,
multBtn, divBtn, solvBtn, decBtn;
private double temp, tempCalc;
private JTextField result;
String display = "";
public CalcPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 3));
panel.add(svnBtn = new JButton("7"));
panel.add(eightBtn = new JButton("8"));
panel.add(nineBtn = new JButton("9"));
panel.add(divBtn = new JButton("/"));
panel.add(fourBtn = new JButton("4"));
panel.add(fiveBtn = new JButton("5"));
panel.add(sixBtn = new JButton("6"));
panel.add(multBtn = new JButton("*"));
panel.add(oneBtn = new JButton("1"));
panel.add(twoBtn = new JButton("2"));
panel.add(threeBtn = new JButton("3"));
panel.add(subBtn = new JButton("-"));
panel.add(tenBtn = new JButton("0"));
panel.add(decBtn = new JButton("."));
panel.add(addBtn = new JButton("+"));
panel.add(solvBtn = new JButton("="));
JPanel panelTwo = new JPanel();
panelTwo.setLayout(new FlowLayout());
panelTwo.add(result = new JTextField(20));
result.setHorizontalAlignment(JTextField.RIGHT);
result.setEditable(false);
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(panelTwo);
p.add(panel);
add(p);
oneBtn.addActionListener(new OneListener());
oneBtn.setPreferredSize(buttonSize);
twoBtn.addActionListener(new TwoListener());
threeBtn.addActionListener(new ThreeListener());
fourBtn.addActionListener(new FourListener());
fiveBtn.addActionListener(new FiveListener());
sixBtn.addActionListener(new SixListener());
svnBtn.addActionListener(new SevenListener());
eightBtn.addActionListener(new EightListener());
nineBtn.addActionListener(new NineListener());
tenBtn.addActionListener(new ZeroListener());
addBtn.addActionListener(new AddListener());
subBtn.addActionListener(new SubListener());
multBtn.addActionListener(new MultListener());
divBtn.addActionListener(new DivListener());
solvBtn.addActionListener(new SolveListener());
decBtn.addActionListener(new DecimalListener());
}
class DecimalListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + ".");
}
}
class OneListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "1");
}
}
class TwoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "2");
}
}
class ThreeListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "3");
}
}
class FourListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "4");
}
}
class FiveListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "5");
}
}
class SixListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "6");
}
}
class SevenListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "7");
}
}
class EightListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "8");
}
}
class NineListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "9");
}
}
class ZeroListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = result.getText();
result.setText(display + "0");
}
}
class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
temp = Double.parseDouble(result.getText());
result.setText("");
add = true;
}
}
class SubListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
temp = Double.parseDouble(result.getText());
result.setText("");
sub = true;
}
}
class MultListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
temp = Double.parseDouble(result.getText());
result.setText("");
multiply = true;
}
}
class DivListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
temp = Double.parseDouble(result.getText());
result.setText("");
divide = true;
}
}
class SolveListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
tempCalc = Double.parseDouble(result.getText());
if (add == true)
tempCalc = tempCalc + temp;
else if (sub == true)
tempCalc = temp - tempCalc;
else if (multiply == true)
tempCalc = tempCalc * temp;
else if (divide == true)
tempCalc = temp / tempCalc;
result.setText(Double.toString(tempCalc));
add = false;
sub = false;
multiply = false;
divide = false;
}
}
}
public static void main(String[] args) {
JFrame frame = new Calculator();
}
} | 6,284 | 0.688097 | 0.682527 | 232 | 26.090517 | 19.174009 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.935345 | false | false | 12 |
9a974adb1c0da983323e75cebe8497d389fc7193 | 12,369,505,875,901 | e1ccac90b98ece60ea9bb3ac6cc17c12f8b46101 | /app/src/main/java/com/example/vmartin/pocmvvm/ui/foodtrucklist/FoodTruckClickCallback.java | 544bc55a9acb14d6391798d0239bd1595165b70d | [] | no_license | Immoweb/MVVM_ARCH_COMP_POC | https://github.com/Immoweb/MVVM_ARCH_COMP_POC | a70d49318441da82bca6960f41aa47965a659db0 | 6107c9a487f5e9f6973f8a58ab6625f67df6b403 | refs/heads/master | 2021-01-01T16:32:57.711000 | 2017-08-03T14:25:37 | 2017-08-03T14:25:37 | 97,856,182 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.vmartin.pocmvvm.ui.foodtrucklist;
import com.example.vmartin.pocmvvm.model.Record;
public interface FoodTruckClickCallback {
void onClick(Record record);
}
| UTF-8 | Java | 184 | java | FoodTruckClickCallback.java | Java | [] | null | [] | package com.example.vmartin.pocmvvm.ui.foodtrucklist;
import com.example.vmartin.pocmvvm.model.Record;
public interface FoodTruckClickCallback {
void onClick(Record record);
}
| 184 | 0.798913 | 0.798913 | 9 | 19.444445 | 22.151554 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 12 |
d8b1e3907b78792661257f762e656d91a94e97eb | 6,828,998,017,547 | d6042554ace48d578eabd7fc7f0d0c8a53fde8bc | /src/utils/FastaExporter.java | 7bce9d870fad9a42a9e878ca42280ff71c356437 | [] | no_license | MisterDeenis/Gen_Project | https://github.com/MisterDeenis/Gen_Project | f0fd34a5e489b7e362456af9b189aad8d55e590b | 0514b5e55ffcd454358fcb712212b5d172169ecc | refs/heads/master | 2021-01-09T05:25:08.558000 | 2017-05-10T23:15:17 | 2017-05-10T23:15:17 | 80,766,514 | 2 | 2 | null | false | 2017-05-05T13:18:48 | 2017-02-02T20:38:27 | 2017-03-29T19:44:26 | 2017-05-05T13:18:48 | 39,452 | 2 | 2 | 0 | Java | null | null | package utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import modele.genome.Chromosome;
import modele.genome.DNA;
import modele.genome.SNP;
/**
* Classe pour exporter l'ADN en un fichier .fasta
*
* @author Les génies du génome
*
*/
public class FastaExporter {
public static void sauvegarder(DNA adn, String path) throws IOException {
File fichierSave = new File(path + "/GPV - ADN.fas");
System.out.println(fichierSave);
PrintWriter printW = new PrintWriter(new FileWriter(fichierSave));
for (String s : adn.getChrSymbols()) {
Chromosome[] pairChromo = adn.getChrPair(s);
for (int i = 0; i < pairChromo.length; i++) {
Chromosome chromosome = pairChromo[i];
for (SNP snp : chromosome.getSnips().values()) {
String allele = snp.getAllele().toString();
String rs = snp.getRS();
String sequence = snp.getSeq();
printW.println("> GPV | Chromosome " + s + "." + (i + 1) + " | allele=" + allele + " at "
+ snp.getVarPos() + " | rs=" + rs);
printW.println(sequence);
printW.println();
}
}
}
printW.close();
}
}
| UTF-8 | Java | 1,177 | java | FastaExporter.java | Java | [
{
"context": "exporter l'ADN en un fichier .fasta\n * \n * @author Les génies du génome\n *\n */\npublic class FastaExporter {\n\n\tpublic stat",
"end": 296,
"score": 0.9883020520210266,
"start": 276,
"tag": "NAME",
"value": "Les génies du génome"
}
] | null | [] | package utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import modele.genome.Chromosome;
import modele.genome.DNA;
import modele.genome.SNP;
/**
* Classe pour exporter l'ADN en un fichier .fasta
*
* @author <NAME>
*
*/
public class FastaExporter {
public static void sauvegarder(DNA adn, String path) throws IOException {
File fichierSave = new File(path + "/GPV - ADN.fas");
System.out.println(fichierSave);
PrintWriter printW = new PrintWriter(new FileWriter(fichierSave));
for (String s : adn.getChrSymbols()) {
Chromosome[] pairChromo = adn.getChrPair(s);
for (int i = 0; i < pairChromo.length; i++) {
Chromosome chromosome = pairChromo[i];
for (SNP snp : chromosome.getSnips().values()) {
String allele = snp.getAllele().toString();
String rs = snp.getRS();
String sequence = snp.getSeq();
printW.println("> GPV | Chromosome " + s + "." + (i + 1) + " | allele=" + allele + " at "
+ snp.getVarPos() + " | rs=" + rs);
printW.println(sequence);
printW.println();
}
}
}
printW.close();
}
}
| 1,161 | 0.640851 | 0.639149 | 48 | 23.479166 | 23.179543 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.416667 | false | false | 12 |
d2de3c5f6b1e504de374cadfbeb9fe940106f342 | 28,647,431,876,772 | 891cac5bd9f232e394499912b3840fc80392b151 | /src/it/caculli/gzc/sokoban/gui/GameFrame.java | dc0d23a3607a261db77e9351f89cdf1ebe550256 | [
"BSD-3-Clause"
] | permissive | GiorgioCaculli/Sokoban-Java | https://github.com/GiorgioCaculli/Sokoban-Java | 83d9a70432fb987734519dcf8b7c2843c37f7b38 | 9b9b7dddebb7cd1095aafaadfe975c85d61db74e | refs/heads/master | 2020-04-07T05:36:33.752000 | 2020-02-15T13:54:29 | 2020-02-15T13:54:29 | 143,467,467 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.caculli.gzc.sokoban.gui;
// AWT
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// SWING
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import static javax.swing.BorderFactory.createEmptyBorder;
// SOKOBAN
import static it.caculli.gzc.sokoban.sokocore.StringHandler.getString;
/**
* Game interface that allows the user to choose among
* new game, load game or back.
* @version 1.0
* @author Giorgio CACULLI
*/
public class GameFrame extends JFrame implements ActionListener
{
private LevelFrame lvl;
private static final long serialVersionUID = 1L;
private static final JButton newGame = new JButton(getString("new_game"));
private static final JButton loadGame = new JButton(getString("load_game"));
private static final JButton backToMenu = new JButton(getString("back_to_main_menu"));
private JPanel gamePanel = new JPanel();
private static final GridLayout gl = new GridLayout(3, 0, 20, 20);
private static final MainFrame mf = new MainFrame();
private static final LevelFrame newLevel = new LevelFrame( "/it/caculli/gzc/sokoban/level/level001.xsb" );
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource() == newGame)
{
this.setVisible(false);
newLevel.setVisible(true);
}
else if(evt.getSource() == backToMenu)
{
this.setVisible(false);
mf.setVisible(true);
}
}
private void buttonActions()
{
loadGame.setEnabled(false);
newGame.addActionListener(this);
backToMenu.addActionListener(this);
}
public GameFrame()
{
buttonActions();
gamePanel.setFocusable(true);
gamePanel.setLayout(gl);
gamePanel.setBorder(createEmptyBorder(50, 50, 50, 50));
gamePanel.add(newGame);
gamePanel.add(loadGame);
gamePanel.add(backToMenu);
add(gamePanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
setResizable(false);
setSize(800, 600);
setTitle(getString("game"));
}
}
| UTF-8 | Java | 2,202 | java | GameFrame.java | Java | [
{
"context": "ame, load game or back.\n * @version 1.0\n * @author Giorgio CACULLI\n */\npublic class GameFrame extends JFrame impleme",
"end": 513,
"score": 0.9998540878295898,
"start": 498,
"tag": "NAME",
"value": "Giorgio CACULLI"
}
] | null | [] | package it.caculli.gzc.sokoban.gui;
// AWT
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// SWING
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import static javax.swing.BorderFactory.createEmptyBorder;
// SOKOBAN
import static it.caculli.gzc.sokoban.sokocore.StringHandler.getString;
/**
* Game interface that allows the user to choose among
* new game, load game or back.
* @version 1.0
* @author <NAME>
*/
public class GameFrame extends JFrame implements ActionListener
{
private LevelFrame lvl;
private static final long serialVersionUID = 1L;
private static final JButton newGame = new JButton(getString("new_game"));
private static final JButton loadGame = new JButton(getString("load_game"));
private static final JButton backToMenu = new JButton(getString("back_to_main_menu"));
private JPanel gamePanel = new JPanel();
private static final GridLayout gl = new GridLayout(3, 0, 20, 20);
private static final MainFrame mf = new MainFrame();
private static final LevelFrame newLevel = new LevelFrame( "/it/caculli/gzc/sokoban/level/level001.xsb" );
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource() == newGame)
{
this.setVisible(false);
newLevel.setVisible(true);
}
else if(evt.getSource() == backToMenu)
{
this.setVisible(false);
mf.setVisible(true);
}
}
private void buttonActions()
{
loadGame.setEnabled(false);
newGame.addActionListener(this);
backToMenu.addActionListener(this);
}
public GameFrame()
{
buttonActions();
gamePanel.setFocusable(true);
gamePanel.setLayout(gl);
gamePanel.setBorder(createEmptyBorder(50, 50, 50, 50));
gamePanel.add(newGame);
gamePanel.add(loadGame);
gamePanel.add(backToMenu);
add(gamePanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
setResizable(false);
setSize(800, 600);
setTitle(getString("game"));
}
}
| 2,193 | 0.671662 | 0.659855 | 74 | 28.756756 | 24.130171 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621622 | false | false | 12 |
bb602e386b5dedeca6e89e4ccba451367348a75a | 15,358,803,083,357 | 6a701a268b9192d8ea496207c4aa51de2dcd85b2 | /src/business/algorithm/decisionAlgorithm/AbstractDecisionAlgorithm.java | 320ae95a94e5292957a8711a50e1a71a6e7de328 | [
"MIT"
] | permissive | 5l1v3r1/AutoTrading | https://github.com/5l1v3r1/AutoTrading | debc5120762b8a6cc812b700a6af67d0dfd4cd7f | b3f6022daccb0d32a765c8d3df64df2655a70fd3 | refs/heads/master | 2023-03-16T13:35:41.034000 | 2018-04-05T13:11:35 | 2018-04-05T13:11:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package business.algorithm.decisionAlgorithm;
import dataAccess.databaseManagement.entity.AssetEntity;
import dataAccess.databaseManagement.entity.PriceEntity;
import java.util.ArrayList;
import java.util.TreeMap;
public abstract class AbstractDecisionAlgorithm {
public abstract OutputForDecisionAlgorithm runAlgorithm();
public AbstractDecisionAlgorithm(
TreeMap<AssetEntity, ArrayList<PriceEntity>> priceList) {
super();
this.priceList = priceList;
}
protected TreeMap<AssetEntity, ArrayList<PriceEntity>> priceList;
public TreeMap<AssetEntity, ArrayList<PriceEntity>> getPriceList() {
return priceList;
}
public void setPriceList(
TreeMap<AssetEntity, ArrayList<PriceEntity>> priceList) {
this.priceList = priceList;
}
@SuppressWarnings("rawtypes")
public TreeMap<String, Class> getParameterList() {
TreeMap<String, Class> map = new TreeMap<String, Class>();
return map;
}
public TreeMap<String, Object> getDefaultValuesList() {
TreeMap<String, Object> map = new TreeMap<String, Object>();
return map;
}
public void setParameterValue(TreeMap<String, Object> map) {
}
}
| UTF-8 | Java | 1,185 | java | AbstractDecisionAlgorithm.java | Java | [] | null | [] | package business.algorithm.decisionAlgorithm;
import dataAccess.databaseManagement.entity.AssetEntity;
import dataAccess.databaseManagement.entity.PriceEntity;
import java.util.ArrayList;
import java.util.TreeMap;
public abstract class AbstractDecisionAlgorithm {
public abstract OutputForDecisionAlgorithm runAlgorithm();
public AbstractDecisionAlgorithm(
TreeMap<AssetEntity, ArrayList<PriceEntity>> priceList) {
super();
this.priceList = priceList;
}
protected TreeMap<AssetEntity, ArrayList<PriceEntity>> priceList;
public TreeMap<AssetEntity, ArrayList<PriceEntity>> getPriceList() {
return priceList;
}
public void setPriceList(
TreeMap<AssetEntity, ArrayList<PriceEntity>> priceList) {
this.priceList = priceList;
}
@SuppressWarnings("rawtypes")
public TreeMap<String, Class> getParameterList() {
TreeMap<String, Class> map = new TreeMap<String, Class>();
return map;
}
public TreeMap<String, Object> getDefaultValuesList() {
TreeMap<String, Object> map = new TreeMap<String, Object>();
return map;
}
public void setParameterValue(TreeMap<String, Object> map) {
}
}
| 1,185 | 0.732489 | 0.732489 | 42 | 26.214285 | 25.261051 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.380952 | false | false | 12 |
5224c6ef1b90f62057938619dc65f6c9d2cf606d | 16,965,120,858,187 | e39954407078ad880abf4e1fd3d8849eb2b021c3 | /1.Two Sum.java | c2b2e27075bc849a20c4d6369257221cf36b8c3b | [] | no_license | remembercode/leetcode | https://github.com/remembercode/leetcode | 81d8e1b9116ed48b0e7848bcec30b81d6837af15 | e5e7adb55a95ef688f5027aa05c50ab06407e031 | refs/heads/main | 2023-07-12T22:30:05.545000 | 2021-08-24T00:29:26 | 2021-08-24T00:29:26 | 399,280,413 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | / *
force
Runtime: 53 ms, faster than 17.90% of Java online submissions for Two Sum.
Memory Usage: 39.1 MB, less than 76.12% of Java online submissions for Two Sum.
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
int first_p = 0;
int second_p = 0;
int[] result = new int[2];
for(first_p = 0; first_p < nums.length ; first_p = first_p + 1)
{
second_p = first_p + 1;
while (second_p < nums.length)
{
if (nums[first_p] + nums[second_p] == target)
{
result[0] = first_p;
result[1] = second_p;
}
second_p = second_p + 1;
}
}
return result;
}
}
/ *
hashmap
Runtime: 31 ms, faster than 40.54% of Java online submissions for Two Sum.
Memory Usage: 40.5 MB, less than 13.34% of Java online submissions for Two Sum.
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> Diff = new HashMap<Integer, Integer>();
int first_p = 0;
int second_p = 0;
int[] result = new int[2];
for(first_p = 0; first_p < nums.length ; first_p = first_p + 1)
{
int diff_ = target - nums[first_p];
int has = -1;
try
{
has = Diff.get(diff_);
}catch(Exception e1)
{
has = -1;
}
if (has >= 0)
{
result[0] = has;
result[1] = first_p;
break;
}
Diff.put(nums[first_p], first_p);
}
return result;
}
}
| UTF-8 | Java | 1,833 | java | 1.Two Sum.java | Java | [] | null | [] | / *
force
Runtime: 53 ms, faster than 17.90% of Java online submissions for Two Sum.
Memory Usage: 39.1 MB, less than 76.12% of Java online submissions for Two Sum.
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
int first_p = 0;
int second_p = 0;
int[] result = new int[2];
for(first_p = 0; first_p < nums.length ; first_p = first_p + 1)
{
second_p = first_p + 1;
while (second_p < nums.length)
{
if (nums[first_p] + nums[second_p] == target)
{
result[0] = first_p;
result[1] = second_p;
}
second_p = second_p + 1;
}
}
return result;
}
}
/ *
hashmap
Runtime: 31 ms, faster than 40.54% of Java online submissions for Two Sum.
Memory Usage: 40.5 MB, less than 13.34% of Java online submissions for Two Sum.
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> Diff = new HashMap<Integer, Integer>();
int first_p = 0;
int second_p = 0;
int[] result = new int[2];
for(first_p = 0; first_p < nums.length ; first_p = first_p + 1)
{
int diff_ = target - nums[first_p];
int has = -1;
try
{
has = Diff.get(diff_);
}catch(Exception e1)
{
has = -1;
}
if (has >= 0)
{
result[0] = has;
result[1] = first_p;
break;
}
Diff.put(nums[first_p], first_p);
}
return result;
}
}
| 1,833 | 0.430987 | 0.405892 | 65 | 27.200001 | 23.409531 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.523077 | false | false | 12 |
d6b04c86f19167b6c66b9032fa77eb3dff9fecd1 | 21,028,159,936,278 | c5a036c14d269a4bd50cda952f7e515bc8239e88 | /src/main/java/org/societies/teleport/DisabledTeleporter.java | b6536fd5a5c98848635a92cc7f775551eb893330 | [
"WTFPL"
] | permissive | mc-societies/societies | https://github.com/mc-societies/societies | ced028a8ed5cd264a9588ec6a9ac09c5ba5a670b | 26efa11313cedbb56ef315583783a833d1260b0b | refs/heads/master | 2021-01-20T08:46:49.895000 | 2015-04-06T20:20:30 | 2015-04-06T20:20:30 | 19,467,852 | 3 | 3 | null | false | 2015-04-06T20:20:30 | 2014-05-05T19:13:34 | 2015-04-06T20:05:00 | 2015-04-06T20:20:30 | 3,657 | 4 | 1 | 3 | Java | null | null | package org.societies.teleport;
import org.societies.api.math.Location;
import org.societies.groups.member.Member;
/**
* Represents a DisabledTeleporter
*/
class DisabledTeleporter implements Teleporter {
@Override
public void teleport(Member member, Location target) {
member.send("teleport.disabled");
}
}
| UTF-8 | Java | 333 | java | DisabledTeleporter.java | Java | [] | null | [] | package org.societies.teleport;
import org.societies.api.math.Location;
import org.societies.groups.member.Member;
/**
* Represents a DisabledTeleporter
*/
class DisabledTeleporter implements Teleporter {
@Override
public void teleport(Member member, Location target) {
member.send("teleport.disabled");
}
}
| 333 | 0.738739 | 0.738739 | 15 | 21.200001 | 20.367294 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 12 |
8cd517618d8c1e057000c9762f75542fc0923e7f | 4,853,313,051,669 | 767f54a7fcc688a646a2585a24fb0a092348f6f3 | /Jlc/src/com/dharmu/jlc/javalangpackage/Lab2C.java | 7c2912baeea51b68b4a887a5a09ffc45a7b25bae | [] | no_license | Hunterr404/Jlc | https://github.com/Hunterr404/Jlc | e6a561716e99a0c69dbb06564142842a8345b935 | a844d4c2eb71c86d9a9b4d075477099ecad923e9 | refs/heads/master | 2020-04-06T07:25:46.588000 | 2019-04-24T14:27:18 | 2019-04-24T14:27:18 | 157,272,094 | 0 | 0 | null | false | 2019-04-24T14:27:19 | 2018-11-12T20:25:36 | 2019-04-24T14:00:18 | 2019-04-24T14:27:19 | 426 | 0 | 0 | 0 | Java | false | false | package com.dharmu.jlc.javalangpackage;
public class Lab2C {
public static void main(String[] args) throws CloneNotSupportedException {
Hai2C hai = new Hai2C(10);
Hello2C h1=new Hello2C(20,hai);
Hello2C h2=(Hello2C)h1.clone();
h1.show();
h2.show();
System.out.println(h1==h2);
System.out.println(h1.hai==h2.hai);
h2.y=30;
h1.show();
h2.show();
h2.hai.x=111;
h1.show();
h2.show();
}
}
class Hai2C{
int x;
Hai2C(int x){
this.x=x;
}
}
class Hello2C implements Cloneable{
int y;
Hai2C hai;
Hello2C(int y,Hai2C hai){
this.y=y;
this.hai=hai;
}
void show() {
System.out.println("Hello-->y: "+y);
System.out.println("Hai-->x: "+hai.x);
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
} | UTF-8 | Java | 794 | java | Lab2C.java | Java | [] | null | [] | package com.dharmu.jlc.javalangpackage;
public class Lab2C {
public static void main(String[] args) throws CloneNotSupportedException {
Hai2C hai = new Hai2C(10);
Hello2C h1=new Hello2C(20,hai);
Hello2C h2=(Hello2C)h1.clone();
h1.show();
h2.show();
System.out.println(h1==h2);
System.out.println(h1.hai==h2.hai);
h2.y=30;
h1.show();
h2.show();
h2.hai.x=111;
h1.show();
h2.show();
}
}
class Hai2C{
int x;
Hai2C(int x){
this.x=x;
}
}
class Hello2C implements Cloneable{
int y;
Hai2C hai;
Hello2C(int y,Hai2C hai){
this.y=y;
this.hai=hai;
}
void show() {
System.out.println("Hello-->y: "+y);
System.out.println("Hai-->x: "+hai.x);
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
} | 794 | 0.629723 | 0.583123 | 42 | 16.952381 | 16.405504 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 12 |
4caed6cfbc8f059672b5a0bf85ad8c6d942c5de2 | 5,119,601,022,992 | f30c473f26d0db389f72f2c5cb81770c79054ce2 | /src/_5_com/ds/linklist_todo/MergeForLargestSum_IMP_3.java | 9bf73721c0de92d37f5e43f72470db455c7b98bc | [] | no_license | njaisw/interview | https://github.com/njaisw/interview | 734097332773a945d6b4c91136c495a0d7b20516 | 55435d85136b4c8253f270e1046c70ac5b28b861 | refs/heads/master | 2022-12-22T22:01:38.734000 | 2020-09-25T23:10:35 | 2020-09-25T23:10:35 | 291,564,085 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package _5_com.ds.linklist_todo;
/*
* http://www.geeksforgeeks.org/maximum-sum-linked-list-two-sorted-linked-lists-common-nodes/
*
* Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end.
* The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists).
Input:
List1 = 1->3->30->90->120->240->511
List2 = 0->3->12->32->90->125->240->249
Output: Following is maximum sum linked list out of two input lists
list = 1->3->12->32->90->125->240->511
we switch at 3 and 240 to get above maximum sum linked list
*/
public class MergeForLargestSum_IMP_3 {
Node maxChain(Node head1, Node head2) {
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
Node curr1 = head1;
Node curr2 = head2;
int sum1 = 0;
int sum2 = 0;
Node result = null;
Node prev = null;
while (curr1 != null && curr2 != null) {
if (curr1.data == curr2.data) {
sum1 += curr1.data;
sum2 += curr2.data;
if (sum1 <= sum2) {
if (result == null) {
result = head2;
prev = curr2;
} else {
prev.next = head2.next;
//TODO moves prev to the tail of the ll
prev = curr2;
}
} else {
if (result == null) {
result = head1;
prev = curr1;
} else {
prev.next = head1.next;
prev = curr1;
}
}
//IMP: Sum sets to 0
head1 = curr1;
head2 = curr2;
sum1 = 0;
sum2 = 0;
curr1 = curr1.next;
curr2 = curr2.next;
} else if (curr1.data < curr2.data) {
sum1 += curr1.data;
curr1 = curr1.next;
} else {
sum2 += curr2.data;
curr2 = curr2.next;
}
}
while (curr1 != null) {
sum1 += curr1.data;
curr1 = curr1.next;
}
while (curr2 != null) {
sum2 += curr2.data;
curr2 = curr2.next;
}
if (result != null) {
if (sum1 <= sum2) {
prev.next = head2.next;
} else {
prev.next = head1.next;
}
} else {
if (sum1 <= sum2) {
result = head2;
} else {
result = head1;
}
}
return result;
}
public static void main(String args[]) {
LinkList_IMP_3 ll = new LinkList_IMP_3();
Node head1 = null;
head1 = ll.addNode(1, head1);
head1 = ll.addNode(3, head1);
head1 = ll.addNode(30, head1);
head1 = ll.addNode(90, head1);
head1 = ll.addNode(120, head1);
head1 = ll.addNode(240, head1);
head1 = ll.addNode(243, head1);
head1 = ll.addNode(251, head1);
head1 = ll.addNode(511, head1);
Node head2 = null;
head2 = ll.addNode(0, head2);
head2 = ll.addNode(3, head2);
head2 = ll.addNode(12, head2);
head2 = ll.addNode(32, head2);
head2 = ll.addNode(90, head2);
head2 = ll.addNode(125, head2);
head2 = ll.addNode(240, head2);
head2 = ll.addNode(249, head2);
head2 = ll.addNode(251, head2);
head2 = ll.addNode(260, head2);
MergeForLargestSum_IMP_3 mls = new MergeForLargestSum_IMP_3();
Node result = mls.maxChain(head1, head2);
ll.printList(result);
}
}
| UTF-8 | Java | 3,098 | java | MergeForLargestSum_IMP_3.java | Java | [] | null | [] | package _5_com.ds.linklist_todo;
/*
* http://www.geeksforgeeks.org/maximum-sum-linked-list-two-sorted-linked-lists-common-nodes/
*
* Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end.
* The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists).
Input:
List1 = 1->3->30->90->120->240->511
List2 = 0->3->12->32->90->125->240->249
Output: Following is maximum sum linked list out of two input lists
list = 1->3->12->32->90->125->240->511
we switch at 3 and 240 to get above maximum sum linked list
*/
public class MergeForLargestSum_IMP_3 {
Node maxChain(Node head1, Node head2) {
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
Node curr1 = head1;
Node curr2 = head2;
int sum1 = 0;
int sum2 = 0;
Node result = null;
Node prev = null;
while (curr1 != null && curr2 != null) {
if (curr1.data == curr2.data) {
sum1 += curr1.data;
sum2 += curr2.data;
if (sum1 <= sum2) {
if (result == null) {
result = head2;
prev = curr2;
} else {
prev.next = head2.next;
//TODO moves prev to the tail of the ll
prev = curr2;
}
} else {
if (result == null) {
result = head1;
prev = curr1;
} else {
prev.next = head1.next;
prev = curr1;
}
}
//IMP: Sum sets to 0
head1 = curr1;
head2 = curr2;
sum1 = 0;
sum2 = 0;
curr1 = curr1.next;
curr2 = curr2.next;
} else if (curr1.data < curr2.data) {
sum1 += curr1.data;
curr1 = curr1.next;
} else {
sum2 += curr2.data;
curr2 = curr2.next;
}
}
while (curr1 != null) {
sum1 += curr1.data;
curr1 = curr1.next;
}
while (curr2 != null) {
sum2 += curr2.data;
curr2 = curr2.next;
}
if (result != null) {
if (sum1 <= sum2) {
prev.next = head2.next;
} else {
prev.next = head1.next;
}
} else {
if (sum1 <= sum2) {
result = head2;
} else {
result = head1;
}
}
return result;
}
public static void main(String args[]) {
LinkList_IMP_3 ll = new LinkList_IMP_3();
Node head1 = null;
head1 = ll.addNode(1, head1);
head1 = ll.addNode(3, head1);
head1 = ll.addNode(30, head1);
head1 = ll.addNode(90, head1);
head1 = ll.addNode(120, head1);
head1 = ll.addNode(240, head1);
head1 = ll.addNode(243, head1);
head1 = ll.addNode(251, head1);
head1 = ll.addNode(511, head1);
Node head2 = null;
head2 = ll.addNode(0, head2);
head2 = ll.addNode(3, head2);
head2 = ll.addNode(12, head2);
head2 = ll.addNode(32, head2);
head2 = ll.addNode(90, head2);
head2 = ll.addNode(125, head2);
head2 = ll.addNode(240, head2);
head2 = ll.addNode(249, head2);
head2 = ll.addNode(251, head2);
head2 = ll.addNode(260, head2);
MergeForLargestSum_IMP_3 mls = new MergeForLargestSum_IMP_3();
Node result = mls.maxChain(head1, head2);
ll.printList(result);
}
}
| 3,098 | 0.606843 | 0.53583 | 120 | 24.816668 | 24.97665 | 226 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.266667 | false | false | 12 |
432a7dee31b6267f73f117634186dfd88529287a | 12,283,606,472,323 | 421e2d00f26c1859e41f1bd9d331bee3d4957d8a | /KHJ/MyApplication/app/src/main/java/kr/ac/sungkyul/myapplication/calculator/abcdadfsa.java | 2d09e7eef1eab160ec5cd067e2d12e62af322cbd | [] | no_license | KimHunJin/GravityStudy | https://github.com/KimHunJin/GravityStudy | c81f14e926461ec4b8fe0234dbeb4aa8a51182b0 | 43d6954e6effa48847db7b0b3da6c1622e4621e0 | refs/heads/master | 2021-01-10T16:45:51.596000 | 2017-09-20T17:08:43 | 2017-09-20T17:08:43 | 48,991,686 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.ac.sungkyul.myapplication.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import kr.ac.sungkyul.myapplication.R;
public class abcdadfsa extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abcdadfsa);
}
}
| UTF-8 | Java | 394 | java | abcdadfsa.java | Java | [] | null | [] | package kr.ac.sungkyul.myapplication.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import kr.ac.sungkyul.myapplication.R;
public class abcdadfsa extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abcdadfsa);
}
}
| 394 | 0.769036 | 0.766497 | 15 | 25.266666 | 22.338209 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 12 |
44bf863b6a7a8bb30f1b7f8c695caa1bad31e3b2 | 16,054,587,758,456 | e4dadacdd9e09b1d2b358ef055b525e7ae032b6f | /app/src/main/java/com/netimen/playground/toolbar/DynamicIconView.java | 28212954f29d84584932ac654429297ff3d700d4 | [] | no_license | netimen/FloatingToolbar | https://github.com/netimen/FloatingToolbar | 199ddb8d34dfc0118462bc2f33538c1caa1ad835 | fe189ac9b6b789d3dc096543befac218cdaa48fc | refs/heads/master | 2016-09-06T01:38:56.116000 | 2015-07-27T15:01:48 | 2015-07-27T15:01:48 | 38,243,435 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 2015 Bookmate.
* All Rights Reserved.
* <p/>
* Author: Dmitry Gordeev <netimen@dreamindustries.co>
* Date: 06.07.15
*/
package com.netimen.playground.toolbar;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
public class DynamicIconView extends View {
@SuppressWarnings("unused")
private static final String LOG_TAG = DynamicIconView.class.getSimpleName();
private IconRenderer renderer;
public DynamicIconView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
renderer.draw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
renderer.onMeasure(getMeasuredWidth(), getMeasuredHeight());
}
public void setRenderer(IconRenderer renderer) {
this.renderer = renderer;
}
public interface IconRenderer {
void draw(Canvas canvas);
void onMeasure(int measuredWidth, int measuredHeight);
}
}
| UTF-8 | Java | 1,170 | java | DynamicIconView.java | Java | [
{
"context": "okmate.\n * All Rights Reserved.\n * <p/>\n * Author: Dmitry Gordeev <netimen@dreamindustries.co>\n * Date: 06.07.15\n",
"end": 93,
"score": 0.9998842477798462,
"start": 79,
"tag": "NAME",
"value": "Dmitry Gordeev"
},
{
"context": "ghts Reserved.\n * <p/>\n * Author: ... | null | [] | /**
* Copyright (c) 2015 Bookmate.
* All Rights Reserved.
* <p/>
* Author: <NAME> <<EMAIL>>
* Date: 06.07.15
*/
package com.netimen.playground.toolbar;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
public class DynamicIconView extends View {
@SuppressWarnings("unused")
private static final String LOG_TAG = DynamicIconView.class.getSimpleName();
private IconRenderer renderer;
public DynamicIconView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
renderer.draw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
renderer.onMeasure(getMeasuredWidth(), getMeasuredHeight());
}
public void setRenderer(IconRenderer renderer) {
this.renderer = renderer;
}
public interface IconRenderer {
void draw(Canvas canvas);
void onMeasure(int measuredWidth, int measuredHeight);
}
}
| 1,143 | 0.705983 | 0.697436 | 45 | 25 | 23.288528 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 12 |
6a2b07f5311e1bbbf66d3ad0c02a27f8de7211f2 | 21,646,635,178,489 | 1742af1c7de3244675db2bee02d7f9acc63cceff | /app/src/main/java/com/scsvn/whc_2016/main/viewImage/ViewImageActivity.java | c1ee574d55852eae83d6d9d7a3c82304d4b49cad | [] | no_license | tranxuanloc/44818c16d3d8784e893e136c10fa8c2e8cacf03f3c0dd7f64fb4c74a45eaa467 | https://github.com/tranxuanloc/44818c16d3d8784e893e136c10fa8c2e8cacf03f3c0dd7f64fb4c74a45eaa467 | 10c22da8110d52414362ca0452fe7f7598b006d9 | a2ebb4739898876a4e17c8b277945f55defd88f7 | refs/heads/master | 2020-04-12T05:36:59.153000 | 2017-04-06T03:01:21 | 2017-04-06T03:01:21 | 61,184,968 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scsvn.whc_2016.main.viewImage;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import com.scsvn.whc_2016.R;
import com.scsvn.whc_2016.login.LoginActivity;
import com.scsvn.whc_2016.main.BaseActivity;
import com.scsvn.whc_2016.preferences.LoginPref;
import com.scsvn.whc_2016.utilities.Const;
import com.scsvn.whc_2016.utilities.Utilities;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ViewImageActivity extends BaseActivity {
@Bind(R.id.iv_view_image_image)
ImageView ivImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_image);
ButterKnife.bind(this);
String src = getIntent().getStringExtra("src");
Utilities.getPicasso(this).load(Utilities.generateUrlImage(this, src)).into(ivImage);
}
@OnClick(R.id.iv_home)
public void home() {
onBackPressed();
}
@Override
protected void onResume() {
Const.isActivating = true;
super.onResume();
}
@Override
protected void onStop() {
Const.isActivating = false;
super.onStop();
}
}
| UTF-8 | Java | 1,265 | java | ViewImageActivity.java | Java | [] | null | [] | package com.scsvn.whc_2016.main.viewImage;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import com.scsvn.whc_2016.R;
import com.scsvn.whc_2016.login.LoginActivity;
import com.scsvn.whc_2016.main.BaseActivity;
import com.scsvn.whc_2016.preferences.LoginPref;
import com.scsvn.whc_2016.utilities.Const;
import com.scsvn.whc_2016.utilities.Utilities;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ViewImageActivity extends BaseActivity {
@Bind(R.id.iv_view_image_image)
ImageView ivImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_image);
ButterKnife.bind(this);
String src = getIntent().getStringExtra("src");
Utilities.getPicasso(this).load(Utilities.generateUrlImage(this, src)).into(ivImage);
}
@OnClick(R.id.iv_home)
public void home() {
onBackPressed();
}
@Override
protected void onResume() {
Const.isActivating = true;
super.onResume();
}
@Override
protected void onStop() {
Const.isActivating = false;
super.onStop();
}
}
| 1,265 | 0.706719 | 0.684585 | 48 | 25.354166 | 20.136503 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.520833 | false | false | 12 |
3c5c5890864af7e615af7053496451419f78d3fc | 12,283,606,476,926 | dadb3bb2800bf7595b3c67b4227d8d724b0de8e9 | /WatchableWebClientNewUI/src/comcast/test/watchpage/VerifyDisplayOfPlaylistTitleWhileScrollDownFromTop.java | 76622dc5d9a62e23221be0cc611ff7cf312280aa | [] | no_license | LalaTesting/Cucumber-Framework | https://github.com/LalaTesting/Cucumber-Framework | ca4bf6092dda7a492551fc5857815b194f3211fd | 171d11e11067753c9cc3dca3e08ace94c8124744 | refs/heads/master | 2021-09-02T04:48:54.361000 | 2017-12-30T12:38:07 | 2017-12-30T12:38:07 | 115,720,963 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package comcast.test.watchpage;
import static comcast.util.PropertyFileReader.ObjRepoProp;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;
import comcast.config.BaseTest;
import comcast.custom.CustomFun;
import comcast.pages.HomePage;
import comcast.pages.WatchPage;
/**
*
* @author Manoj.Paragen
* Description: This test script verifies the display of playlist title in header while scrolling down from top of the page.
* Created on 22-November-2016
* Last updated on 22-November-2016
*
*/
public class VerifyDisplayOfPlaylistTitleWhileScrollDownFromTop extends
BaseTest {
static HomePage homePage;
static WatchPage watchPage;
/**
* Open the browser, Enter the Watchable URL
*/
@Test(description = "Step 1: Open the browser, Enter the Watchable URL", priority = 1)
public void Step01_NavigeteToURL() throws Exception {
// Home page object instance creation
// homePage = new HomePage(driver);
// Navigates to Watchable application URL
homePage = HomePage.navigateToWatchableHomePage(driver, baseUrl);
log.info("Successfully navigated to Watchable Home page\n");
Reporter.log("<p>Successfully navigated to Watchable Home page");
}
/**
* Verify play lists section
*/
@Test(description = "Step 2: Verify Play list section is present in home page.", priority = 2)
public void Step02_VerifyPlaylistSection() throws Exception {
// Verify play lists section
Assert.assertTrue(CustomFun.isElementPresent(By.xpath(ObjRepoProp
.getProperty("homePagePlaylistSection_XPATH")), driver),
"Play list section is not present in home page.");
log.info("Play list section is present in home page.\n");
Reporter.log("<p>Play list section is present in home page.");
}
/**
* Click on play icon from any of the playlist
*/
@Test(description = "Step 3: Click on play icon from any of the playlist from playlist section.", priority = 3)
public void Step03_ClickOnPlaylistIcon() throws Exception {
// Playlist page object instance creation
// playlistPage = new PlaylistPage(driver);
// Click on play icon from selected playlist.
watchPage = homePage.clickOnPlaylistPlayIcon();
log.info("Successfully navigated to Watch page.\n");
Reporter.log("<p>Successfully navigated to Watch page.");
}
/**
* Scroll down from the top of the page.
*/
@Test(description = "Step 4: Scroll down from the top of the page.", priority = 4)
public void Step04_ScrollDownFromTopOfPage() throws Exception {
// Scroll down from the top of the page.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,250)", "");
Thread.sleep(2500);
// Verify Playlist title is displaying
Assert.assertTrue(CustomFun.isElementPresent(By.xpath(ObjRepoProp
.getProperty("watchPagePLaylistShowTitle_XPATH")), driver),
"Playlist title is displayed next to the hamburger menu.");
log.info("Playlist title is displayed next to the hamburger menu.\n");
Reporter.log("<p>Playlist title is displayed next to the hamburger menu.");
log.info("Show title displayed is: "
+ driver.findElement(
By.xpath(ObjRepoProp
.getProperty("watchPagePLaylistShowTitle_XPATH")))
.getText() + "\n");
Reporter.log("<p>Show title displayed is: "
+ driver.findElement(
By.xpath(ObjRepoProp
.getProperty("watchPagePLaylistShowTitle_XPATH")))
.getText());
}
}
| UTF-8 | Java | 3,516 | java | VerifyDisplayOfPlaylistTitleWhileScrollDownFromTop.java | Java | [
{
"context": "mport comcast.pages.WatchPage;\n\n/**\n * \n * @author Manoj.Paragen \n * Description: This test script verifies the di",
"end": 421,
"score": 0.9998941421508789,
"start": 408,
"tag": "NAME",
"value": "Manoj.Paragen"
}
] | null | [] | package comcast.test.watchpage;
import static comcast.util.PropertyFileReader.ObjRepoProp;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;
import comcast.config.BaseTest;
import comcast.custom.CustomFun;
import comcast.pages.HomePage;
import comcast.pages.WatchPage;
/**
*
* @author Manoj.Paragen
* Description: This test script verifies the display of playlist title in header while scrolling down from top of the page.
* Created on 22-November-2016
* Last updated on 22-November-2016
*
*/
public class VerifyDisplayOfPlaylistTitleWhileScrollDownFromTop extends
BaseTest {
static HomePage homePage;
static WatchPage watchPage;
/**
* Open the browser, Enter the Watchable URL
*/
@Test(description = "Step 1: Open the browser, Enter the Watchable URL", priority = 1)
public void Step01_NavigeteToURL() throws Exception {
// Home page object instance creation
// homePage = new HomePage(driver);
// Navigates to Watchable application URL
homePage = HomePage.navigateToWatchableHomePage(driver, baseUrl);
log.info("Successfully navigated to Watchable Home page\n");
Reporter.log("<p>Successfully navigated to Watchable Home page");
}
/**
* Verify play lists section
*/
@Test(description = "Step 2: Verify Play list section is present in home page.", priority = 2)
public void Step02_VerifyPlaylistSection() throws Exception {
// Verify play lists section
Assert.assertTrue(CustomFun.isElementPresent(By.xpath(ObjRepoProp
.getProperty("homePagePlaylistSection_XPATH")), driver),
"Play list section is not present in home page.");
log.info("Play list section is present in home page.\n");
Reporter.log("<p>Play list section is present in home page.");
}
/**
* Click on play icon from any of the playlist
*/
@Test(description = "Step 3: Click on play icon from any of the playlist from playlist section.", priority = 3)
public void Step03_ClickOnPlaylistIcon() throws Exception {
// Playlist page object instance creation
// playlistPage = new PlaylistPage(driver);
// Click on play icon from selected playlist.
watchPage = homePage.clickOnPlaylistPlayIcon();
log.info("Successfully navigated to Watch page.\n");
Reporter.log("<p>Successfully navigated to Watch page.");
}
/**
* Scroll down from the top of the page.
*/
@Test(description = "Step 4: Scroll down from the top of the page.", priority = 4)
public void Step04_ScrollDownFromTopOfPage() throws Exception {
// Scroll down from the top of the page.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,250)", "");
Thread.sleep(2500);
// Verify Playlist title is displaying
Assert.assertTrue(CustomFun.isElementPresent(By.xpath(ObjRepoProp
.getProperty("watchPagePLaylistShowTitle_XPATH")), driver),
"Playlist title is displayed next to the hamburger menu.");
log.info("Playlist title is displayed next to the hamburger menu.\n");
Reporter.log("<p>Playlist title is displayed next to the hamburger menu.");
log.info("Show title displayed is: "
+ driver.findElement(
By.xpath(ObjRepoProp
.getProperty("watchPagePLaylistShowTitle_XPATH")))
.getText() + "\n");
Reporter.log("<p>Show title displayed is: "
+ driver.findElement(
By.xpath(ObjRepoProp
.getProperty("watchPagePLaylistShowTitle_XPATH")))
.getText());
}
}
| 3,516 | 0.733504 | 0.723265 | 112 | 30.392857 | 28.626085 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6875 | false | false | 12 |
1c53c47d2afd78a7ab6259085c4c8331b111f386 | 20,461,224,208,021 | 2ec1577180d0302808d285daddf927454d0fc94a | /dssd-backend/src/main/java/io/dssd/repository/AbstractRepository.java | 2b6e1d698f409bb6df040720fdca1c99793f8f97 | [] | no_license | fede0dea/dssd-incidentes | https://github.com/fede0dea/dssd-incidentes | d836561526208a90a8ae0becd3ef83347d1dafd6 | f97ccc4f9863b6fedb81a2a349bf4db8c06bf717 | refs/heads/master | 2021-08-27T20:08:19.255000 | 2017-11-28T06:44:43 | 2017-11-28T06:44:43 | 104,413,363 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.dssd.repository;
import io.dssd.model.Cliente;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Created by federico on 12/10/17.
*/
public abstract class AbstractRepository<T> {
@PersistenceContext
protected EntityManager entityManager;
public T save(T entity) {
entityManager.persist(entity);
return entity;
}
public abstract T getById(Long entityId);
}
| UTF-8 | Java | 568 | java | AbstractRepository.java | Java | [
{
"context": "persistence.PersistenceContext;\n\n/**\n * Created by federico on 12/10/17.\n */\npublic abstract class AbstractRe",
"end": 287,
"score": 0.9344775080680847,
"start": 279,
"tag": "USERNAME",
"value": "federico"
}
] | null | [] | package io.dssd.repository;
import io.dssd.model.Cliente;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Created by federico on 12/10/17.
*/
public abstract class AbstractRepository<T> {
@PersistenceContext
protected EntityManager entityManager;
public T save(T entity) {
entityManager.persist(entity);
return entity;
}
public abstract T getById(Long entityId);
}
| 568 | 0.757042 | 0.746479 | 25 | 21.719999 | 20.110733 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 12 |
5f3c83c9e7e0f5415d9286ea9b8061f033fa3173 | 3,461,743,651,996 | 8884705ee8f10f65d947352a9bf95c6732bafbd5 | /src/main/java/dareboost/api/client/report/pojos/Config.java | a313cf7d653684269b9d0f065d9226424a0b3884 | [] | no_license | DareBoost/dareboost-api-client | https://github.com/DareBoost/dareboost-api-client | 0a934077b6437f888ed481ebd33c57099de6b3af | f377c02d6cde8bcd0ba99b3432b0a9a047255660 | refs/heads/master | 2021-01-17T12:12:56.536000 | 2014-11-21T07:51:46 | 2014-11-21T07:51:46 | 26,908,081 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dareboost.api.client.report.pojos;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import dareboost.api.client.config.Browser;
import dareboost.api.client.global.Bandwidth;
import dareboost.api.client.global.BasicAuth;
import dareboost.api.client.global.Screen;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
*
* The config described in a report POJO
*
* @author Remi Damlencour
*/
@JsonInclude(value=Include.NON_EMPTY)
public class Config {
public String location;
public Browser browser;
public boolean isMobile;
public Bandwidth bandwidth;
public Integer latency;
public boolean isPrivate;
public Screen screen;
public BasicAuth basicAuth;
public List<Map<String, String>> postData = new ArrayList<>();
public List<Map<String, String>> header = new ArrayList<>();
}
| UTF-8 | Java | 895 | java | Config.java | Java | [
{
"context": "e config described in a report POJO\n * \n * @author Remi Damlencour\n */\n@JsonInclude(value=Include.NON_EMPTY)\npublic ",
"end": 492,
"score": 0.9998815655708313,
"start": 477,
"tag": "NAME",
"value": "Remi Damlencour"
}
] | null | [] | package dareboost.api.client.report.pojos;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import dareboost.api.client.config.Browser;
import dareboost.api.client.global.Bandwidth;
import dareboost.api.client.global.BasicAuth;
import dareboost.api.client.global.Screen;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
*
* The config described in a report POJO
*
* @author <NAME>
*/
@JsonInclude(value=Include.NON_EMPTY)
public class Config {
public String location;
public Browser browser;
public boolean isMobile;
public Bandwidth bandwidth;
public Integer latency;
public boolean isPrivate;
public Screen screen;
public BasicAuth basicAuth;
public List<Map<String, String>> postData = new ArrayList<>();
public List<Map<String, String>> header = new ArrayList<>();
}
| 886 | 0.782123 | 0.782123 | 33 | 26.121212 | 18.978069 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 12 |
1d94ee140ec35f0069b4af7d5057f0abcd2227b0 | 20,882,131,003,074 | e35f42320124dbcb1d6feafd4a02e955b7884d51 | /src/test/java/com/leokom/games/chess/player/PlayerBuilderTest.java | 7368ced897a09f9938371064758ee578579f54b3 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | lrozenblyum/chess | https://github.com/lrozenblyum/chess | 412bcc52395fd2355918772f226fc349787eaeba | c1e3eba8238eb61849fc53474f9d2d6144543d00 | refs/heads/master | 2023-06-27T11:06:04.264000 | 2023-02-26T18:46:23 | 2023-02-26T18:46:23 | 5,416,161 | 13 | 2 | Apache-2.0 | false | 2023-06-14T22:22:24 | 2012-08-14T17:34:07 | 2023-06-11T09:32:45 | 2023-06-14T22:22:20 | 3,062 | 11 | 3 | 119 | Java | false | false | package com.leokom.games.chess.player;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.mockito.Mockito;
import com.leokom.games.chess.engine.Move;
//it's a test for test infrastructure
public class PlayerBuilderTest {
@Test
public void initialPositionNotTerminal() {
Player player = new PlayerBuilder(Mockito.mock( Player.class )).build();
player.opponentSuggestsMeStartNewGameWhite();
assertFalse( player.getPosition().isTerminal() );
}
//ensures proper position returning by the built player
@Test
public void positionAfterResignTerminal() {
Player player = new PlayerBuilder(Mockito.mock( Player.class )).move( Move.RESIGN ).build();
player.opponentSuggestsMeStartNewGameWhite();
assertTrue( player.getPosition().isTerminal() );
}
}
| UTF-8 | Java | 833 | java | PlayerBuilderTest.java | Java | [] | null | [] | package com.leokom.games.chess.player;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.mockito.Mockito;
import com.leokom.games.chess.engine.Move;
//it's a test for test infrastructure
public class PlayerBuilderTest {
@Test
public void initialPositionNotTerminal() {
Player player = new PlayerBuilder(Mockito.mock( Player.class )).build();
player.opponentSuggestsMeStartNewGameWhite();
assertFalse( player.getPosition().isTerminal() );
}
//ensures proper position returning by the built player
@Test
public void positionAfterResignTerminal() {
Player player = new PlayerBuilder(Mockito.mock( Player.class )).move( Move.RESIGN ).build();
player.opponentSuggestsMeStartNewGameWhite();
assertTrue( player.getPosition().isTerminal() );
}
}
| 833 | 0.77551 | 0.77551 | 27 | 29.851852 | 25.239159 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.148148 | false | false | 12 |
15deaaa1437eaa612124925354c83c20323e82e0 | 16,819,091,940,893 | 04a32921f2bb8f859d4e2495479ba8ee4064830f | /summer-dubbo/provider/src/main/java/tanaduus/github/io/SummerProvider.java | 1eb8b873222315753ea47219337c22ffafa6c54e | [] | no_license | tanaduus/tanaduus.github.io | https://github.com/tanaduus/tanaduus.github.io | 26494e52acbcf109b6c60fb50465ff6b66ab66ff | 6f72091e527bc5edb28982505045671db397ff2b | refs/heads/master | 2022-12-21T10:21:23.069000 | 2022-10-13T07:17:21 | 2022-10-13T07:17:21 | 184,445,559 | 1 | 0 | null | false | 2022-12-16T09:44:08 | 2019-05-01T16:24:09 | 2022-01-05T07:57:45 | 2022-12-16T09:44:06 | 290 | 1 | 0 | 16 | Java | false | false | package tanaduus.github.io;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.ClusterRules;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.InitializingBean;
import java.math.BigDecimal;
/**
* @author 夏加龙
* @date 2022/9/16
*/
@Slf4j
@DubboService(version = "1.0", validation = "true", cluster = ClusterRules.FAIL_FAST)
public class SummerProvider implements ISummerProvider, InitializingBean {
@Override
public BaseResult<SummerResp> call(BaseReq req) {
RpcContext.getContext();
return BaseResult.newSuccess(SummerResp.builder()
.name("测试:" + Constant.UID)
.amount(BigDecimal.valueOf(12))
.extra("额外信息")
.build());
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("SummerProvider loaded");
}
} | UTF-8 | Java | 971 | java | SummerProvider.java | Java | [
{
"context": "an;\n\nimport java.math.BigDecimal;\n\n/**\n * @author 夏加龙\n * @date 2022/9/16\n */\n@Slf4j\n@DubboService(versi",
"end": 322,
"score": 0.9995734691619873,
"start": 319,
"tag": "NAME",
"value": "夏加龙"
}
] | null | [] | package tanaduus.github.io;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.ClusterRules;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.InitializingBean;
import java.math.BigDecimal;
/**
* @author 夏加龙
* @date 2022/9/16
*/
@Slf4j
@DubboService(version = "1.0", validation = "true", cluster = ClusterRules.FAIL_FAST)
public class SummerProvider implements ISummerProvider, InitializingBean {
@Override
public BaseResult<SummerResp> call(BaseReq req) {
RpcContext.getContext();
return BaseResult.newSuccess(SummerResp.builder()
.name("测试:" + Constant.UID)
.amount(BigDecimal.valueOf(12))
.extra("额外信息")
.build());
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("SummerProvider loaded");
}
} | 971 | 0.685205 | 0.670514 | 35 | 26.257143 | 24.181862 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371429 | false | false | 12 |
249e8d604a041340844d93b7819c4af5a031a62c | 29,635,274,352,412 | 58c60d0c3cf43043858547f3a1439c17c2203d0f | /src/programmer_interview/Q037_MaxBST.java | e2df29e45acb75d3b87b87a0b4df56fa1dc87e38 | [] | no_license | zhengjilei/Algorithm | https://github.com/zhengjilei/Algorithm | 6ecf3ff774b5e16561519afbcda5fdb96c0a34ff | ca581019fd5cdd1eb7f1eded932018d6f1f3f6c5 | refs/heads/master | 2023-04-09T11:43:37.556000 | 2021-04-10T04:54:07 | 2021-04-10T04:54:07 | 157,518,526 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package programmer_interview;
import org.junit.Test;
/**
* 求二叉树的最大二叉搜索树,返回根节点
* created by Ethan-Walker on 2018/12/27
*/
public class Q037_MaxBST {
public TreeNode getMaxBST(TreeNode root) {
int[] record = new int[3];
return getMaxBST(root, record);
}
/**
* record[0] 节点总数: 表示以root为根的树中最大二叉搜索子树的节点总数
* record[1] 最小值:表示以root为根的树 且 该树是BST 时,所有节点的最小值(当该树不是 BST 时该值没有意义)
* record[2] 最大值:表示以root为根的树 且 该树是BST 时,所有节点的最大值(当该树不是 BST 时该值没有意义)
*
* @param record
* @return
*/
public TreeNode getMaxBST(TreeNode root, int[] record) {
if (root == null) {
record[0] = 0;
record[1] = Integer.MAX_VALUE;// 因为要和 父节点比较,让父节点满足二叉搜索树的判定条件,故设为最大数
record[2] = Integer.MIN_VALUE;
return null;
}
TreeNode lBSTRoot = getMaxBST(root.left, record); // 左子树中的最大二叉搜索树信息
int lSize = record[0];
int lMin = record[1];
int lMax = record[2];
TreeNode rBSTRoot = getMaxBST(root.right, record);// 不用担心 左子树的record 值对右子树的 record 计算有影响,因为 record 值都是自下往上推导的
int rSize = record[0];
int rMin = record[1];
int rMax = record[2];
// 判断当前root为根的二叉树是否是 BST
if (root.left == lBSTRoot && root.right == rBSTRoot && root.val > lMax && root.val < rMin) {
record[0] = lSize + rSize + 1;
record[1] = lMin;
record[2] = rMax;
return root;
} else {
record[0] = Math.max(lSize, rSize);
// 不存储 record[1] [2] , 当前以 root 为节点的树不能构成BST,存储 min max 没有意义了
return lSize > rSize ? lBSTRoot : rBSTRoot;
}
}
@Test
public void test(){
}
}
| UTF-8 | Java | 2,245 | java | Q037_MaxBST.java | Java | [
{
"context": "Test;\r\n\r\n/**\r\n * 求二叉树的最大二叉搜索树,返回根节点\r\n * created by Ethan-Walker on 2018/12/27\r\n */\r\npublic class Q037_MaxBST {\r\n\r",
"end": 113,
"score": 0.9784532785415649,
"start": 101,
"tag": "NAME",
"value": "Ethan-Walker"
}
] | null | [] | package programmer_interview;
import org.junit.Test;
/**
* 求二叉树的最大二叉搜索树,返回根节点
* created by Ethan-Walker on 2018/12/27
*/
public class Q037_MaxBST {
public TreeNode getMaxBST(TreeNode root) {
int[] record = new int[3];
return getMaxBST(root, record);
}
/**
* record[0] 节点总数: 表示以root为根的树中最大二叉搜索子树的节点总数
* record[1] 最小值:表示以root为根的树 且 该树是BST 时,所有节点的最小值(当该树不是 BST 时该值没有意义)
* record[2] 最大值:表示以root为根的树 且 该树是BST 时,所有节点的最大值(当该树不是 BST 时该值没有意义)
*
* @param record
* @return
*/
public TreeNode getMaxBST(TreeNode root, int[] record) {
if (root == null) {
record[0] = 0;
record[1] = Integer.MAX_VALUE;// 因为要和 父节点比较,让父节点满足二叉搜索树的判定条件,故设为最大数
record[2] = Integer.MIN_VALUE;
return null;
}
TreeNode lBSTRoot = getMaxBST(root.left, record); // 左子树中的最大二叉搜索树信息
int lSize = record[0];
int lMin = record[1];
int lMax = record[2];
TreeNode rBSTRoot = getMaxBST(root.right, record);// 不用担心 左子树的record 值对右子树的 record 计算有影响,因为 record 值都是自下往上推导的
int rSize = record[0];
int rMin = record[1];
int rMax = record[2];
// 判断当前root为根的二叉树是否是 BST
if (root.left == lBSTRoot && root.right == rBSTRoot && root.val > lMax && root.val < rMin) {
record[0] = lSize + rSize + 1;
record[1] = lMin;
record[2] = rMax;
return root;
} else {
record[0] = Math.max(lSize, rSize);
// 不存储 record[1] [2] , 当前以 root 为节点的树不能构成BST,存储 min max 没有意义了
return lSize > rSize ? lBSTRoot : rBSTRoot;
}
}
@Test
public void test(){
}
}
| 2,245 | 0.546584 | 0.528515 | 62 | 26.564516 | 26.378523 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false | 12 |
c34f764727978bbf1125976aa5ad31f545b70c27 | 4,518,305,608,325 | 6553bb5e7e043ffd1a11977c5f579b7eaadea42b | /app/src/main/java/done/homework/com/homeworkdone/interfaces/DateDialogListener.java | ed5b52d5ed7db899de875394ea23645651ed0a09 | [] | no_license | c1kad14/HomeworkDone | https://github.com/c1kad14/HomeworkDone | 572469e99f783fd182db56178052866563af7814 | df903ef5bcf17731aacdb58399c9cfbcf5966bf2 | refs/heads/master | 2020-05-29T13:56:24.030000 | 2019-06-17T22:40:29 | 2019-06-17T22:40:29 | 189,178,736 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package done.homework.com.homeworkdone.interfaces;
public interface DateDialogListener {
void onDateSelectedDialog(String inputText);
} | UTF-8 | Java | 143 | java | DateDialogListener.java | Java | [] | null | [] | package done.homework.com.homeworkdone.interfaces;
public interface DateDialogListener {
void onDateSelectedDialog(String inputText);
} | 143 | 0.811189 | 0.811189 | 8 | 17 | 21.971573 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 12 |
95b99bd32bba16a45b1024a2f69ac466ca96b1ea | 4,355,096,850,102 | 40ea74dbd62654ee78cef71bcf349e8e7164d6fe | /dp4j-tests/src/test/java/com/dp4j/samples/sub/ProtectedTest.java | cd67bc7fc48b8d37bad7bd7ab077569f0ca7202c | [] | no_license | 724686158/dp4j | https://github.com/724686158/dp4j | 5d48d7a945fb6a19d466611e0a64310001d62152 | f38bd9ce856997e15293a0f3d35afa1eaff2975a | refs/heads/master | 2020-05-09T21:54:31.277000 | 2018-08-11T05:47:40 | 2018-08-11T05:47:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.dp4j.samples.sub;
import com.dp4j.samples.ProtectedClass;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author simpatico
*/
public class ProtectedTest {
@Test
public void test() {
new ProtectedClass().doSth();
}
}
| UTF-8 | Java | 431 | java | ProtectedTest.java | Java | [
{
"context": "port static org.junit.Assert.*;\n\n/**\n *\n * @author simpatico\n */\npublic class ProtectedTest {\n\n @Test\n p",
"end": 315,
"score": 0.9985950589179993,
"start": 306,
"tag": "USERNAME",
"value": "simpatico"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.dp4j.samples.sub;
import com.dp4j.samples.ProtectedClass;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author simpatico
*/
public class ProtectedTest {
@Test
public void test() {
new ProtectedClass().doSth();
}
}
| 431 | 0.693735 | 0.689095 | 23 | 17.73913 | 15.905201 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 12 |
3139d0c33aa99933fa341bec62deb11a693154fd | 17,154,099,385,950 | 9757b9287eaac2478fd93c4a5ff1272250c54ab2 | /org.schema/src/main/java/org/schema/ILegislativeBuilding.java | 79a9fc4e45f4d55adbeea486017712b86dcbf77d | [] | no_license | schwichti/astro | https://github.com/schwichti/astro | 2d24e0310967cde7b5b2d19f2abf4405288f07a9 | ac550bf483579d78dc2cedba1d5b8fbf8f1cf22e | refs/heads/master | 2021-05-05T15:15:39.769000 | 2018-11-26T20:28:21 | 2018-11-26T20:28:21 | 117,298,133 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.schema;
/**
* A legislative building—for example, the state capitol.
*/
public interface ILegislativeBuilding extends IGovernmentBuilding{
}
| UTF-8 | Java | 172 | java | ILegislativeBuilding.java | Java | [] | null | [] | package org.schema;
/**
* A legislative building—for example, the state capitol.
*/
public interface ILegislativeBuilding extends IGovernmentBuilding{
}
| 172 | 0.738372 | 0.715116 | 8 | 19.5 | 26.598871 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 12 |
3b70152bdb0af528ca8928119b9ffe21cebe778f | 36,455,682,418,708 | e28082fa222c44377d84c014f341a4b719de8646 | /src/multithreading/blocking_buffer/SingleElementBuffer.java | e43a5ce7915f508d3499703a07a5f97c7e7b4dbc | [] | no_license | skorobagatko/GolovachCourses | https://github.com/skorobagatko/GolovachCourses | 2cee132f9e65ed7b949ae2d90ecaa8abf69775f1 | 9a49335b16899655d1a7a5ae7020f0e074d3f807 | refs/heads/master | 2020-12-11T02:32:16.676000 | 2016-08-13T19:04:30 | 2016-08-13T19:04:30 | 52,149,502 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package multithreading.blocking_buffer;
import java.util.concurrent.TimeoutException;
public class SingleElementBuffer {
private Integer elem;
public synchronized void put(Integer newElem, long timeout) throws InterruptedException, TimeoutException {
// На мой взгляд:
// Такая реализация не корректна, если в метод передать timeout=0
// В этом случае мы даже не выполним проверку на наличие в буфере эелемента
// В итоге, новый элемент перезатрет тот, который был в очереди - т.е. мы теряем данные
long waitTime = timeout;
while (elem != null && waitTime > 0) {
long t0 = System.currentTimeMillis();
this.wait(waitTime);
long t1 = System.currentTimeMillis();
long elapsedTime = t1 - t0;
waitTime -= elapsedTime;
}
if (waitTime <= 0 && elem != null) throw new TimeoutException();
elem = newElem;
this.notifyAll();
}
public synchronized Integer get(long timeout) throws InterruptedException, TimeoutException {
long waitTime = timeout;
while (elem != null && waitTime > 0) {
long t0 = System.currentTimeMillis();
this.wait(waitTime);
long t1 = System.currentTimeMillis();
long elapsedTime = t1 - t0;
waitTime -= elapsedTime;
}
if (waitTime <= 0 && elem == null) throw new TimeoutException();
int result = elem;
elem = null;
this.notifyAll();
return result;
}
}
| UTF-8 | Java | 1,728 | java | SingleElementBuffer.java | Java | [] | null | [] | package multithreading.blocking_buffer;
import java.util.concurrent.TimeoutException;
public class SingleElementBuffer {
private Integer elem;
public synchronized void put(Integer newElem, long timeout) throws InterruptedException, TimeoutException {
// На мой взгляд:
// Такая реализация не корректна, если в метод передать timeout=0
// В этом случае мы даже не выполним проверку на наличие в буфере эелемента
// В итоге, новый элемент перезатрет тот, который был в очереди - т.е. мы теряем данные
long waitTime = timeout;
while (elem != null && waitTime > 0) {
long t0 = System.currentTimeMillis();
this.wait(waitTime);
long t1 = System.currentTimeMillis();
long elapsedTime = t1 - t0;
waitTime -= elapsedTime;
}
if (waitTime <= 0 && elem != null) throw new TimeoutException();
elem = newElem;
this.notifyAll();
}
public synchronized Integer get(long timeout) throws InterruptedException, TimeoutException {
long waitTime = timeout;
while (elem != null && waitTime > 0) {
long t0 = System.currentTimeMillis();
this.wait(waitTime);
long t1 = System.currentTimeMillis();
long elapsedTime = t1 - t0;
waitTime -= elapsedTime;
}
if (waitTime <= 0 && elem == null) throw new TimeoutException();
int result = elem;
elem = null;
this.notifyAll();
return result;
}
}
| 1,728 | 0.611111 | 0.602713 | 41 | 36.756096 | 27.505901 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707317 | false | false | 12 |
d9cd5ee59241cdf81e5f72d5756e856863548192 | 30,253,749,694,443 | 6b2d550098d384c8217cb870b72a43b689b88a4b | /src/main/java/_3_hw_List/work/withString/MainWorkWithString.java | 1f9e722cf29f5e543f532ce957e093ffbd7ffa37 | [] | no_license | ProkazaEvgeniy/LessonJava | https://github.com/ProkazaEvgeniy/LessonJava | 9b310cd40659edc7510799f6c44c41fc2cd91092 | a99d2ae31625740c6fe2b9e87c9081391f11a4b4 | refs/heads/master | 2020-12-25T21:00:55.020000 | 2016-03-25T09:46:49 | 2016-03-25T09:46:49 | 52,032,320 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package _3_hw_List.work.withString;
/**
* Created by admin on 19.02.2016.
*/
public class MainWorkWithString {
public static void main(String[] args) {
WorkWithString workWithString = new WorkWithString();
//
//
// System.out.println(workWithString.isEmptyString("Hello!"));
//
//
// System.out.println(workWithString.attendWithStringNumber("Hello!"));
//
//
// System.out.println(workWithString.conformityStringPattern("Hello!", "Hello"));
//
//
// System.out.println(workWithString.deleteAllSymbol("Hello!", "!"));
//
//
// System.out.println(workWithString.createListString("Hello! World Java", " "));
//
//
// System.out.println(workWithString.howManyWordsInSentence("Hello! World Java"));
//
//
// System.out.println(workWithString.addCurrentDate("Now date is "));
//
//
// System.out.println(workWithString.checkInConformity("Hello!", "Hello"));
//
//
workWithString.repetitionInString1("Hello!");
//
//
// System.out.println(workWithString.turoverString("Hello!"));
}
}
| UTF-8 | Java | 1,158 | java | MainWorkWithString.java | Java | [
{
"context": "age _3_hw_List.work.withString;\n\n/**\n * Created by admin on 19.02.2016.\n */\npublic class MainWorkWithStrin",
"end": 60,
"score": 0.9981167316436768,
"start": 55,
"tag": "USERNAME",
"value": "admin"
}
] | null | [] | package _3_hw_List.work.withString;
/**
* Created by admin on 19.02.2016.
*/
public class MainWorkWithString {
public static void main(String[] args) {
WorkWithString workWithString = new WorkWithString();
//
//
// System.out.println(workWithString.isEmptyString("Hello!"));
//
//
// System.out.println(workWithString.attendWithStringNumber("Hello!"));
//
//
// System.out.println(workWithString.conformityStringPattern("Hello!", "Hello"));
//
//
// System.out.println(workWithString.deleteAllSymbol("Hello!", "!"));
//
//
// System.out.println(workWithString.createListString("Hello! World Java", " "));
//
//
// System.out.println(workWithString.howManyWordsInSentence("Hello! World Java"));
//
//
// System.out.println(workWithString.addCurrentDate("Now date is "));
//
//
// System.out.println(workWithString.checkInConformity("Hello!", "Hello"));
//
//
workWithString.repetitionInString1("Hello!");
//
//
// System.out.println(workWithString.turoverString("Hello!"));
}
}
| 1,158 | 0.601036 | 0.592401 | 51 | 21.705883 | 30.124769 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.313726 | false | false | 12 |
4daefd08d7c1b572f9ce0cdb7b671c32bfa3f0b4 | 29,128,468,264,672 | 3bd29f14e7571466e590a0be34b08ec63ce62b96 | /src/main/java/socialnetwork/service/FriendshipService.java | 0976bda22ef6fbec54762aa47c7555113224d16f | [] | no_license | alebirle/socialnetwork | https://github.com/alebirle/socialnetwork | a5d75610f51f68b74e8679009eb076f74061ba64 | 3014982815ebee5a06eab6a66392b054cc7dad0f | refs/heads/master | 2023-03-12T00:23:51.748000 | 2021-01-18T09:41:37 | 2021-01-18T09:41:37 | 343,851,703 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package socialnetwork.service;
import socialnetwork.domain.Friendship;
import socialnetwork.domain.Tuple;
import socialnetwork.domain.User;
import socialnetwork.repository.Repository;
import java.util.ArrayList;
import java.util.List;
public class FriendshipService {
private Repository<Tuple<Long,Long>, Friendship> repo;
public FriendshipService(Repository<Tuple<Long,Long>, Friendship> repo) {
this.repo = repo;
}
/**
*
* @param f -the friendship that has to be added
* f must not be null
* @return a friendship - if it already existed
* or null - if the friendship was added
*/
public Friendship addFriendship(Friendship f){
Tuple<Long, Long> t=new Tuple(f.getId().getRight(),f.getId().getLeft());
Friendship k=getOne(t);
if(k!=null&&k.getId()!=null&&!k.getStatus().equals("Rejected"))
return k;
Friendship fr = repo.save(f);
return fr;
}
/**
*
* @param t - the id of the friendship
* @return the friendship with the specified id
*/
public Friendship getOne(Tuple<Long,Long> t){
Friendship f= repo.findOne(t);
if(f.getId()==null) {
Tuple<Long, Long> t2 = new Tuple(t.getRight(), t.getLeft());
return repo.findOne(t2);
}
else
return f;
}
/**
*
* @return all existing friendships
*/
public Iterable<Friendship> getAll(){
return repo.findAll();
}
/**
*
* @param id - the id of the friendship
* @return the friendship that was deleted
* or null, if it didn't exist in the first place
*/
public Friendship deleteFriendship(Tuple<Long,Long> id){
Friendship f=repo.delete(id);
return f;
}
public Friendship update(Friendship f){
return repo.update(f);
}
public String getStatus(Long id1, Long id2){
return repo.getStatus(id1,id2);
}
public Iterable<Friendship> getSome(User u, String s) {
return repo.findSome(u,s);
}
}
| UTF-8 | Java | 2,106 | java | FriendshipService.java | Java | [] | null | [] | package socialnetwork.service;
import socialnetwork.domain.Friendship;
import socialnetwork.domain.Tuple;
import socialnetwork.domain.User;
import socialnetwork.repository.Repository;
import java.util.ArrayList;
import java.util.List;
public class FriendshipService {
private Repository<Tuple<Long,Long>, Friendship> repo;
public FriendshipService(Repository<Tuple<Long,Long>, Friendship> repo) {
this.repo = repo;
}
/**
*
* @param f -the friendship that has to be added
* f must not be null
* @return a friendship - if it already existed
* or null - if the friendship was added
*/
public Friendship addFriendship(Friendship f){
Tuple<Long, Long> t=new Tuple(f.getId().getRight(),f.getId().getLeft());
Friendship k=getOne(t);
if(k!=null&&k.getId()!=null&&!k.getStatus().equals("Rejected"))
return k;
Friendship fr = repo.save(f);
return fr;
}
/**
*
* @param t - the id of the friendship
* @return the friendship with the specified id
*/
public Friendship getOne(Tuple<Long,Long> t){
Friendship f= repo.findOne(t);
if(f.getId()==null) {
Tuple<Long, Long> t2 = new Tuple(t.getRight(), t.getLeft());
return repo.findOne(t2);
}
else
return f;
}
/**
*
* @return all existing friendships
*/
public Iterable<Friendship> getAll(){
return repo.findAll();
}
/**
*
* @param id - the id of the friendship
* @return the friendship that was deleted
* or null, if it didn't exist in the first place
*/
public Friendship deleteFriendship(Tuple<Long,Long> id){
Friendship f=repo.delete(id);
return f;
}
public Friendship update(Friendship f){
return repo.update(f);
}
public String getStatus(Long id1, Long id2){
return repo.getStatus(id1,id2);
}
public Iterable<Friendship> getSome(User u, String s) {
return repo.findSome(u,s);
}
}
| 2,106 | 0.60114 | 0.598291 | 79 | 25.658228 | 22.032707 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.493671 | false | false | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.