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
f96ed3283997a97c789c8d02117382fe9c706348
19,164,144,112,182
f21e2990547a37e087bf866c2659f8ed4f70ca84
/apphub-service/apphub-service-skyxplore/apphub-service-skyxplore-game/src/main/java/com/github/saphyra/apphub/service/skyxplore/game/domain/chat/SystemMessage.java
bf438b6da2dde2b93532fff39de3305bec3e334b
[]
no_license
Saphyra/apphub
https://github.com/Saphyra/apphub
207b8e049ca3d8f88c15213656cf596663e2850b
13d01c18ff4568edc693da102b7822781de83fa3
refs/heads/master
2023-09-04T05:31:41.969000
2023-09-02T19:29:17
2023-09-02T19:29:17
250,788,236
0
2
null
false
2023-09-09T20:23:43
2020-03-28T12:22:39
2022-01-09T14:53:32
2023-09-09T20:23:43
16,536
0
2
2
Java
false
false
package com.github.saphyra.apphub.service.skyxplore.game.domain.chat; import lombok.AllArgsConstructor; import lombok.Data; import java.util.UUID; @Data @AllArgsConstructor public class SystemMessage { private String room; private String characterName; private UUID userId; }
UTF-8
Java
291
java
SystemMessage.java
Java
[ { "context": "package com.github.saphyra.apphub.service.skyxplore.game.domain.chat;\n\nimpor", "end": 26, "score": 0.9976739883422852, "start": 19, "tag": "USERNAME", "value": "saphyra" } ]
null
[]
package com.github.saphyra.apphub.service.skyxplore.game.domain.chat; import lombok.AllArgsConstructor; import lombok.Data; import java.util.UUID; @Data @AllArgsConstructor public class SystemMessage { private String room; private String characterName; private UUID userId; }
291
0.786942
0.786942
14
19.785715
18.178396
69
false
false
0
0
0
0
0
0
0.5
false
false
2
a30d7176aec47f223b37b5db8c9c53c56b2e29ee
25,159,918,451,016
2c37f6b4c2214528256d50b7953ee287b607ef77
/src/main/java/com/redspark/nycl/persistence/PostgresqlLeagueConfigurationRepository.java
af75184f14c1fa375fc133786b561a6379dd2506
[]
no_license
simonpark1971/nycl-server
https://github.com/simonpark1971/nycl-server
2380b4574e54a4d0c43192bb79962f3354297d4e
f047cc6e882bbf0c55a881a700465a8d3ffc2329
refs/heads/master
2022-12-23T08:11:17.017000
2020-02-06T20:18:29
2020-02-06T20:18:29
144,731,831
0
0
null
false
2022-12-16T05:04:17
2018-08-14T14:30:55
2020-02-06T20:18:40
2022-12-16T05:04:15
81
0
0
10
Java
false
false
package com.redspark.nycl.persistence; import com.redspark.nycl.domain.AgeGroup; import com.redspark.nycl.domain.LeagueConfiguration; import org.springframework.data.repository.CrudRepository; public interface PostgresqlLeagueConfigurationRepository extends CrudRepository<LeagueConfiguration, String> { LeagueConfiguration findLeagueConfigurationByAgeGroup(AgeGroup ageGroup); }
UTF-8
Java
385
java
PostgresqlLeagueConfigurationRepository.java
Java
[]
null
[]
package com.redspark.nycl.persistence; import com.redspark.nycl.domain.AgeGroup; import com.redspark.nycl.domain.LeagueConfiguration; import org.springframework.data.repository.CrudRepository; public interface PostgresqlLeagueConfigurationRepository extends CrudRepository<LeagueConfiguration, String> { LeagueConfiguration findLeagueConfigurationByAgeGroup(AgeGroup ageGroup); }
385
0.867532
0.867532
10
37.5
35.855961
110
false
false
0
0
0
0
0
0
0.6
false
false
2
3ffba8521f8bfe4da4b15a6a486daaeb242250f2
33,200,097,222,488
351e030fbf7f57d6f7be4aa088fa8f04de11a03b
/MyProjects/Storehouse/project/Product.java
1e1152e7908cbddec664d1e2dd1a93f17a63e55e
[]
no_license
michalFied/Java
https://github.com/michalFied/Java
ab08ee250de40dd8abb44e8a6e093e97e0323cb7
72d752c82b86acf886ee696fac633496ea50f398
refs/heads/master
2016-08-09T19:23:08.732000
2016-03-13T21:45:11
2016-03-13T21:45:11
53,781,127
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project; public class Product { protected static int ProductId; protected static String ProductName; protected static double ProductPrice; protected static int ProductQuantity; protected static int[] ID = {1, 2, 3, 4, 5}; protected static String[] name = {"Samsung", "Alcatel", "Iphone", "Nokia", "LG"}; protected static double[] price = {5, 10, 15, 20, 25}; protected static int[] quantity = {1, 10, 25, 50, 100}; protected static Product[] product = new Product[5]; public Product(int ProductId, String ProductName, double ProductPrice, int ProductQuantity) { Product.ProductId = ProductId; Product.ProductName = ProductName; Product.ProductPrice = ProductPrice; Product.ProductQuantity = ProductQuantity; } public static Product make(int typ) { if (typ >= 5) { System.out.println("Błędna wartość! Podaj wartość od 1 do 5"); return null; } if (product[typ] == null) product[typ] = new Product(ID[typ], name[typ], price[typ], quantity[typ]); return product[typ]; } public void show() { System.out.println("ID: " + getProductId() + ". Nazwa Produktu: " + getProductName() + ". Cena Produktu: " + getProductPrice() + " Ilość: " + getProductQuantity()); } public static int getProductId() { return ProductId; } public static String getProductName() { return ProductName; } public static double getProductPrice() { return ProductPrice; } public static int getProductQuantity() { return ProductQuantity; } }
UTF-8
Java
1,665
java
Product.java
Java
[]
null
[]
package project; public class Product { protected static int ProductId; protected static String ProductName; protected static double ProductPrice; protected static int ProductQuantity; protected static int[] ID = {1, 2, 3, 4, 5}; protected static String[] name = {"Samsung", "Alcatel", "Iphone", "Nokia", "LG"}; protected static double[] price = {5, 10, 15, 20, 25}; protected static int[] quantity = {1, 10, 25, 50, 100}; protected static Product[] product = new Product[5]; public Product(int ProductId, String ProductName, double ProductPrice, int ProductQuantity) { Product.ProductId = ProductId; Product.ProductName = ProductName; Product.ProductPrice = ProductPrice; Product.ProductQuantity = ProductQuantity; } public static Product make(int typ) { if (typ >= 5) { System.out.println("Błędna wartość! Podaj wartość od 1 do 5"); return null; } if (product[typ] == null) product[typ] = new Product(ID[typ], name[typ], price[typ], quantity[typ]); return product[typ]; } public void show() { System.out.println("ID: " + getProductId() + ". Nazwa Produktu: " + getProductName() + ". Cena Produktu: " + getProductPrice() + " Ilość: " + getProductQuantity()); } public static int getProductId() { return ProductId; } public static String getProductName() { return ProductName; } public static double getProductPrice() { return ProductPrice; } public static int getProductQuantity() { return ProductQuantity; } }
1,665
0.62583
0.608932
54
29.666666
31.674269
172
false
false
0
0
0
0
0
0
0.833333
false
false
2
3dd706f7ae3d7fc1ab5dfb46aad20459a4007b80
29,678,224,044,638
c225fbc8db3593046353dd16844de731dc6712df
/sample02/src/main/java/sample02/model/Product.java
2a41401e7c1f8abcba0905d4134e579c8af39ce6
[]
no_license
xyzcamp/springboot
https://github.com/xyzcamp/springboot
014486cc9ed7ed6c3163336322a92ebc1fbad08f
63ba83bbc8b8b33cfb511dd8891b7b44a1273cac
refs/heads/master
2021-01-24T16:40:06.101000
2018-04-12T13:54:07
2018-04-12T13:54:07
123,207,526
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample02.model; public class Product { public int getId() { return id; } public String getTitle() { return title; } public String getDescr() { return descr; } public int id; public String title; public String descr; }
UTF-8
Java
242
java
Product.java
Java
[]
null
[]
package sample02.model; public class Product { public int getId() { return id; } public String getTitle() { return title; } public String getDescr() { return descr; } public int id; public String title; public String descr; }
242
0.690083
0.681818
17
13.294118
9.766478
27
false
false
0
0
0
0
0
0
1.294118
false
false
2
9d91684971c35091622ffde57b5051021d6129b5
11,862,699,693,524
8162d9577a40e3cf4146f7eb6e7f6db8c75c5f60
/checkpoint1/Lab1/src/com/danco/training/dobrilko/property/PropertyStorage.java
b67a6cba7f17f226d83402803b71d2b547fe224c
[]
no_license
KateDobrilko/danco-tr-java-dobrilko-kate
https://github.com/KateDobrilko/danco-tr-java-dobrilko-kate
173d3237435c067906b11f50b3b9d8f947821f25
ecd16086a66c9373f57046121687611a256d6608
refs/heads/master
2016-08-12T19:27:42.231000
2015-05-25T08:45:14
2015-05-25T08:45:14
44,364,915
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.danco.training.dobrilko.property; import java.util.Properties; public class PropertyStorage { private static Properties properties = new Properties(); private static PropertyStorage instance; private PropertyStorage() { PropertyReader.setProperties(properties); } public static PropertyStorage getInstance() { if (instance == null) { instance = new PropertyStorage(); } return instance; } public Properties getProperties() { return properties; } public String getReadPath() { String readPath = ""; readPath = properties.getProperty("READ_PATH"); return readPath; } public String getWritePath() { String writePath = ""; writePath = properties.getProperty("WRITE_PATH"); return writePath; } }
UTF-8
Java
790
java
PropertyStorage.java
Java
[]
null
[]
package com.danco.training.dobrilko.property; import java.util.Properties; public class PropertyStorage { private static Properties properties = new Properties(); private static PropertyStorage instance; private PropertyStorage() { PropertyReader.setProperties(properties); } public static PropertyStorage getInstance() { if (instance == null) { instance = new PropertyStorage(); } return instance; } public Properties getProperties() { return properties; } public String getReadPath() { String readPath = ""; readPath = properties.getProperty("READ_PATH"); return readPath; } public String getWritePath() { String writePath = ""; writePath = properties.getProperty("WRITE_PATH"); return writePath; } }
790
0.693671
0.693671
39
18.256411
18.266851
57
false
false
0
0
0
0
0
0
1.307692
false
false
2
0c71c9181e32d8da1eb0d44fa6b1ce48ffdd1cf7
7,748,121,025,999
3fb84a90b6629f89481ac7dda16307b2d34c65f0
/src/main/java/com/cjh/websocket/erp/Erp.java
981732e263952f492965c92b1054b9073f1d79c5
[]
no_license
520f/websocket
https://github.com/520f/websocket
d3d9d1376be7d5526c3af2bbdbb7d35c0624e4b0
eeadc0d7eb347070826b3c478be26b183dd7ddec
refs/heads/master
2020-06-04T07:14:09.020000
2019-06-14T09:58:42
2019-06-14T09:58:42
191,919,770
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cjh.websocket.erp; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component public class Erp { private Erp() { } // <配置key, 配置value> private static Map<String, String> erpMap = new HashMap<>(); //获取用户名 public static String getUserName(String sessiobId) { return erpMap.getOrDefault(sessiobId,"黑客入侵"); } //存用户名 public static void setUserName(String name) { erpMap.put(String.valueOf(erpMap.size()),name); } }
UTF-8
Java
524
java
Erp.java
Java
[]
null
[]
package com.cjh.websocket.erp; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component public class Erp { private Erp() { } // <配置key, 配置value> private static Map<String, String> erpMap = new HashMap<>(); //获取用户名 public static String getUserName(String sessiobId) { return erpMap.getOrDefault(sessiobId,"黑客入侵"); } //存用户名 public static void setUserName(String name) { erpMap.put(String.valueOf(erpMap.size()),name); } }
524
0.730612
0.730612
25
18.639999
20.045708
61
false
false
0
0
0
0
0
0
1
false
false
2
12453681feeefdd7b670ae56f969c05d1974ddb5
33,560,874,474,962
8433820146eca6c5f8d2ada8bddfc21f0bcda6a7
/1-evosuite-fuzzer/master/src/main/java/org/evosuite/statistics/backend/HTMLStatisticsBackend.java
8c050bb2391045b6ed44ee409c6ac5a2768d0f32
[ "MIT", "LGPL-3.0-only" ]
permissive
mitchellolsthoorn/ASE-NIER-2020-replication
https://github.com/mitchellolsthoorn/ASE-NIER-2020-replication
da5993621fa334be33fb8fc1f3a2e7b676674c1b
d921c324d95346b2d962d913c21b993fa5a51d18
refs/heads/main
2023-04-15T18:34:14.719000
2020-08-26T13:03:52
2020-08-26T13:03:52
283,782,470
0
0
MIT
false
2021-04-26T20:36:37
2020-07-30T13:24:16
2020-08-26T13:04:03
2021-04-26T20:36:37
73,213
0
0
5
Java
false
false
/* * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.statistics.backend; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringEscapeUtils; import org.evosuite.Properties; import org.evosuite.ga.Chromosome; import org.evosuite.statistics.OutputVariable; import org.evosuite.statistics.RuntimeVariable; import org.evosuite.testcase.TestCase; import org.evosuite.testcase.TestChromosome; import org.evosuite.testsuite.TestSuiteChromosome; import org.evosuite.utils.HtmlAnalyzer; import org.evosuite.utils.FileIOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HTMLStatisticsBackend implements StatisticsBackend { protected static final Logger logger = LoggerFactory.getLogger(HTMLStatisticsBackend.class); protected static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; protected static final HtmlAnalyzer html_analyzer = new HtmlAnalyzer(); @Override public void writeData(Chromosome result, Map<String, OutputVariable<?>> data) { new File(getReportDir().getAbsolutePath() + "/img").mkdirs(); new File(getReportDir().getAbsolutePath() + "/html/files/").mkdirs(); new File(getReportDir().getAbsolutePath() + "/data/").mkdirs(); new File(getReportDir().getAbsolutePath() + "/files/").mkdirs(); copyFile("prettify.js"); copyFile("prettify.css"); copyFile("style.css"); copyFile("foldButton.js"); copyFile("foldButton.css"); copyFile("jquery.js"); copyFile("detected.png"); copyFile("not_detected.png"); copyFile("img01.jpg"); copyFile("img02.jpg"); copyFile("img03.jpg"); copyFile("img04.png"); copyFile("evosuite.png"); File file = new File(getReportDir(), "report-generation.html"); StringBuffer report = new StringBuffer(); if (file.exists()) { List<String> lines = FileIOUtils.readFile(file); for (String line : lines) { if (line.contains("<!-- EVOSUITE INSERTION POINT -->")) { break; } report.append(line); } } else { writeHTMLHeader(report, Properties.PROJECT_PREFIX); report.append("<div id=\"header\">\n<div id=\"logo\">"); /* if (!Properties.PROJECT_PREFIX.isEmpty()) { report.append("<h1 class=title>EvoSuite: " + Properties.PROJECT_PREFIX + "</h1>\n"); } */ report.append("\n</div><br></div>"); try { report.append("Run on " + java.net.InetAddress.getLocalHost().getHostName() + "\n"); } catch (Exception e) { } report.append("<div id=\"page\">\n"); report.append("<div id=\"page-bgtop\">\n"); report.append("<div id=\"page-bgbtm\">\n"); report.append("<div id=\"content\">\n"); report.append("<div id=\"post\">"); report.append("<h2 class=\"title\">Test generation runs:</h2>\n"); report.append("<div style=\"clear: both;\">&nbsp;</div><div class=\"entry\">"); report.append("<table cellspacing=0>"); // border=0 cellspacing=0 cellpadding=3>"); report.append("<tr class=\"top bottom\">"); // report.append("<td>Run</td>"); report.append("<td>Date</td>"); report.append("<td>Time</td>"); report.append("<td>Coverage</td>"); report.append("<td>Class</td>"); // report.append("<td></td>"); report.append("</tr>\n"); } writeRunTable((TestSuiteChromosome)result, data, report); report.append("</div></div></div></div></div></div>"); writeHTMLFooter(report); FileIOUtils.writeFile(report.toString(), file); } public static void copyFile(URL src, File dest) { try { InputStream in; in = src.openStream(); OutputStream out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void copyFile(String name) { URL systemResource = ClassLoader.getSystemResource("report/" + name); logger.debug("Copying from resource: " + systemResource); copyFile(systemResource, new File(getReportDir(), "files" + File.separator + name)); copyFile(systemResource, new File(getReportDir().getAbsolutePath() + File.separator+ "html" + File.separator + "files" + File.separator + name)); } /** * Return the folder of where reports should be generated. * If the folder does not exist, try to create it * * @return * @throws RuntimeException if folder does not exist, and we cannot create it */ public static File getReportDir() throws RuntimeException{ File dir = new File(Properties.REPORT_DIR); if(!dir.exists()){ boolean created = dir.mkdirs(); if(!created){ String msg = "Cannot create report dir: "+Properties.REPORT_DIR; logger.error(msg); throw new RuntimeException(msg); } } return dir; } /** * HTML header * * @param buffer * a {@link java.lang.StringBuffer} object. * @param title * a {@link java.lang.String} object. */ public static void writeHTMLHeader(StringBuffer buffer, String title) { buffer.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">\n"); buffer.append("<html>\n"); buffer.append("<head>\n"); buffer.append("<title>\n"); buffer.append(title); buffer.append("\n</title>\n"); buffer.append("<link href=\"files/prettify.css\" type=\"text/css\" rel=\"stylesheet\" />\n"); buffer.append("<link href=\"files/style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\n"); buffer.append("<script type=\"text/javascript\" src=\"files/prettify.js\"></script>\n"); buffer.append("<script type=\"text/javascript\" src=\"files/jquery.js\"></script>\n"); buffer.append("<script type=\"text/javascript\" src=\"files/foldButton.js\"></script>\n"); buffer.append("<script type=\"text/javascript\">\n"); buffer.append(" $(document).ready(function() {\n"); //buffer.append(" $('div.tests').foldButton({'closedText':'open TITLE' });\n"); //buffer.append(" $('div.source').foldButton({'closedText':'open TITLE' });\n"); //buffer.append(" $('div.statistics').foldButton({'closedText':'open TITLE' });\n"); buffer.append(" $('H2#tests').foldButton();\n"); buffer.append(" $('H2#source').foldButton();\n"); buffer.append(" $('H2#parameters').foldButton();\n"); buffer.append(" });"); buffer.append("</script>\n"); buffer.append("<link href=\"files/foldButton.css\" rel=\"stylesheet\" type=\"text/css\">\n"); buffer.append("</head>\n"); buffer.append("<body onload=\"prettyPrint()\">\n"); buffer.append("<div id=\"wrapper\">\n"); buffer.append("<img src=\"files/evosuite.png\" height=\"40\"/>\n"); } /** * HTML footer * * @param buffer * a {@link java.lang.StringBuffer} object. */ public static void writeHTMLFooter(StringBuffer buffer) { buffer.append("</div>\n"); buffer.append("</body>\n"); buffer.append("</html>\n"); } /** * The big table of results * * @param buffer * a {@link java.lang.StringBuffer} object. */ protected void writeRunTable(TestSuiteChromosome suite, Map<String, OutputVariable<?>> data, StringBuffer buffer) { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); buffer.append("<tr>"); // buffer.append("<td>" + entry.id + "</td>"); buffer.append("<td>"); buffer.append(sdf.format(new Date())); buffer.append("</td>"); buffer.append("<td>"); if (data.containsKey(RuntimeVariable.Total_Time.name())) { long duration = (Long)data.get(RuntimeVariable.Total_Time.name()).getValue() / 1000L; buffer.append(String.format("%d:%02d:%02d", duration / 3600, (duration % 3600) / 60, (duration % 60))); } else buffer.append("UNKNOWN"); buffer.append("</td>"); buffer.append("<td>"); Double coverage = (Double)getOutputVariableValue(data, RuntimeVariable.Coverage.name()); buffer.append((coverage != null) ? NumberFormat.getPercentInstance().format(coverage) : "UNKNOWN"); buffer.append("</td>"); buffer.append("<td><a href=\"html/"); String filename = writeRunPage(suite, data); buffer.append(filename); buffer.append("\">"); buffer.append(data.get("TARGET_CLASS").getValue()); buffer.append("</tr>\n"); buffer.append("<!-- EVOSUITE INSERTION POINT -->\n"); buffer.append("<tr class=\"top\"><td colspan=\"3\">&nbsp;<td></tr>\n"); buffer.append("</table>"); } /** * Write a file for a particular run * * @param run * a {@link org.evosuite.utils.ReportGenerator.StatisticEntry} * object. * @return a {@link java.lang.String} object. */ @SuppressWarnings("deprecation") protected String writeRunPage(TestSuiteChromosome suite, Map<String, OutputVariable<?>> data) { StringBuffer sb = new StringBuffer(); String className = (String)data.get("TARGET_CLASS").getValue(); writeHTMLHeader(sb, className); sb.append("<br><br><h2 class=title>Summary</h2>\n"); sb.append("<ul><li>Target class: "); sb.append(getOutputVariableValue(data, "TARGET_CLASS")); sb.append(": "); sb.append(suite.getCoverage()); sb.append("</ul>\n"); writeResultTable(suite, sb, data); // writeMutationTable(sb); sb.append("<div id=\"page\">\n"); sb.append("<div id=\"page-bgtop\">\n"); sb.append("<div id=\"page-bgbtm\">\n"); sb.append("<div id=\"content\">\n"); sb.append("<div id=\"post\">\n"); // Resulting test case sb.append("<h2 class=title id=tests>Test suite</h2>\n"); sb.append("<div class=tests>\n"); int num = 0; for (TestChromosome testChromosome : suite.getTestChromosomes()) { TestCase test = testChromosome.getTestCase(); sb.append("<h3>Test case "); sb.append(++num); sb.append("</h3>\n"); /* * if(test.exceptionThrown != null) { sb.append("<p>Raises:"); * sb.append(test.exceptionThrown); sb.append("</p>"); } */ sb.append("<pre class=\"prettyprint\" style=\"border: 1px solid #888;padding: 2px\">\n"); int linecount = 1; String code = null; if (testChromosome.getLastExecutionResult() != null) { code = test.toCode(testChromosome.getLastExecutionResult().exposeExceptionMapping()); } else code = test.toCode(); for (String line : code.split("\n")) { sb.append(String.format("<span class=\"nocode\"><a name=\"%d\">%3d: </a></span>", linecount, linecount)); /* * if(test.exceptionsThrown != null && * test.exception_statement == test_line) * sb.append("<span style=\"background: #FF0000\">"); */ sb.append(StringEscapeUtils.escapeHtml4(line)); /* * if(test.exceptionThrown != null && * test.exception_statement == test_line) * sb.append("</span>"); */ linecount++; sb.append("\n"); } sb.append("</pre>\n"); } sb.append("</div>"); sb.append("<div id=\"post\">\n"); OutputVariable<?> ov_covered_lines = data.get(RuntimeVariable.Covered_Lines.name()); @SuppressWarnings("unchecked") Set<Integer> coveredLines = (ov_covered_lines != null) ? (Set<Integer>) ov_covered_lines.getValue() : new HashSet<Integer>(); // Source code try { Iterable<String> source = html_analyzer.getClassContent(className); sb.append("<h2 class=title id=source>Source Code</h2>\n"); sb.append("<div class=source>\n"); sb.append("<p>"); sb.append("<pre class=\"prettyprint\" style=\"border: 1px solid #888;padding: 2px\">"); int linecount = 1; for (String line : source) { sb.append(String.format("<span class=\"nocode\"><a name=\"%d\">%3d: </a></span>", linecount, linecount)); if (coveredLines.contains(linecount)) { sb.append("<span style=\"background-color: #ffffcc\">"); sb.append(StringEscapeUtils.escapeHtml4(line)); sb.append("</span>"); } else sb.append(StringEscapeUtils.escapeHtml4(line)); sb.append("\n"); linecount++; } sb.append("</pre>\n"); sb.append("</p>\n"); } catch (Exception e) { // Don't display source if there is an error } sb.append("</div>\n"); sb.append("<div id=\"post\">\n"); writeParameterTable(sb, data); sb.append("</div>\n"); sb.append("<p><br><a href=\"../report-generation.html\">Back to Overview</a></p>\n"); writeHTMLFooter(sb); String filename = "report-" + className + "-" + getNumber(className) + ".html"; File file = new File(getReportDir().getAbsolutePath() + "/html/" + filename); FileIOUtils.writeFile(sb.toString(), file); // return file.getAbsolutePath(); return filename; } protected int getNumber(final String className) { int num = 0; FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { // report-ncs.Triangle-0.html return name.startsWith("report-" + className) && (name.endsWith(".html")); } }; List<String> filenames = new ArrayList<String>(); File[] files = (new File(getReportDir().getAbsolutePath() + "/html")).listFiles(filter); if (files != null) { for (File f : files) filenames.add(f.getName()); while (filenames.contains("report-" + className + "-" + num + ".html")) num++; } return num; } protected Object getOutputVariableValue(Map<String, OutputVariable<?>> data, String key) { OutputVariable<?> ov = data.get(key); return (ov != null) ? ov.getValue() : null; } /** * Write some overall stats * * @param buffer * a {@link java.lang.StringBuffer} object. * @param entry * a {@link org.evosuite.utils.ReportGenerator.StatisticEntry} * object. */ protected void writeResultTable(TestSuiteChromosome suite, StringBuffer buffer, Map<String, OutputVariable<?>> data) { //buffer.append("<h2>Statistics</h2>\n"); buffer.append("<ul>\n"); buffer.append("<li>"); buffer.append(suite.getFitness()); buffer.append(" fitness evaluations, "); buffer.append(suite.getAge()); buffer.append(" generations, "); buffer.append(getOutputVariableValue(data, RuntimeVariable.Statements_Executed.name())); buffer.append(" statements, "); buffer.append(suite.size()); buffer.append(" tests.\n"); /* long duration_GA = (entry.end_time - entry.start_time) / 1000; long duration_MI = (entry.minimized_time - entry.end_time) / 1000; long duration_TO = (entry.minimized_time - entry.start_time) / 1000; buffer.append("<li>Time: " + String.format("%d:%02d:%02d", duration_TO / 3600, (duration_TO % 3600) / 60, (duration_TO % 60))); buffer.append("(Search: " + String.format("%d:%02d:%02d", duration_GA / 3600, (duration_GA % 3600) / 60, (duration_GA % 60)) + ", "); buffer.append("minimization: " + String.format("%d:%02d:%02d", duration_MI / 3600, (duration_MI % 3600) / 60, (duration_MI % 60)) + ")\n"); */ buffer.append("<li>Covered " + getOutputVariableValue(data, RuntimeVariable.Covered_Branches.name()) + "/" + getOutputVariableValue(data, RuntimeVariable.Total_Branches.name()) + " branches, "); buffer.append("<li>Covered "+ getOutputVariableValue(data, RuntimeVariable.Covered_Methods.name()) + "/" + getOutputVariableValue(data, RuntimeVariable.Total_Methods.name()) + " methods, "); buffer.append("<li>Covered "+ getOutputVariableValue(data, RuntimeVariable.Covered_Goals.name()) + "/" + getOutputVariableValue(data, RuntimeVariable.Total_Goals.name()) + " total goals\n"); if(data.containsKey(RuntimeVariable.MutationScore.name())) buffer.append("<li>Mutation score: " + NumberFormat.getPercentInstance().format((Double)data.get(RuntimeVariable.MutationScore.name()).getValue()) + "\n"); buffer.append("</ul>\n"); } /** * Write some overall stats * * @param buffer * a {@link java.lang.StringBuffer} object. * @param entry * a {@link org.evosuite.utils.ReportGenerator.StatisticEntry} * object. */ protected void writeParameterTable(StringBuffer buffer, Map<String, OutputVariable<?>> data) { buffer.append("<h2 id=parameters>EvoSuite Parameters</h2>\n"); buffer.append("<div class=statistics><ul>\n"); for (String key : data.keySet()) { buffer.append("<li>" + key + ": " + data.get(key).getValue() + "\n"); } buffer.append("</ul></div>\n"); } }
UTF-8
Java
17,356
java
HTMLStatisticsBackend.java
Java
[ { "context": "/*\n * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite\n * contributors\n *\n *", "end": 43, "score": 0.9998247027397156, "start": 30, "tag": "NAME", "value": "Gordon Fraser" }, { "context": "/*\n * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri ...
null
[]
/* * Copyright (C) 2010-2018 <NAME>, <NAME> and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.statistics.backend; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringEscapeUtils; import org.evosuite.Properties; import org.evosuite.ga.Chromosome; import org.evosuite.statistics.OutputVariable; import org.evosuite.statistics.RuntimeVariable; import org.evosuite.testcase.TestCase; import org.evosuite.testcase.TestChromosome; import org.evosuite.testsuite.TestSuiteChromosome; import org.evosuite.utils.HtmlAnalyzer; import org.evosuite.utils.FileIOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HTMLStatisticsBackend implements StatisticsBackend { protected static final Logger logger = LoggerFactory.getLogger(HTMLStatisticsBackend.class); protected static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; protected static final HtmlAnalyzer html_analyzer = new HtmlAnalyzer(); @Override public void writeData(Chromosome result, Map<String, OutputVariable<?>> data) { new File(getReportDir().getAbsolutePath() + "/img").mkdirs(); new File(getReportDir().getAbsolutePath() + "/html/files/").mkdirs(); new File(getReportDir().getAbsolutePath() + "/data/").mkdirs(); new File(getReportDir().getAbsolutePath() + "/files/").mkdirs(); copyFile("prettify.js"); copyFile("prettify.css"); copyFile("style.css"); copyFile("foldButton.js"); copyFile("foldButton.css"); copyFile("jquery.js"); copyFile("detected.png"); copyFile("not_detected.png"); copyFile("img01.jpg"); copyFile("img02.jpg"); copyFile("img03.jpg"); copyFile("img04.png"); copyFile("evosuite.png"); File file = new File(getReportDir(), "report-generation.html"); StringBuffer report = new StringBuffer(); if (file.exists()) { List<String> lines = FileIOUtils.readFile(file); for (String line : lines) { if (line.contains("<!-- EVOSUITE INSERTION POINT -->")) { break; } report.append(line); } } else { writeHTMLHeader(report, Properties.PROJECT_PREFIX); report.append("<div id=\"header\">\n<div id=\"logo\">"); /* if (!Properties.PROJECT_PREFIX.isEmpty()) { report.append("<h1 class=title>EvoSuite: " + Properties.PROJECT_PREFIX + "</h1>\n"); } */ report.append("\n</div><br></div>"); try { report.append("Run on " + java.net.InetAddress.getLocalHost().getHostName() + "\n"); } catch (Exception e) { } report.append("<div id=\"page\">\n"); report.append("<div id=\"page-bgtop\">\n"); report.append("<div id=\"page-bgbtm\">\n"); report.append("<div id=\"content\">\n"); report.append("<div id=\"post\">"); report.append("<h2 class=\"title\">Test generation runs:</h2>\n"); report.append("<div style=\"clear: both;\">&nbsp;</div><div class=\"entry\">"); report.append("<table cellspacing=0>"); // border=0 cellspacing=0 cellpadding=3>"); report.append("<tr class=\"top bottom\">"); // report.append("<td>Run</td>"); report.append("<td>Date</td>"); report.append("<td>Time</td>"); report.append("<td>Coverage</td>"); report.append("<td>Class</td>"); // report.append("<td></td>"); report.append("</tr>\n"); } writeRunTable((TestSuiteChromosome)result, data, report); report.append("</div></div></div></div></div></div>"); writeHTMLFooter(report); FileIOUtils.writeFile(report.toString(), file); } public static void copyFile(URL src, File dest) { try { InputStream in; in = src.openStream(); OutputStream out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void copyFile(String name) { URL systemResource = ClassLoader.getSystemResource("report/" + name); logger.debug("Copying from resource: " + systemResource); copyFile(systemResource, new File(getReportDir(), "files" + File.separator + name)); copyFile(systemResource, new File(getReportDir().getAbsolutePath() + File.separator+ "html" + File.separator + "files" + File.separator + name)); } /** * Return the folder of where reports should be generated. * If the folder does not exist, try to create it * * @return * @throws RuntimeException if folder does not exist, and we cannot create it */ public static File getReportDir() throws RuntimeException{ File dir = new File(Properties.REPORT_DIR); if(!dir.exists()){ boolean created = dir.mkdirs(); if(!created){ String msg = "Cannot create report dir: "+Properties.REPORT_DIR; logger.error(msg); throw new RuntimeException(msg); } } return dir; } /** * HTML header * * @param buffer * a {@link java.lang.StringBuffer} object. * @param title * a {@link java.lang.String} object. */ public static void writeHTMLHeader(StringBuffer buffer, String title) { buffer.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">\n"); buffer.append("<html>\n"); buffer.append("<head>\n"); buffer.append("<title>\n"); buffer.append(title); buffer.append("\n</title>\n"); buffer.append("<link href=\"files/prettify.css\" type=\"text/css\" rel=\"stylesheet\" />\n"); buffer.append("<link href=\"files/style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\n"); buffer.append("<script type=\"text/javascript\" src=\"files/prettify.js\"></script>\n"); buffer.append("<script type=\"text/javascript\" src=\"files/jquery.js\"></script>\n"); buffer.append("<script type=\"text/javascript\" src=\"files/foldButton.js\"></script>\n"); buffer.append("<script type=\"text/javascript\">\n"); buffer.append(" $(document).ready(function() {\n"); //buffer.append(" $('div.tests').foldButton({'closedText':'open TITLE' });\n"); //buffer.append(" $('div.source').foldButton({'closedText':'open TITLE' });\n"); //buffer.append(" $('div.statistics').foldButton({'closedText':'open TITLE' });\n"); buffer.append(" $('H2#tests').foldButton();\n"); buffer.append(" $('H2#source').foldButton();\n"); buffer.append(" $('H2#parameters').foldButton();\n"); buffer.append(" });"); buffer.append("</script>\n"); buffer.append("<link href=\"files/foldButton.css\" rel=\"stylesheet\" type=\"text/css\">\n"); buffer.append("</head>\n"); buffer.append("<body onload=\"prettyPrint()\">\n"); buffer.append("<div id=\"wrapper\">\n"); buffer.append("<img src=\"files/evosuite.png\" height=\"40\"/>\n"); } /** * HTML footer * * @param buffer * a {@link java.lang.StringBuffer} object. */ public static void writeHTMLFooter(StringBuffer buffer) { buffer.append("</div>\n"); buffer.append("</body>\n"); buffer.append("</html>\n"); } /** * The big table of results * * @param buffer * a {@link java.lang.StringBuffer} object. */ protected void writeRunTable(TestSuiteChromosome suite, Map<String, OutputVariable<?>> data, StringBuffer buffer) { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); buffer.append("<tr>"); // buffer.append("<td>" + entry.id + "</td>"); buffer.append("<td>"); buffer.append(sdf.format(new Date())); buffer.append("</td>"); buffer.append("<td>"); if (data.containsKey(RuntimeVariable.Total_Time.name())) { long duration = (Long)data.get(RuntimeVariable.Total_Time.name()).getValue() / 1000L; buffer.append(String.format("%d:%02d:%02d", duration / 3600, (duration % 3600) / 60, (duration % 60))); } else buffer.append("UNKNOWN"); buffer.append("</td>"); buffer.append("<td>"); Double coverage = (Double)getOutputVariableValue(data, RuntimeVariable.Coverage.name()); buffer.append((coverage != null) ? NumberFormat.getPercentInstance().format(coverage) : "UNKNOWN"); buffer.append("</td>"); buffer.append("<td><a href=\"html/"); String filename = writeRunPage(suite, data); buffer.append(filename); buffer.append("\">"); buffer.append(data.get("TARGET_CLASS").getValue()); buffer.append("</tr>\n"); buffer.append("<!-- EVOSUITE INSERTION POINT -->\n"); buffer.append("<tr class=\"top\"><td colspan=\"3\">&nbsp;<td></tr>\n"); buffer.append("</table>"); } /** * Write a file for a particular run * * @param run * a {@link org.evosuite.utils.ReportGenerator.StatisticEntry} * object. * @return a {@link java.lang.String} object. */ @SuppressWarnings("deprecation") protected String writeRunPage(TestSuiteChromosome suite, Map<String, OutputVariable<?>> data) { StringBuffer sb = new StringBuffer(); String className = (String)data.get("TARGET_CLASS").getValue(); writeHTMLHeader(sb, className); sb.append("<br><br><h2 class=title>Summary</h2>\n"); sb.append("<ul><li>Target class: "); sb.append(getOutputVariableValue(data, "TARGET_CLASS")); sb.append(": "); sb.append(suite.getCoverage()); sb.append("</ul>\n"); writeResultTable(suite, sb, data); // writeMutationTable(sb); sb.append("<div id=\"page\">\n"); sb.append("<div id=\"page-bgtop\">\n"); sb.append("<div id=\"page-bgbtm\">\n"); sb.append("<div id=\"content\">\n"); sb.append("<div id=\"post\">\n"); // Resulting test case sb.append("<h2 class=title id=tests>Test suite</h2>\n"); sb.append("<div class=tests>\n"); int num = 0; for (TestChromosome testChromosome : suite.getTestChromosomes()) { TestCase test = testChromosome.getTestCase(); sb.append("<h3>Test case "); sb.append(++num); sb.append("</h3>\n"); /* * if(test.exceptionThrown != null) { sb.append("<p>Raises:"); * sb.append(test.exceptionThrown); sb.append("</p>"); } */ sb.append("<pre class=\"prettyprint\" style=\"border: 1px solid #888;padding: 2px\">\n"); int linecount = 1; String code = null; if (testChromosome.getLastExecutionResult() != null) { code = test.toCode(testChromosome.getLastExecutionResult().exposeExceptionMapping()); } else code = test.toCode(); for (String line : code.split("\n")) { sb.append(String.format("<span class=\"nocode\"><a name=\"%d\">%3d: </a></span>", linecount, linecount)); /* * if(test.exceptionsThrown != null && * test.exception_statement == test_line) * sb.append("<span style=\"background: #FF0000\">"); */ sb.append(StringEscapeUtils.escapeHtml4(line)); /* * if(test.exceptionThrown != null && * test.exception_statement == test_line) * sb.append("</span>"); */ linecount++; sb.append("\n"); } sb.append("</pre>\n"); } sb.append("</div>"); sb.append("<div id=\"post\">\n"); OutputVariable<?> ov_covered_lines = data.get(RuntimeVariable.Covered_Lines.name()); @SuppressWarnings("unchecked") Set<Integer> coveredLines = (ov_covered_lines != null) ? (Set<Integer>) ov_covered_lines.getValue() : new HashSet<Integer>(); // Source code try { Iterable<String> source = html_analyzer.getClassContent(className); sb.append("<h2 class=title id=source>Source Code</h2>\n"); sb.append("<div class=source>\n"); sb.append("<p>"); sb.append("<pre class=\"prettyprint\" style=\"border: 1px solid #888;padding: 2px\">"); int linecount = 1; for (String line : source) { sb.append(String.format("<span class=\"nocode\"><a name=\"%d\">%3d: </a></span>", linecount, linecount)); if (coveredLines.contains(linecount)) { sb.append("<span style=\"background-color: #ffffcc\">"); sb.append(StringEscapeUtils.escapeHtml4(line)); sb.append("</span>"); } else sb.append(StringEscapeUtils.escapeHtml4(line)); sb.append("\n"); linecount++; } sb.append("</pre>\n"); sb.append("</p>\n"); } catch (Exception e) { // Don't display source if there is an error } sb.append("</div>\n"); sb.append("<div id=\"post\">\n"); writeParameterTable(sb, data); sb.append("</div>\n"); sb.append("<p><br><a href=\"../report-generation.html\">Back to Overview</a></p>\n"); writeHTMLFooter(sb); String filename = "report-" + className + "-" + getNumber(className) + ".html"; File file = new File(getReportDir().getAbsolutePath() + "/html/" + filename); FileIOUtils.writeFile(sb.toString(), file); // return file.getAbsolutePath(); return filename; } protected int getNumber(final String className) { int num = 0; FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { // report-ncs.Triangle-0.html return name.startsWith("report-" + className) && (name.endsWith(".html")); } }; List<String> filenames = new ArrayList<String>(); File[] files = (new File(getReportDir().getAbsolutePath() + "/html")).listFiles(filter); if (files != null) { for (File f : files) filenames.add(f.getName()); while (filenames.contains("report-" + className + "-" + num + ".html")) num++; } return num; } protected Object getOutputVariableValue(Map<String, OutputVariable<?>> data, String key) { OutputVariable<?> ov = data.get(key); return (ov != null) ? ov.getValue() : null; } /** * Write some overall stats * * @param buffer * a {@link java.lang.StringBuffer} object. * @param entry * a {@link org.evosuite.utils.ReportGenerator.StatisticEntry} * object. */ protected void writeResultTable(TestSuiteChromosome suite, StringBuffer buffer, Map<String, OutputVariable<?>> data) { //buffer.append("<h2>Statistics</h2>\n"); buffer.append("<ul>\n"); buffer.append("<li>"); buffer.append(suite.getFitness()); buffer.append(" fitness evaluations, "); buffer.append(suite.getAge()); buffer.append(" generations, "); buffer.append(getOutputVariableValue(data, RuntimeVariable.Statements_Executed.name())); buffer.append(" statements, "); buffer.append(suite.size()); buffer.append(" tests.\n"); /* long duration_GA = (entry.end_time - entry.start_time) / 1000; long duration_MI = (entry.minimized_time - entry.end_time) / 1000; long duration_TO = (entry.minimized_time - entry.start_time) / 1000; buffer.append("<li>Time: " + String.format("%d:%02d:%02d", duration_TO / 3600, (duration_TO % 3600) / 60, (duration_TO % 60))); buffer.append("(Search: " + String.format("%d:%02d:%02d", duration_GA / 3600, (duration_GA % 3600) / 60, (duration_GA % 60)) + ", "); buffer.append("minimization: " + String.format("%d:%02d:%02d", duration_MI / 3600, (duration_MI % 3600) / 60, (duration_MI % 60)) + ")\n"); */ buffer.append("<li>Covered " + getOutputVariableValue(data, RuntimeVariable.Covered_Branches.name()) + "/" + getOutputVariableValue(data, RuntimeVariable.Total_Branches.name()) + " branches, "); buffer.append("<li>Covered "+ getOutputVariableValue(data, RuntimeVariable.Covered_Methods.name()) + "/" + getOutputVariableValue(data, RuntimeVariable.Total_Methods.name()) + " methods, "); buffer.append("<li>Covered "+ getOutputVariableValue(data, RuntimeVariable.Covered_Goals.name()) + "/" + getOutputVariableValue(data, RuntimeVariable.Total_Goals.name()) + " total goals\n"); if(data.containsKey(RuntimeVariable.MutationScore.name())) buffer.append("<li>Mutation score: " + NumberFormat.getPercentInstance().format((Double)data.get(RuntimeVariable.MutationScore.name()).getValue()) + "\n"); buffer.append("</ul>\n"); } /** * Write some overall stats * * @param buffer * a {@link java.lang.StringBuffer} object. * @param entry * a {@link org.evosuite.utils.ReportGenerator.StatisticEntry} * object. */ protected void writeParameterTable(StringBuffer buffer, Map<String, OutputVariable<?>> data) { buffer.append("<h2 id=parameters>EvoSuite Parameters</h2>\n"); buffer.append("<div class=statistics><ul>\n"); for (String key : data.keySet()) { buffer.append("<li>" + key + ": " + data.get(key).getValue() + "\n"); } buffer.append("</ul></div>\n"); } }
17,342
0.64675
0.637359
491
34.34827
28.726587
127
false
false
0
0
0
0
0
0
2.537678
false
false
2
53a2a23dbf8f42b35a9a3d34cd2729314af56236
8,057,358,672,398
af0a03f061cf4eac5a16e14ffc87914ff343709f
/src/ru/rem/clans/Clan.java
57a4aa744a798e5f61bbc71f451f6240b8fed726
[]
no_license
DevRem/Clans
https://github.com/DevRem/Clans
eb55528b758b9a10bc96b50efc19af6d03fa6d1e
fb4e88a38f72559dfd837bd9b2495f4a929b1d34
refs/heads/master
2016-08-13T00:41:34.465000
2016-04-24T22:07:35
2016-04-24T22:07:35
45,393,082
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.rem.clans; import java.util.TreeSet; import org.bukkit.Bukkit; public final class Clan extends AbstractClan{ // Второстепенные параметры клана public TreeSet<AbstractMember> members = new TreeSet<>(); public TreeSet<AbstractMember> spectators = new TreeSet<>(); public ClanLocation location; public long deposit; public Clan(String name, String leader, long time, double exp, double deposit, ClanLocation loc) { super(name, leader, time); this.location = loc; } public Clan(String name, String leader, long time) { super(name, leader, time); } @Override public void addPlayer(AbstractMember player) { player.setClan(this); members.add(player); } @Override public boolean removePlayer(AbstractMember player) { boolean result = members.remove(player); player.removeClan(); return result; } @Override public TreeSet<AbstractMember> getMembers() { return members; } @Override public void sendMessage(String message) { for(AbstractMember pl: members){ if(!pl.isOnline()){ break; } Bukkit.getPlayer(pl.getName()).sendMessage(message); } } @Override public boolean isLeader(String player) { return getLeader().equals(player); } @Override public ClanLocation getClanHome() { return location; } @Override public void setClanHome(ClanLocation clanHome) { location = clanHome; } @Override public long getDeposit() { return deposit; } @Override public void updateDeposit(int sum) { deposit = deposit + sum; } @Override public void setSum(long sum) { deposit = sum; } @Override public boolean amountAvailable(long sum) { return deposit >= sum; } @Override public AbstractMember getPlayer(String player) { for(AbstractMember mem: members){ if(mem.getName().equals(player)){ return mem; } } return null; } @Override public void incExp(double ex) { exp = exp + ex; } @Override public void refreshDataPlayer(AbstractMember mem, boolean status) { members.remove(mem); mem.updateStatus(status); addPlayer(mem); } }
WINDOWS-1251
Java
2,201
java
Clan.java
Java
[]
null
[]
package ru.rem.clans; import java.util.TreeSet; import org.bukkit.Bukkit; public final class Clan extends AbstractClan{ // Второстепенные параметры клана public TreeSet<AbstractMember> members = new TreeSet<>(); public TreeSet<AbstractMember> spectators = new TreeSet<>(); public ClanLocation location; public long deposit; public Clan(String name, String leader, long time, double exp, double deposit, ClanLocation loc) { super(name, leader, time); this.location = loc; } public Clan(String name, String leader, long time) { super(name, leader, time); } @Override public void addPlayer(AbstractMember player) { player.setClan(this); members.add(player); } @Override public boolean removePlayer(AbstractMember player) { boolean result = members.remove(player); player.removeClan(); return result; } @Override public TreeSet<AbstractMember> getMembers() { return members; } @Override public void sendMessage(String message) { for(AbstractMember pl: members){ if(!pl.isOnline()){ break; } Bukkit.getPlayer(pl.getName()).sendMessage(message); } } @Override public boolean isLeader(String player) { return getLeader().equals(player); } @Override public ClanLocation getClanHome() { return location; } @Override public void setClanHome(ClanLocation clanHome) { location = clanHome; } @Override public long getDeposit() { return deposit; } @Override public void updateDeposit(int sum) { deposit = deposit + sum; } @Override public void setSum(long sum) { deposit = sum; } @Override public boolean amountAvailable(long sum) { return deposit >= sum; } @Override public AbstractMember getPlayer(String player) { for(AbstractMember mem: members){ if(mem.getName().equals(player)){ return mem; } } return null; } @Override public void incExp(double ex) { exp = exp + ex; } @Override public void refreshDataPlayer(AbstractMember mem, boolean status) { members.remove(mem); mem.updateStatus(status); addPlayer(mem); } }
2,201
0.671882
0.671882
110
17.754545
18.916172
99
false
false
0
0
0
0
0
0
1.6
false
false
2
594cf43a321de0fab4875a045176c591ff293d99
31,310,311,608,254
a65785ab0a5d113b4157b2e2d0a486415fba426d
/src/main/java/chapter2/item5/Lexicon.java
73a98fa6c7fa2fd10da8693f4534163c06c0c0e7
[]
no_license
StrongSoft/effectivejava
https://github.com/StrongSoft/effectivejava
ab2824d643bf04c484331c877a7f2bd0db682e3c
7c065c59e4cce35ac9d989f81a94cf523259f98f
refs/heads/master
2023-05-26T03:36:21.187000
2021-06-08T13:34:34
2021-06-08T13:34:34
372,699,828
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter2.item5; public class Lexicon { }
UTF-8
Java
51
java
Lexicon.java
Java
[]
null
[]
package chapter2.item5; public class Lexicon { }
51
0.745098
0.705882
5
9.2
10.870143
23
false
false
0
0
0
0
0
0
0.2
false
false
2
1c88e708e935730168b1905f09c3e88b3c70a108
30,021,821,427,909
573fc8c73cf9ac2b840b0b9427a1adb929a1e4b1
/Robot Code/Prentice/src/org/usfirst/frc/team5810/robot/XboxE.java
2b328d73d803fc83a9773d2763203ac927449321
[]
no_license
XBotsFRC/TeamFiles
https://github.com/XBotsFRC/TeamFiles
7a306d5930b4d388f44b5d625ea031fdb07d4fa8
af75bd5ac6f51328d5339927dd1849d6b6c22057
refs/heads/master
2018-01-08T11:07:22.085000
2016-04-01T06:14:32
2016-04-01T06:14:32
49,618,755
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.usfirst.frc.team5810.robot; public class XboxE { public static final int ID = 0; //AXES public static final int LEFTXAXIS = 0; public static final int LEFTYAXIS = 1; public static final int LEFTTRIGGER = 2; public static final int RIGHTTRIGGER = 3; public static final int RIGHTXAXIS = 4; public static final int RIGHTYAXIS = 5; //BUTTONS public static final int A = 1; public static final int B = 2; public static final int X = 3; public static final int Y = 4; public static final int LB = 5; public static final int RB = 6; public static final int BACK = 4; public static final int START = 4; public static final int DRIVERFORWARD = RIGHTTRIGGER; public static final int DRIVERBACKWARDS = LEFTTRIGGER; public static final int DRIVEANGLEAXIS = RIGHTXAXIS; public static final int DRIVERSHOOTER = LB; public static final int LOAD = B; public static final int FIREPREP = A; public static final int RAISE = Y; public static final int LOWER = X; public static final int BRAKE = RB; }
UTF-8
Java
1,031
java
XboxE.java
Java
[]
null
[]
package org.usfirst.frc.team5810.robot; public class XboxE { public static final int ID = 0; //AXES public static final int LEFTXAXIS = 0; public static final int LEFTYAXIS = 1; public static final int LEFTTRIGGER = 2; public static final int RIGHTTRIGGER = 3; public static final int RIGHTXAXIS = 4; public static final int RIGHTYAXIS = 5; //BUTTONS public static final int A = 1; public static final int B = 2; public static final int X = 3; public static final int Y = 4; public static final int LB = 5; public static final int RB = 6; public static final int BACK = 4; public static final int START = 4; public static final int DRIVERFORWARD = RIGHTTRIGGER; public static final int DRIVERBACKWARDS = LEFTTRIGGER; public static final int DRIVEANGLEAXIS = RIGHTXAXIS; public static final int DRIVERSHOOTER = LB; public static final int LOAD = B; public static final int FIREPREP = A; public static final int RAISE = Y; public static final int LOWER = X; public static final int BRAKE = RB; }
1,031
0.735209
0.71678
35
28.457144
16.689335
55
false
false
0
0
0
0
0
0
1.6
false
false
2
deefe6b55552e3e851f08422204b467eb9787605
18,236,431,170,743
51b0113105c204b93973b2521a66e34dc2b1fc7a
/src/main/java/integration/api/vo/ObjectVO.java
2ec9b44ba0a513bb719391f769e0696dd0a73bcd
[]
no_license
uzair1990/SVN_BackUP_CLK
https://github.com/uzair1990/SVN_BackUP_CLK
8109f091fe94f860b9c672801e15880aff3a4eeb
7f4fed9bf309bbaea05926bdb5af374e0a126333
refs/heads/master
2017-11-30T11:25:05.537000
2016-11-11T17:17:50
2016-11-11T17:17:50
81,482,743
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package integration.api.vo; import integration.api.vi.ObjectVI; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; ; /** * PowerSteering Software * User: dzaremba * Date: 10/2/13 */ @XmlRootElement(name = MetadataInfo.IT_OBJECT) @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = MetadataInfo.IT_OBJECT) @MetadataTypeAnnotation(integrationType = MetadataInfo.IT_OBJECT, notes = "Object instance") public class ObjectVO extends BaseObjectVO implements ObjectVI { @MetadataAnnotation(dataType = MetadataInfo.IT_STRING, notes = "Object's type") private String type; @MetadataAnnotation(dataType = MetadataInfo.IT_STRING, notes = "Object visibility") private String visibility; @MetadataAnnotation(dataType = MetadataInfo.IT_ID_NAME, update = false, notes = "Link to user-creator") private IdNamePairVO creator; @MetadataAnnotation(dataType = MetadataInfo.IT_DATE, update = false, notes = "Creation date") private String createDate; @MetadataAnnotation(dataType = MetadataInfo.IT_DATE, update = false, notes = "Last change date") private String lastChangeDate; @Override public String getVisibility() { return visibility; } @Override public void setVisibility(String visibility) { this.visibility = visibility; } @Override public IdNamePairVO getCreator() { return creator; } @Override public void setCreator(IdNamePairVO creator) { this.creator = creator; } @Override public String getCreateDate() { return createDate; } @Override public void setCreateDate(String createDate) { this.createDate = createDate; } @Override public String getLastChangeDate() { return lastChangeDate; } @Override public void setLastChangeDate(String lastChangeDate) { this.lastChangeDate = lastChangeDate; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } }
UTF-8
Java
2,292
java
ObjectVO.java
Java
[ { "context": ";\r\n\r\n;\r\n\r\n/**\r\n * PowerSteering Software\r\n * User: dzaremba\r\n * Date: 10/2/13\r\n */\r\n\r\n@XmlRootElement(name = ", "end": 319, "score": 0.9996912479400635, "start": 311, "tag": "USERNAME", "value": "dzaremba" } ]
null
[]
package integration.api.vo; import integration.api.vi.ObjectVI; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; ; /** * PowerSteering Software * User: dzaremba * Date: 10/2/13 */ @XmlRootElement(name = MetadataInfo.IT_OBJECT) @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = MetadataInfo.IT_OBJECT) @MetadataTypeAnnotation(integrationType = MetadataInfo.IT_OBJECT, notes = "Object instance") public class ObjectVO extends BaseObjectVO implements ObjectVI { @MetadataAnnotation(dataType = MetadataInfo.IT_STRING, notes = "Object's type") private String type; @MetadataAnnotation(dataType = MetadataInfo.IT_STRING, notes = "Object visibility") private String visibility; @MetadataAnnotation(dataType = MetadataInfo.IT_ID_NAME, update = false, notes = "Link to user-creator") private IdNamePairVO creator; @MetadataAnnotation(dataType = MetadataInfo.IT_DATE, update = false, notes = "Creation date") private String createDate; @MetadataAnnotation(dataType = MetadataInfo.IT_DATE, update = false, notes = "Last change date") private String lastChangeDate; @Override public String getVisibility() { return visibility; } @Override public void setVisibility(String visibility) { this.visibility = visibility; } @Override public IdNamePairVO getCreator() { return creator; } @Override public void setCreator(IdNamePairVO creator) { this.creator = creator; } @Override public String getCreateDate() { return createDate; } @Override public void setCreateDate(String createDate) { this.createDate = createDate; } @Override public String getLastChangeDate() { return lastChangeDate; } @Override public void setLastChangeDate(String lastChangeDate) { this.lastChangeDate = lastChangeDate; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } }
2,292
0.672775
0.670593
87
24.344828
25.756075
107
false
false
0
0
0
0
0
0
0.356322
false
false
2
bb6a386cc618e7e9fc2557b42d782f0a21603dfe
15,573,551,432,265
938439901faea827ead169d4e6b11b037c7bd42f
/src/RBTreePanel.java
ddd3b37a5d31026f70cceec62b185f85e3aae3aa
[]
no_license
Arvind-Maan/Red-BlackTree
https://github.com/Arvind-Maan/Red-BlackTree
e4c8dde4244453641db2565cb8ebc366e60d152f
5ccc2ad8b2bc6d178748e5af8fdac3d3dcf06577
refs/heads/master
2020-06-23T02:54:51.409000
2019-10-22T03:00:05
2019-10-22T03:00:05
198,485,275
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.swing.*; import java.awt.*; public class RBTreePanel extends JPanel { private static final long serialVersionUID = 1250L; private RedBlackTree tree; private int radius = 20; private int yOffset = 50; private Color textCol = new Color(230, 230, 230); public RBTreePanel(RedBlackTree tree) { this.tree = tree; } @Override protected void paintComponent(Graphics gfx) { super.paintComponent(gfx); if (!tree.isEmpty()) { Graphics2D gfx2d = (Graphics2D) gfx; gfx2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gfx2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); paintTree(gfx2d, tree.getRoot(), getWidth() / 2, 30, getGap()); } } private void paintTree(Graphics2D g, RedBlackNode root, int x, int y, int xOffset) { //update the view if unbound layout if (x < 0) setPreferredSize(new Dimension(2 * getWidth(), getHeight())); drawNode(g, root, x, y); if (root.left != null) { join(g, x - xOffset, y + yOffset, x, y); paintTree(g, root.left, x - xOffset, y + yOffset, xOffset / 2); } if (root.right != null) { join(g, x + xOffset, y + yOffset, x, y); paintTree(g, root.right, x + xOffset, y + yOffset, xOffset / 2); } } private void drawNode(Graphics2D g, RedBlackNode node, int x, int y) { g.setColor(node.getColor()); g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius); g.setColor(textCol); String text = Integer.toString(node.key); drawCentreText(g, text, x, y); g.setColor(Color.GRAY); } private void drawCentreText(Graphics2D g, String text, int x, int y) { FontMetrics fm = g.getFontMetrics(); double t_width = fm.getStringBounds(text, g).getWidth(); g.drawString(text, (int) (x - t_width / 2), (int) (y + fm.getMaxAscent() / 2)); } private void join(Graphics2D g, int x1, int y1, int x2, int y2) { double hypot = Math.hypot(yOffset, x2 - x1); int x11 = (int) (x1 + radius * (x2 - x1) / hypot); int y11 = (int) (y1 - radius * yOffset / hypot); int x21 = (int) (x2 - radius * (x2 - x1) / hypot); int y21 = (int) (y2 + radius * yOffset / hypot); g.drawLine(x11, y11, x21, y21); } private int getGap() { int depth = tree.getDepth(); int multiplier = 30; float exponent = (float) 1.4; if (depth > 6) { multiplier += depth * 3; exponent += .1; } return (int) Math.pow(depth, exponent) * multiplier; } }
UTF-8
Java
2,841
java
RBTreePanel.java
Java
[]
null
[]
import javax.swing.*; import java.awt.*; public class RBTreePanel extends JPanel { private static final long serialVersionUID = 1250L; private RedBlackTree tree; private int radius = 20; private int yOffset = 50; private Color textCol = new Color(230, 230, 230); public RBTreePanel(RedBlackTree tree) { this.tree = tree; } @Override protected void paintComponent(Graphics gfx) { super.paintComponent(gfx); if (!tree.isEmpty()) { Graphics2D gfx2d = (Graphics2D) gfx; gfx2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gfx2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); paintTree(gfx2d, tree.getRoot(), getWidth() / 2, 30, getGap()); } } private void paintTree(Graphics2D g, RedBlackNode root, int x, int y, int xOffset) { //update the view if unbound layout if (x < 0) setPreferredSize(new Dimension(2 * getWidth(), getHeight())); drawNode(g, root, x, y); if (root.left != null) { join(g, x - xOffset, y + yOffset, x, y); paintTree(g, root.left, x - xOffset, y + yOffset, xOffset / 2); } if (root.right != null) { join(g, x + xOffset, y + yOffset, x, y); paintTree(g, root.right, x + xOffset, y + yOffset, xOffset / 2); } } private void drawNode(Graphics2D g, RedBlackNode node, int x, int y) { g.setColor(node.getColor()); g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius); g.setColor(textCol); String text = Integer.toString(node.key); drawCentreText(g, text, x, y); g.setColor(Color.GRAY); } private void drawCentreText(Graphics2D g, String text, int x, int y) { FontMetrics fm = g.getFontMetrics(); double t_width = fm.getStringBounds(text, g).getWidth(); g.drawString(text, (int) (x - t_width / 2), (int) (y + fm.getMaxAscent() / 2)); } private void join(Graphics2D g, int x1, int y1, int x2, int y2) { double hypot = Math.hypot(yOffset, x2 - x1); int x11 = (int) (x1 + radius * (x2 - x1) / hypot); int y11 = (int) (y1 - radius * yOffset / hypot); int x21 = (int) (x2 - radius * (x2 - x1) / hypot); int y21 = (int) (y2 + radius * yOffset / hypot); g.drawLine(x11, y11, x21, y21); } private int getGap() { int depth = tree.getDepth(); int multiplier = 30; float exponent = (float) 1.4; if (depth > 6) { multiplier += depth * 3; exponent += .1; } return (int) Math.pow(depth, exponent) * multiplier; } }
2,841
0.56459
0.538191
80
34.512501
25.939831
113
false
false
0
0
0
0
0
0
1.2
false
false
2
0b850390b7ed09487176e5083cc6687787530abf
5,093,831,231,033
db0a77215b4e53884c715d28dba365cfe30b55be
/src/main/java/com/photochecker/controllers/mlka/MlkaExcelReportController.java
8fb06cc58405f5885e5142fed8ba18ab3c511441
[]
no_license
rustaqs/photocheker
https://github.com/rustaqs/photocheker
313b9757ad820313fc7cc5ae6b2b6ae5ef2d11ba
5a5a818a2f25aeae7765f69e72cdb8ce214cfafe
refs/heads/master
2021-09-04T11:16:15.967000
2018-01-18T06:40:18
2018-01-18T06:40:18
114,601,621
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.photochecker.controllers.mlka; import com.photochecker.excelViews.MlkaExcelReportView; import com.photochecker.service.mlka.MlkaExcelReportService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @Controller public class MlkaExcelReportController { @Autowired private MlkaExcelReportService mlkaExcelReportService; @GetMapping(value = "/reports/mlka/getExcelReport", produces = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") public ModelAndView getExcelReport (HttpServletRequest request, HttpServletResponse response) { Map<String, Object> excelParams = new HashMap<>(); excelParams.put("dateFrom", request.getParameter("dateFrom")); excelParams.put("dateTo", request.getParameter("dateTo")); excelParams.put("mlkaExcelReportService", mlkaExcelReportService); return new ModelAndView(new MlkaExcelReportView(), "excelParams", excelParams); } }
UTF-8
Java
1,316
java
MlkaExcelReportController.java
Java
[]
null
[]
package com.photochecker.controllers.mlka; import com.photochecker.excelViews.MlkaExcelReportView; import com.photochecker.service.mlka.MlkaExcelReportService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @Controller public class MlkaExcelReportController { @Autowired private MlkaExcelReportService mlkaExcelReportService; @GetMapping(value = "/reports/mlka/getExcelReport", produces = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") public ModelAndView getExcelReport (HttpServletRequest request, HttpServletResponse response) { Map<String, Object> excelParams = new HashMap<>(); excelParams.put("dateFrom", request.getParameter("dateFrom")); excelParams.put("dateTo", request.getParameter("dateTo")); excelParams.put("mlkaExcelReportService", mlkaExcelReportService); return new ModelAndView(new MlkaExcelReportView(), "excelParams", excelParams); } }
1,316
0.765198
0.765198
33
38.878788
29.043079
91
false
false
0
0
0
0
0
0
0.757576
false
false
2
60990ef0f21686f4876c263426a442984fabcb58
11,089,605,584,905
a03f3e00dff2c60e7811c179e6e633afb3ea582f
/Kando/test/kando/bl/data/BoardTest.java
45288b544270d3a2a844c71d386b1940ee9331f2
[]
no_license
l0ll/kando
https://github.com/l0ll/kando
25d45a417dd60c0ef40d3ac000b41dc4ff9ee2d1
2e43a88a6d8718881732c23e117b7e398354d3c5
refs/heads/master
2018-01-03T21:23:25.241000
2016-10-18T20:21:36
2016-10-18T20:21:36
71,276,569
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kando.bl.data; import static org.junit.Assert.assertEquals; import org.junit.Test; import kando.data.Board; import kando.data.Column; public class BoardTest { @Test public void initialisation() { Board b = new Board(1l); assertEquals(0, b.getNumberOfColumns()); } @Test public void addColumns() { Board b = new Board(1l); b.addColumn(new Column()); b.addColumn(new Column()); b.addColumn(new Column()); b.addColumn(new Column()); b.addColumn(new Column()); assertEquals(5, b.getNumberOfColumns()); } @Test public void removeColumn() { Board b = new Board(1l); Column column = new Column(); b.addColumn(column); assertEquals(1, b.getNumberOfColumns()); b.removeColumn(column); assertEquals(0, b.getNumberOfColumns()); } @Test public void addAndMoveColumns() { Board b = new Board(1l); Column c1 = new Column(); Column c2 = new Column(); Column c3 = new Column(); b.addColumn(c1); b.addColumn(c2); b.addColumn(c3); b.moveColumnToIndex(c3, 1); assertEquals(b.getColumn(1), c3); assertEquals(b.getColumn(2), c2); }}
UTF-8
Java
1,178
java
BoardTest.java
Java
[]
null
[]
package kando.bl.data; import static org.junit.Assert.assertEquals; import org.junit.Test; import kando.data.Board; import kando.data.Column; public class BoardTest { @Test public void initialisation() { Board b = new Board(1l); assertEquals(0, b.getNumberOfColumns()); } @Test public void addColumns() { Board b = new Board(1l); b.addColumn(new Column()); b.addColumn(new Column()); b.addColumn(new Column()); b.addColumn(new Column()); b.addColumn(new Column()); assertEquals(5, b.getNumberOfColumns()); } @Test public void removeColumn() { Board b = new Board(1l); Column column = new Column(); b.addColumn(column); assertEquals(1, b.getNumberOfColumns()); b.removeColumn(column); assertEquals(0, b.getNumberOfColumns()); } @Test public void addAndMoveColumns() { Board b = new Board(1l); Column c1 = new Column(); Column c2 = new Column(); Column c3 = new Column(); b.addColumn(c1); b.addColumn(c2); b.addColumn(c3); b.moveColumnToIndex(c3, 1); assertEquals(b.getColumn(1), c3); assertEquals(b.getColumn(2), c2); }}
1,178
0.632428
0.61545
62
17
14.136432
44
false
false
0
0
0
0
0
0
1.903226
false
false
2
17cfd93f4dc7a65737995ee54640db9401280ed4
16,630,113,394,244
0c32a113795669da7a8eb923763c77cb5403ceda
/src/Leetcode/No_14_Longest_Common_Prefix/Solution.java
5e6f64f21adf3362fa8718b5bf4aa88511505254
[]
no_license
pete965/LeetcodeJava
https://github.com/pete965/LeetcodeJava
63dd0c2296d990bc49fff6f18fe2fe01551d36fe
7d2496fe2728be92fc2c053dba8ab21b2de1b0f3
refs/heads/master
2021-10-28T02:39:50.144000
2021-10-22T02:40:54
2021-10-22T02:40:54
207,782,506
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Leetcode.No_14_Longest_Common_Prefix; class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length==0){ return ""; } int i; int length = strs[0].length(); for (int j=1;j<strs.length;j++){ length=Math.min(length,strs[j].length()); } boolean end = false; for(i=0;i<length;i++){ Character character = strs[0].charAt(i); for (int j=1;j<strs.length;j++){ if (character!=strs[j].charAt(i)){ end=true; break; } } if (end){ break; } } String output=strs[0].substring(0,i); return output; } }
UTF-8
Java
785
java
Solution.java
Java
[]
null
[]
package Leetcode.No_14_Longest_Common_Prefix; class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length==0){ return ""; } int i; int length = strs[0].length(); for (int j=1;j<strs.length;j++){ length=Math.min(length,strs[j].length()); } boolean end = false; for(i=0;i<length;i++){ Character character = strs[0].charAt(i); for (int j=1;j<strs.length;j++){ if (character!=strs[j].charAt(i)){ end=true; break; } } if (end){ break; } } String output=strs[0].substring(0,i); return output; } }
785
0.443312
0.430573
30
25.166666
16.516827
54
false
false
0
0
0
0
0
0
0.666667
false
false
2
358d28688a1dd1c5a56916b0b214c19b057c962d
19,009,525,277,958
61e0411217eebcd79a7f226dce877c47df824e58
/Servico SOA/src/main/java/br/ufc/quixada/es/ScrumTool/entidades/Estado.java
f70f6429d649d4701eaeb9507922cf3f20b3ea1d
[]
no_license
OtavioAugustoSousa/ScrumTool
https://github.com/OtavioAugustoSousa/ScrumTool
add14b0f96a415d55519b55acf801401b840ea0a
28cd01aae446cf3cf176560b9f31a862d362a6af
refs/heads/master
2021-01-10T15:59:29.909000
2016-02-13T02:01:40
2016-02-13T02:01:40
51,627,548
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.ufc.quixada.es.ScrumTool.entidades; public enum Estado { TODO, DOING, DONE; }
UTF-8
Java
91
java
Estado.java
Java
[]
null
[]
package br.ufc.quixada.es.ScrumTool.entidades; public enum Estado { TODO, DOING, DONE; }
91
0.747253
0.747253
5
17.200001
16.726028
46
false
false
0
0
0
0
0
0
1
false
false
2
8d098934841e59e5ea3537fcc440b564377b729c
19,009,525,279,530
c9f0deb2ec0cb06c613fe544ac356ec01c04c07b
/src/main/java/com/acat/dao/UserDao.java
173566a2141bdedb1b0295150835a2be8737bc10
[]
no_license
rocky1996/wxdemo
https://github.com/rocky1996/wxdemo
2a2f53f1cdd0c69feef61877f2d0a2f394a2bd68
622b3a0cdc4f40e2e52554c89e617668307f8f59
refs/heads/master
2020-05-07T08:24:15.669000
2019-04-09T08:58:19
2019-04-09T08:58:19
180,326,175
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.acat.dao; import com.acat.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface UserDao extends JpaRepository<UserEntity,Integer> { @Query(value = "select en from UserEntity en where en.wx_user_username=?1 and en.wx_user_password=?2") UserEntity login(String wx_user_username,String wx_user_password); }
UTF-8
Java
426
java
UserDao.java
Java
[ { "context": "e en.wx_user_username=?1 and en.wx_user_password=?2\")\n UserEntity login(String wx_user_username,St", "end": 349, "score": 0.6625921726226807, "start": 348, "tag": "PASSWORD", "value": "2" } ]
null
[]
package com.acat.dao; import com.acat.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface UserDao extends JpaRepository<UserEntity,Integer> { @Query(value = "select en from UserEntity en where en.wx_user_username=?1 and en.wx_user_password=?2") UserEntity login(String wx_user_username,String wx_user_password); }
426
0.788732
0.784038
12
34.5
34.886723
106
false
false
0
0
0
0
0
0
0.583333
false
false
2
d2a3cdffee4b08eb9f23ab029ea7053dafd4e903
27,006,754,362,053
056a1f8ba8bb95bf9e5b3cbfc2f5e0999d38c95c
/src/main/java/stream/AddressSearcher.java
a5a2805b21ef7c18e34d2416be865002cf408b86
[]
no_license
shinharad/java8-lab
https://github.com/shinharad/java8-lab
cf70a2b51bcf757d80c0ec780d4d51c65fa96dac
ad0971473e8096f62e30942f0dc586bef7c167a0
refs/heads/master
2019-08-20T06:47:10.988000
2016-05-19T14:31:29
2016-05-19T14:31:29
58,647,017
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; import java.util.stream.Stream; import lombok.Value; import lombok.extern.java.Log; /** * <p> * 住所検索クラス * </p> * * <p> * Java8のストリームAPI、ラムダ式を使用し、<br /> * 日本郵政が提供する以下の郵便番号データから指定した郵便番号に合致する住所を検索します。<br /> * <br /> * 読み仮名データの促音・拗音を小書きで表記するもの(zip形式)<br /> * KEN_ALL.CSV<br /> * http://www.post.japanpost.jp/zipcode/dl/kogaki-zip.html<br /> * </p> * * @author shinharad */ @Log public class AddressSearcher { /** 郵便番号データの場所。プロジェクトルートと同じ階層に配置する */ private static final String DEFAULT_PATH = System.getProperty("user.dir") + "/../KEN_ALL.CSV"; /** 郵便番号データの文字セット */ private static final String DEFAULT_CHARSET = "SJIS"; /** * 住所検索 * * @param zip * @return * @throws Exception */ public Optional<Address> findByZip(final String zip) throws Exception { return findByZip(zip, DEFAULT_PATH); } /** * 住所検索 * * @param zip * @param path * @return * @throws Exception */ public Optional<Address> findByZip(final String zip, final String path) throws Exception { log.info("zip:" + zip + "/path:" + path); // あらかじめ郵便番号をダブルクォートで括っておく final String key = "\"" + zip + "\""; // 郵便番号データ読み込み Optional<Address> address; try (Stream<String> stream = Files.lines(Paths.get(path), Charset.forName(DEFAULT_CHARSET))) { // StreamAPIで郵便番号が合致する住所を取得 address = stream.filter(x -> { String[] xs = x.split(",", 4); return (xs.length > 3 && xs[2].trim().equals(key)); }) .map(x -> x.replace("\"", "")) .map(x -> { String[] xs = x.split(",", 10); return (xs.length > 9) ? new Address(xs[6], xs[7], xs[8]) : null; }) .findFirst(); } return address; } /** 住所情報格納クラス */ @Value public static class Address { private String address1; private String address2; private String address3; } }
UTF-8
Java
2,610
java
AddressSearcher.java
Java
[ { "context": "de/dl/kogaki-zip.html<br />\n * </p>\n * \n * @author shinharad\n */\n@Log\npublic class AddressSearcher {\n\n /** ", "end": 516, "score": 0.9969901442527771, "start": 507, "tag": "USERNAME", "value": "shinharad" } ]
null
[]
package stream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; import java.util.stream.Stream; import lombok.Value; import lombok.extern.java.Log; /** * <p> * 住所検索クラス * </p> * * <p> * Java8のストリームAPI、ラムダ式を使用し、<br /> * 日本郵政が提供する以下の郵便番号データから指定した郵便番号に合致する住所を検索します。<br /> * <br /> * 読み仮名データの促音・拗音を小書きで表記するもの(zip形式)<br /> * KEN_ALL.CSV<br /> * http://www.post.japanpost.jp/zipcode/dl/kogaki-zip.html<br /> * </p> * * @author shinharad */ @Log public class AddressSearcher { /** 郵便番号データの場所。プロジェクトルートと同じ階層に配置する */ private static final String DEFAULT_PATH = System.getProperty("user.dir") + "/../KEN_ALL.CSV"; /** 郵便番号データの文字セット */ private static final String DEFAULT_CHARSET = "SJIS"; /** * 住所検索 * * @param zip * @return * @throws Exception */ public Optional<Address> findByZip(final String zip) throws Exception { return findByZip(zip, DEFAULT_PATH); } /** * 住所検索 * * @param zip * @param path * @return * @throws Exception */ public Optional<Address> findByZip(final String zip, final String path) throws Exception { log.info("zip:" + zip + "/path:" + path); // あらかじめ郵便番号をダブルクォートで括っておく final String key = "\"" + zip + "\""; // 郵便番号データ読み込み Optional<Address> address; try (Stream<String> stream = Files.lines(Paths.get(path), Charset.forName(DEFAULT_CHARSET))) { // StreamAPIで郵便番号が合致する住所を取得 address = stream.filter(x -> { String[] xs = x.split(",", 4); return (xs.length > 3 && xs[2].trim().equals(key)); }) .map(x -> x.replace("\"", "")) .map(x -> { String[] xs = x.split(",", 10); return (xs.length > 9) ? new Address(xs[6], xs[7], xs[8]) : null; }) .findFirst(); } return address; } /** 住所情報格納クラス */ @Value public static class Address { private String address1; private String address2; private String address3; } }
2,610
0.553895
0.548007
90
23.533333
23.045944
102
false
false
0
0
0
0
0
0
0.366667
false
false
2
19da3b7f5f6e185f588e15876af6e456252b704c
15,934,328,685,857
1f2073269378e734b5c9baafa23890558b004673
/struts2.1/src/com/helloweenvsfei/struts2/action/tags/UITag/OptiontransferselectAction.java
742ff24a2e206bd8619e6287efa3064fcc123648
[]
no_license
hungmans6779/Java-Web-integration-development
https://github.com/hungmans6779/Java-Web-integration-development
7db40c418c13c3efa27e249cdf1e8fe8e39dfa83
289d03edd927484e30b053d1e23b218f003d2359
refs/heads/master
2020-04-14T01:14:35.712000
2018-12-30T02:28:32
2018-12-30T02:28:32
163,555,635
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.helloweenvsfei.struts2.action.tags.UITag; import java.util.ArrayList; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import com.opensymphony.xwork2.ActionSupport; @Namespace(value="/tags") @Action(value="optiontransferselectTag",results={ @Result(name="success",location="/form/tags/UITag/optiontransferselectTag.jsp") }) public class OptiontransferselectAction extends ActionSupport { // 勾選的省份的List private List<String> provinceSelected = new ArrayList<String>(){ { add("北京"); // 增加資料 add("上海"); // 增加資料 add("天津"); // 增加資料 add("重慶"); // 增加資料 add("河北"); // 增加資料 add("河南"); // 增加資料 add("山東"); // 增加資料 add("山西"); // 增加資料 add("江蘇"); // 增加資料 add("浙江"); // 增加資料 } }; // end private List<String> provinceSelected // 沒有勾選的省份 List private List <String> provinceUnselected = new ArrayList<String>(){ { add("湖南"); // 增加資料 add("湖北"); // 增加資料 add("雲南"); // 增加資料 add("廣東"); // 增加資料 add("廣西"); // 增加資料 } }; // end private List <String> provinceUnselected // 主方法 public String execute(){ System.out.println(OptiontransferselectAction.class.getName()+",execute()..."); return "success"; } // end execute() public List<String> getProvinceSelected() { return provinceSelected; } public void setProvinceSelected(List<String> provinceSelected) { this.provinceSelected = provinceSelected; } public List<String> getProvinceUnselected() { return provinceUnselected; } public void setProvinceUnselected(List<String> provinceUnselected) { this.provinceUnselected = provinceUnselected; } }
BIG5
Java
2,012
java
OptiontransferselectAction.java
Java
[]
null
[]
package com.helloweenvsfei.struts2.action.tags.UITag; import java.util.ArrayList; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import com.opensymphony.xwork2.ActionSupport; @Namespace(value="/tags") @Action(value="optiontransferselectTag",results={ @Result(name="success",location="/form/tags/UITag/optiontransferselectTag.jsp") }) public class OptiontransferselectAction extends ActionSupport { // 勾選的省份的List private List<String> provinceSelected = new ArrayList<String>(){ { add("北京"); // 增加資料 add("上海"); // 增加資料 add("天津"); // 增加資料 add("重慶"); // 增加資料 add("河北"); // 增加資料 add("河南"); // 增加資料 add("山東"); // 增加資料 add("山西"); // 增加資料 add("江蘇"); // 增加資料 add("浙江"); // 增加資料 } }; // end private List<String> provinceSelected // 沒有勾選的省份 List private List <String> provinceUnselected = new ArrayList<String>(){ { add("湖南"); // 增加資料 add("湖北"); // 增加資料 add("雲南"); // 增加資料 add("廣東"); // 增加資料 add("廣西"); // 增加資料 } }; // end private List <String> provinceUnselected // 主方法 public String execute(){ System.out.println(OptiontransferselectAction.class.getName()+",execute()..."); return "success"; } // end execute() public List<String> getProvinceSelected() { return provinceSelected; } public void setProvinceSelected(List<String> provinceSelected) { this.provinceSelected = provinceSelected; } public List<String> getProvinceUnselected() { return provinceUnselected; } public void setProvinceUnselected(List<String> provinceUnselected) { this.provinceUnselected = provinceUnselected; } }
2,012
0.667778
0.665
81
21.222221
22.891586
83
false
false
0
0
0
0
0
0
0.839506
false
false
2
916f61d71d90fc46e584ccb4924850819ebe05c0
26,147,760,911,948
46b11f84ee377d74174f981717647b3128c63c3e
/src/main/java/com/sns/invest/user/UserController.java
d60bdd5c1044f6cd200703e0fdf809517c6c0cfa
[]
no_license
doriver/stock_invest_sns
https://github.com/doriver/stock_invest_sns
979578a4c62e56cabf42338f39fe4aed03b0f166
199cd178a5948826d647614e431a39fcccafc8f5
refs/heads/master
2023-08-21T09:40:27.046000
2022-06-23T08:55:29
2022-06-23T08:55:29
406,562,322
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sns.invest.user; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @GetMapping("/sign_view") public String signView() { return "user/sign"; } @GetMapping("/sign_out") public String signOut(HttpServletRequest request) { HttpSession session = request.getSession(); session.removeAttribute("userId"); session.removeAttribute("userLoginId"); session.removeAttribute("userNickName"); session.removeAttribute("userLocation"); return "redirect:/user/sign_view"; } @GetMapping("/test") public String test() { return "user/NewFile"; } }
UTF-8
Java
855
java
UserController.java
Java
[]
null
[]
package com.sns.invest.user; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @GetMapping("/sign_view") public String signView() { return "user/sign"; } @GetMapping("/sign_out") public String signOut(HttpServletRequest request) { HttpSession session = request.getSession(); session.removeAttribute("userId"); session.removeAttribute("userLoginId"); session.removeAttribute("userNickName"); session.removeAttribute("userLocation"); return "redirect:/user/sign_view"; } @GetMapping("/test") public String test() { return "user/NewFile"; } }
855
0.759064
0.759064
36
22.75
19.248919
62
false
false
0
0
0
0
0
0
1.277778
false
false
2
f4cf3ad4f6cb22d285a755132b5740e93666e234
17,600,775,984,387
34c7427a49a5a3abd0f9dd070162c4ba1a8e051b
/src/ClippingExample/Main.java
e2696456ae25f677b8370999444ae5d31c27fc68
[]
no_license
ksadprasidUNB3035/CS-3035-example-code
https://github.com/ksadprasidUNB3035/CS-3035-example-code
69d9df01ccb87f7886150dbdd132a2ff0fcbdfb4
696c863875b1345d6823179a9468814853cfe356
refs/heads/master
2023-01-29T09:26:54.967000
2020-12-08T13:55:02
2020-12-08T13:55:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ClippingExample; import com.sun.javafx.css.Style; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.BorderPane; import javafx.scene.paint.Color; import javafx.stage.Stage; /** * Demonstrate creating a clipping region and drawing to the clipping region. */ public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { BorderPane root = new BorderPane(); Canvas c = new Canvas(); c.setWidth(400); c.setHeight(400); root.setCenter(c); Scene scene = new Scene(root, 400, 400); clipTest(c.getGraphicsContext2D()); primaryStage.setScene(scene); primaryStage.show(); } public void clipTest(GraphicsContext graphicsContext2D) { graphicsContext2D.save(); graphicsContext2D.setFill(Color.DARKGREEN); graphicsContext2D.fillRect(10, 10, 300, 300); // Create a clipping path for a rectangular area and a bezier curve graphicsContext2D.beginPath(); graphicsContext2D.rect(20, 20, 60, 60); graphicsContext2D.bezierCurveTo(0,0, 100,200, 400,400); graphicsContext2D.closePath(); //clip the areas graphicsContext2D.clip(); // Draw red rectangle after clip() only the parts inside clip should be red graphicsContext2D.setFill(Color.RED); graphicsContext2D.fillRect(0, 0, 400, 400); //draw a random shape and it will only fill up part of the path that it intersects with graphicsContext2D.setFill(Color.PAPAYAWHIP); graphicsContext2D.fillRoundRect(300, 300, 100, 100, 10, 10); graphicsContext2D.restore(); } }
UTF-8
Java
1,870
java
Main.java
Java
[]
null
[]
package ClippingExample; import com.sun.javafx.css.Style; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.BorderPane; import javafx.scene.paint.Color; import javafx.stage.Stage; /** * Demonstrate creating a clipping region and drawing to the clipping region. */ public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { BorderPane root = new BorderPane(); Canvas c = new Canvas(); c.setWidth(400); c.setHeight(400); root.setCenter(c); Scene scene = new Scene(root, 400, 400); clipTest(c.getGraphicsContext2D()); primaryStage.setScene(scene); primaryStage.show(); } public void clipTest(GraphicsContext graphicsContext2D) { graphicsContext2D.save(); graphicsContext2D.setFill(Color.DARKGREEN); graphicsContext2D.fillRect(10, 10, 300, 300); // Create a clipping path for a rectangular area and a bezier curve graphicsContext2D.beginPath(); graphicsContext2D.rect(20, 20, 60, 60); graphicsContext2D.bezierCurveTo(0,0, 100,200, 400,400); graphicsContext2D.closePath(); //clip the areas graphicsContext2D.clip(); // Draw red rectangle after clip() only the parts inside clip should be red graphicsContext2D.setFill(Color.RED); graphicsContext2D.fillRect(0, 0, 400, 400); //draw a random shape and it will only fill up part of the path that it intersects with graphicsContext2D.setFill(Color.PAPAYAWHIP); graphicsContext2D.fillRoundRect(300, 300, 100, 100, 10, 10); graphicsContext2D.restore(); } }
1,870
0.675936
0.631551
63
28.682539
24.089664
95
false
false
0
0
0
0
0
0
0.84127
false
false
2
4e4a50a0eb216851b061d423ea4a1359e0636a5b
8,366,596,327,953
85a0b8488b268bdc8646f25994f5792da13be119
/src/main/java/com/example/demo/sock/SockService.java
62ec1b139d4fafedc6870d35231b8ab872ce45ac
[ "MIT" ]
permissive
Unlife86/cib-interns-test-task
https://github.com/Unlife86/cib-interns-test-task
10581252e08c1c24a4fe87f1575a671047f016d5
41a6a5f3c118d283b9028f0a11b69c37947b1409
refs/heads/main
2023-08-28T03:00:22.424000
2021-10-14T19:22:35
2021-10-14T19:22:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.sock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class SockService { private final SockRepository sockRepository; @Autowired public SockService(SockRepository sockRepository) { this.sockRepository = sockRepository; } public Optional<String> getSocks(String color, String operation, Byte cottonPart) { switch (operation) { case "moreThan": return Optional.of(sockRepository.findByColorAndCottonPartGreaterThan(color, cottonPart).get().getQuantity().toString()); case "lessThan": return Optional.of(sockRepository.findByColorAndCottonPartLessThan(color, cottonPart).get().getQuantity().toString()); default: return Optional.of(sockRepository.findByColorAndCottonPart(color, cottonPart).get().getQuantity().toString()); } } public void modifySock(Sock sock, String uri) { Short quantity; Optional<Sock> sockByColor = sockRepository.findByColorAndCottonPart(sock.getColor(), sock.getCottonPart()); System.out.println(uri); if (sockByColor.isPresent()) { if (uri.equals("/api/socks/outcome")) { quantity = (short)(sockByColor.get().getQuantity() - Short.valueOf(sock.getQuantity())); } else { quantity = (short)(sockByColor.get().getQuantity() + Short.valueOf(sock.getQuantity())); } //throw new IllegalStateException("color taken"); sockRepository.setQuantity((short)(quantity),sockByColor.get().getId()); } else { sockRepository.save(sock); } } }
UTF-8
Java
1,801
java
SockService.java
Java
[]
null
[]
package com.example.demo.sock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class SockService { private final SockRepository sockRepository; @Autowired public SockService(SockRepository sockRepository) { this.sockRepository = sockRepository; } public Optional<String> getSocks(String color, String operation, Byte cottonPart) { switch (operation) { case "moreThan": return Optional.of(sockRepository.findByColorAndCottonPartGreaterThan(color, cottonPart).get().getQuantity().toString()); case "lessThan": return Optional.of(sockRepository.findByColorAndCottonPartLessThan(color, cottonPart).get().getQuantity().toString()); default: return Optional.of(sockRepository.findByColorAndCottonPart(color, cottonPart).get().getQuantity().toString()); } } public void modifySock(Sock sock, String uri) { Short quantity; Optional<Sock> sockByColor = sockRepository.findByColorAndCottonPart(sock.getColor(), sock.getCottonPart()); System.out.println(uri); if (sockByColor.isPresent()) { if (uri.equals("/api/socks/outcome")) { quantity = (short)(sockByColor.get().getQuantity() - Short.valueOf(sock.getQuantity())); } else { quantity = (short)(sockByColor.get().getQuantity() + Short.valueOf(sock.getQuantity())); } //throw new IllegalStateException("color taken"); sockRepository.setQuantity((short)(quantity),sockByColor.get().getId()); } else { sockRepository.save(sock); } } }
1,801
0.657968
0.657968
46
38.152172
38.686569
137
false
false
0
0
0
0
0
0
0.565217
false
false
2
7d7d54882af5a31ca063b07fbc9569ad358c7d38
7,636,451,917,537
74db95ac521939b803ce2e8fc201ad44deed2250
/RePractice/SwordOffer0316Twice/Code_0407_50firstNotRepeating.java
956eab2233e24a2389375856f5802f30290e1ab5
[]
no_license
Submergechen/AlgoriPractice
https://github.com/Submergechen/AlgoriPractice
220329489f7f962c44d45cd36151b6ca3ba9e3fe
769d29e4789c5a2398ec1005c3bd740390e9ac6c
refs/heads/master
2021-08-09T00:41:53.875000
2020-09-24T07:48:23
2020-09-24T07:48:23
222,943,801
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package RePractice.SwordOffer0316Twice; import java.util.HashMap; import java.util.Map; public class Code_0407_50firstNotRepeating { //存两次,第一次把 字符和对应次数存进去 //第二次, 循环一遍,如果发现 次数为1 就返回即可 public char solution(String str){ if (str == null){ throw new RuntimeException("error!"); } char[] chars = str.toCharArray(); Map<Character,Integer> map = new HashMap<>(); for (char x: chars){ map.put(x,map.getOrDefault(x,0) + 1); } for (char x : chars){ if (map.get(x) == 1){ return x; } } return '#'; } }
UTF-8
Java
726
java
Code_0407_50firstNotRepeating.java
Java
[]
null
[]
package RePractice.SwordOffer0316Twice; import java.util.HashMap; import java.util.Map; public class Code_0407_50firstNotRepeating { //存两次,第一次把 字符和对应次数存进去 //第二次, 循环一遍,如果发现 次数为1 就返回即可 public char solution(String str){ if (str == null){ throw new RuntimeException("error!"); } char[] chars = str.toCharArray(); Map<Character,Integer> map = new HashMap<>(); for (char x: chars){ map.put(x,map.getOrDefault(x,0) + 1); } for (char x : chars){ if (map.get(x) == 1){ return x; } } return '#'; } }
726
0.529321
0.507716
28
22.142857
16.762445
53
false
false
0
0
0
0
0
0
0.428571
false
false
2
5101b90cbd2e5b48ec760218ff09e696e142caf2
18,580,028,536,949
d1aaf5ced59c89328383b9614debd5ceb9ce2aed
/200402076_hadiid/src/PROGRAM10/Tes.java
da849b30119c8ff83ccc8dd338274e6e1b541d53
[]
no_license
hadiid-studentcode/P.PBO_Semester2
https://github.com/hadiid-studentcode/P.PBO_Semester2
274bedcff080671620f205138e693a7d3fb4aa65
ec46724bc8f3be1e21bee26b1ee761f5d6073df8
refs/heads/main
2023-06-10T14:56:03.282000
2021-07-04T03:18:35
2021-07-04T03:18:35
381,552,205
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 PROGRAM10; // tipe bilangan bulat /** * * @author HADIID ANDRI YULISON */ public class Tes { public static void main (String args []){ int a = 12; int b = 012; int c = 0x12; System.out.println(a); System.out.println(b); System.out.println(c); } }
UTF-8
Java
520
java
Tes.java
Java
[ { "context": "AM10;\r\n// tipe bilangan bulat\r\n/**\r\n *\r\n * @author HADIID ANDRI YULISON\r\n */\r\npublic class Tes {\r\n public static void ", "end": 274, "score": 0.9998302459716797, "start": 254, "tag": "NAME", "value": "HADIID ANDRI YULISON" } ]
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 PROGRAM10; // tipe bilangan bulat /** * * @author <NAME> */ public class Tes { public static void main (String args []){ int a = 12; int b = 012; int c = 0x12; System.out.println(a); System.out.println(b); System.out.println(c); } }
506
0.596154
0.576923
21
22.761906
19.774694
79
false
false
0
0
0
0
0
0
0.47619
false
false
2
03f7f4730226ce6a061b607310217c556cff91a3
26,671,746,966,025
f088991c3b48460bca94a92d2979ab6a86b9d414
/app/src/main/java/com/puhui/dataanalysis/hxdataanalysis/HostService.java
2a7360109f2d9ba88b609ce3a5a68c37835c7697
[]
no_license
s1356891/HxDataAnalysis2
https://github.com/s1356891/HxDataAnalysis2
6e98ef0d1d4bbefef2b400c3c08fffffe6f3e608
bddbbe0e298672336aaac0c903c20f0b5ff6165f
refs/heads/master
2020-03-19T01:32:59.479000
2018-05-31T08:18:37
2018-05-31T08:18:37
135,553,320
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.puhui.dataanalysis.hxdataanalysis; import java.util.ArrayList; import java.util.List; /** * Created by chenb on 2018/5/21. */ public abstract class HostService { private static volatile List services = new ArrayList(); private String type; private int i; public static HostService appService = new AppHost("APP", 0); public static HostService e = new SqlHost("APP_SQL", 7); public static HostService[] hosts; protected HostService(String type, int i) { this.type = type; this.i = i; addServices(type); } private void addServices(String type) { try { if (!HxUtils.isEmpty(type) && !services.contains(type)) { services.add(type); } } catch (Exception e) { e.printStackTrace(); } } public int getApiType() { return this.i; } public String getType() { return this.type; } public abstract String getHost(); public abstract String getAddress(); public abstract String getDataFormat(); public static HostService[] getHosts() { return hosts; } public static ArrayList getServices() { ArrayList arrayList = new ArrayList(); for (int i = 0; i < services.size(); i++) { arrayList.add(getHost((String) services.get(i))); } return arrayList; } public static HostService getHost(String var0) { return var0.equals(appService.getType()) ? appService : (var0.equals(e.getType()) ? e : null); } static { hosts = new HostService[]{appService, e}; } }
UTF-8
Java
1,645
java
HostService.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by chenb on 2018/5/21.\n */\n\npublic abstract class HostServ", "end": 123, "score": 0.9996356964111328, "start": 118, "tag": "USERNAME", "value": "chenb" } ]
null
[]
package com.puhui.dataanalysis.hxdataanalysis; import java.util.ArrayList; import java.util.List; /** * Created by chenb on 2018/5/21. */ public abstract class HostService { private static volatile List services = new ArrayList(); private String type; private int i; public static HostService appService = new AppHost("APP", 0); public static HostService e = new SqlHost("APP_SQL", 7); public static HostService[] hosts; protected HostService(String type, int i) { this.type = type; this.i = i; addServices(type); } private void addServices(String type) { try { if (!HxUtils.isEmpty(type) && !services.contains(type)) { services.add(type); } } catch (Exception e) { e.printStackTrace(); } } public int getApiType() { return this.i; } public String getType() { return this.type; } public abstract String getHost(); public abstract String getAddress(); public abstract String getDataFormat(); public static HostService[] getHosts() { return hosts; } public static ArrayList getServices() { ArrayList arrayList = new ArrayList(); for (int i = 0; i < services.size(); i++) { arrayList.add(getHost((String) services.get(i))); } return arrayList; } public static HostService getHost(String var0) { return var0.equals(appService.getType()) ? appService : (var0.equals(e.getType()) ? e : null); } static { hosts = new HostService[]{appService, e}; } }
1,645
0.598784
0.590881
68
23.191177
22.294987
102
false
false
0
0
0
0
0
0
0.455882
false
false
2
8a45348365356279f3c1e6a72ddd1862b95d50b2
27,341,761,813,348
8aa53495593a0732e5937418a17e75abc05396e3
/core/src/main/java/edu/gvsu/prestongarno/service/CRunnable.java
6ca6a1b143b427b7ed5d6395f6e959e6ccfa7e53
[ "Apache-2.0" ]
permissive
prestongarno/Dynamic-MVP
https://github.com/prestongarno/Dynamic-MVP
a7aa253ee783721680b9fdb578cd2457a6bdb26b
456c2d70ee771a2569a1a8a22c5ac3e0b7a859b9
refs/heads/master
2021-01-21T10:19:21.339000
2017-04-23T20:31:07
2017-04-23T20:31:07
83,404,438
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.gvsu.prestongarno.service; import edu.gvsu.prestongarno.api.Event; /**************************************** * Created by preston on 4/16/17. * * Wrapper class for an event also implements Runnable * which enables a View to override the onJoin() method * and submit that runnable to a different thread/thread pool * * This class will be submitted to the * callback queue instance linked with a particular view ****************************************/ abstract class CRunnable<E extends Event> implements Runnable { /***************************************** * this array of objects stores the arguments to the callback * method when the view has instructed EzMVP to pause joins ****************************************/ private Object[] args; /***************************************** * Construct a new CallbackRunnable to wrap the event. * @param event the event ****************************************/ CRunnable(E event) { } void onStoreCallbackArguments(Object[] args) { } }
UTF-8
Java
1,029
java
CRunnable.java
Java
[ { "context": "************************************\n * Created by preston on 4/16/17.\n *\n * Wrapper class for an event also", "end": 144, "score": 0.9749902486801147, "start": 137, "tag": "USERNAME", "value": "preston" } ]
null
[]
package edu.gvsu.prestongarno.service; import edu.gvsu.prestongarno.api.Event; /**************************************** * Created by preston on 4/16/17. * * Wrapper class for an event also implements Runnable * which enables a View to override the onJoin() method * and submit that runnable to a different thread/thread pool * * This class will be submitted to the * callback queue instance linked with a particular view ****************************************/ abstract class CRunnable<E extends Event> implements Runnable { /***************************************** * this array of objects stores the arguments to the callback * method when the view has instructed EzMVP to pause joins ****************************************/ private Object[] args; /***************************************** * Construct a new CallbackRunnable to wrap the event. * @param event the event ****************************************/ CRunnable(E event) { } void onStoreCallbackArguments(Object[] args) { } }
1,029
0.562682
0.557823
34
29.264706
23.218031
63
false
false
0
0
0
0
0
0
0.470588
false
false
2
ba1c92ef0c00caafee04f15c58bba7babbb4a7d5
1,494,648,664,936
5d038d985c6abe44ce59f2f581b8d40be4fcb644
/app/src/main/java/com/wilson/tasker/ui/SceneListActivity.java
5142a31e6933e508f08fc863fa51b2670b0d1422
[]
no_license
achieverForever/Tasker
https://github.com/achieverForever/Tasker
e381f3e4dc74ababe3ebbeda27376d4f01c2e377
a9ba8e621e5694f03d2a79cc59247c73ef5b69cf
refs/heads/master
2016-09-06T07:11:20.104000
2015-05-07T10:06:05
2015-05-07T10:06:05
30,623,087
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wilson.tasker.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import com.wilson.tasker.R; public class SceneListActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_content); setupActionBar(); if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .add(R.id.content, SceneListFragment.newInstance(), "scene_list") .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_new_scene: ((SceneListFragment) getSupportFragmentManager() .findFragmentByTag("scene_list")).createScene(); return true; case R.id.action_view_timeline: Intent intent = new Intent(this, TimelineActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void setupActionBar() { super.setupActionBar(); ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); } }
UTF-8
Java
1,410
java
SceneListActivity.java
Java
[]
null
[]
package com.wilson.tasker.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import com.wilson.tasker.R; public class SceneListActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_content); setupActionBar(); if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .add(R.id.content, SceneListFragment.newInstance(), "scene_list") .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_new_scene: ((SceneListFragment) getSupportFragmentManager() .findFragmentByTag("scene_list")).createScene(); return true; case R.id.action_view_timeline: Intent intent = new Intent(this, TimelineActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void setupActionBar() { super.setupActionBar(); ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); } }
1,410
0.741844
0.741135
57
23.736841
19.728443
70
false
false
0
0
0
0
0
0
2.087719
false
false
2
0bba914221ae1ff8afc6bb73a4ad7d852f2268e2
16,776,142,279,482
25721155a3bff652cd02dbb8f2e9cce4da7682cf
/src/test/java/mohttp/TestAsync.java
d6848731f40196e0211678171b28bb72c93dad28
[ "MIT" ]
permissive
xcr1234/mohttp
https://github.com/xcr1234/mohttp
63886242937d9a7412790df2787c0c0d816ea1de
1b12935def1026c9503b838ca40474854bbcaec7
refs/heads/master
2021-01-17T16:58:18.217000
2016-11-17T08:54:36
2016-11-17T08:54:36
70,062,887
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mohttp; import com.mo.mohttp.Http; import com.mo.mohttp.Request; import com.mo.mohttp.Response; import com.mo.mohttp.async.HttpCallback; import com.mo.mohttp.constant.Agents; import com.mo.mohttp.constant.Headers; import java.io.IOException; import java.util.concurrent.Future; public class TestAsync { public static void main(String[] args) { Request request = Http.GET("http://apis.baidu.com/heweather/weather/free") .header(Headers.host, "apis.baidu.com") .header("apikey", "5eca5cdb5c9b5f390fb24f7f2e3f0148").agent(Agents.Chrome) .param("city=北京"); final long t = System.currentTimeMillis(); Future<Response> future = request.execute(new HttpCallback() { @Override public void complete(Response response) throws IOException { System.out.println(response.string()); long time = System.currentTimeMillis() - t; System.out.println("request cost "+time+" ms."); } @Override public void failed(Throwable e) { e.printStackTrace(); } @Override public void cancelled() { System.out.println("cancelled!"); } }); Http.getExecutorService().shutdown(); //关闭线程池资源 } }
UTF-8
Java
1,422
java
TestAsync.java
Java
[ { "context": "s.baidu.com\")\r\n .header(\"apikey\", \"5eca5cdb5c9b5f390fb24f7f2e3f0148\").agent(Agents.Chrome)\r\n .param(\"c", "end": 583, "score": 0.9997238516807556, "start": 551, "tag": "KEY", "value": "5eca5cdb5c9b5f390fb24f7f2e3f0148" } ]
null
[]
package mohttp; import com.mo.mohttp.Http; import com.mo.mohttp.Request; import com.mo.mohttp.Response; import com.mo.mohttp.async.HttpCallback; import com.mo.mohttp.constant.Agents; import com.mo.mohttp.constant.Headers; import java.io.IOException; import java.util.concurrent.Future; public class TestAsync { public static void main(String[] args) { Request request = Http.GET("http://apis.baidu.com/heweather/weather/free") .header(Headers.host, "apis.baidu.com") .header("apikey", "<KEY>").agent(Agents.Chrome) .param("city=北京"); final long t = System.currentTimeMillis(); Future<Response> future = request.execute(new HttpCallback() { @Override public void complete(Response response) throws IOException { System.out.println(response.string()); long time = System.currentTimeMillis() - t; System.out.println("request cost "+time+" ms."); } @Override public void failed(Throwable e) { e.printStackTrace(); } @Override public void cancelled() { System.out.println("cancelled!"); } }); Http.getExecutorService().shutdown(); //关闭线程池资源 } }
1,395
0.581197
0.569088
44
29.90909
24.465019
90
false
false
0
0
0
0
0
0
0.454545
false
false
2
19b350ea6cb2a6a80a0fc114280c33cc5b12c359
11,587,821,774,519
b64b2edcec31fefa032de5809938982ee68c1968
/app/src/main/java/allpointech/touchall/network/http/TNHttpMultiPartTaskEx.java
a121ddc221f7999d4602bae010d092deab49daa4
[]
no_license
jasemabeed114/TouchAll
https://github.com/jasemabeed114/TouchAll
3e3305cf875a479fc895cef0095ad862672f7754
7632be028b3514785d1424d452dddaaca4b768ab
refs/heads/master
2022-11-12T05:03:34.010000
2020-06-24T01:29:34
2020-06-24T01:29:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package allpointech.touchall.network.http; import android.app.Dialog; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.util.Log; import android.widget.Toast; import com.tuna.ui.fragment.BaseDialogFragment; import com.tuna.utils.SLog; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import allpointech.touchall.BuildConfig; import allpointech.touchall.dialog.MsgSingleDialog; import allpointech.touchall.dialog.ProgressDialog; import allpointech.touchall.network.http.exception.ParsingException; import allpointech.touchall.network.http.resource.BaseHttpResource; import allpointech.touchall.network.http.resource.ResBaseHttp; import allpointech.touchall.network.http.resource.ResourceError; import allpointech.touchall.network.http.utils.HttpPopupManager; public class TNHttpMultiPartTaskEx extends AsyncTask<BaseHttpResource, Void, BaseHttpResource[]> implements HttpPopupManager.PopupDialog.OnResultListener { private static final String TAG = "HttpLog"; private ProgressDialog mProgress; private Context mContext; private FragmentManager mFm; private static boolean debug = BuildConfig.DEBUG; private boolean isDialogEnable = true; private boolean isTransparent = false; // multi part //private String boundary; private static final String LINE_FEED = "\r\n"; private HttpURLConnection conn; private String charset; private OutputStream outputStream; private PrintWriter writer; // multi part private long mTimeGap = 0; public void setOnHttpResultListener(onHttpNetResultListener listener) { mListener = listener; } private onHttpNetResultListener mListener; public interface onHttpNetResultListener { public void onHttpNetSuccessEvent(BaseHttpResource[] o); // debug public void onHttpDebugEvent(String debug_msg); // debug public void onHttpNetFailEvent(int errorCode, String errorMsg); } /////////////////////////////////////////////////////////////////////////////////////////////// public void setOnHttpFailResultListener(onHttpNetFailResultListener listener) { mFailListener = listener; } private onHttpNetFailResultListener mFailListener; public interface onHttpNetFailResultListener { public void onHttpNetFailResultListener(BaseHttpResource resource); } /////////////////////////////////////////////////////////////////////////////////////////////// public TNHttpMultiPartTaskEx(Context c, FragmentManager fm) { super(); this.mContext = c; this.mFm = fm; } @Override protected void onPreExecute() { mTimeGap = System.currentTimeMillis(); // try { // mProgress = new ProgressDialog(); // if (isDialogEnable) { // try { // mProgress.show(mFm, "dialog_progress"); // if (isTransparent) // mProgress.setTransparent(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // } catch (Exception e) { // e.printStackTrace(); // } super.onPreExecute(); } public void setDialogEnabled(boolean isEnable) { isDialogEnable = isEnable; } public void setTransparent(boolean isEnable) { isTransparent = isEnable; } @Override protected void onPostExecute(final BaseHttpResource[] result) { super.onPostExecute(result); // if (isDialogEnable) { // try { // mProgress.dismiss(); // } catch (Exception e) { // e.printStackTrace(); // } // } boolean successFlag = true; for (int i = 0; i < result.length; i++) { int return_code = ResourceError.ERROR; String return_msg = null; if (result[i].mErrorCode == HttpURLConnection.HTTP_OK) { try { JSONObject res_obj = (JSONObject) result[i].getParseData(); if (res_obj == null) { SLog.LogE("Resource Name : '" + result[i].getTargetName() + "' ------ " + "통신중 응답을 정상적으로 받지 못하였음!"); successFlag = false; continue; } SLog.LogW("##" + res_obj.toString()); if (!res_obj.isNull(ResBaseHttp.RETURNCODE)) { String returnStr = res_obj.getString(ResBaseHttp.RETURNCODE); String[] resStr = returnStr.split("_"); try { //return_code = Integer.parseInt(resStr[0]); return_code = Boolean.parseBoolean(resStr[0]) ? ResourceError.SUCCESS : ResourceError.ERROR; } catch (NumberFormatException nfe) { return_code = ResourceError.ERROR; } } if (!res_obj.isNull(ResBaseHttp.RETURNMSG)) { return_msg = res_obj.getString(ResBaseHttp.RETURNMSG); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else //if (result[i].mErrorCode == ResourceError.ERR_NOT_CONNECTED) { return_code = ResourceError.ERROR;//result[i].mErrorCode; //if (result[i].getParseData() != null) { try { JSONObject res_obj = (JSONObject) result[i].getParseData(); if (res_obj == null) { SLog.LogE("Resource Name : '" + result[i].getTargetName() + "' ------ " + "통신중 응답을 정상적으로 받지 못하였음!"); successFlag = false; continue; } SLog.LogW("##" + res_obj.toString()); if (!res_obj.isNull(ResBaseHttp.RETURNMSG)) { return_msg = res_obj.getString(ResBaseHttp.RETURNMSG); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } switch (return_code) { case ResourceError.SUCCESS: // 성공 break; case ResourceError.ERROR: successFlag = false; // final BaseHttpResource res = result[i]; // Bundle b = new Bundle(); // b.putString("dialog_msg", return_msg); // // if (isTransparent == false) { // MsgSingleDialog dialog = new MsgSingleDialog(); // dialog.setArguments(b); // dialog.setOnResultListener(new BaseDialogFragment.OnResultListener() { // @Override // public void onDialogResult(Object... objects) { // if (mFailListener != null) { // mFailListener.onHttpNetFailResultListener(res); // } // } // }); // dialog.show(mFm, "dialog"); // } if (mListener != null) { mListener.onHttpNetFailEvent(return_code, return_msg); } break; default: successFlag = false; // // String message = ResourceError.getErrorMsg(return_code); // if (message != null) { // Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show(); // } else { // // invalid error // Toast.makeText(mContext, "알 수 없는 오류입니다.", Toast.LENGTH_SHORT).show(); // } if (mListener != null) { mListener.onHttpNetFailEvent(return_code, return_msg); } break; } } if (successFlag) { if (mListener != null) { mListener.onHttpNetSuccessEvent(result); } } mTimeGap = System.currentTimeMillis() - mTimeGap; SLog.LogD("Time Gap : " + mTimeGap + "ms"); } @Override public void onDialogResult(Dialog dialog, String... results) { HttpPopupManager.PopupDialog popup = (HttpPopupManager.PopupDialog) dialog; if (mListener != null) mListener.onHttpNetFailEvent(popup.nErrorCode, null); if (isDialogEnable) dialog.dismiss(); } @Override protected BaseHttpResource[] doInBackground(BaseHttpResource... params) { BaseHttpResource[] retVal = new BaseHttpResource[params.length]; if (debug) Log.d(TAG, "params length " + params.length); for (int i = 0; i < params.length; i++) { BaseHttpResource param = params[i]; if (!isOnline()) { param.mErrorCode = ResourceError.ERR_NOT_CONNECTED; return new BaseHttpResource[]{param}; } param = multipost(param); retVal[i] = param; } return retVal; } public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } private BaseHttpResource multipost(BaseHttpResource param) { // creates a unique boundary based on time stamp //boundary = "===" + System.currentTimeMillis() + "==="; charset = HttpInfo.UTF8; try { String szUrl = param.getURL(); if (param.getType() == HttpInfo.GET) { String getSubUrl = requestGetData(param); if (getSubUrl.length() > 0) { szUrl += getSubUrl; } } else if (param.getType() == HttpInfo.GET_PARAM){ String getParams = requestGetParam(param); if (getParams.length() > 0) szUrl += getParams; } // SJH ssl >>>>>>>>>>>>>>>>>>>> SSLConnect ssl = new SSLConnect(); ssl.postHttps(szUrl, 1000, 1000); // SJH >>>>>>>>>>>>>>>>>>>> URL url = new URL(szUrl); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(HttpInfo.TIME_OUT); conn.setConnectTimeout(HttpInfo.TIME_OUT); if (param.getType() == HttpInfo.GET) { conn.setRequestMethod(param.getType()); String token = param.getToken(); if (token != null && token.length() > 0) conn.addRequestProperty("Authorization", token); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else if (param.getType() == HttpInfo.GET_TEXT) { conn.setRequestMethod(HttpInfo.GET); String token = param.getToken(); if (token != null && token.length() > 0) conn.addRequestProperty("Authorization", token); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else if (param.getType() == HttpInfo.GET_PARAM) { conn.setRequestMethod(HttpInfo.GET); String token = param.getToken(); if (token != null && token.length() > 0) conn.addRequestProperty("Authorization", token); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else if (param.getType() == HttpInfo.JSON){ conn.setRequestMethod(HttpInfo.POST); conn.setUseCaches(false); conn.setDoOutput(true); // indicates POST method conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", HttpInfo.Header.USER_AGENT); outputStream = conn.getOutputStream(); StringWriter sw = new StringWriter(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); // param에서 multi data를 조회 requestMultiPartJson(param); } else if (param.getType() == HttpInfo.PUT){ conn.setRequestMethod(param.getType()); String token = param.getToken(); if (token != null && token.length() > 0) conn.addRequestProperty("Authorization", token); conn.setUseCaches(false); conn.setDoOutput(true); // indicates POST method conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", HttpInfo.Header.USER_AGENT); outputStream = conn.getOutputStream(); StringWriter sw = new StringWriter(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); // param에서 multi data를 조회 requestMultiPartJson(param); } else { conn.setRequestMethod(param.getType()); conn.setUseCaches(false); conn.setDoOutput(true); // indicates POST method conn.setDoInput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;"); conn.setRequestProperty("User-Agent", HttpInfo.Header.USER_AGENT); //conn.setRequestProperty("Test", "P.R.T"); outputStream = conn.getOutputStream(); StringWriter sw = new StringWriter(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); // param에서 multi data를 조회 requestMultiPartData(param); } param.mErrorCode = conn.getResponseCode(); if (debug) SLog.LogD("> err : " + param.mErrorCode + "- 200이면 성공한거임."); if (param.mErrorCode == HttpURLConnection.HTTP_OK) { InputStream is = null; String response = null; JSONObject responseJSON = null; ByteArrayOutputStream baos = null; mListener.onHttpDebugEvent("> 응답 성공!!"); is = conn.getInputStream(); baos = new ByteArrayOutputStream(); //byte[] byteBuffer = new byte[1024]; byte[] byteBuffer = new byte[4096]; byte[] byteData = null; int nLength = 0; while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { baos.write(byteBuffer, 0, nLength); } byteData = baos.toByteArray(); response = new String(byteData, HttpInfo.UTF8); if (debug) SLog.LogW("> 응답 변환 전 데이터 : " + param.getTargetName() + "::" + response); // mListener.onHttpDebugEvent("> 응답 변환 전 데이터 : " + response); if (param.getType() == HttpInfo.GET_TEXT) { responseJSON = new JSONObject(); try { //responseJSON.put(ResBaseHttp.RETURNCODE, ResourceError.ERR_NOT_CONNECTED); responseJSON.put("result", "true"); responseJSON.put("message", response); param.parsorRes(responseJSON); } catch (JSONException e1) { e1.printStackTrace(); } } else { responseJSON = new JSONObject(response); param.parsorRes(responseJSON); } if (debug) SLog.LogW("> 응답 데이터 : " + responseJSON.toString()); // mListener.onHttpDebugEvent("> 응답 데이터 : " + responseJSON.toString()); } else { //debug InputStream is = null; String response = null; JSONObject responseJSON = null; ByteArrayOutputStream baos = null; mListener.onHttpDebugEvent("> 응답 에러!!"); is = conn.getErrorStream(); baos = new ByteArrayOutputStream(); //byte[] byteBuffer = new byte[1024]; byte[] byteBuffer = new byte[4096]; byte[] byteData = null; int nLength = 0; while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { baos.write(byteBuffer, 0, nLength); } byteData = baos.toByteArray(); response = new String(byteData, HttpInfo.UTF8); if (debug) SLog.LogW("> 응답 변환 전 데이터 : " + param.getTargetName() + "::" + response); // mListener.onHttpDebugEvent("> 응답 변환 전 데이터 : " + response); responseJSON = new JSONObject(response); param.parsorRes(responseJSON); if (debug) SLog.LogW("> 응답 에러 : " + param.mErrorCode); // mListener.onHttpDebugEvent("> 응답 에러 : "+param.mErrorCode); } conn.disconnect(); } catch (ConnectException e) { JSONObject responseJSON = new JSONObject(); param.mErrorCode = ResourceError.ERR_NOT_CONNECTED; try { responseJSON.put(ResBaseHttp.RETURNCODE, ResourceError.ERR_NOT_CONNECTED); } catch (JSONException e1) { e1.printStackTrace(); } try { param.parsorRes(responseJSON); } catch (ParsingException e1) { e1.printStackTrace(); } } catch (Exception e) { Log.e(TAG, "multipart post error " + e + "(" + param.getURL() + ")"); } return param; } private void requestMultiPartData(BaseHttpResource param) { ArrayList<MultiPartData> multi_data = param.getMultipartData(); if (debug) SLog.LogI("data size:" + multi_data.size()); JSONObject jsonParam = new JSONObject(); for (int i = 0; i < multi_data.size(); i++) { MultiPartData mp = multi_data.get(i); switch (mp.type) { case MultiPartData.HEADER: // header addHeaderField(mp.name, mp.value); break; case MultiPartData.FORM: // form addFormField(mp.name, mp.value); break; case MultiPartData.FORM_ONCE: // form addFormFieldOnce(mp.name, mp.value); break; case MultiPartData.FILE: // file try { addFilePart(mp.name, new File(mp.value)); } catch (IOException e) { e.printStackTrace(); } break; } if (debug) SLog.LogI("type:" + mp.type + ", key:" + mp.name + ", value:" + mp.value); } // multi part end try { writer.write(jsonParam.toString()); finish(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void requestMultiPartJson(BaseHttpResource param) { ArrayList<MultiPartData> multi_data = param.getMultipartData(); if (debug) SLog.LogI("data size:" + multi_data.size()); JSONObject jsonParam = new JSONObject(); for (int i = 0; i < multi_data.size(); i++) { MultiPartData mp = multi_data.get(i); switch (mp.type) { case MultiPartData.FORM: // form //addFormField(mp.name, mp.value); try { jsonParam.put(mp.name, mp.value); } catch (JSONException e) { e.printStackTrace(); } break; } if (debug) SLog.LogI("type:" + mp.type + ", key:" + mp.name + ", value:" + mp.value); } // multi part end try { writer.write(jsonParam.toString()); finish(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String requestGetData(BaseHttpResource param) { String getParamData = ""; ArrayList<String> get_datas = param.getGetUrlData(); if (debug) SLog.LogI("get data size:" + get_datas.size()); for (int i = 0; i < get_datas.size(); i++) { String sub_url = get_datas.get(i); getParamData += sub_url; if (debug) SLog.LogI("sub url:" + sub_url); } return getParamData; } private String requestGetParam(BaseHttpResource param) { String getParamData = ""; ArrayList<MultiPartData> multi_data = param.getMultipartData(); if (multi_data.size() > 0) getParamData += "?"; for (int i = 0; i < multi_data.size(); i++) { MultiPartData mp = multi_data.get(i); switch (mp.type) { case MultiPartData.FORM: // form //addFormField(mp.name, mp.value); getParamData += mp.name; getParamData += "="; getParamData += mp.value; if (i < multi_data.size() - 1) getParamData += "&"; break; } if (debug) SLog.LogI("type:" + mp.type + ", key:" + mp.name + ", value:" + mp.value); } return getParamData; } /** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(String name, String value) { //writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); } public void addFormFieldOnce(String name, String value) { //writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED); writer.append(LINE_FEED); writer.append(value); writer.flush(); } /** * Adds a upload file section to the request * * @param fieldName name attribute in <input type="file" name="..." /> * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); //writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED); String file_type = URLConnection.guessContentTypeFromName(fileName); writer.append("Content-Type: " + file_type.replaceAll("jpeg", "jpg")).append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); SLog.LogV("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\""); SLog.LogV("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)); SLog.LogV("Content-Transfer-Encoding: binary"); writer.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } /** * Adds a header field to the request. * * @param name - name of the header field * @param value - value of the header field */ public void addHeaderField(String name, String value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); } /** * Completes the request and receives response from the server. * * @return a list of Strings as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public void finish() throws IOException { writer.append(LINE_FEED).flush(); //writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); } // public List<String> finish() throws IOException { // List<String> response = new ArrayList<String>(); // // writer.append(LINE_FEED).flush(); // writer.append("--" + boundary + "--").append(LINE_FEED); // writer.close(); // // // checks server's status code first // int status = conn.getResponseCode(); // if (status == HttpURLConnection.HTTP_OK) { // BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); // String line = null; // while ((line = reader.readLine()) != null) { // response.add(line); // } // reader.close(); // conn.disconnect(); // } else { // throw new IOException("Server returned non-OK status: " + status); // } // // return response; // } private String map_index = null; public void setStorePostion(String index) { map_index = index; } public String getStorePostion() { return map_index; } }
UTF-8
Java
27,547
java
TNHttpMultiPartTaskEx.java
Java
[]
null
[]
package allpointech.touchall.network.http; import android.app.Dialog; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.util.Log; import android.widget.Toast; import com.tuna.ui.fragment.BaseDialogFragment; import com.tuna.utils.SLog; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import allpointech.touchall.BuildConfig; import allpointech.touchall.dialog.MsgSingleDialog; import allpointech.touchall.dialog.ProgressDialog; import allpointech.touchall.network.http.exception.ParsingException; import allpointech.touchall.network.http.resource.BaseHttpResource; import allpointech.touchall.network.http.resource.ResBaseHttp; import allpointech.touchall.network.http.resource.ResourceError; import allpointech.touchall.network.http.utils.HttpPopupManager; public class TNHttpMultiPartTaskEx extends AsyncTask<BaseHttpResource, Void, BaseHttpResource[]> implements HttpPopupManager.PopupDialog.OnResultListener { private static final String TAG = "HttpLog"; private ProgressDialog mProgress; private Context mContext; private FragmentManager mFm; private static boolean debug = BuildConfig.DEBUG; private boolean isDialogEnable = true; private boolean isTransparent = false; // multi part //private String boundary; private static final String LINE_FEED = "\r\n"; private HttpURLConnection conn; private String charset; private OutputStream outputStream; private PrintWriter writer; // multi part private long mTimeGap = 0; public void setOnHttpResultListener(onHttpNetResultListener listener) { mListener = listener; } private onHttpNetResultListener mListener; public interface onHttpNetResultListener { public void onHttpNetSuccessEvent(BaseHttpResource[] o); // debug public void onHttpDebugEvent(String debug_msg); // debug public void onHttpNetFailEvent(int errorCode, String errorMsg); } /////////////////////////////////////////////////////////////////////////////////////////////// public void setOnHttpFailResultListener(onHttpNetFailResultListener listener) { mFailListener = listener; } private onHttpNetFailResultListener mFailListener; public interface onHttpNetFailResultListener { public void onHttpNetFailResultListener(BaseHttpResource resource); } /////////////////////////////////////////////////////////////////////////////////////////////// public TNHttpMultiPartTaskEx(Context c, FragmentManager fm) { super(); this.mContext = c; this.mFm = fm; } @Override protected void onPreExecute() { mTimeGap = System.currentTimeMillis(); // try { // mProgress = new ProgressDialog(); // if (isDialogEnable) { // try { // mProgress.show(mFm, "dialog_progress"); // if (isTransparent) // mProgress.setTransparent(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // } catch (Exception e) { // e.printStackTrace(); // } super.onPreExecute(); } public void setDialogEnabled(boolean isEnable) { isDialogEnable = isEnable; } public void setTransparent(boolean isEnable) { isTransparent = isEnable; } @Override protected void onPostExecute(final BaseHttpResource[] result) { super.onPostExecute(result); // if (isDialogEnable) { // try { // mProgress.dismiss(); // } catch (Exception e) { // e.printStackTrace(); // } // } boolean successFlag = true; for (int i = 0; i < result.length; i++) { int return_code = ResourceError.ERROR; String return_msg = null; if (result[i].mErrorCode == HttpURLConnection.HTTP_OK) { try { JSONObject res_obj = (JSONObject) result[i].getParseData(); if (res_obj == null) { SLog.LogE("Resource Name : '" + result[i].getTargetName() + "' ------ " + "통신중 응답을 정상적으로 받지 못하였음!"); successFlag = false; continue; } SLog.LogW("##" + res_obj.toString()); if (!res_obj.isNull(ResBaseHttp.RETURNCODE)) { String returnStr = res_obj.getString(ResBaseHttp.RETURNCODE); String[] resStr = returnStr.split("_"); try { //return_code = Integer.parseInt(resStr[0]); return_code = Boolean.parseBoolean(resStr[0]) ? ResourceError.SUCCESS : ResourceError.ERROR; } catch (NumberFormatException nfe) { return_code = ResourceError.ERROR; } } if (!res_obj.isNull(ResBaseHttp.RETURNMSG)) { return_msg = res_obj.getString(ResBaseHttp.RETURNMSG); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else //if (result[i].mErrorCode == ResourceError.ERR_NOT_CONNECTED) { return_code = ResourceError.ERROR;//result[i].mErrorCode; //if (result[i].getParseData() != null) { try { JSONObject res_obj = (JSONObject) result[i].getParseData(); if (res_obj == null) { SLog.LogE("Resource Name : '" + result[i].getTargetName() + "' ------ " + "통신중 응답을 정상적으로 받지 못하였음!"); successFlag = false; continue; } SLog.LogW("##" + res_obj.toString()); if (!res_obj.isNull(ResBaseHttp.RETURNMSG)) { return_msg = res_obj.getString(ResBaseHttp.RETURNMSG); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } switch (return_code) { case ResourceError.SUCCESS: // 성공 break; case ResourceError.ERROR: successFlag = false; // final BaseHttpResource res = result[i]; // Bundle b = new Bundle(); // b.putString("dialog_msg", return_msg); // // if (isTransparent == false) { // MsgSingleDialog dialog = new MsgSingleDialog(); // dialog.setArguments(b); // dialog.setOnResultListener(new BaseDialogFragment.OnResultListener() { // @Override // public void onDialogResult(Object... objects) { // if (mFailListener != null) { // mFailListener.onHttpNetFailResultListener(res); // } // } // }); // dialog.show(mFm, "dialog"); // } if (mListener != null) { mListener.onHttpNetFailEvent(return_code, return_msg); } break; default: successFlag = false; // // String message = ResourceError.getErrorMsg(return_code); // if (message != null) { // Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show(); // } else { // // invalid error // Toast.makeText(mContext, "알 수 없는 오류입니다.", Toast.LENGTH_SHORT).show(); // } if (mListener != null) { mListener.onHttpNetFailEvent(return_code, return_msg); } break; } } if (successFlag) { if (mListener != null) { mListener.onHttpNetSuccessEvent(result); } } mTimeGap = System.currentTimeMillis() - mTimeGap; SLog.LogD("Time Gap : " + mTimeGap + "ms"); } @Override public void onDialogResult(Dialog dialog, String... results) { HttpPopupManager.PopupDialog popup = (HttpPopupManager.PopupDialog) dialog; if (mListener != null) mListener.onHttpNetFailEvent(popup.nErrorCode, null); if (isDialogEnable) dialog.dismiss(); } @Override protected BaseHttpResource[] doInBackground(BaseHttpResource... params) { BaseHttpResource[] retVal = new BaseHttpResource[params.length]; if (debug) Log.d(TAG, "params length " + params.length); for (int i = 0; i < params.length; i++) { BaseHttpResource param = params[i]; if (!isOnline()) { param.mErrorCode = ResourceError.ERR_NOT_CONNECTED; return new BaseHttpResource[]{param}; } param = multipost(param); retVal[i] = param; } return retVal; } public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } private BaseHttpResource multipost(BaseHttpResource param) { // creates a unique boundary based on time stamp //boundary = "===" + System.currentTimeMillis() + "==="; charset = HttpInfo.UTF8; try { String szUrl = param.getURL(); if (param.getType() == HttpInfo.GET) { String getSubUrl = requestGetData(param); if (getSubUrl.length() > 0) { szUrl += getSubUrl; } } else if (param.getType() == HttpInfo.GET_PARAM){ String getParams = requestGetParam(param); if (getParams.length() > 0) szUrl += getParams; } // SJH ssl >>>>>>>>>>>>>>>>>>>> SSLConnect ssl = new SSLConnect(); ssl.postHttps(szUrl, 1000, 1000); // SJH >>>>>>>>>>>>>>>>>>>> URL url = new URL(szUrl); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(HttpInfo.TIME_OUT); conn.setConnectTimeout(HttpInfo.TIME_OUT); if (param.getType() == HttpInfo.GET) { conn.setRequestMethod(param.getType()); String token = param.getToken(); if (token != null && token.length() > 0) conn.addRequestProperty("Authorization", token); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else if (param.getType() == HttpInfo.GET_TEXT) { conn.setRequestMethod(HttpInfo.GET); String token = param.getToken(); if (token != null && token.length() > 0) conn.addRequestProperty("Authorization", token); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else if (param.getType() == HttpInfo.GET_PARAM) { conn.setRequestMethod(HttpInfo.GET); String token = param.getToken(); if (token != null && token.length() > 0) conn.addRequestProperty("Authorization", token); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else if (param.getType() == HttpInfo.JSON){ conn.setRequestMethod(HttpInfo.POST); conn.setUseCaches(false); conn.setDoOutput(true); // indicates POST method conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", HttpInfo.Header.USER_AGENT); outputStream = conn.getOutputStream(); StringWriter sw = new StringWriter(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); // param에서 multi data를 조회 requestMultiPartJson(param); } else if (param.getType() == HttpInfo.PUT){ conn.setRequestMethod(param.getType()); String token = param.getToken(); if (token != null && token.length() > 0) conn.addRequestProperty("Authorization", token); conn.setUseCaches(false); conn.setDoOutput(true); // indicates POST method conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", HttpInfo.Header.USER_AGENT); outputStream = conn.getOutputStream(); StringWriter sw = new StringWriter(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); // param에서 multi data를 조회 requestMultiPartJson(param); } else { conn.setRequestMethod(param.getType()); conn.setUseCaches(false); conn.setDoOutput(true); // indicates POST method conn.setDoInput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;"); conn.setRequestProperty("User-Agent", HttpInfo.Header.USER_AGENT); //conn.setRequestProperty("Test", "P.R.T"); outputStream = conn.getOutputStream(); StringWriter sw = new StringWriter(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); // param에서 multi data를 조회 requestMultiPartData(param); } param.mErrorCode = conn.getResponseCode(); if (debug) SLog.LogD("> err : " + param.mErrorCode + "- 200이면 성공한거임."); if (param.mErrorCode == HttpURLConnection.HTTP_OK) { InputStream is = null; String response = null; JSONObject responseJSON = null; ByteArrayOutputStream baos = null; mListener.onHttpDebugEvent("> 응답 성공!!"); is = conn.getInputStream(); baos = new ByteArrayOutputStream(); //byte[] byteBuffer = new byte[1024]; byte[] byteBuffer = new byte[4096]; byte[] byteData = null; int nLength = 0; while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { baos.write(byteBuffer, 0, nLength); } byteData = baos.toByteArray(); response = new String(byteData, HttpInfo.UTF8); if (debug) SLog.LogW("> 응답 변환 전 데이터 : " + param.getTargetName() + "::" + response); // mListener.onHttpDebugEvent("> 응답 변환 전 데이터 : " + response); if (param.getType() == HttpInfo.GET_TEXT) { responseJSON = new JSONObject(); try { //responseJSON.put(ResBaseHttp.RETURNCODE, ResourceError.ERR_NOT_CONNECTED); responseJSON.put("result", "true"); responseJSON.put("message", response); param.parsorRes(responseJSON); } catch (JSONException e1) { e1.printStackTrace(); } } else { responseJSON = new JSONObject(response); param.parsorRes(responseJSON); } if (debug) SLog.LogW("> 응답 데이터 : " + responseJSON.toString()); // mListener.onHttpDebugEvent("> 응답 데이터 : " + responseJSON.toString()); } else { //debug InputStream is = null; String response = null; JSONObject responseJSON = null; ByteArrayOutputStream baos = null; mListener.onHttpDebugEvent("> 응답 에러!!"); is = conn.getErrorStream(); baos = new ByteArrayOutputStream(); //byte[] byteBuffer = new byte[1024]; byte[] byteBuffer = new byte[4096]; byte[] byteData = null; int nLength = 0; while ((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { baos.write(byteBuffer, 0, nLength); } byteData = baos.toByteArray(); response = new String(byteData, HttpInfo.UTF8); if (debug) SLog.LogW("> 응답 변환 전 데이터 : " + param.getTargetName() + "::" + response); // mListener.onHttpDebugEvent("> 응답 변환 전 데이터 : " + response); responseJSON = new JSONObject(response); param.parsorRes(responseJSON); if (debug) SLog.LogW("> 응답 에러 : " + param.mErrorCode); // mListener.onHttpDebugEvent("> 응답 에러 : "+param.mErrorCode); } conn.disconnect(); } catch (ConnectException e) { JSONObject responseJSON = new JSONObject(); param.mErrorCode = ResourceError.ERR_NOT_CONNECTED; try { responseJSON.put(ResBaseHttp.RETURNCODE, ResourceError.ERR_NOT_CONNECTED); } catch (JSONException e1) { e1.printStackTrace(); } try { param.parsorRes(responseJSON); } catch (ParsingException e1) { e1.printStackTrace(); } } catch (Exception e) { Log.e(TAG, "multipart post error " + e + "(" + param.getURL() + ")"); } return param; } private void requestMultiPartData(BaseHttpResource param) { ArrayList<MultiPartData> multi_data = param.getMultipartData(); if (debug) SLog.LogI("data size:" + multi_data.size()); JSONObject jsonParam = new JSONObject(); for (int i = 0; i < multi_data.size(); i++) { MultiPartData mp = multi_data.get(i); switch (mp.type) { case MultiPartData.HEADER: // header addHeaderField(mp.name, mp.value); break; case MultiPartData.FORM: // form addFormField(mp.name, mp.value); break; case MultiPartData.FORM_ONCE: // form addFormFieldOnce(mp.name, mp.value); break; case MultiPartData.FILE: // file try { addFilePart(mp.name, new File(mp.value)); } catch (IOException e) { e.printStackTrace(); } break; } if (debug) SLog.LogI("type:" + mp.type + ", key:" + mp.name + ", value:" + mp.value); } // multi part end try { writer.write(jsonParam.toString()); finish(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void requestMultiPartJson(BaseHttpResource param) { ArrayList<MultiPartData> multi_data = param.getMultipartData(); if (debug) SLog.LogI("data size:" + multi_data.size()); JSONObject jsonParam = new JSONObject(); for (int i = 0; i < multi_data.size(); i++) { MultiPartData mp = multi_data.get(i); switch (mp.type) { case MultiPartData.FORM: // form //addFormField(mp.name, mp.value); try { jsonParam.put(mp.name, mp.value); } catch (JSONException e) { e.printStackTrace(); } break; } if (debug) SLog.LogI("type:" + mp.type + ", key:" + mp.name + ", value:" + mp.value); } // multi part end try { writer.write(jsonParam.toString()); finish(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String requestGetData(BaseHttpResource param) { String getParamData = ""; ArrayList<String> get_datas = param.getGetUrlData(); if (debug) SLog.LogI("get data size:" + get_datas.size()); for (int i = 0; i < get_datas.size(); i++) { String sub_url = get_datas.get(i); getParamData += sub_url; if (debug) SLog.LogI("sub url:" + sub_url); } return getParamData; } private String requestGetParam(BaseHttpResource param) { String getParamData = ""; ArrayList<MultiPartData> multi_data = param.getMultipartData(); if (multi_data.size() > 0) getParamData += "?"; for (int i = 0; i < multi_data.size(); i++) { MultiPartData mp = multi_data.get(i); switch (mp.type) { case MultiPartData.FORM: // form //addFormField(mp.name, mp.value); getParamData += mp.name; getParamData += "="; getParamData += mp.value; if (i < multi_data.size() - 1) getParamData += "&"; break; } if (debug) SLog.LogI("type:" + mp.type + ", key:" + mp.name + ", value:" + mp.value); } return getParamData; } /** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(String name, String value) { //writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); } public void addFormFieldOnce(String name, String value) { //writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED); writer.append(LINE_FEED); writer.append(value); writer.flush(); } /** * Adds a upload file section to the request * * @param fieldName name attribute in <input type="file" name="..." /> * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); //writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED); String file_type = URLConnection.guessContentTypeFromName(fileName); writer.append("Content-Type: " + file_type.replaceAll("jpeg", "jpg")).append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); SLog.LogV("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\""); SLog.LogV("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)); SLog.LogV("Content-Transfer-Encoding: binary"); writer.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } /** * Adds a header field to the request. * * @param name - name of the header field * @param value - value of the header field */ public void addHeaderField(String name, String value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); } /** * Completes the request and receives response from the server. * * @return a list of Strings as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public void finish() throws IOException { writer.append(LINE_FEED).flush(); //writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); } // public List<String> finish() throws IOException { // List<String> response = new ArrayList<String>(); // // writer.append(LINE_FEED).flush(); // writer.append("--" + boundary + "--").append(LINE_FEED); // writer.close(); // // // checks server's status code first // int status = conn.getResponseCode(); // if (status == HttpURLConnection.HTTP_OK) { // BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); // String line = null; // while ((line = reader.readLine()) != null) { // response.add(line); // } // reader.close(); // conn.disconnect(); // } else { // throw new IOException("Server returned non-OK status: " + status); // } // // return response; // } private String map_index = null; public void setStorePostion(String index) { map_index = index; } public String getStorePostion() { return map_index; } }
27,547
0.529032
0.526505
704
37.774147
26.786432
155
false
false
0
0
0
0
97
0.00707
0.650568
false
false
2
9a24640dff04cf09b67290d675c81ce3f6889f6b
27,693,949,189,344
32822175d2fb204f0b030ecefe96857e46c25609
/src/entity/yonetmenler.java
dfdbb275f5e77fc5fe58e0c423e7534fcdc1f378
[]
no_license
bunyamingoymen/Cinema_With_Postgresql
https://github.com/bunyamingoymen/Cinema_With_Postgresql
e13c3297aafac61d3efade594da9f5d8275925e6
3ba427b0254e043edde32f9e8a0d480177930789
refs/heads/master
2023-05-31T12:50:10.874000
2021-06-14T08:24:39
2021-06-14T08:24:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entity; public class yonetmenler { private int yonetmen_id; private String yonetmen_name; private String yonetmen_sur_name; private int film_sayisi; public yonetmenler(String yonetmen_name, String yonetmen_sur_name, int film_sayisi) { this.yonetmen_name = yonetmen_name; this.yonetmen_sur_name = yonetmen_sur_name; this.film_sayisi = film_sayisi; } public yonetmenler(int yonetmen_id, String yonetmen_name, String yonetmen_sur_name, int film_sayisi) { this.yonetmen_id = yonetmen_id; this.yonetmen_name = yonetmen_name; this.yonetmen_sur_name = yonetmen_sur_name; this.film_sayisi = film_sayisi; } public yonetmenler() { } public int getYonetmen_id() { return yonetmen_id; } public void setYonetmen_id(int yonetmen_id) { this.yonetmen_id = yonetmen_id; } public String getYonetmen_name() { return yonetmen_name; } public void setYonetmen_name(String yonetmen_name) { this.yonetmen_name = yonetmen_name; } public String getYonetmen_sur_name() { return yonetmen_sur_name; } public void setYonetmen_sur_name(String yonetmen_sur_name) { this.yonetmen_sur_name = yonetmen_sur_name; } public int getFilm_sayisi() { return film_sayisi; } public void setFilm_sayisi(int film_sayisi) { this.film_sayisi = film_sayisi; } }
UTF-8
Java
1,459
java
yonetmenler.java
Java
[]
null
[]
package entity; public class yonetmenler { private int yonetmen_id; private String yonetmen_name; private String yonetmen_sur_name; private int film_sayisi; public yonetmenler(String yonetmen_name, String yonetmen_sur_name, int film_sayisi) { this.yonetmen_name = yonetmen_name; this.yonetmen_sur_name = yonetmen_sur_name; this.film_sayisi = film_sayisi; } public yonetmenler(int yonetmen_id, String yonetmen_name, String yonetmen_sur_name, int film_sayisi) { this.yonetmen_id = yonetmen_id; this.yonetmen_name = yonetmen_name; this.yonetmen_sur_name = yonetmen_sur_name; this.film_sayisi = film_sayisi; } public yonetmenler() { } public int getYonetmen_id() { return yonetmen_id; } public void setYonetmen_id(int yonetmen_id) { this.yonetmen_id = yonetmen_id; } public String getYonetmen_name() { return yonetmen_name; } public void setYonetmen_name(String yonetmen_name) { this.yonetmen_name = yonetmen_name; } public String getYonetmen_sur_name() { return yonetmen_sur_name; } public void setYonetmen_sur_name(String yonetmen_sur_name) { this.yonetmen_sur_name = yonetmen_sur_name; } public int getFilm_sayisi() { return film_sayisi; } public void setFilm_sayisi(int film_sayisi) { this.film_sayisi = film_sayisi; } }
1,459
0.642906
0.642906
58
24.155172
23.837671
106
false
false
0
0
0
0
0
0
0.431034
false
false
2
4905c47fada9fa8f68900758e70c976279fcdf27
2,130,303,805,217
b91fd19e8f8f419931525dd7d47287a3f8369689
/src/test/java/io/github/fmachado091/search/LinearSearchTest.java
d1ba5b19497a8d2e944d9688703cf1bce19d47af
[ "MIT" ]
permissive
fmachado091/java-algorithms
https://github.com/fmachado091/java-algorithms
0638611f81ff1d5259b4795dd9fc28ca55cf1f17
40f44c73480470f50e833acb9fe0f08111e3ebc4
refs/heads/master
2020-06-03T06:57:13.167000
2020-05-10T04:25:21
2020-05-10T04:25:21
124,017,946
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.github.fmachado091.search; import org.junit.Assert; import org.junit.Test; public class LinearSearchTest { @Test public void whenTheListHasOneElementAndItIsTheTargetThenZeroIsReturned() { int[] list = { 3 }; final int target = 3; int result = LinearSearch.search(list, target); Assert.assertEquals(0, result); } @Test public void whenTheListHasOneElementAndItIsNotTheTargetThenNegativeOneIsReturned() { int[] list = { 3 }; final int target = 4; int result = LinearSearch.search(list, target); Assert.assertEquals(-1, result); } @Test public void whenTheListHasMultipleElementsAndTheTargetIsPresentOnceThenItsIndexIsReturned() { int[] list = { 3, 1, 4, 1, 5 }; final int target = 4; int result = LinearSearch.search(list, target); Assert.assertEquals(2, result); } @Test public void whenTheListHasMultipleElementsAndTheTargetIsPresentTwiceThenItsFirstAppearanceIndexIsReturned() { int[] list = { 3, 1, 4, 1, 5 }; final int target = 1; int result = LinearSearch.search(list, target); Assert.assertEquals(1, result); } @Test public void whenTheListHasMultipleElementsAndTheTargetIsNotPresentThenItsIndexIsReturned() { int[] list = { 3, 1, 4, 1, 5 }; final int target = 2; int result = LinearSearch.search(list, target); Assert.assertEquals(-1, result); } }
UTF-8
Java
1,502
java
LinearSearchTest.java
Java
[ { "context": "package io.github.fmachado091.search;\n\nimport org.junit.Assert;\nimport org.juni", "end": 29, "score": 0.9995994567871094, "start": 18, "tag": "USERNAME", "value": "fmachado091" } ]
null
[]
package io.github.fmachado091.search; import org.junit.Assert; import org.junit.Test; public class LinearSearchTest { @Test public void whenTheListHasOneElementAndItIsTheTargetThenZeroIsReturned() { int[] list = { 3 }; final int target = 3; int result = LinearSearch.search(list, target); Assert.assertEquals(0, result); } @Test public void whenTheListHasOneElementAndItIsNotTheTargetThenNegativeOneIsReturned() { int[] list = { 3 }; final int target = 4; int result = LinearSearch.search(list, target); Assert.assertEquals(-1, result); } @Test public void whenTheListHasMultipleElementsAndTheTargetIsPresentOnceThenItsIndexIsReturned() { int[] list = { 3, 1, 4, 1, 5 }; final int target = 4; int result = LinearSearch.search(list, target); Assert.assertEquals(2, result); } @Test public void whenTheListHasMultipleElementsAndTheTargetIsPresentTwiceThenItsFirstAppearanceIndexIsReturned() { int[] list = { 3, 1, 4, 1, 5 }; final int target = 1; int result = LinearSearch.search(list, target); Assert.assertEquals(1, result); } @Test public void whenTheListHasMultipleElementsAndTheTargetIsNotPresentThenItsIndexIsReturned() { int[] list = { 3, 1, 4, 1, 5 }; final int target = 2; int result = LinearSearch.search(list, target); Assert.assertEquals(-1, result); } }
1,502
0.6498
0.629827
57
25.350878
28.292019
113
false
false
0
0
0
0
93
0.209055
0.789474
false
false
2
60378b632d5092f029adcfea5ce59b684ef2f935
27,204,322,856,410
175727283a9d831794fbdf06f2e91536140e9f00
/src/test/java/com/casino/game/GameApplicationTests.java
75c33494911ae201aacf55e960f521dd40457abb
[]
no_license
Onks-dev/game
https://github.com/Onks-dev/game
6b2e802d4f4802d76aaed76a45fabfd33617a2f0
6126e867b617e03180ff9bc07e1d2cc07a03e272
refs/heads/master
2023-07-26T01:55:15.033000
2021-09-06T08:49:18
2021-09-06T08:49:18
403,550,310
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.casino.game; import com.casino.game.entity.Player; import com.casino.game.repository.CasinoRepository; import com.casino.game.service.CasinoService; import org.aspectj.lang.annotation.Before; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest class GameApplicationTests { @Autowired private CasinoService casinoService; @Autowired private CasinoRepository casinoRepo; @Before("") void before(){ } @Test void testGetPresentPlayer(){ Player player = new Player("Dineo", 50); casinoRepo.save(player); Player actual = casinoService.getPlayerBalance(1L, 1L); assertEquals(player.getUsername(), actual.getUsername()); } @Test void testWager(){ Player player = new Player("Onkabetse", 100); casinoRepo.save(player); casinoService.wager(100L, 2L, new BigDecimal(20)); Player actual = casinoService.getPlayerBalance(200L, 2L); assertEquals( "80.00" , actual.getBalance().toString()); } @Test void testWin(){ Player player = new Player("Tumi", 200); casinoRepo.save(player); casinoService.win(200L, 3L, new BigDecimal(20)); Player actual = casinoService.getPlayerBalance(200L, 3L); assertEquals( "220.00" , actual.getBalance().toString()); } //Extend tests }
UTF-8
Java
1,442
java
GameApplicationTests.java
Java
[ { "context": "GetPresentPlayer(){\n\t\tPlayer player = new Player(\"Dineo\", 50);\n\t\tcasinoRepo.save(player);\n\t\tPlayer actual", "end": 711, "score": 0.9974188208580017, "start": 706, "tag": "NAME", "value": "Dineo" }, { "context": "\n\tvoid testWager(){\n\t\tPlayer player = new ...
null
[]
package com.casino.game; import com.casino.game.entity.Player; import com.casino.game.repository.CasinoRepository; import com.casino.game.service.CasinoService; import org.aspectj.lang.annotation.Before; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest class GameApplicationTests { @Autowired private CasinoService casinoService; @Autowired private CasinoRepository casinoRepo; @Before("") void before(){ } @Test void testGetPresentPlayer(){ Player player = new Player("Dineo", 50); casinoRepo.save(player); Player actual = casinoService.getPlayerBalance(1L, 1L); assertEquals(player.getUsername(), actual.getUsername()); } @Test void testWager(){ Player player = new Player("Onkabetse", 100); casinoRepo.save(player); casinoService.wager(100L, 2L, new BigDecimal(20)); Player actual = casinoService.getPlayerBalance(200L, 2L); assertEquals( "80.00" , actual.getBalance().toString()); } @Test void testWin(){ Player player = new Player("Tumi", 200); casinoRepo.save(player); casinoService.win(200L, 3L, new BigDecimal(20)); Player actual = casinoService.getPlayerBalance(200L, 3L); assertEquals( "220.00" , actual.getBalance().toString()); } //Extend tests }
1,442
0.751734
0.724688
66
20.848484
22.110769
62
false
false
0
0
0
0
0
0
1.272727
false
false
2
626230fc68c4dae82a23e07be2575607e6b6c292
28,647,431,874,682
f867ff9a6134fc197f8a8c0f068aeb2155983f84
/src/game/Computer.java
33c157ff40f061a4402a824ae111f51bba28378c
[]
no_license
aditidatta/pattern-recog-RockPaperScissor
https://github.com/aditidatta/pattern-recog-RockPaperScissor
53d42d8e1977bbc34c3b4e899a76a99928a84167
6c5ea696ef51eb11713190ef0e92f77530e4ff14
refs/heads/master
2021-05-15T21:06:42.767000
2017-10-23T02:30:46
2017-10-23T02:30:46
107,907,380
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Random; public class Computer implements Serializable{ private Random randomGenerator; private HashMap<Pattern,Integer> map; public Computer(){ randomGenerator = new Random(); map = new HashMap<Pattern,Integer>(); } public Weapon getRandomWeapon() { Weapon[] weapons = Weapon.values(); int index = randomGenerator.nextInt(weapons.length); return weapons[index]; } public void storePattern(Pattern p) { int length = p.getPattern().length(); while(length>1) { Integer time = map.get(p); if (time == null) { map.put(p, 1); } else { map.put(p, time + 1); } String pattern = p.getPattern().substring(0,length-1); p = new Pattern(pattern); length = pattern.length(); } } public int getRPS(String patt, String rps){ Pattern pattern = new Pattern(rps + patt); Integer value = map.get(pattern); if(value == null){ return 0; } return value; } public Weapon getWeapon(String userPattern) { String patt = new String(userPattern); while(patt.length() > 0) { //System.out.println(patt); int r = getRPS(patt, "R"); int p = getRPS(patt, "P"); int s = getRPS(patt, "S"); //System.out.println(r+" "+p+" "+s); if ((s - r) > 0 && (s - p) > 0) return Weapon.Rock; if ((p - s) > 0 && (p - r) > 0) return Weapon.Scissors; if ((r - s) > 0 && (r - p) > 0) return Weapon.Paper; if (s == r && r != 0) return Weapon.Paper; if (s == p && s != 0) return Weapon.Rock; if (r == p && p != 0) return Weapon.Scissors; patt = patt.substring(0,patt.length()-1); } return getRandomWeapon(); } public void getMap() { System.out.println("Map size: " + map.size()); for (Map.Entry<Pattern, Integer> entry : map.entrySet()) { System.out.println(entry.getKey().getPattern()+ "\t\t" +entry.getValue()); } } }
UTF-8
Java
2,387
java
Computer.java
Java
[]
null
[]
package game; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Random; public class Computer implements Serializable{ private Random randomGenerator; private HashMap<Pattern,Integer> map; public Computer(){ randomGenerator = new Random(); map = new HashMap<Pattern,Integer>(); } public Weapon getRandomWeapon() { Weapon[] weapons = Weapon.values(); int index = randomGenerator.nextInt(weapons.length); return weapons[index]; } public void storePattern(Pattern p) { int length = p.getPattern().length(); while(length>1) { Integer time = map.get(p); if (time == null) { map.put(p, 1); } else { map.put(p, time + 1); } String pattern = p.getPattern().substring(0,length-1); p = new Pattern(pattern); length = pattern.length(); } } public int getRPS(String patt, String rps){ Pattern pattern = new Pattern(rps + patt); Integer value = map.get(pattern); if(value == null){ return 0; } return value; } public Weapon getWeapon(String userPattern) { String patt = new String(userPattern); while(patt.length() > 0) { //System.out.println(patt); int r = getRPS(patt, "R"); int p = getRPS(patt, "P"); int s = getRPS(patt, "S"); //System.out.println(r+" "+p+" "+s); if ((s - r) > 0 && (s - p) > 0) return Weapon.Rock; if ((p - s) > 0 && (p - r) > 0) return Weapon.Scissors; if ((r - s) > 0 && (r - p) > 0) return Weapon.Paper; if (s == r && r != 0) return Weapon.Paper; if (s == p && s != 0) return Weapon.Rock; if (r == p && p != 0) return Weapon.Scissors; patt = patt.substring(0,patt.length()-1); } return getRandomWeapon(); } public void getMap() { System.out.println("Map size: " + map.size()); for (Map.Entry<Pattern, Integer> entry : map.entrySet()) { System.out.println(entry.getKey().getPattern()+ "\t\t" +entry.getValue()); } } }
2,387
0.499791
0.49225
88
26.125
19.782804
86
false
false
0
0
0
0
0
0
0.568182
false
false
2
7bc5600b1d58b01264e6e377fb65c859279fc56d
18,665,927,895,541
9bb67cabce6f8e5fa47a38260cf36f1a298370e0
/exercicioR.java
709d713de0eb8055dd08224db40a17c675d8a1f7
[]
no_license
monteirotitov/SegundaLista
https://github.com/monteirotitov/SegundaLista
b3e035c638904c7d7f70d05c97a96e32cf9fae21
7b99153ea5d035f82b4a062a6d44ecc0d96260b8
refs/heads/master
2022-12-12T01:19:33.556000
2020-09-21T18:09:01
2020-09-21T18:09:01
297,419,257
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class exercicioR { public static void main(String[] args) { int fulano = 160; int ciclano = 110; int i = 0; while(fulano >= ciclano) { fulano += 2; ciclano += 3; i++; } System.out.println("Ciclano superou a altura de Fulano em " + i + " anos"); } }
UTF-8
Java
409
java
exercicioR.java
Java
[]
null
[]
public class exercicioR { public static void main(String[] args) { int fulano = 160; int ciclano = 110; int i = 0; while(fulano >= ciclano) { fulano += 2; ciclano += 3; i++; } System.out.println("Ciclano superou a altura de Fulano em " + i + " anos"); } }
409
0.408313
0.386308
29
12.034483
18.069756
83
false
false
0
0
0
0
0
0
0.310345
false
false
2
f262f15d90641f223451330dbfa06fc51020cc9a
21,595,095,625,743
a7b6d779fbbffaf3ede36cd36de53d6022019271
/AI/src/Othello/Block.java
8ebdaaab15cfaec4b92630ec789aeb325afca8b0
[]
no_license
AndreasStrid/Ai_Othello_Game
https://github.com/AndreasStrid/Ai_Othello_Game
f2b80b60875bd3e720410b94fc090ecfedce6c01
8e2f3f0cc11a1d573f7d36be7cc02a97303a1111
refs/heads/master
2021-01-01T05:10:49.738000
2016-05-22T19:31:27
2016-05-22T19:31:27
59,412,765
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Othello; import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; /** * This class creates blocks that represents a piece of the board. * A block has a position which the game pieces will be placed on * @author Andreas * */ public class Block { private Image img; private int x, y; private int field; private int width, height; private String cord; private int row, colom; private Piece piece = null; private boolean occupied = false; /** * Creates a Block object * @param x: The x position on the screen * @param y: The y position on the screen * @param img: The picture that will show the block * @param cord: The text based coordinate for the block */ public Block(int x, int y, Image img,String cord) { this.img = img; this.x = x; this.y = y; this.cord = cord; this.width = img.getWidth(null); this.height = img.getHeight(null); } /** * Draws the block * @param g */ public void draw(Graphics g) { g.drawImage(img, x, y, width, height, null); } /** * Set the block to occupied by attaching a piece * @param p: The piece */ public void setOccupied(Piece p) { piece = null; piece = p; occupied = true; } /** * Checks if the block is occupied * @return */ public boolean checkOccupied() { return occupied; } /** * Returns the piece standing on the block * @return: piece */ public Piece getPiece() { return this.piece; } /** * Returns the color of the piece standing on the block * @return: colort */ public String getPieceColor() { return this.piece.getColor(); } //------------------------------------------ Geter and setters ------------------------------------------------------ /** * Gives the block a text based coordinate * @param cord */ public void setCord(String cord) { this.cord = cord; } /** * Returns the block a text based coordinate * @return: cord */ public String getCord() { return this.cord; } /** * Returns the Blocks X position * @return: x */ public int getX() { return this.x; } /** * Returns the Blocks X position * @return */ public int getY() { return this.y; } /** * Returns the row coordinate for the block * @return */ public int getRow() { return row; } /** * Sets the row coordinate for the block * @param r: row */ public void setRow(int r) { this.row = r; } /** * Returns the column coordinate for the block * @return column */ public int getColom() { return colom; } /** * Sets the column coordinate for the block * @param c: column */ public void setColom(int c) { this.colom = c; } }
UTF-8
Java
2,681
java
Block.java
Java
[ { "context": "which the game pieces will be placed on\n * @author Andreas\n *\n */\npublic class Block\n{\n\tprivate Image img;\n\t", "end": 261, "score": 0.9988736510276794, "start": 254, "tag": "NAME", "value": "Andreas" } ]
null
[]
package Othello; import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; /** * This class creates blocks that represents a piece of the board. * A block has a position which the game pieces will be placed on * @author Andreas * */ public class Block { private Image img; private int x, y; private int field; private int width, height; private String cord; private int row, colom; private Piece piece = null; private boolean occupied = false; /** * Creates a Block object * @param x: The x position on the screen * @param y: The y position on the screen * @param img: The picture that will show the block * @param cord: The text based coordinate for the block */ public Block(int x, int y, Image img,String cord) { this.img = img; this.x = x; this.y = y; this.cord = cord; this.width = img.getWidth(null); this.height = img.getHeight(null); } /** * Draws the block * @param g */ public void draw(Graphics g) { g.drawImage(img, x, y, width, height, null); } /** * Set the block to occupied by attaching a piece * @param p: The piece */ public void setOccupied(Piece p) { piece = null; piece = p; occupied = true; } /** * Checks if the block is occupied * @return */ public boolean checkOccupied() { return occupied; } /** * Returns the piece standing on the block * @return: piece */ public Piece getPiece() { return this.piece; } /** * Returns the color of the piece standing on the block * @return: colort */ public String getPieceColor() { return this.piece.getColor(); } //------------------------------------------ Geter and setters ------------------------------------------------------ /** * Gives the block a text based coordinate * @param cord */ public void setCord(String cord) { this.cord = cord; } /** * Returns the block a text based coordinate * @return: cord */ public String getCord() { return this.cord; } /** * Returns the Blocks X position * @return: x */ public int getX() { return this.x; } /** * Returns the Blocks X position * @return */ public int getY() { return this.y; } /** * Returns the row coordinate for the block * @return */ public int getRow() { return row; } /** * Sets the row coordinate for the block * @param r: row */ public void setRow(int r) { this.row = r; } /** * Returns the column coordinate for the block * @return column */ public int getColom() { return colom; } /** * Sets the column coordinate for the block * @param c: column */ public void setColom(int c) { this.colom = c; } }
2,681
0.612085
0.612085
151
16.754967
17.675129
118
false
false
0
0
0
0
0
0
1.331126
false
false
2
59e5e2a35a95011a5d9b735c5864cd6aa2cba88c
1,709,397,028,664
ddf022fc0169c1fa48105c12e0a2d722cc03d386
/src/BST.java
f0460f4e31b8e34ccd074b283fcb31da8a4ff20a
[]
no_license
josolennoso/algorithms1
https://github.com/josolennoso/algorithms1
119fb4cfec6266af131be992dd84e376d25a1ee1
25bf4dea38fa56d77c74be9dab0dd560665d48d4
refs/heads/master
2018-01-09T17:23:31.144000
2016-02-04T09:44:51
2016-02-04T09:44:51
47,104,451
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import edu.princeton.cs.algs4.Queue; public class BST<Key extends Comparable<Key>, Value> { private Node root; private class Node { private Key key; private Value val; private Node left; private Node right; private int count; // number of nodes in subtree including root itself public Node(Key key, Value val, int count) { this.key = key; this.val = val; this.count = count; } } public void put(Key key, Value val) { root = put(root, key, val); } private Node put(Node x, Key key, Value val) { if (x == null) { return new Node(key, val, 1); } int cmp = key.compareTo(x.key); if (cmp < 0) { x.left = put(x.left, key, val); } else if (cmp > 0) { x.right = put(x.right, key, val); } else { x.val = val; } x.count = 1 + size(x.left) + size(x.right); return x; } /** * Does this symbol table contain the given key? * @param key * @return */ public boolean contains(Key key) { return get(key) != null; } /** * Returns the value associated with the given key. * @param key * @return */ public Value get(Key key) { Node x = root; while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } /** * Returns the smallest key in the symbol table * @return */ public Node min() { return min(root); } private Node min(Node x) { if (x.left == null) return x; return min(x.left); } /** * Returns the largest key in the symbol table. * @return */ public Node max() { return max(root); } private Node max(Node x) { if (x.right == null) return x; return max(x.right); } /** * Returns the largest key in the symbol key less than or equal to the key. * @param key * @return */ public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; return x.key; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) { return t; } else { return x; } } /** * Returns the number of keys in the symbol table strictly less than the key. * @param key * @return */ public int rank(Key key) { return rank(key, root); } private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) { return rank(key, x.left); } else if (cmp > 0) { return size(x.left) + 1 + rank(key, x.right); } else { return size(x.left); } } /** * Returns all keys in the symbol table as an Iterable * * @return */ public Iterable<Key> keys() { Queue<Key> q = new Queue<Key>(); inorder(root, q); return q; } private void inorder(Node x, Queue<Key> q) { if (x == null) return; inorder(x.left, q); q.enqueue(x.key); inorder(x.right, q); } /** * Returns all keys in the symbol table in the given range, * as an Iterable. * @param lo * @param hi * @return */ public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in this symbol table. * @return */ public int size() { return size(root); } // return number of key-value pairs in BST rooted at x. private int size(Node x) { if (x == null) return 0; return x.count; } /** * Returns true if this symbol table is empty. * @return */ public boolean isEmpty() { return size() == 0; } /** * Removes the smallest key and associated value from the symbol table. */ public void deleteMin() { root = deleteMin(root); } // returns root node after min node is deleted private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); x.count = 1 + size(x.left) + size(x.right); return x; } /** * Removes the largest key and associated value from the symbol table. */ public void deleteMax() { root = deleteMax(root); } // returns root node after max node is deleted. private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMax(x.right); x.count = size(x.left) + size(x.right) + 1; return x; } /** * Removes the key and associated value from the symbol table * @param key */ public void delete(Key key) { root = delete(root, key); } // Hibbard deletion. private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) { x.left = delete(x.left, key); } else if (cmp > 0) { x.right = delete(x.right, key); } else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; x = min(t.right); x.right = deleteMin(x.right); x.left = t.left; } x.count = size(x.left) + size(x.right) + 1; return x; } // public Iterable<Key> iterator() { // // } }
UTF-8
Java
6,370
java
BST.java
Java
[]
null
[]
import edu.princeton.cs.algs4.Queue; public class BST<Key extends Comparable<Key>, Value> { private Node root; private class Node { private Key key; private Value val; private Node left; private Node right; private int count; // number of nodes in subtree including root itself public Node(Key key, Value val, int count) { this.key = key; this.val = val; this.count = count; } } public void put(Key key, Value val) { root = put(root, key, val); } private Node put(Node x, Key key, Value val) { if (x == null) { return new Node(key, val, 1); } int cmp = key.compareTo(x.key); if (cmp < 0) { x.left = put(x.left, key, val); } else if (cmp > 0) { x.right = put(x.right, key, val); } else { x.val = val; } x.count = 1 + size(x.left) + size(x.right); return x; } /** * Does this symbol table contain the given key? * @param key * @return */ public boolean contains(Key key) { return get(key) != null; } /** * Returns the value associated with the given key. * @param key * @return */ public Value get(Key key) { Node x = root; while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } /** * Returns the smallest key in the symbol table * @return */ public Node min() { return min(root); } private Node min(Node x) { if (x.left == null) return x; return min(x.left); } /** * Returns the largest key in the symbol table. * @return */ public Node max() { return max(root); } private Node max(Node x) { if (x.right == null) return x; return max(x.right); } /** * Returns the largest key in the symbol key less than or equal to the key. * @param key * @return */ public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; return x.key; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) { return t; } else { return x; } } /** * Returns the number of keys in the symbol table strictly less than the key. * @param key * @return */ public int rank(Key key) { return rank(key, root); } private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) { return rank(key, x.left); } else if (cmp > 0) { return size(x.left) + 1 + rank(key, x.right); } else { return size(x.left); } } /** * Returns all keys in the symbol table as an Iterable * * @return */ public Iterable<Key> keys() { Queue<Key> q = new Queue<Key>(); inorder(root, q); return q; } private void inorder(Node x, Queue<Key> q) { if (x == null) return; inorder(x.left, q); q.enqueue(x.key); inorder(x.right, q); } /** * Returns all keys in the symbol table in the given range, * as an Iterable. * @param lo * @param hi * @return */ public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in this symbol table. * @return */ public int size() { return size(root); } // return number of key-value pairs in BST rooted at x. private int size(Node x) { if (x == null) return 0; return x.count; } /** * Returns true if this symbol table is empty. * @return */ public boolean isEmpty() { return size() == 0; } /** * Removes the smallest key and associated value from the symbol table. */ public void deleteMin() { root = deleteMin(root); } // returns root node after min node is deleted private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); x.count = 1 + size(x.left) + size(x.right); return x; } /** * Removes the largest key and associated value from the symbol table. */ public void deleteMax() { root = deleteMax(root); } // returns root node after max node is deleted. private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMax(x.right); x.count = size(x.left) + size(x.right) + 1; return x; } /** * Removes the key and associated value from the symbol table * @param key */ public void delete(Key key) { root = delete(root, key); } // Hibbard deletion. private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) { x.left = delete(x.left, key); } else if (cmp > 0) { x.right = delete(x.right, key); } else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; x = min(t.right); x.right = deleteMin(x.right); x.left = t.left; } x.count = size(x.left) + size(x.right) + 1; return x; } // public Iterable<Key> iterator() { // // } }
6,370
0.499215
0.495447
264
23.128788
18.808002
81
false
false
0
0
0
0
0
0
0.507576
false
false
2
1eb9a394c2a79be321c0f1beee717510f1934eba
31,885,837,224,057
429f0fb13d1590995af1d4212688d63cea29b524
/src/val/mx/de/Snake.java
ba479d82aeb49ef902d182e04f8583f561d4de3e
[]
no_license
val-mx/VSnake3
https://github.com/val-mx/VSnake3
417e2de1a2681d3e924699107191af07964cebba
49636a08fbc820bbb5ed0795e4ce855c584d2b46
refs/heads/master
2022-12-06T19:39:28.564000
2020-08-29T15:18:55
2020-08-29T15:18:55
291,295,615
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package val.mx.de; import sas.Circle; import sas.View; import java.awt.*; import java.util.Random; public class Snake { private Queue<Circle> python, python2; private View v; private Circle head, tail, food; private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); public Snake() { food = new Circle(82, 82, 19); food.setColor(Color.RED); v = new View((int) screen.getWidth(), (int) screen.getHeight()); python = new Queue<>(); python2 = new Queue<>(); head = new Circle(202, 202, 19); python.enqueue(head); tail = head; run(); } public void run() { while (true) { int lastDirection = -1; while (!python.isEmpty()) { Circle c = python.front(); if (lastDirection != -1) { int newDir = lastDirection; lastDirection = (int) c.getDirection(); c.setDirection(newDir); } else { lastDirection = (int) c.getDirection(); } if (v.keyUpPressed()) head.setDirection(0); else if (v.keyDownPressed()) head.setDirection(180); else if (v.keyLeftPressed()) head.setDirection(270); else if (v.keyRightPressed()) head.setDirection(90); c.move(40); python2.enqueue(c); python.dequeue(); } while (!python2.isEmpty()) { python.enqueue(python2.front()); System.out.println(python.front().equals(head)); System.out.println(python.front().intersects(head)); if(python.front().getShapeX() != head.getShapeX() && python.front().getShapeY() != head.getShapeY()) { if (python.front().intersects(head)) System.exit(0); } python2.dequeue(); } if (head.intersects(food)) { Random r = new Random(); food.moveTo(r.nextInt((int) screen.getWidth() / 40) * 40 + 2, r.nextInt((int) screen.getHeight() / 40) * 40 + 2); add(); } if (v.keyEnterPressed()) add(); v.wait(60); } } private void add() { switch ((int) tail.getDirection()) { case 90: tail = new Circle(tail.getShapeX() - 40, tail.getShapeY(), 20); break; case 180: tail = new Circle(tail.getShapeX(), tail.getShapeY() - 40, 20); break; case 0: tail = new Circle(tail.getShapeX(), tail.getShapeY() + 40, 20); break; case 270: tail = new Circle(tail.getShapeX() + 40, tail.getShapeY(), 20); break; } python.enqueue(tail); } }
UTF-8
Java
2,944
java
Snake.java
Java
[]
null
[]
package val.mx.de; import sas.Circle; import sas.View; import java.awt.*; import java.util.Random; public class Snake { private Queue<Circle> python, python2; private View v; private Circle head, tail, food; private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); public Snake() { food = new Circle(82, 82, 19); food.setColor(Color.RED); v = new View((int) screen.getWidth(), (int) screen.getHeight()); python = new Queue<>(); python2 = new Queue<>(); head = new Circle(202, 202, 19); python.enqueue(head); tail = head; run(); } public void run() { while (true) { int lastDirection = -1; while (!python.isEmpty()) { Circle c = python.front(); if (lastDirection != -1) { int newDir = lastDirection; lastDirection = (int) c.getDirection(); c.setDirection(newDir); } else { lastDirection = (int) c.getDirection(); } if (v.keyUpPressed()) head.setDirection(0); else if (v.keyDownPressed()) head.setDirection(180); else if (v.keyLeftPressed()) head.setDirection(270); else if (v.keyRightPressed()) head.setDirection(90); c.move(40); python2.enqueue(c); python.dequeue(); } while (!python2.isEmpty()) { python.enqueue(python2.front()); System.out.println(python.front().equals(head)); System.out.println(python.front().intersects(head)); if(python.front().getShapeX() != head.getShapeX() && python.front().getShapeY() != head.getShapeY()) { if (python.front().intersects(head)) System.exit(0); } python2.dequeue(); } if (head.intersects(food)) { Random r = new Random(); food.moveTo(r.nextInt((int) screen.getWidth() / 40) * 40 + 2, r.nextInt((int) screen.getHeight() / 40) * 40 + 2); add(); } if (v.keyEnterPressed()) add(); v.wait(60); } } private void add() { switch ((int) tail.getDirection()) { case 90: tail = new Circle(tail.getShapeX() - 40, tail.getShapeY(), 20); break; case 180: tail = new Circle(tail.getShapeX(), tail.getShapeY() - 40, 20); break; case 0: tail = new Circle(tail.getShapeX(), tail.getShapeY() + 40, 20); break; case 270: tail = new Circle(tail.getShapeX() + 40, tail.getShapeY(), 20); break; } python.enqueue(tail); } }
2,944
0.483356
0.459239
106
26.773584
26.863485
129
false
false
0
0
0
0
0
0
0.632075
false
false
2
c71b62038ba1fec10350f289628d9cae47196f3d
266,287,992,092
61c87613c164389c1e0657ddb0793630c137cd7d
/session_Two/src/test/java/WebCheckMDN.java
6f9b4d8b8013ff1a0daaeb491d2b1044fbd76f41
[]
no_license
nixsala/Phase_02_Assignment_Automation
https://github.com/nixsala/Phase_02_Assignment_Automation
6e1b5e664694f3a13d767f843f80c5b54e192020
462e11d8668b08b24c128390a4d65fa4ccd4ec83
refs/heads/master
2023-05-05T15:41:28.784000
2021-05-29T15:27:03
2021-05-29T15:27:03
368,071,396
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class WebCheckMDN { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","src/main/resources/chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://opensource-demo.orangehrmlive.com/"); WebElement input=driver.findElement(By.cssSelector("input[id=\"txtUsername\"]")); input.sendKeys("Admin"); WebElement inputTwo=driver.findElement(By.cssSelector("input[name=\"txtPassword\"]")); inputTwo.sendKeys("admin123"); WebElement clickOne=driver.findElement(By.cssSelector("input[type=\"submit\"]")); clickOne.click(); driver.quit(); } }
UTF-8
Java
884
java
WebCheckMDN.java
Java
[ { "context": "t[id=\\\"txtUsername\\\"]\"));\n input.sendKeys(\"Admin\");\n WebElement inputTwo=driver.findElement", "end": 598, "score": 0.9975579380989075, "start": 593, "tag": "USERNAME", "value": "Admin" }, { "context": "e=\\\"txtPassword\\\"]\"));\n inputTwo...
null
[]
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class WebCheckMDN { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","src/main/resources/chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://opensource-demo.orangehrmlive.com/"); WebElement input=driver.findElement(By.cssSelector("input[id=\"txtUsername\"]")); input.sendKeys("Admin"); WebElement inputTwo=driver.findElement(By.cssSelector("input[name=\"txtPassword\"]")); inputTwo.sendKeys("<PASSWORD>"); WebElement clickOne=driver.findElement(By.cssSelector("input[type=\"submit\"]")); clickOne.click(); driver.quit(); } }
886
0.691176
0.687783
22
39.18182
29.84907
94
false
false
0
0
0
0
0
0
0.727273
false
false
2
901e8cd3b22591c2c8250b9cc343897db5653a2e
558,345,767,363
187fc9a6e12e82430eea2e8aaa6686ded2098cee
/src/com/company/Square.java
47c9dbc2b19ecc0979f4d6549d10ef60e132a943
[]
no_license
emrecoskun705/Chess
https://github.com/emrecoskun705/Chess
caf9068104d90986cc86d4dad23dcae6f0606c2d
03f2333759608d62cffc3346df087ff7a1b9c58a
refs/heads/main
2023-02-25T10:47:36.436000
2021-02-03T15:27:25
2021-02-03T15:27:25
335,667,327
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.ArrayList; public class Square extends ChessBoard { protected Piece piece = null; private String column; private String row; public Square(String column, String row) { this.column = column; this.row = row; } public void addPiece(Piece piece) { this.piece = piece; } @Override public ChessBoard getBoard() { return super.getBoard(); } @Override public String toString() { return column+row; } public int getRowDistance(Square location) { Integer currentRow = Integer.parseInt(this.row); Integer otherRow = Integer.parseInt(location.getRow()); return currentRow-otherRow; } public String getColumn() { return column; } public String getRow() { return row; } public boolean isAtSameColumn(Square targetLocation) { int columnLocation = arrayLocation(targetLocation.getColumn() + targetLocation.getRow())[1]; int columnThis = arrayLocation(column + row)[1]; return columnLocation == columnThis; } public boolean isDiagonal(Square targetLocation) { ArrayList<Square> answer = new ArrayList<>(); int[] arrayLocation = arrayLocation(this.getColumn() + this.getRow()); int x = arrayLocation[0];//array row int y = arrayLocation[1];//array column int xNew = x - 1; int yNew = y - 1; while (isValid(xNew, yNew)) { answer.add(board[xNew][yNew]); xNew--; yNew--; } xNew = x + 1; yNew = y - 1; while (isValid(xNew, yNew)) { answer.add(board[xNew][yNew]); yNew--; xNew++; } xNew = x + 1; yNew = y + 1; while (isValid(xNew, yNew)) { answer.add(board[xNew][yNew]); yNew++; xNew++; } xNew = x - 1; yNew = y + 1; while (isValid(xNew, yNew)) { answer.add(board[xNew][yNew]); yNew++; xNew++; } return answer.contains(targetLocation); } public boolean isEmpty() { return this.piece == null; } // TODO: 24.04.2020 bütün çaprazlara bakıyo düzelmesi lazım public boolean isNeighborColumn(Square targetLocation) { int[] arrayLocationOfTarget = arrayLocation(targetLocation.getColumn() + targetLocation.getRow()); int[] arrayLocationOfThis = arrayLocation(column + row); int targetRow = arrayLocationOfTarget[0]; int targetColumn = arrayLocationOfTarget[1]; int thisRow = arrayLocationOfThis[0]; int thisColumn = arrayLocationOfThis[1]; return Math.abs(targetRow - thisRow) == 1 && (Math.abs(targetColumn - thisColumn) == 1 || Math.abs(targetColumn - thisColumn) == 2); } public Piece getPiece() { return piece; } public void clear() { this.piece = null; } public boolean isAtLastRow(int color) { color = turn; if (turn == 0) { return getRow().equals("8"); } else { return getRow().equals("1"); } } public void putNewQueen(int color) { this.piece = new Queen(color, this); } public void setPiece(Piece piece) { this.piece = piece; } @Override public int[] arrayLocation(String destination) { return super.arrayLocation(destination); } public boolean isAtSameRow(Square targetLocation) { int rowLocation = arrayLocation(targetLocation.getColumn() + targetLocation.getRow())[0]; int rowThis = arrayLocation(column + row)[0]; return rowLocation == rowThis; } public ArrayList<Square> possibleMovementsForKnight() { ArrayList<Square> answer = new ArrayList<>(); int[] arrayLocation = arrayLocation(column + row); int currentRow = arrayLocation[0]; int currentColumn = arrayLocation[1]; for (int row=-2; row <= 2; row++) { for(int column=-2; column<=2; column++) { if(Math.abs(row * column) == 2 && isValid(row+currentRow,column+currentColumn)) { answer.add(board[row+currentRow][column+currentColumn]); } } } return answer; } public ArrayList<Square> possibleMovementsForKing() { ArrayList<Square> answer = new ArrayList<>(); int[] arrayLocation = arrayLocation(column + row); int currentRow = arrayLocation[0]; int currentColumn = arrayLocation[1]; int[][] sets = {{1, 0}, {0, 1},{-1, 0},{0, -1},{1, 1},{-1, 1},{-1, -1},{1, -1}}; for(int[] set : sets) { int newRow = currentRow+set[0]; int newColumn = currentColumn+set[1]; if(isValid(newRow, newColumn )) { answer.add(board[newRow][newColumn]); } } return answer; } public boolean isValid(int row, int column) { return row >= 0 && row <= 7 && column >= 0 && column <= 7; } }
UTF-8
Java
5,161
java
Square.java
Java
[]
null
[]
package com.company; import java.util.ArrayList; public class Square extends ChessBoard { protected Piece piece = null; private String column; private String row; public Square(String column, String row) { this.column = column; this.row = row; } public void addPiece(Piece piece) { this.piece = piece; } @Override public ChessBoard getBoard() { return super.getBoard(); } @Override public String toString() { return column+row; } public int getRowDistance(Square location) { Integer currentRow = Integer.parseInt(this.row); Integer otherRow = Integer.parseInt(location.getRow()); return currentRow-otherRow; } public String getColumn() { return column; } public String getRow() { return row; } public boolean isAtSameColumn(Square targetLocation) { int columnLocation = arrayLocation(targetLocation.getColumn() + targetLocation.getRow())[1]; int columnThis = arrayLocation(column + row)[1]; return columnLocation == columnThis; } public boolean isDiagonal(Square targetLocation) { ArrayList<Square> answer = new ArrayList<>(); int[] arrayLocation = arrayLocation(this.getColumn() + this.getRow()); int x = arrayLocation[0];//array row int y = arrayLocation[1];//array column int xNew = x - 1; int yNew = y - 1; while (isValid(xNew, yNew)) { answer.add(board[xNew][yNew]); xNew--; yNew--; } xNew = x + 1; yNew = y - 1; while (isValid(xNew, yNew)) { answer.add(board[xNew][yNew]); yNew--; xNew++; } xNew = x + 1; yNew = y + 1; while (isValid(xNew, yNew)) { answer.add(board[xNew][yNew]); yNew++; xNew++; } xNew = x - 1; yNew = y + 1; while (isValid(xNew, yNew)) { answer.add(board[xNew][yNew]); yNew++; xNew++; } return answer.contains(targetLocation); } public boolean isEmpty() { return this.piece == null; } // TODO: 24.04.2020 bütün çaprazlara bakıyo düzelmesi lazım public boolean isNeighborColumn(Square targetLocation) { int[] arrayLocationOfTarget = arrayLocation(targetLocation.getColumn() + targetLocation.getRow()); int[] arrayLocationOfThis = arrayLocation(column + row); int targetRow = arrayLocationOfTarget[0]; int targetColumn = arrayLocationOfTarget[1]; int thisRow = arrayLocationOfThis[0]; int thisColumn = arrayLocationOfThis[1]; return Math.abs(targetRow - thisRow) == 1 && (Math.abs(targetColumn - thisColumn) == 1 || Math.abs(targetColumn - thisColumn) == 2); } public Piece getPiece() { return piece; } public void clear() { this.piece = null; } public boolean isAtLastRow(int color) { color = turn; if (turn == 0) { return getRow().equals("8"); } else { return getRow().equals("1"); } } public void putNewQueen(int color) { this.piece = new Queen(color, this); } public void setPiece(Piece piece) { this.piece = piece; } @Override public int[] arrayLocation(String destination) { return super.arrayLocation(destination); } public boolean isAtSameRow(Square targetLocation) { int rowLocation = arrayLocation(targetLocation.getColumn() + targetLocation.getRow())[0]; int rowThis = arrayLocation(column + row)[0]; return rowLocation == rowThis; } public ArrayList<Square> possibleMovementsForKnight() { ArrayList<Square> answer = new ArrayList<>(); int[] arrayLocation = arrayLocation(column + row); int currentRow = arrayLocation[0]; int currentColumn = arrayLocation[1]; for (int row=-2; row <= 2; row++) { for(int column=-2; column<=2; column++) { if(Math.abs(row * column) == 2 && isValid(row+currentRow,column+currentColumn)) { answer.add(board[row+currentRow][column+currentColumn]); } } } return answer; } public ArrayList<Square> possibleMovementsForKing() { ArrayList<Square> answer = new ArrayList<>(); int[] arrayLocation = arrayLocation(column + row); int currentRow = arrayLocation[0]; int currentColumn = arrayLocation[1]; int[][] sets = {{1, 0}, {0, 1},{-1, 0},{0, -1},{1, 1},{-1, 1},{-1, -1},{1, -1}}; for(int[] set : sets) { int newRow = currentRow+set[0]; int newColumn = currentColumn+set[1]; if(isValid(newRow, newColumn )) { answer.add(board[newRow][newColumn]); } } return answer; } public boolean isValid(int row, int column) { return row >= 0 && row <= 7 && column >= 0 && column <= 7; } }
5,161
0.561397
0.549176
189
26.275133
24.229906
106
false
false
0
0
0
0
0
0
0.571429
false
false
2
614b890cd821bb7ca0dfcd783c9185ecf6e3e2cd
19,748,259,654,964
c1e0bbcddf2efee61d8d4bbdfaf200a6026524ce
/grouper/src/grouper/edu/internet2/middleware/grouper/cache/GrouperCacheUtils.java
2f75f77a3886e5349fb583b701afe0a34b9a830b
[ "Apache-2.0" ]
permissive
Internet2/grouper
https://github.com/Internet2/grouper
094bb61f3f58d98e531684c205b884354db8d451
7a27d1460b45a79bf276fa05a726e83706f6ff65
refs/heads/GROUPER_4_BRANCH
2023-09-03T08:22:10.136000
2023-09-02T04:56:10
2023-09-02T04:56:10
21,910,720
74
82
NOASSERTION
false
2023-08-12T18:48:54
2014-07-16T17:42:37
2023-08-11T03:25:09
2023-08-12T18:48:53
2,619,994
71
76
8
Java
false
false
/** * Copyright 2014 Internet2 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author mchyzer * $Id: GrouperCacheUtils.java,v 1.2 2009-08-11 20:18:09 mchyzer Exp $ */ package edu.internet2.middleware.grouper.cache; import edu.internet2.middleware.grouper.SubjectFinder; import edu.internet2.middleware.grouper.app.attestation.GrouperAttestationJob; import edu.internet2.middleware.grouper.app.grouperTypes.GrouperObjectTypesAttributeNames; import edu.internet2.middleware.grouper.hooks.examples.AttributeAutoCreateHook; import edu.internet2.middleware.grouper.subj.cache.SubjectSourceCache; import edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase; import edu.internet2.middleware.grouperClient.config.GrouperUiApiTextConfig; import edu.internet2.middleware.grouperClient.config.db.ConfigDatabaseLogic; import edu.internet2.middleware.grouperClient.util.ExpirableCache; /** * */ public class GrouperCacheUtils { /** * */ public static void clearAllCaches() { AttributeAutoCreateHook.clearCache(); ConfigPropertiesCascadeBase.clearCache(); ConfigDatabaseLogic.clearCache(); ExpirableCache.clearAll(); SubjectSourceCache.clearCache(); SubjectFinder.internalClearSubjectCustomizerCache(); GrouperUiApiTextConfig.clearCache(); // whats the difference between these two? EhcacheController.ehcacheController().flushCache(); GrouperObjectTypesAttributeNames.clearCache(); GrouperAttestationJob.clearCache(); } }
UTF-8
Java
2,112
java
GrouperCacheUtils.java
Java
[ { "context": "imitations under the License.\r\n */\r\n/*\r\n * @author mchyzer\r\n * $Id: GrouperCacheUtils.java,v 1.2 2009-08-11 ", "end": 629, "score": 0.9995198249816895, "start": 622, "tag": "USERNAME", "value": "mchyzer" } ]
null
[]
/** * Copyright 2014 Internet2 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author mchyzer * $Id: GrouperCacheUtils.java,v 1.2 2009-08-11 20:18:09 mchyzer Exp $ */ package edu.internet2.middleware.grouper.cache; import edu.internet2.middleware.grouper.SubjectFinder; import edu.internet2.middleware.grouper.app.attestation.GrouperAttestationJob; import edu.internet2.middleware.grouper.app.grouperTypes.GrouperObjectTypesAttributeNames; import edu.internet2.middleware.grouper.hooks.examples.AttributeAutoCreateHook; import edu.internet2.middleware.grouper.subj.cache.SubjectSourceCache; import edu.internet2.middleware.grouperClient.config.ConfigPropertiesCascadeBase; import edu.internet2.middleware.grouperClient.config.GrouperUiApiTextConfig; import edu.internet2.middleware.grouperClient.config.db.ConfigDatabaseLogic; import edu.internet2.middleware.grouperClient.util.ExpirableCache; /** * */ public class GrouperCacheUtils { /** * */ public static void clearAllCaches() { AttributeAutoCreateHook.clearCache(); ConfigPropertiesCascadeBase.clearCache(); ConfigDatabaseLogic.clearCache(); ExpirableCache.clearAll(); SubjectSourceCache.clearCache(); SubjectFinder.internalClearSubjectCustomizerCache(); GrouperUiApiTextConfig.clearCache(); // whats the difference between these two? EhcacheController.ehcacheController().flushCache(); GrouperObjectTypesAttributeNames.clearCache(); GrouperAttestationJob.clearCache(); } }
2,112
0.749053
0.732481
65
30.492308
29.44101
90
true
false
0
0
0
0
0
0
0.4
false
false
2
3f049932210bff83e864a7e54f47e62187a0fbab
266,287,994,324
5166b23163dea0c0619e57d9acd54cc4b6b2cd74
/src/main/java/se/sics/hop/metadata/ndb/wrapper/HopsQueryDomainType.java
86bc6b61dcf4f19ddf75047fbbed0b261445c3c9
[]
no_license
maismail/hops-metadata-dal-impl-ndb-old
https://github.com/maismail/hops-metadata-dal-impl-ndb-old
bfc1527c89e6fa25196732796ded9b4780727fe9
ae478dd762cf184078e6f460857b129cbd96e5eb
refs/heads/master
2020-03-30T15:52:41.071000
2014-12-15T16:12:53
2014-12-15T16:12:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.sics.hop.metadata.ndb.wrapper; import com.mysql.clusterj.ClusterJException; import com.mysql.clusterj.query.Predicate; import com.mysql.clusterj.query.PredicateOperand; import com.mysql.clusterj.query.QueryDefinition; import com.mysql.clusterj.query.QueryDomainType; import se.sics.hop.exception.StorageException; public class HopsQueryDomainType<E> { private final QueryDomainType<E> queryDomainType; public HopsQueryDomainType(QueryDomainType<E> queryDomainType) { this.queryDomainType = queryDomainType; } public HopsPredicateOperand get(String s) throws StorageException { try { return new HopsPredicateOperand(queryDomainType.get(s)); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } public Class<E> getType() throws StorageException { try { return queryDomainType.getType(); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } public HopsQueryDefinition<E> where(HopsPredicate predicate) throws StorageException { try { return new HopsQueryDefinition<E>(queryDomainType.where(predicate.getPredicate())); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } public HopsPredicateOperand param(String s) throws StorageException { try { return new HopsPredicateOperand(queryDomainType.param(s)); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } public HopsPredicate not(HopsPredicate predicate) throws StorageException { try { return new HopsPredicate(queryDomainType.not(predicate.getPredicate())); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } QueryDomainType<E> getQueryDomainType() { return queryDomainType; } }
UTF-8
Java
2,615
java
HopsQueryDomainType.java
Java
[]
null
[]
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.sics.hop.metadata.ndb.wrapper; import com.mysql.clusterj.ClusterJException; import com.mysql.clusterj.query.Predicate; import com.mysql.clusterj.query.PredicateOperand; import com.mysql.clusterj.query.QueryDefinition; import com.mysql.clusterj.query.QueryDomainType; import se.sics.hop.exception.StorageException; public class HopsQueryDomainType<E> { private final QueryDomainType<E> queryDomainType; public HopsQueryDomainType(QueryDomainType<E> queryDomainType) { this.queryDomainType = queryDomainType; } public HopsPredicateOperand get(String s) throws StorageException { try { return new HopsPredicateOperand(queryDomainType.get(s)); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } public Class<E> getType() throws StorageException { try { return queryDomainType.getType(); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } public HopsQueryDefinition<E> where(HopsPredicate predicate) throws StorageException { try { return new HopsQueryDefinition<E>(queryDomainType.where(predicate.getPredicate())); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } public HopsPredicateOperand param(String s) throws StorageException { try { return new HopsPredicateOperand(queryDomainType.param(s)); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } public HopsPredicate not(HopsPredicate predicate) throws StorageException { try { return new HopsPredicate(queryDomainType.not(predicate.getPredicate())); } catch (ClusterJException e) { throw HopsExceptionHelper.wrap(e); } } QueryDomainType<E> getQueryDomainType() { return queryDomainType; } }
2,615
0.739579
0.73805
78
32.525642
26.440414
89
false
false
0
0
0
0
0
0
0.320513
false
false
2
c7d631dd950f156ef2540ecc9a1eedef1c2dfd31
36,189,394,438,217
c78a483eefacf13a4022c825469b93693b625056
/src/main/java/com/altimetrik/usermanagement/api/service/impl/PgAssessmentLevelApiServiceImpl.java
36f8efd471c2456b7d15b2697a966829c91ccae4
[]
no_license
def-demo/Weavon1504706105228
https://github.com/def-demo/Weavon1504706105228
e17e83a05c6db6513e9961f3fe2970d464250944
3d945dae740a37fc1e1d6fd6b553030d9a013bd2
refs/heads/master
2021-01-23T10:28:53.422000
2017-09-06T13:55:09
2017-09-06T13:55:09
102,614,971
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.altimetrik.usermanagement.api.service.impl; import com.altimetrik.usermanagement.api.service.*; import com.altimetrik.usermanagement.models.*; import org.springframework.stereotype.Service; import com.altimetrik.usermanagement.models.repository.*; import org.springframework.http.HttpStatus; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.altimetrik.usermanagement.models.PgAssessmentLevel; import java.util.List; import com.altimetrik.usermanagement.exception.NotFoundException; @Service @Transactional public class PgAssessmentLevelApiServiceImpl implements PgAssessmentLevelApiService { @Autowired private PgAssessmentLevelRepository pgAssessmentLevelRepository ; @Override public List<PgAssessmentLevel> findAllPgAssessmentLevel() throws NotFoundException { return pgAssessmentLevelRepository.findAll(); } @Override public PgAssessmentLevel updatePgAssessmentLevel(PgAssessmentLevel pgAssessmentLevel) throws NotFoundException { return pgAssessmentLevelRepository.save(pgAssessmentLevel); } @Override public PgAssessmentLevel addPgAssessmentLevel(PgAssessmentLevel pgAssessmentLevel) throws NotFoundException { return pgAssessmentLevelRepository.save(pgAssessmentLevel); } @Override public PgAssessmentLevel findByIdPgAssessmentLevel(Long id) throws NotFoundException { return pgAssessmentLevelRepository.findOne(id); } @Override public void deletePgAssessmentLevel(Long id) throws NotFoundException { } }
UTF-8
Java
2,208
java
PgAssessmentLevelApiServiceImpl.java
Java
[]
null
[]
package com.altimetrik.usermanagement.api.service.impl; import com.altimetrik.usermanagement.api.service.*; import com.altimetrik.usermanagement.models.*; import org.springframework.stereotype.Service; import com.altimetrik.usermanagement.models.repository.*; import org.springframework.http.HttpStatus; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.altimetrik.usermanagement.models.PgAssessmentLevel; import java.util.List; import com.altimetrik.usermanagement.exception.NotFoundException; @Service @Transactional public class PgAssessmentLevelApiServiceImpl implements PgAssessmentLevelApiService { @Autowired private PgAssessmentLevelRepository pgAssessmentLevelRepository ; @Override public List<PgAssessmentLevel> findAllPgAssessmentLevel() throws NotFoundException { return pgAssessmentLevelRepository.findAll(); } @Override public PgAssessmentLevel updatePgAssessmentLevel(PgAssessmentLevel pgAssessmentLevel) throws NotFoundException { return pgAssessmentLevelRepository.save(pgAssessmentLevel); } @Override public PgAssessmentLevel addPgAssessmentLevel(PgAssessmentLevel pgAssessmentLevel) throws NotFoundException { return pgAssessmentLevelRepository.save(pgAssessmentLevel); } @Override public PgAssessmentLevel findByIdPgAssessmentLevel(Long id) throws NotFoundException { return pgAssessmentLevelRepository.findOne(id); } @Override public void deletePgAssessmentLevel(Long id) throws NotFoundException { } }
2,208
0.605525
0.605525
126
15.507936
22.449148
91
false
false
0
0
0
0
0
0
1.285714
false
false
2
fabd2623a06e9513fdab690f8d03968332c5adbb
29,978,871,747,221
1072f5d657f667f39bd7257bfae102285aafc318
/src/main/java/norsker/topdownshooter/TopdownshooterApplication.java
39ad77f04c1a9d96eb5319e281820dd31e5f3a6f
[]
no_license
emilnorsker/topdonshooter
https://github.com/emilnorsker/topdonshooter
86b73dd06263c40e6dbc78371a9e7668ca61c80f
eb2f73d6970c09780c42c351d87b2005c5570d04
refs/heads/master
2023-01-23T13:09:19.742000
2021-05-08T20:44:27
2021-05-08T20:44:27
318,799,500
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package norsker.topdownshooter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TopdownshooterApplication { public static void main(String[] args) { SpringApplication.run(TopdownshooterApplication.class, args); } }
UTF-8
Java
347
java
TopdownshooterApplication.java
Java
[]
null
[]
package norsker.topdownshooter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TopdownshooterApplication { public static void main(String[] args) { SpringApplication.run(TopdownshooterApplication.class, args); } }
347
0.795389
0.795389
14
23.785715
25.105999
69
false
false
0
0
0
0
0
0
0.357143
false
false
2
87772624a85c70f340b09bfd9a9370841515b08b
35,768,487,641,604
01c2e23e48cf8b678e787d26e12746295e4384fc
/src/main/java/com/gopi/learning/data/webservice/RoomController.java
de21cfa7726bec3cc676f6d4b09796de38807c13
[]
no_license
gopiyengiteela/learning-spring
https://github.com/gopiyengiteela/learning-spring
f0aa560baa44bfb8a761cfa1b9c60e45bb24596a
7572fe16dcf89280c8d3c8f680edf779d6b3964f
refs/heads/master
2020-03-27T20:10:03.648000
2018-09-02T02:23:42
2018-09-02T02:23:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gopi.learning.data.webservice; import com.gopi.learning.data.entity.Room; import com.gopi.learning.data.repository.RoomRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class RoomController { @Autowired private RoomRepository roomRepo; @RequestMapping(value="/rooms", method = RequestMethod.GET) List<Room> findAll(@RequestParam(required=false)String roomNumber){ List<Room> rooms=new ArrayList<>(); if(null==roomNumber){ Iterable<Room> results=this.roomRepo.findAll(); results.forEach(room -> {rooms.add(room);}); }else{ Room room=this.roomRepo.findByNumber(roomNumber); if(null!=room){ rooms.add(room); } } return rooms; } }
UTF-8
Java
1,127
java
RoomController.java
Java
[]
null
[]
package com.gopi.learning.data.webservice; import com.gopi.learning.data.entity.Room; import com.gopi.learning.data.repository.RoomRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class RoomController { @Autowired private RoomRepository roomRepo; @RequestMapping(value="/rooms", method = RequestMethod.GET) List<Room> findAll(@RequestParam(required=false)String roomNumber){ List<Room> rooms=new ArrayList<>(); if(null==roomNumber){ Iterable<Room> results=this.roomRepo.findAll(); results.forEach(room -> {rooms.add(room);}); }else{ Room room=this.roomRepo.findByNumber(roomNumber); if(null!=room){ rooms.add(room); } } return rooms; } }
1,127
0.709849
0.709849
33
33.151516
23.175381
71
false
false
0
0
0
0
0
0
0.575758
false
false
2
455481e26c5db20448984c12ccc36a256d0818ee
5,291,399,734,596
47cf021b0217e45558ee608d4b09495c2c696b96
/src/modelos/Arqueo.java
7e3e8725e7d7e2175b1418973222f11674b91ab1
[]
no_license
ProgramacionPARE/escritorio
https://github.com/ProgramacionPARE/escritorio
a1a1fbd275767e6b495a09a4f3cb696ca4010676
d5d5998711ef66f2411a13f64fe672661cc5689b
refs/heads/master
2021-01-18T17:17:25.210000
2015-04-30T17:44:12
2015-04-30T17:44:12
23,720,898
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Modelo de un arqueo */ package modelos; import modelosReportesAux.DetallesArqueo; import java.util.ArrayList; public class Arqueo { long id; long folioInicial; long folioFinal; float subTotalM; float subTotalB; float subTotalR; float total; String fecha; ArrayList <DetallesArqueo> detallesArqueo; public Arqueo(long folioInicial, long folioFinal, float subTotalM, float subTotalB,float subTotalR,float total, String fecha) { this.folioInicial = folioInicial; this.folioFinal = folioFinal; this.subTotalM = subTotalM; this.subTotalB = subTotalB; this.subTotalR = subTotalR; this.total = total; this.fecha = fecha; this.detallesArqueo = new ArrayList <DetallesArqueo>(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public float getSubTotalR() { return subTotalR; } public void setSubTotalR(float subTotalR) { this.subTotalR = subTotalR; } public long getFolioInicial() { return folioInicial; } public void setFolioInicial(long folioInicial) { this.folioInicial = folioInicial; } public long getFolioFinal() { return folioFinal; } public void setFolioFinal(long folioFinal) { this.folioFinal = folioFinal; } public float getSubTotalM() { return subTotalM; } public void setSubTotalM(float subTotalM) { this.subTotalM = subTotalM; } public float getSubTotalB() { return subTotalB; } public void setSubTotalB(float subTotalB) { this.subTotalB = subTotalB; } public float getTotal() { return total; } public void setTotal(float total) { this.total = total; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public ArrayList<DetallesArqueo> getDetallesArqueo() { return detallesArqueo; } public void setDetallesArqueo(ArrayList<DetallesArqueo> detallesArqueo) { this.detallesArqueo = detallesArqueo; } }
UTF-8
Java
2,231
java
Arqueo.java
Java
[]
null
[]
/* Modelo de un arqueo */ package modelos; import modelosReportesAux.DetallesArqueo; import java.util.ArrayList; public class Arqueo { long id; long folioInicial; long folioFinal; float subTotalM; float subTotalB; float subTotalR; float total; String fecha; ArrayList <DetallesArqueo> detallesArqueo; public Arqueo(long folioInicial, long folioFinal, float subTotalM, float subTotalB,float subTotalR,float total, String fecha) { this.folioInicial = folioInicial; this.folioFinal = folioFinal; this.subTotalM = subTotalM; this.subTotalB = subTotalB; this.subTotalR = subTotalR; this.total = total; this.fecha = fecha; this.detallesArqueo = new ArrayList <DetallesArqueo>(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public float getSubTotalR() { return subTotalR; } public void setSubTotalR(float subTotalR) { this.subTotalR = subTotalR; } public long getFolioInicial() { return folioInicial; } public void setFolioInicial(long folioInicial) { this.folioInicial = folioInicial; } public long getFolioFinal() { return folioFinal; } public void setFolioFinal(long folioFinal) { this.folioFinal = folioFinal; } public float getSubTotalM() { return subTotalM; } public void setSubTotalM(float subTotalM) { this.subTotalM = subTotalM; } public float getSubTotalB() { return subTotalB; } public void setSubTotalB(float subTotalB) { this.subTotalB = subTotalB; } public float getTotal() { return total; } public void setTotal(float total) { this.total = total; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public ArrayList<DetallesArqueo> getDetallesArqueo() { return detallesArqueo; } public void setDetallesArqueo(ArrayList<DetallesArqueo> detallesArqueo) { this.detallesArqueo = detallesArqueo; } }
2,231
0.627073
0.627073
106
20.047171
20.577229
131
false
false
0
0
0
0
0
0
0.415094
false
false
2
799532b9fcb89ddd31b6d387581137ffa3c35fe9
5,291,399,735,581
66152b41602f0c5a8161190334d1dcd7d4f4c682
/app/src/main/java/br/com/usinasantafe/pbi/control/ConfigCTR.java
a538eba0b0cff1e409a218658c96f6599d589b81
[]
no_license
andinhodelgado/PBI
https://github.com/andinhodelgado/PBI
21dfdfd33c7e606908dd429f350d5b6bedfd5e5b
5e05f373be0e2892231b9061130144e4484d4213
refs/heads/master
2023-02-15T04:09:17.347000
2021-01-04T17:36:09
2021-01-04T17:36:09
306,425,536
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.usinasantafe.pbi.control; import android.app.ProgressDialog; import android.content.Context; import br.com.usinasantafe.pbi.model.bean.estaticas.ColabBean; import br.com.usinasantafe.pbi.model.bean.variaveis.ConfigBean; import br.com.usinasantafe.pbi.model.dao.ColabDAO; import br.com.usinasantafe.pbi.model.dao.ConfigDAO; import br.com.usinasantafe.pbi.util.AtualDadosServ; public class ConfigCTR { public ConfigCTR() { } public boolean hasElements(){ ConfigDAO configDAO = new ConfigDAO(); return configDAO.hasElements(); } public boolean verConfig(String senha){ ConfigDAO configDAO = new ConfigDAO(); return configDAO.verConfig(senha); } public ConfigBean getConfig(){ ConfigDAO configDAO = new ConfigDAO(); return configDAO.getConfig(); } public ColabBean getColab(){ ColabDAO colabDAO = new ColabDAO(); return colabDAO.getMatricColab(getConfig().getMatricFuncConfig()); } public void insertConfig(Long idEquip, String senha){ ConfigDAO configDAO = new ConfigDAO(); configDAO.insert(idEquip, senha); } public void matricFuncConfig(Long matricFunc){ ConfigDAO configDAO = new ConfigDAO(); configDAO.matricFuncConfig(matricFunc); } public void atualTodasTabelas(Context context, ProgressDialog progressDialog){ AtualDadosServ.getInstance().atualTodasTabelas(progressDialog, context); } }
UTF-8
Java
1,486
java
ConfigCTR.java
Java
[]
null
[]
package br.com.usinasantafe.pbi.control; import android.app.ProgressDialog; import android.content.Context; import br.com.usinasantafe.pbi.model.bean.estaticas.ColabBean; import br.com.usinasantafe.pbi.model.bean.variaveis.ConfigBean; import br.com.usinasantafe.pbi.model.dao.ColabDAO; import br.com.usinasantafe.pbi.model.dao.ConfigDAO; import br.com.usinasantafe.pbi.util.AtualDadosServ; public class ConfigCTR { public ConfigCTR() { } public boolean hasElements(){ ConfigDAO configDAO = new ConfigDAO(); return configDAO.hasElements(); } public boolean verConfig(String senha){ ConfigDAO configDAO = new ConfigDAO(); return configDAO.verConfig(senha); } public ConfigBean getConfig(){ ConfigDAO configDAO = new ConfigDAO(); return configDAO.getConfig(); } public ColabBean getColab(){ ColabDAO colabDAO = new ColabDAO(); return colabDAO.getMatricColab(getConfig().getMatricFuncConfig()); } public void insertConfig(Long idEquip, String senha){ ConfigDAO configDAO = new ConfigDAO(); configDAO.insert(idEquip, senha); } public void matricFuncConfig(Long matricFunc){ ConfigDAO configDAO = new ConfigDAO(); configDAO.matricFuncConfig(matricFunc); } public void atualTodasTabelas(Context context, ProgressDialog progressDialog){ AtualDadosServ.getInstance().atualTodasTabelas(progressDialog, context); } }
1,486
0.711305
0.711305
51
28.137255
24.514118
82
false
false
0
0
0
0
0
0
0.490196
false
false
2
680f85ef97b6b3f833777091d7b78599fdcbe707
25,898,652,835,578
3ee4cb548c499b6620fa2ae2f0163aa6e667bf5b
/src/test/NewsletterLet.java
059c0f1214d17555300d625e4912b48066445c67
[]
no_license
HamedSad/TeamRocket2
https://github.com/HamedSad/TeamRocket2
6e6857bc5685ee83faab4d34ee123b6df6d5dc23
c456dfde3789401982f8a4647ede3f0b3bfaa20b
refs/heads/master
2020-03-28T16:04:46.245000
2019-02-18T12:41:50
2019-02-18T12:41:50
148,657,247
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class NewsletterLet */ @WebServlet("/NewsletterLet") public class NewsletterLet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public NewsletterLet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); String emNews = request.getParameter("email"); BeanNewsletter news = new BeanNewsletter(); news.setEmail(emNews); NewsletterDao confirmationNewsletter = new NewsletterDao(); confirmationNewsletter.registerNewsletter(news); request.setAttribute("confirmNewsletter", "Ton email a bien été enregistré"); this.getServletContext().getRequestDispatcher("/Register.jsp").forward(request, response); } }
ISO-8859-1
Java
1,637
java
NewsletterLet.java
Java
[]
null
[]
package test; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class NewsletterLet */ @WebServlet("/NewsletterLet") public class NewsletterLet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public NewsletterLet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); String emNews = request.getParameter("email"); BeanNewsletter news = new BeanNewsletter(); news.setEmail(emNews); NewsletterDao confirmationNewsletter = new NewsletterDao(); confirmationNewsletter.registerNewsletter(news); request.setAttribute("confirmNewsletter", "Ton email a bien été enregistré"); this.getServletContext().getRequestDispatcher("/Register.jsp").forward(request, response); } }
1,637
0.727662
0.72705
55
27.709091
30.616497
119
false
false
0
0
0
0
0
0
1.363636
false
false
2
074e7d9eed1a7d35fa9331e547ae26607049553a
24,902,220,410,562
65c3585ce6a4875fb486287cf59a938e58de40cc
/consumer-server/src/main/java/com/lee/consumer/user/fallback/UserClientFallBack.java
3625d261792eb1255faf31d98d8f0d720d3e70b5
[]
no_license
leebw1985/springCloudDemo
https://github.com/leebw1985/springCloudDemo
6080a263e26d531b763c275146fef8d8c98baa5a
b5956a5dd7f0a78b355bb9e64c2044894bdfc78c
refs/heads/master
2020-04-02T16:05:29.402000
2018-10-26T18:24:40
2018-10-26T18:24:40
154,597,626
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lee.consumer.user.fallback; import com.lee.consumer.user.entity.UserInfo; import com.lee.consumer.user.feign.UserClient; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; @Component public class UserClientFallBack implements UserClient { //private static final Logger LOGGER = LoggerFactory.getLogger(UserClientFallBack.class); private static final Logger logger = LogManager.getLogger(UserClientFallBack.class.getName()); /** * hystrix fallback方法 * @param id id * @return 默认的用户 */ @Override public UserInfo findByIdFeign(String id) { UserClientFallBack.logger.error("异常发生,进入fallback方法,接收的参数:id = {}", id); UserInfo user = makeUser(); return user; } @Override public UserInfo testTimeOutFeign(long time) { UserClientFallBack.logger.error("异常发生,进入fallback方法,接收的参数:time = {}", time); UserInfo user = makeUser(); return user; } private UserInfo makeUser() { UserInfo user = new UserInfo(); user.setId("none"); user.setUsername("default username"); user.setAge(0); return user; } }
UTF-8
Java
1,307
java
UserClientFallBack.java
Java
[ { "context": " user.setId(\"none\");\n user.setUsername(\"default username\");\n user.setAge(0);\n return user;\n ", "end": 1172, "score": 0.9990056753158569, "start": 1156, "tag": "USERNAME", "value": "default username" } ]
null
[]
package com.lee.consumer.user.fallback; import com.lee.consumer.user.entity.UserInfo; import com.lee.consumer.user.feign.UserClient; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; @Component public class UserClientFallBack implements UserClient { //private static final Logger LOGGER = LoggerFactory.getLogger(UserClientFallBack.class); private static final Logger logger = LogManager.getLogger(UserClientFallBack.class.getName()); /** * hystrix fallback方法 * @param id id * @return 默认的用户 */ @Override public UserInfo findByIdFeign(String id) { UserClientFallBack.logger.error("异常发生,进入fallback方法,接收的参数:id = {}", id); UserInfo user = makeUser(); return user; } @Override public UserInfo testTimeOutFeign(long time) { UserClientFallBack.logger.error("异常发生,进入fallback方法,接收的参数:time = {}", time); UserInfo user = makeUser(); return user; } private UserInfo makeUser() { UserInfo user = new UserInfo(); user.setId("none"); user.setUsername("default username"); user.setAge(0); return user; } }
1,307
0.685924
0.683483
40
29.725
25.629072
98
false
false
0
0
0
0
0
0
0.525
false
false
2
bf6d60d94cbb584cc2bd3a71c3a89736ac61b9f7
11,922,829,250,077
9f992580e76f24ec76e76155cd2d22f8eaba6743
/timeStartText.java
44aba527e2137727d6f9dc6d0a4736ca24bf6cfd
[]
no_license
ADolgovykh/PlaneShooterGame
https://github.com/ADolgovykh/PlaneShooterGame
520ef25cabec36112cf137c8c68da093b472c0cd
051015594b9c6fbe5cb656b480b1903e8d42b9ea
refs/heads/master
2021-01-20T10:37:30.865000
2015-01-24T16:39:55
2015-01-24T16:39:55
29,783,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * timeStartText handles the time counting down at the start of the game * @author (Anton Dolgovykh, Andrew Stroz) * @version (March 7th, 2013) */ public class timeStartText extends counter { public void act() { int time = ((space) getWorld()).getStartTime(); setImage(new GreenfootImage(time + " Seconds", 20, Color.BLACK, Color.WHITE)); if (time <= 0){ getWorld().removeObject(this); } } }
UTF-8
Java
570
java
timeStartText.java
Java
[ { "context": "ounting down at the start of the game\n * @author (Anton Dolgovykh, Andrew Stroz) \n * @version (March 7th, 2013)\n */", "end": 208, "score": 0.9998825192451477, "start": 193, "tag": "NAME", "value": "Anton Dolgovykh" }, { "context": "the start of the game\n * @author (...
null
[]
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * timeStartText handles the time counting down at the start of the game * @author (<NAME>, <NAME>) * @version (March 7th, 2013) */ public class timeStartText extends counter { public void act() { int time = ((space) getWorld()).getStartTime(); setImage(new GreenfootImage(time + " Seconds", 20, Color.BLACK, Color.WHITE)); if (time <= 0){ getWorld().removeObject(this); } } }
555
0.62807
0.614035
20
27.5
27.139454
86
false
false
0
0
0
0
0
0
0.65
false
false
2
5082f9761d757903b43290bbf3970bfc177ba5fe
13,159,779,829,196
604337cf6e67236b5621f8fa8bc6dade258e24b9
/Questao2/Carros/Sedan/Hyunda.java
06a9663c34aca00a7f8deb9832a3b2e9bac2efab
[]
no_license
talitagomess/AP2-ProgramacaoAvancada
https://github.com/talitagomess/AP2-ProgramacaoAvancada
52eb67db14d73f11c36503fdcdc4b0aecc8e3ea6
a54e042d60a6a690e07303c3d9b1115120db169b
refs/heads/master
2022-10-12T11:11:47.397000
2020-06-01T02:17:39
2020-06-01T02:17:39
267,979,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Questao2.Carros.Sedan; import Questao2.Carros.Carro; public class Hyunda extends Carro { @Override public void ligar() { System.out.println("O Hyunda está ligado!"); } }
UTF-8
Java
205
java
Hyunda.java
Java
[]
null
[]
package Questao2.Carros.Sedan; import Questao2.Carros.Carro; public class Hyunda extends Carro { @Override public void ligar() { System.out.println("O Hyunda está ligado!"); } }
205
0.666667
0.656863
11
17.636364
16.745543
52
false
false
0
0
0
0
0
0
0.272727
false
false
2
c75acdf3319801eb89a14fa67ce48b369a09aa6d
695,784,752,550
9f162d15b49d99680cbfcb447dcb29a87c1e3bb3
/src/com/tc25/action/UserAction.java
f1f55e2f38ddbd18e6ed9db24b0ca66cd89a25be
[]
no_license
huanghe1234/LeavePro
https://github.com/huanghe1234/LeavePro
4f61c43dcfb1423c6dcb4467fa60a2424b33b90d
ad92e6c0ae64443ea07c4eaca9297eff48012ed9
refs/heads/master
2021-05-16T16:19:16.258000
2018-02-02T06:04:22
2018-02-02T06:04:22
119,939,556
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tc25.action; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.junit.Test; import com.opensymphony.xwork2.ModelDriven; import com.tc25.HButil.HBUtils; import com.tc25.entity.Job; import com.tc25.entity.Leaveform; import com.tc25.entity.Teacher; import com.tc25.entity.User; public class UserAction implements ModelDriven<User>{ private User u = new User(); private String tip; private Session session = HBUtils.getSession(); private Teacher tea = new Teacher(); private List<Leaveform> list = null; private List<Leaveform> listStu = null; public String regist(){ System.out.println(u); //设置角色 Job j = new Job(); j.setJobName(u.getJob().getJobName()); session.save(j); //设置老师 Teacher teacher = new Teacher(); teacher.setUserName("老师1"); teacher.setRealName(u.getTeacher().getUserName()); teacher.setUserPwd("1234"); session.save(teacher); //保存到用户对象中 u.setJob(j); u.setTeacher(teacher); session.save(u); session.beginTransaction().commit(); session.close(); return "login"; } public String login(){ String hql = "from User where username = ? and userpwd = ?"; Query query = session.createQuery(hql); query.setString(0, u.getUserName()); query.setString(1, u.getUserPwd()); u = (User) query.uniqueResult(); if(u==null){ tip = "用户名或密码错误!"; return "login"; }else{ String hql2 = "from Leaveform where asker.userId = ? "; Query query2 = session.createQuery(hql2); query2.setInteger(0, u.getUserId()); listStu = query2.list(); for (Leaveform leaveform : listStu) { System.out.println(leaveform); } return "studentLeave"; } } public String check(){ if(u.getUserName() == null){ tip="您还没有登录!"; return "login"; }else{ return "isStudent"; } } public String getAllLeave(){ String hql="from Leaveform where status = '新建'"; Query query = session.createQuery(hql); list = query.list(); return "leaveList"; } @Override public User getModel() { return u; } public User getU() { return u; } public String getTip() { return tip; } public Teacher getTea() { return tea; } public List<Leaveform> getList() { return list; } public List<Leaveform> getListStu() { return listStu; } }
UTF-8
Java
2,563
java
UserAction.java
Java
[ { "context": " teacher = new Teacher();\r\n\t\tteacher.setUserName(\"老师1\");\r\n\t\tteacher.setRealName(u.getTeacher().getUserN", "end": 861, "score": 0.9990429282188416, "start": 858, "tag": "USERNAME", "value": "老师1" }, { "context": "tTeacher().getUserName());\r\n\t\tteacher.setUse...
null
[]
package com.tc25.action; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.junit.Test; import com.opensymphony.xwork2.ModelDriven; import com.tc25.HButil.HBUtils; import com.tc25.entity.Job; import com.tc25.entity.Leaveform; import com.tc25.entity.Teacher; import com.tc25.entity.User; public class UserAction implements ModelDriven<User>{ private User u = new User(); private String tip; private Session session = HBUtils.getSession(); private Teacher tea = new Teacher(); private List<Leaveform> list = null; private List<Leaveform> listStu = null; public String regist(){ System.out.println(u); //设置角色 Job j = new Job(); j.setJobName(u.getJob().getJobName()); session.save(j); //设置老师 Teacher teacher = new Teacher(); teacher.setUserName("老师1"); teacher.setRealName(u.getTeacher().getUserName()); teacher.setUserPwd("<PASSWORD>"); session.save(teacher); //保存到用户对象中 u.setJob(j); u.setTeacher(teacher); session.save(u); session.beginTransaction().commit(); session.close(); return "login"; } public String login(){ String hql = "from User where username = ? and userpwd = ?"; Query query = session.createQuery(hql); query.setString(0, u.getUserName()); query.setString(1, u.getUserPwd()); u = (User) query.uniqueResult(); if(u==null){ tip = "用户名或密码错误!"; return "login"; }else{ String hql2 = "from Leaveform where asker.userId = ? "; Query query2 = session.createQuery(hql2); query2.setInteger(0, u.getUserId()); listStu = query2.list(); for (Leaveform leaveform : listStu) { System.out.println(leaveform); } return "studentLeave"; } } public String check(){ if(u.getUserName() == null){ tip="您还没有登录!"; return "login"; }else{ return "isStudent"; } } public String getAllLeave(){ String hql="from Leaveform where status = '新建'"; Query query = session.createQuery(hql); list = query.list(); return "leaveList"; } @Override public User getModel() { return u; } public User getU() { return u; } public String getTip() { return tip; } public Teacher getTea() { return tea; } public List<Leaveform> getList() { return list; } public List<Leaveform> getListStu() { return listStu; } }
2,569
0.620441
0.61002
139
15.94964
15.821543
62
false
false
0
0
0
0
0
0
1.841727
false
false
2
5845bd28125a1905ca88182c84b55ea9edfa4fba
12,498,354,875,467
09fb5a9ca92e413ec9b2167b77fba9063132e950
/src/com/example/gerenciador/GerenciadorDb.java
4230b70788fd54bdb0d200835e4d3a5809f5e2a1
[]
no_license
salesqueiroha/Suapinho
https://github.com/salesqueiroha/Suapinho
80d114a5507f93af023fca1ae7f38ac7237185df
76c8e6d8e916bcbfcc1d600f9e5d5b86523a4fc7
refs/heads/master
2021-01-10T18:59:43.383000
2013-09-13T10:56:21
2013-09-13T10:56:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.gerenciador; public class GerenciadorDb { }
UTF-8
Java
67
java
GerenciadorDb.java
Java
[]
null
[]
package com.example.gerenciador; public class GerenciadorDb { }
67
0.776119
0.776119
6
10.166667
14.076181
32
false
false
0
0
0
0
0
0
0.166667
false
false
2
b8bf5af8380e71a74fd07b07ff485d994df45036
13,529,147,023,452
fb9ca3477b4fae83be6dbb8412132c84499a1e5d
/src/main/java/org/kly/javaCode/springCode/aop/impl/AopServiceImpl.java
3079c3c011bc95cbfe31614b4f033be558f040e8
[]
no_license
Colia1994/BasicSkills
https://github.com/Colia1994/BasicSkills
88abb44f69c277d54dd583de8beda74ed3fbc518
117e554036b5fc4a2f676cd07c6c18109aef91ec
refs/heads/master
2021-01-01T16:23:53.831000
2020-08-05T13:26:37
2020-08-05T13:26:37
97,815,407
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.kly.javaCode.springCode.aop.impl; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.kly.javaCode.springCode.aop.AopService; import org.kly.javaCode.springCode.aop.annotation.Validate; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @Author konglingyao * @Date 2018/9/6 */ @Service public class AopServiceImpl implements AopService { private static ObjectMapper mapper = new ObjectMapper(); static { // mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); // mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); //该特性决定parser是否允许JSON字符串包含非引号控制字符(值小于32的ASCII字符,包含制表符和换行符)。 如果该属性关闭,则如果遇到这些字符,则会抛出异常。 } public boolean complateAop() { String json = "{2:{\"pid\":\"2\",\"url\":\"http://item.jd.com/2.html\"}}"; try { Map<String, Map<String, Object>> imap; imap = mapper.readValue(json, new TypeReference<Map<String, Map<String, Object>>>() { }); System.out.println(imap); System.out.println(imap.get(2L)); System.out.println(imap.get("2")); } catch (JsonParseException e) { System.out.println("json2Map(), 出错的json内容:" + " ,JsonParseException: " + e.getMessage()); } catch (JsonMappingException e) { System.out.println("json2Map(), 出错的json内容:" + " ,JsonMappingException: " + e.getMessage()); } catch (IOException e) { System.out.println("json2Map(), 出错的json内容为:" + " ,IOException: " + e.getMessage()); } System.out.println("程序运行"); return true; } @Validate(value = "#{str}") @Override public void del(String str) { if (org.apache.commons.lang3.StringUtils.isBlank(str)) { System.out.println("null"); } System.out.println(str); } private void printInt() { HashMap<Long, String> imap = new HashMap<>(); imap.put(2L, "2ahmadabad"); String asd = "2"; System.out.println(imap.get(parseLong(asd))); } private static long parseLong(Object origin) { long result = 0; if (origin == null) { return result; } String s = origin.toString(); if (!isDigit(s)) { return result; } try { result = Long.parseLong(s); } catch (Exception ignored) { } return result; } /** * 判断是纯数字 */ private static boolean isDigit(Object origin) { if (null == origin) { return false; } String value = origin.toString(); if (StringUtils.isEmpty(value)) { return false; } for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c < 48 || c > 57) { return false; } } return true; } }
UTF-8
Java
3,604
java
AopServiceImpl.java
Java
[ { "context": "til.HashMap;\nimport java.util.Map;\n\n/**\n * @Author konglingyao\n * @Date 2018/9/6\n */\n@Service\npublic class AopSe", "end": 622, "score": 0.9994366765022278, "start": 611, "tag": "USERNAME", "value": "konglingyao" } ]
null
[]
package org.kly.javaCode.springCode.aop.impl; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.kly.javaCode.springCode.aop.AopService; import org.kly.javaCode.springCode.aop.annotation.Validate; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @Author konglingyao * @Date 2018/9/6 */ @Service public class AopServiceImpl implements AopService { private static ObjectMapper mapper = new ObjectMapper(); static { // mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); // mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); //该特性决定parser是否允许JSON字符串包含非引号控制字符(值小于32的ASCII字符,包含制表符和换行符)。 如果该属性关闭,则如果遇到这些字符,则会抛出异常。 } public boolean complateAop() { String json = "{2:{\"pid\":\"2\",\"url\":\"http://item.jd.com/2.html\"}}"; try { Map<String, Map<String, Object>> imap; imap = mapper.readValue(json, new TypeReference<Map<String, Map<String, Object>>>() { }); System.out.println(imap); System.out.println(imap.get(2L)); System.out.println(imap.get("2")); } catch (JsonParseException e) { System.out.println("json2Map(), 出错的json内容:" + " ,JsonParseException: " + e.getMessage()); } catch (JsonMappingException e) { System.out.println("json2Map(), 出错的json内容:" + " ,JsonMappingException: " + e.getMessage()); } catch (IOException e) { System.out.println("json2Map(), 出错的json内容为:" + " ,IOException: " + e.getMessage()); } System.out.println("程序运行"); return true; } @Validate(value = "#{str}") @Override public void del(String str) { if (org.apache.commons.lang3.StringUtils.isBlank(str)) { System.out.println("null"); } System.out.println(str); } private void printInt() { HashMap<Long, String> imap = new HashMap<>(); imap.put(2L, "2ahmadabad"); String asd = "2"; System.out.println(imap.get(parseLong(asd))); } private static long parseLong(Object origin) { long result = 0; if (origin == null) { return result; } String s = origin.toString(); if (!isDigit(s)) { return result; } try { result = Long.parseLong(s); } catch (Exception ignored) { } return result; } /** * 判断是纯数字 */ private static boolean isDigit(Object origin) { if (null == origin) { return false; } String value = origin.toString(); if (StringUtils.isEmpty(value)) { return false; } for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c < 48 || c > 57) { return false; } } return true; } }
3,604
0.598361
0.590749
120
27.466667
25.914904
103
false
false
0
0
0
0
0
0
0.575
false
false
2
26a24edc769a5ec0f312abc8db403ae531ec89d8
4,011,499,479,958
92d09e5f8acf4117199357f31521d009489aaf22
/core/src/main/java/com/infoshareacademy/jjdd6/czfureczka/searchForRouteShortName/RouteIdForStopId.java
4e81c69bf28889aaa37a770a997d909a2411c1aa
[]
no_license
infoshareacademy/jjdd6-czfureczka
https://github.com/infoshareacademy/jjdd6-czfureczka
eaf2ddb3fca03ca8e13e4b104f053527ae55a096
83a580672291b56a5bfbfec8e3913ec64b663c3a
refs/heads/develop
2020-05-01T17:35:56.448000
2019-05-20T21:53:52
2019-05-20T21:53:53
177,604,060
0
0
null
false
2019-05-20T21:53:54
2019-03-25T14:36:11
2019-05-20T15:51:01
2019-05-20T21:53:53
17,409
0
0
0
Java
false
false
package com.infoshareacademy.jjdd6.czfureczka.searchForRouteShortName; import com.infoshareacademy.jjdd6.czfureczka.model.StopInTrip; import com.infoshareacademy.jjdd6.czfureczka.repository.Repository; import javax.ejb.Stateless; import java.util.List; import java.util.stream.Collectors; @Stateless public class RouteIdForStopId { public List<Integer> routeIdForStopId(List<Integer> stopId) { List<StopInTrip> newStopInTrip = Repository.getInstance().getStopsInTrip(); List<Integer> stopIdsInTrip = newStopInTrip.stream() .filter(s -> stopId.contains(s.getStopId())) .map(s -> s.getRouteId()) .distinct() .collect(Collectors.toList()); return stopIdsInTrip; } }
UTF-8
Java
764
java
RouteIdForStopId.java
Java
[]
null
[]
package com.infoshareacademy.jjdd6.czfureczka.searchForRouteShortName; import com.infoshareacademy.jjdd6.czfureczka.model.StopInTrip; import com.infoshareacademy.jjdd6.czfureczka.repository.Repository; import javax.ejb.Stateless; import java.util.List; import java.util.stream.Collectors; @Stateless public class RouteIdForStopId { public List<Integer> routeIdForStopId(List<Integer> stopId) { List<StopInTrip> newStopInTrip = Repository.getInstance().getStopsInTrip(); List<Integer> stopIdsInTrip = newStopInTrip.stream() .filter(s -> stopId.contains(s.getStopId())) .map(s -> s.getRouteId()) .distinct() .collect(Collectors.toList()); return stopIdsInTrip; } }
764
0.70288
0.698953
23
32.217392
26.837606
83
false
false
0
0
0
0
0
0
0.391304
false
false
2
8cf454935b4de6eb5852d0c3affaae7e00df5648
20,538,533,639,679
93141239429e90b654f44eb42c6fb33de1ed3dd0
/src/entidades/Provincia.java
a3bc39633de9fb0b560b101c28e9060379aa76d2
[]
no_license
Franco-Hasper/SisemaSeguros
https://github.com/Franco-Hasper/SisemaSeguros
d1b6a7fa1a0a06bb1b033c44a36fa6360dc092d8
380ebb95a56b0b443c49d0a3fbde85bb9cd88ec8
refs/heads/master
2022-12-28T13:22:53.032000
2020-10-14T01:54:46
2020-10-14T01:54:46
274,511,273
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entidades; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author TELCOM MPC */ @Entity @Table(name = "provincia") public class Provincia { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "nombre") private String nombre; @OneToMany(mappedBy = "provinciaId") private List<Localidad> localidades; public Provincia() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public List<Localidad> getLocalidades() { return localidades; } public void setLocalidades(List<Localidad> localidades) { this.localidades = localidades; } }
UTF-8
Java
1,144
java
Provincia.java
Java
[ { "context": "import javax.persistence.Table;\n\n/**\n *\n * @author TELCOM MPC\n */\n@Entity\n@Table(name = \"provincia\")\npublic", "end": 313, "score": 0.8536519408226013, "start": 307, "tag": "NAME", "value": "TELCOM" }, { "context": "javax.persistence.Table;\n\n/**\n *\n * @auth...
null
[]
package entidades; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author TELCOM MPC */ @Entity @Table(name = "provincia") public class Provincia { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "nombre") private String nombre; @OneToMany(mappedBy = "provinciaId") private List<Localidad> localidades; public Provincia() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public List<Localidad> getLocalidades() { return localidades; } public void setLocalidades(List<Localidad> localidades) { this.localidades = localidades; } }
1,144
0.653846
0.653846
63
17.15873
16.293154
61
false
false
0
0
0
0
0
0
0.285714
false
false
2
40b5e9808d79ae109941e50da0af74225bf6f9e6
18,571,438,617,239
9def97e284d4f7813754bbecec3ffa584bd677ae
/src/main/java/com/codingcompetition/statefarm/Category.java
43c39ef5dce7f55ab4bbe96707f830196b13fb6f
[]
no_license
HemangRajvanshy/2018-StateFarm-CodingCompetitionProblem
https://github.com/HemangRajvanshy/2018-StateFarm-CodingCompetitionProblem
497d77d366b09ff66935704c78f6cf39332ab4da
10ff9095dace2a16b562028749d7d061b88bbefd
refs/heads/master
2020-04-01T05:58:08.569000
2018-10-14T04:58:30
2018-10-14T04:58:30
152,927,525
0
1
null
true
2018-10-14T01:02:14
2018-10-14T01:02:14
2018-10-14T01:00:44
2018-10-14T01:00:40
0
0
0
0
null
false
null
package com.codingcompetition.statefarm; import com.codingcompetition.statefarm.model.PointOfInterest; import java.util.function.BiFunction; import static com.codingcompetition.statefarm.MatchingStrategy.ENDS_WITH; import static com.codingcompetition.statefarm.MatchingStrategy.EXACT_MATCH; import static com.codingcompetition.statefarm.MatchingStrategy.STARTS_WITH; public enum Category { LEISURE, NAME, AMENITY, CUISINE, SHOP, WHEELCHAIR, HIGHWAY, PLACE, POPULATION, POWER, BUILDING, BEAUTY, NAMESTARTSWITH, NAMEENDSWITH; }
UTF-8
Java
535
java
Category.java
Java
[]
null
[]
package com.codingcompetition.statefarm; import com.codingcompetition.statefarm.model.PointOfInterest; import java.util.function.BiFunction; import static com.codingcompetition.statefarm.MatchingStrategy.ENDS_WITH; import static com.codingcompetition.statefarm.MatchingStrategy.EXACT_MATCH; import static com.codingcompetition.statefarm.MatchingStrategy.STARTS_WITH; public enum Category { LEISURE, NAME, AMENITY, CUISINE, SHOP, WHEELCHAIR, HIGHWAY, PLACE, POPULATION, POWER, BUILDING, BEAUTY, NAMESTARTSWITH, NAMEENDSWITH; }
535
0.833645
0.833645
14
37.214287
40.650387
137
false
false
0
0
0
0
0
0
1.428571
false
false
2
61a9b4579bf14c5d90d2fd9e27d871a8c30efed6
20,409,684,616,911
5a77449ff1627e7b80ff6a4a415028d117c01c11
/Array/SlidingWindowMaximum.java
380be6b2fee299876a21ebf0cff8ab2040d44dd1
[]
no_license
walkman-kuan/leetcode-practice
https://github.com/walkman-kuan/leetcode-practice
5d31c62886de33429814399f24cd08b38d89151a
8ef8929d878c29dc52506ad87a0170c31aa45870
refs/heads/master
2018-07-30T14:27:31.454000
2018-07-22T03:55:21
2018-07-22T03:55:21
108,755,239
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Q: Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Therefore, return the max sliding window as [3,3,5,5,6,7]. Note: You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array. Follow up: Could you solve it in linear time? */ // Deque to keep track of the maximum of current window. Remove the maximum if it's the left most value of current window. public class SlidingWindowMaximum { public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0 || nums.length < k || k == 0) { return nums; } int[] maxs = new int[nums.length - k + 1]; // Construct an empty array deque an initial capacity k Deque<Integer> maxsDeque = new ArrayDeque<>(k); // Perform enqueue operations for the first k - 1 elements for (int i = 0; i < k - 1; i++) { enqueue(maxsDeque, nums[i]); } // Continue from k-th element, find a maximum for each window for (int j = k - 1; j < nums.length; j++) { enqueue(maxsDeque, nums[j]); maxs[j - k + 1] = maxsDeque.peekFirst(); dequeue(maxsDeque, nums[j - k + 1]); } return maxs; } // enqueue makes sure that the maximum value is at the head of Deque. // Remove any nums[x] where x is in [j - k + 1, j] and nums[x] < nums[j]. // If nums[x] < nums[j], nums[x] must not be a maximum of the window [j - k + 1, j] private void enqueue(Deque<Integer> maxsDeque, int value) { while (!maxsDeque.isEmpty() && maxsDeque.peekLast() < value) { maxsDeque.pollLast(); } maxsDeque.offerLast(value); } // If maximum is the left most element, we need to remove it since // it can't be used in the next window private void dequeue(Deque<Integer> maxsDeque, int leftMostValue) { if (maxsDeque.peekFirst() == leftMostValue) { maxsDeque.pollFirst(); } } }
UTF-8
Java
2,497
java
SlidingWindowMaximum.java
Java
[]
null
[]
/* Q: Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Therefore, return the max sliding window as [3,3,5,5,6,7]. Note: You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array. Follow up: Could you solve it in linear time? */ // Deque to keep track of the maximum of current window. Remove the maximum if it's the left most value of current window. public class SlidingWindowMaximum { public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0 || nums.length < k || k == 0) { return nums; } int[] maxs = new int[nums.length - k + 1]; // Construct an empty array deque an initial capacity k Deque<Integer> maxsDeque = new ArrayDeque<>(k); // Perform enqueue operations for the first k - 1 elements for (int i = 0; i < k - 1; i++) { enqueue(maxsDeque, nums[i]); } // Continue from k-th element, find a maximum for each window for (int j = k - 1; j < nums.length; j++) { enqueue(maxsDeque, nums[j]); maxs[j - k + 1] = maxsDeque.peekFirst(); dequeue(maxsDeque, nums[j - k + 1]); } return maxs; } // enqueue makes sure that the maximum value is at the head of Deque. // Remove any nums[x] where x is in [j - k + 1, j] and nums[x] < nums[j]. // If nums[x] < nums[j], nums[x] must not be a maximum of the window [j - k + 1, j] private void enqueue(Deque<Integer> maxsDeque, int value) { while (!maxsDeque.isEmpty() && maxsDeque.peekLast() < value) { maxsDeque.pollLast(); } maxsDeque.offerLast(value); } // If maximum is the left most element, we need to remove it since // it can't be used in the next window private void dequeue(Deque<Integer> maxsDeque, int leftMostValue) { if (maxsDeque.peekFirst() == leftMostValue) { maxsDeque.pollFirst(); } } }
2,497
0.567589
0.535098
71
34.112675
29.611832
122
false
false
0
0
0
0
0
0
0.690141
false
false
2
8f2437b2ea711ee2fd978ecafe087adf42ab5977
19,327,352,834,510
d5f09c7b0e954cd20dd613af600afd91b039c48a
/sources/mtopsdk/xstate/a.java
80f066a0081ea28dc1dfca6936946a5f514ab6a8
[]
no_license
t0HiiBwn/CoolapkRelease
https://github.com/t0HiiBwn/CoolapkRelease
af5e00c701bf82c4e90b1033f5c5f9dc8526f4b3
a6a2b03e32cde0e5163016e0078391271a8d33ab
refs/heads/main
2022-07-29T23:28:35.867000
2021-03-26T11:41:18
2021-03-26T11:41:18
345,290,891
5
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package mtopsdk.xstate; import mtopsdk.common.util.AsyncServiceBinder; import mtopsdk.mtop.util.MtopSDKThreadPoolExecutorFactory; import mtopsdk.xstate.aidl.IXState; /* compiled from: XState */ final class a extends AsyncServiceBinder<IXState> { a(Class cls, Class cls2) { super(cls, cls2); } @Override // mtopsdk.common.util.AsyncServiceBinder protected final void afterAsyncBind() { XState.a.compareAndSet(true, false); MtopSDKThreadPoolExecutorFactory.submit(new b(this)); } }
UTF-8
Java
527
java
a.java
Java
[]
null
[]
package mtopsdk.xstate; import mtopsdk.common.util.AsyncServiceBinder; import mtopsdk.mtop.util.MtopSDKThreadPoolExecutorFactory; import mtopsdk.xstate.aidl.IXState; /* compiled from: XState */ final class a extends AsyncServiceBinder<IXState> { a(Class cls, Class cls2) { super(cls, cls2); } @Override // mtopsdk.common.util.AsyncServiceBinder protected final void afterAsyncBind() { XState.a.compareAndSet(true, false); MtopSDKThreadPoolExecutorFactory.submit(new b(this)); } }
527
0.73055
0.726755
18
28.277779
21.444517
61
false
false
0
0
0
0
0
0
0.555556
false
false
2
0bc4896fbc98aae88ef8538040072614f4689d68
12,266,426,615,661
3314d9afb9971361c74d9951384f4cb000ccb1a1
/Idea_Java_EE/ee/src/cdi/DiSpecializationExample.java
24334c1080ec81bba6cc89a25a310447544a2b09
[]
no_license
RyabcevPM/rpm.stady
https://github.com/RyabcevPM/rpm.stady
cf51fc7f75714a2a485247e04b0cf0cbdf84b812
d24bcbf81c57a97a54d058a4c9470266459887a1
refs/heads/master
2021-05-25T10:31:45.109000
2020-09-22T12:48:10
2020-09-22T12:48:10
127,105,367
0
0
null
false
2018-05-11T13:15:59
2018-03-28T08:00:51
2018-05-11T12:43:10
2018-05-11T13:15:41
6
0
0
0
Java
false
null
package cdi; import javax.enterprise.inject.Specializes; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/di8") public class DiSpecializationExample extends HttpServlet { @Inject IMan man; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { man.printName(); resp.getWriter().write("DiSpecializationExample: Hello!"); } } interface IMan{ void printName(); } class SuperMan implements IMan { @Override public void printName() { System.out.println("I'm Bill!"); } } @Specializes class Paco extends SuperMan { @Override public void printName() { System.out.println("I'm Paco, baby!"); } }
UTF-8
Java
977
java
DiSpecializationExample.java
Java
[ { "context": "void printName() {\n System.out.println(\"I'm Bill!\");\n }\n}\n\n@Specializes\nclass Paco extends Supe", "end": 820, "score": 0.9937940835952759, "start": 816, "tag": "NAME", "value": "Bill" }, { "context": "void printName() {\n System.out.println(\"I'...
null
[]
package cdi; import javax.enterprise.inject.Specializes; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/di8") public class DiSpecializationExample extends HttpServlet { @Inject IMan man; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { man.printName(); resp.getWriter().write("DiSpecializationExample: Hello!"); } } interface IMan{ void printName(); } class SuperMan implements IMan { @Override public void printName() { System.out.println("I'm Bill!"); } } @Specializes class Paco extends SuperMan { @Override public void printName() { System.out.println("I'm Paco, baby!"); } }
977
0.725691
0.724667
41
22.804878
22.85289
113
false
false
0
0
0
0
0
0
0.439024
false
false
2
33a9b4e363eec24e8f97473af043f879ddd8c923
26,010,321,975,435
1255fce290d981fec996405230abee94e0f3fa17
/Moccha-Android/src/de/tel/moccha/activities/fragments/CategoryListFragment.java
15254059b54eb9aa1f8d6466451147899cb994ee
[ "Apache-2.0" ]
permissive
QULab/MoCCha-Android
https://github.com/QULab/MoCCha-Android
ad1a5be8cf4f9b7fa0375844ca7684c28ef99580
f25cdb3063d869b55535857993a5a68cbf20c5e1
refs/heads/master
2021-03-12T23:54:02.079000
2015-07-17T11:23:35
2015-07-17T11:23:35
29,012,339
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2015 Quality and Usability Lab, Telekom Innvation Laboratories, TU Berlin.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tel.moccha.activities.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import de.tel.moccha.entities.Category; import de.tel.moccha.entities.course.CategoryNameConverter; import de.zell.android.util.activities.MainNavigationActivity; import de.zell.android.util.adapters.EntityListAdapter; import de.zell.android.util.async.AsyncGETRequester; import de.zell.android.util.async.GetRequestInfo; import de.zell.android.util.db.Entity; import de.zell.android.util.fragments.ActionBarTitleManager; import de.zell.android.util.fragments.EntityListFragment; import de.zell.android.util.fragments.FragmentReplacer; import de.zell.android.util.json.JSONUnmarshaller; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Represents the category list fragment which shows the * current categories. * * For example different universities or event categories. * * @author Christopher Zell <zelldon91@googlemail.com> */ public abstract class CategoryListFragment extends EntityListFragment { /** * The json key to extract the categories json array. */ public static final String JSON_CATEGORY_KEY = "categories"; public abstract Bundle getArgumentsForFragment(Category c); public abstract Fragment getOnClickFragment(); @Override protected void onEntityClick(Entity e) { Category c = (Category) e; Fragment frg = getOnClickFragment(); if (frg != null) { Bundle bundle = getArgumentsForFragment(c); bundle.putString(ActionBarTitleManager.ARG_ACTION_BAR_TITLE, CategoryNameConverter.getLongName(c.getName())); frg.setArguments(bundle); FragmentReplacer.replace(getActivity().getSupportFragmentManager(), frg, FragmentReplacer.MAIN_CONTENT); } } @Override protected void onSectionClick(Object o) { //do nothing } @Override protected void loadEntities() { AsyncGETRequester request = new AsyncGETRequester(new AsyncGETRequester.PostExecuteJob() { public void doJob(JSONObject response) { if (entities == null) entities = new ArrayList<Entity>(); try { JSONArray categories = response.getJSONArray(JSON_CATEGORY_KEY); int len = categories.length(); for (int i = 0; i < len; i++) { JSONObject obj = categories.getJSONObject(i); entities.add(JSONUnmarshaller.unmarshall(obj, Category.class)); } } catch (JSONException ex) { Log.e(CategoryListFragment.class.getName(), ex.getMessage(), ex); } EntityListAdapter adapter = (EntityListAdapter) getListAdapter(); adapter.setEntities(entities); adapter.notifyDataSetChanged(); } public void doExeptionHandling(Throwable t) { if (t != null) Log.e(CategoryListFragment.class.getName(), t.getMessage(), t); } public void handleNewEtag(String url, String newEtag) { //TODO } }); request.showProgress(((MainNavigationActivity) getActivity()).getProgressBar()); GetRequestInfo info = new GetRequestInfo(getURL(), null); request.execute(info); } }
UTF-8
Java
4,061
java
CategoryListFragment.java
Java
[ { "context": "universities or event categories.\r\n * \r\n * @author Christopher Zell <zelldon91@googlemail.com>\r\n */\r\npublic abstract ", "end": 1713, "score": 0.9997918009757996, "start": 1697, "tag": "NAME", "value": "Christopher Zell" }, { "context": "nt categories.\r\n * \r\n...
null
[]
/* * Copyright 2015 Quality and Usability Lab, Telekom Innvation Laboratories, TU Berlin.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tel.moccha.activities.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import de.tel.moccha.entities.Category; import de.tel.moccha.entities.course.CategoryNameConverter; import de.zell.android.util.activities.MainNavigationActivity; import de.zell.android.util.adapters.EntityListAdapter; import de.zell.android.util.async.AsyncGETRequester; import de.zell.android.util.async.GetRequestInfo; import de.zell.android.util.db.Entity; import de.zell.android.util.fragments.ActionBarTitleManager; import de.zell.android.util.fragments.EntityListFragment; import de.zell.android.util.fragments.FragmentReplacer; import de.zell.android.util.json.JSONUnmarshaller; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Represents the category list fragment which shows the * current categories. * * For example different universities or event categories. * * @author <NAME> <<EMAIL>> */ public abstract class CategoryListFragment extends EntityListFragment { /** * The json key to extract the categories json array. */ public static final String JSON_CATEGORY_KEY = "categories"; public abstract Bundle getArgumentsForFragment(Category c); public abstract Fragment getOnClickFragment(); @Override protected void onEntityClick(Entity e) { Category c = (Category) e; Fragment frg = getOnClickFragment(); if (frg != null) { Bundle bundle = getArgumentsForFragment(c); bundle.putString(ActionBarTitleManager.ARG_ACTION_BAR_TITLE, CategoryNameConverter.getLongName(c.getName())); frg.setArguments(bundle); FragmentReplacer.replace(getActivity().getSupportFragmentManager(), frg, FragmentReplacer.MAIN_CONTENT); } } @Override protected void onSectionClick(Object o) { //do nothing } @Override protected void loadEntities() { AsyncGETRequester request = new AsyncGETRequester(new AsyncGETRequester.PostExecuteJob() { public void doJob(JSONObject response) { if (entities == null) entities = new ArrayList<Entity>(); try { JSONArray categories = response.getJSONArray(JSON_CATEGORY_KEY); int len = categories.length(); for (int i = 0; i < len; i++) { JSONObject obj = categories.getJSONObject(i); entities.add(JSONUnmarshaller.unmarshall(obj, Category.class)); } } catch (JSONException ex) { Log.e(CategoryListFragment.class.getName(), ex.getMessage(), ex); } EntityListAdapter adapter = (EntityListAdapter) getListAdapter(); adapter.setEntities(entities); adapter.notifyDataSetChanged(); } public void doExeptionHandling(Throwable t) { if (t != null) Log.e(CategoryListFragment.class.getName(), t.getMessage(), t); } public void handleNewEtag(String url, String newEtag) { //TODO } }); request.showProgress(((MainNavigationActivity) getActivity()).getProgressBar()); GetRequestInfo info = new GetRequestInfo(getURL(), null); request.execute(info); } }
4,034
0.687762
0.684807
112
34.25893
27.26613
115
false
false
0
0
0
0
0
0
0.544643
false
false
2
aa3af9018903dbab5f1c65f77484faf55d012175
20,014,547,644,176
bd673bf457a72e9cead5e3dd26eb93610b28158c
/F1-Data/src/com/freq/parser/OfficialSitePageParser.java
a96c1f5f57ab6125be126a48e72bc0c7d959cd2b
[]
no_license
audiofreq/tropefisher
https://github.com/audiofreq/tropefisher
703c4e267c3fb6815f298c78a9f3557b0a9582be
55566994d70a9b21645fa42b0305f3f78d440e6f
refs/heads/master
2020-12-30T09:38:11.618000
2012-12-30T19:33:04
2012-12-30T19:33:04
32,737,559
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.freq.parser; import java.util.HashMap; import java.util.Iterator; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.freq.main.Driver; public class OfficialSitePageParser { private HashMap<String, Driver> driverMap; public OfficialSitePageParser() { driverMap = new HashMap<String, Driver>(); } public void parsePage(Document page, int session, int type) { //System.out.println(""); String header = page.getElementsByClass("raceResultsHeading").first() .getElementsByTag("h2").first().text(); String year = header.substring(0, 4); Elements results = page.getElementsByClass("raceResults").first() .getElementsByTag("tr"); results.remove(0); for (Element result : results) { Elements values = result.getElementsByTag("td"); if(session == OfficialSite.SESSION_PRACTICE){ if(type == OfficialSite.TYPE_RESULT){ HashMap<String,String> data = practiceResult(values); Driver driver = getOrPut(data.get("drivername")); } } //System.out.println(pos + ":" + name + ":" + laps); } } public void printResultSummary(){ Iterator<Driver> driveIT = driverMap.values().iterator(); while(driveIT.hasNext()){ Driver d = driveIT.next(); System.out.println(d.toString()); } System.out.println(driverMap.size()); } public HashMap<String,String> practiceResult(Elements values){ HashMap<String,String> result = new HashMap<String,String>(); result.put("carno", values.get(1).text()); result.put("drivername", values.get(2).text()); result.put("team", values.get(3).text()); result.put("time", values.get(4).text()); result.put("gap", values.get(5).text()); result.put("laps", values.get(6).text()); return result; } private Driver getOrPut(String name) { Driver val; if(!driverMap.containsKey(name)){ val = new Driver(name); driverMap.put(name,val); }else val = driverMap.get(name); return val; } }
UTF-8
Java
2,107
java
OfficialSitePageParser.java
Java
[]
null
[]
package com.freq.parser; import java.util.HashMap; import java.util.Iterator; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.freq.main.Driver; public class OfficialSitePageParser { private HashMap<String, Driver> driverMap; public OfficialSitePageParser() { driverMap = new HashMap<String, Driver>(); } public void parsePage(Document page, int session, int type) { //System.out.println(""); String header = page.getElementsByClass("raceResultsHeading").first() .getElementsByTag("h2").first().text(); String year = header.substring(0, 4); Elements results = page.getElementsByClass("raceResults").first() .getElementsByTag("tr"); results.remove(0); for (Element result : results) { Elements values = result.getElementsByTag("td"); if(session == OfficialSite.SESSION_PRACTICE){ if(type == OfficialSite.TYPE_RESULT){ HashMap<String,String> data = practiceResult(values); Driver driver = getOrPut(data.get("drivername")); } } //System.out.println(pos + ":" + name + ":" + laps); } } public void printResultSummary(){ Iterator<Driver> driveIT = driverMap.values().iterator(); while(driveIT.hasNext()){ Driver d = driveIT.next(); System.out.println(d.toString()); } System.out.println(driverMap.size()); } public HashMap<String,String> practiceResult(Elements values){ HashMap<String,String> result = new HashMap<String,String>(); result.put("carno", values.get(1).text()); result.put("drivername", values.get(2).text()); result.put("team", values.get(3).text()); result.put("time", values.get(4).text()); result.put("gap", values.get(5).text()); result.put("laps", values.get(6).text()); return result; } private Driver getOrPut(String name) { Driver val; if(!driverMap.containsKey(name)){ val = new Driver(name); driverMap.put(name,val); }else val = driverMap.get(name); return val; } }
2,107
0.646417
0.641671
89
21.674158
21.340879
71
false
false
0
0
0
0
0
0
2.146067
false
false
2
680b7471daa1818d48732f82b6e3b9c2a013ab01
15,247,133,947,614
0b4bdea018adda14d13627e4aa2317e7a222fbd4
/src/main/java/mcjty/enigma/code/actions/IfAction.java
f2a4ba9f4b76ca8693518678c472cfaa8e55a9e6
[ "MIT" ]
permissive
McJtyMods/Enigma
https://github.com/McJtyMods/Enigma
882d52a2a100be05fbe2d09f2a81b795b987578d
d1949a8a1eaa8a2b2d3da51a26f6e7685944cddd
refs/heads/1.12
2023-06-21T23:13:15.898000
2023-06-13T14:18:29
2023-06-13T14:18:29
89,237,054
2
2
MIT
false
2023-06-02T06:06:37
2017-04-24T12:22:47
2023-05-31T13:57:28
2023-06-02T06:06:36
610
3
1
0
Java
false
false
package mcjty.enigma.code.actions; import mcjty.enigma.code.Action; import mcjty.enigma.code.ActionBlock; import mcjty.enigma.code.EnigmaFunctionContext; import mcjty.enigma.code.ExecutionException; import mcjty.enigma.parser.Expression; import mcjty.enigma.parser.ObjectTools; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class IfAction extends Action { @Nonnull private final Expression<EnigmaFunctionContext> condition; @Nullable private final ActionBlock positiveBlock; @Nullable private final ActionBlock negativeBlock; public IfAction(Expression<EnigmaFunctionContext> condition, ActionBlock positiveBlock, ActionBlock negativeBlock) { this.condition = condition; this.positiveBlock = positiveBlock; this.negativeBlock = negativeBlock; } @Override public void dump(int indent) { System.out.println(StringUtils.repeat(' ', indent) + "If"); if (positiveBlock != null) { positiveBlock.dump(indent); } if (negativeBlock != null) { System.out.println(StringUtils.repeat(' ', indent) + "Else"); negativeBlock.dump(indent); } } @Override public void execute(EnigmaFunctionContext context) throws ExecutionException { if (ObjectTools.asBoolSafe(condition.eval(context))) { if (positiveBlock != null) { positiveBlock.execute(context); } } else { if (negativeBlock != null) { negativeBlock.execute(context); } } } }
UTF-8
Java
1,640
java
IfAction.java
Java
[]
null
[]
package mcjty.enigma.code.actions; import mcjty.enigma.code.Action; import mcjty.enigma.code.ActionBlock; import mcjty.enigma.code.EnigmaFunctionContext; import mcjty.enigma.code.ExecutionException; import mcjty.enigma.parser.Expression; import mcjty.enigma.parser.ObjectTools; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class IfAction extends Action { @Nonnull private final Expression<EnigmaFunctionContext> condition; @Nullable private final ActionBlock positiveBlock; @Nullable private final ActionBlock negativeBlock; public IfAction(Expression<EnigmaFunctionContext> condition, ActionBlock positiveBlock, ActionBlock negativeBlock) { this.condition = condition; this.positiveBlock = positiveBlock; this.negativeBlock = negativeBlock; } @Override public void dump(int indent) { System.out.println(StringUtils.repeat(' ', indent) + "If"); if (positiveBlock != null) { positiveBlock.dump(indent); } if (negativeBlock != null) { System.out.println(StringUtils.repeat(' ', indent) + "Else"); negativeBlock.dump(indent); } } @Override public void execute(EnigmaFunctionContext context) throws ExecutionException { if (ObjectTools.asBoolSafe(condition.eval(context))) { if (positiveBlock != null) { positiveBlock.execute(context); } } else { if (negativeBlock != null) { negativeBlock.execute(context); } } } }
1,640
0.67622
0.67561
49
32.469387
25.044533
120
false
false
0
0
0
0
0
0
0.530612
false
false
2
ecf95cecbd29d65cad72eeae7c599a00943526c6
31,808,527,836,111
2e5bba4135ce29bd532c61bc72befcf32afae152
/MyStudyRecoder/Java/AnnotationTest/src/qmsggg/cl/Client.java
b1fba43738408d1f688ab622a3526c16f06655e3
[]
no_license
qmsggg/qmsggg_java
https://github.com/qmsggg/qmsggg_java
332f07a46584070cdddf05d4ea8a2b80f9161c1c
7503ed8b9949b4cce7588fb2fc696e958cf552b6
refs/heads/master
2020-03-21T10:29:06.761000
2018-08-12T03:34:47
2018-08-12T03:34:47
138,453,254
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package qmsggg.cl; @TestAnnotations2(count = 2) public class Client { public static void main(String[] args) { TestAnnotations2 annotations2 = Client.class.getAnnotation(TestAnnotations2.class); System.out.println(annotations2.count()); System.out.println(annotations2.count()); System.out.println(annotations2.annotationType()); } }
UTF-8
Java
377
java
Client.java
Java
[]
null
[]
package qmsggg.cl; @TestAnnotations2(count = 2) public class Client { public static void main(String[] args) { TestAnnotations2 annotations2 = Client.class.getAnnotation(TestAnnotations2.class); System.out.println(annotations2.count()); System.out.println(annotations2.count()); System.out.println(annotations2.annotationType()); } }
377
0.702918
0.681698
13
28
27.408588
91
false
false
0
0
0
0
0
0
0.384615
false
false
2
eae70a109f2ed46921d44f95c4e1fe286a612051
6,648,609,425,869
039f6540ccb81c365f34277ae18812eaac85c995
/src/Conccurency/ReentrantLockPrac.java
7be6c3052d00707bc93546630d83615bf3b09613
[]
no_license
Fan4530/Algorithm
https://github.com/Fan4530/Algorithm
6a45d2464762b6dbb68a1aae8c907c488b05f03f
2642f0c44354f586498e51235d24c519dfb33f53
refs/heads/master
2021-09-14T11:32:49.186000
2018-05-12T23:07:13
2018-05-12T23:07:13
106,373,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Conccurency; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by program on 12/7/2017. */ class ReentranQ { private Queue<Integer> q; private final int limit; private Lock lock; private Condition notFull; private Condition notEmpty; public ReentranQ(int limit) { this.limit = limit; q = new LinkedList(); this.lock = new ReentrantLock(); this.notFull = lock.newCondition();//和lock联系起来了,full 一直await,直到full siginal的时候,解锁,解lock这把锁 this.notEmpty = lock.newCondition(); } public void put(Integer ele) { lock.lock(); try{ while(q.size() == limit) { notFull.await(); } if(q.size() == 0) { notEmpty.signal();//给一个不满的信号,取弄醒所有因为空而睡着的take 线程 } q.offer(ele); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public Integer take() { lock.lock(); try{ while(q.size() == 0) { notEmpty.await(); } if(q.size() == limit) { notFull.signalAll(); } return q.poll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } return null; } } public class ReentrantLockPrac { public static void main(String [] args) { ReentranQ q = new ReentranQ(5); List<Thread> threads = new ArrayList<>(); final int[] count = {0}; for(int i = 0; i < 10; i ++) { threads.add(new Thread(){ public void run() { q.put(count[0]); System.out.println("put " + count[0]); count[0]++; } }); } for(int i = 0; i < 10; i ++) { threads.add(new Thread() { public void run() { System.out.println("Take " + q.take()); } }); } for(Thread t : threads) { t.start(); } } }
UTF-8
Java
2,481
java
ReentrantLockPrac.java
Java
[ { "context": "concurrent.locks.ReentrantLock;\n\n/**\n * Created by program on 12/7/2017.\n */\n\nclass ReentranQ {\n private ", "end": 286, "score": 0.9945486187934875, "start": 279, "tag": "USERNAME", "value": "program" } ]
null
[]
package Conccurency; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by program on 12/7/2017. */ class ReentranQ { private Queue<Integer> q; private final int limit; private Lock lock; private Condition notFull; private Condition notEmpty; public ReentranQ(int limit) { this.limit = limit; q = new LinkedList(); this.lock = new ReentrantLock(); this.notFull = lock.newCondition();//和lock联系起来了,full 一直await,直到full siginal的时候,解锁,解lock这把锁 this.notEmpty = lock.newCondition(); } public void put(Integer ele) { lock.lock(); try{ while(q.size() == limit) { notFull.await(); } if(q.size() == 0) { notEmpty.signal();//给一个不满的信号,取弄醒所有因为空而睡着的take 线程 } q.offer(ele); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public Integer take() { lock.lock(); try{ while(q.size() == 0) { notEmpty.await(); } if(q.size() == limit) { notFull.signalAll(); } return q.poll(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } return null; } } public class ReentrantLockPrac { public static void main(String [] args) { ReentranQ q = new ReentranQ(5); List<Thread> threads = new ArrayList<>(); final int[] count = {0}; for(int i = 0; i < 10; i ++) { threads.add(new Thread(){ public void run() { q.put(count[0]); System.out.println("put " + count[0]); count[0]++; } }); } for(int i = 0; i < 10; i ++) { threads.add(new Thread() { public void run() { System.out.println("Take " + q.take()); } }); } for(Thread t : threads) { t.start(); } } }
2,481
0.490163
0.481792
90
25.544445
16.672106
98
false
false
0
0
0
0
0
0
0.5
false
false
2
9846b6856326d566bc712a8167f6abdd22b986f8
23,089,744,219,075
c34fd563a668af7f79bb0aaafb5ea3d4856f9c7f
/src/Main.java
7208939914659954ef095aef400dd65787607ff3
[]
no_license
liuluke0325/GroceryList
https://github.com/liuluke0325/GroceryList
c5bdae4f1b9597beab9c4be414664b08af54fe2a
3d025f1c6ed993a2adeb7707e8bc70f4e0d28850
refs/heads/master
2020-05-18T14:27:42.756000
2019-05-01T20:05:55
2019-05-01T20:05:55
184,472,429
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Scanner; public class Main { private static GroceryList groceryList = new GroceryList(); private static Scanner scanner = new Scanner(System.in); public static void main(String [] args){ boolean flag = true; do { printMenu(); int select = scanner.nextInt(); scanner.nextLine(); switch (select){ case 1: System.out.println("Please enter the item name"); groceryList.addGroceryItem(scanner.nextLine()); break; case 2: groceryList.printGroceryItem(); break; case 3: System.out.println("Please enter the number you want to delete"); int option1 = scanner.nextInt(); scanner.nextLine(); groceryList.deleteGroceryItem(option1-1); break; case 4: System.out.println("Please enter the index you want to change"); int option = scanner.nextInt(); scanner.nextLine(); System.out.println("Please enter the new name of that item"); String newname = scanner.nextLine(); groceryList.modifiedGroceryItem(option-1,newname); break; case 5: System.out.println("Copy the array..."); break; case 0 : flag = false; System.out.println("Closing....."); break; default: System.out.println("Please Enter the correct number"); } System.out.println("------------------------------------"); }while(flag); } public static void printMenu(){ System.out.println("1. Add Item"); System.out.println("2. Display Item"); System.out.println("3. Delete Item"); System.out.println("4. Modified Item"); System.out.println("0. Exit the application"); System.out.println("\t Please enter the number: "); } public static void cpyArray(){ ArrayList<String> newArray= new ArrayList<String>(groceryList.getGrocerylist()); String [] nextArray = new String[groceryList.getGrocerylist().size()]; nextArray = groceryList.getGrocerylist().toArray(nextArray); } }
UTF-8
Java
2,551
java
Main.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.Scanner; public class Main { private static GroceryList groceryList = new GroceryList(); private static Scanner scanner = new Scanner(System.in); public static void main(String [] args){ boolean flag = true; do { printMenu(); int select = scanner.nextInt(); scanner.nextLine(); switch (select){ case 1: System.out.println("Please enter the item name"); groceryList.addGroceryItem(scanner.nextLine()); break; case 2: groceryList.printGroceryItem(); break; case 3: System.out.println("Please enter the number you want to delete"); int option1 = scanner.nextInt(); scanner.nextLine(); groceryList.deleteGroceryItem(option1-1); break; case 4: System.out.println("Please enter the index you want to change"); int option = scanner.nextInt(); scanner.nextLine(); System.out.println("Please enter the new name of that item"); String newname = scanner.nextLine(); groceryList.modifiedGroceryItem(option-1,newname); break; case 5: System.out.println("Copy the array..."); break; case 0 : flag = false; System.out.println("Closing....."); break; default: System.out.println("Please Enter the correct number"); } System.out.println("------------------------------------"); }while(flag); } public static void printMenu(){ System.out.println("1. Add Item"); System.out.println("2. Display Item"); System.out.println("3. Delete Item"); System.out.println("4. Modified Item"); System.out.println("0. Exit the application"); System.out.println("\t Please enter the number: "); } public static void cpyArray(){ ArrayList<String> newArray= new ArrayList<String>(groceryList.getGrocerylist()); String [] nextArray = new String[groceryList.getGrocerylist().size()]; nextArray = groceryList.getGrocerylist().toArray(nextArray); } }
2,551
0.505684
0.499804
90
27.344444
26.571146
88
false
false
0
0
0
0
0
0
0.477778
false
false
2
0e1d36f117f6eb3f017bd159ab8fdbe5efe208a3
5,497,558,185,385
693b70ca890f801e72ee7d32638df364e4ba32f8
/quality-manager_ANDROID/src/br/edu/ifpb/util/Constantes.java
3e2d6ad127fa42959f817b9791e9559841ec1531
[]
no_license
LADOSSIFPB/quality-manager
https://github.com/LADOSSIFPB/quality-manager
65f371ce52f16ffc0e77eeca0522985ec929a464
6144bf96720a706e4197587515605a2709762022
refs/heads/master
2016-09-15T10:40:01.555000
2016-03-03T23:08:24
2016-03-03T23:09:24
38,027,178
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.edu.ifpb.util; public class Constantes { public static final String URL_WEB_SERVICE = "http://200.129.68.181:8773/quality-manager_SERVICE"; public static final String URL_INTERNA_SERVICE = "http://192.168.1.245:8773/quality-manager_SERVICE"; public static final String URL_LOCAL_SERVICE = "http://192.168.2.100:8080/quality-manager_SERVICE"; public static final String SERVIDOR_ONLINE = "/cadastrar/servidorOnline"; public static final String CADASTRAR_INSTITUICAO_FINANCIADORA = "/cadastrar/instituicaofinanciadora"; public static final String CADASTRAR_PROGRAMA_INSTITUCIONAL = "/cadastrar/programainstitucional"; public static final String CADASTRAR_EDITAL = "/cadastrar/edital"; public static final String CADASTRAR_CURSO = "/cadastrar/curso"; public static final String CADASTRAR_INSTITUICAO_BANCARIA = "/cadastrar/instituicaobancaria"; public static final String CONSULTAR_INSTITUICOES_FINANCIADORAS = "/consultar/instituicoesfinanciadoras/listar"; public static final String CONSULTAR_PROGRAMAS_INSTITUCIONAIS = "/consultar/programasinstitucionais/listar"; public static final String CONSULTAR_EDITAIS = "/consultar/editais/listar"; public static final String CONSULTAR_CURSOS = "/consultar/cursos/listar"; public static final String CONSULTAR_COORDENADORES = "/consultar/coordenadores"; public static final String CONSULTAR_ORIENTADORES = "/consultar/orientadores/listar"; public static final String CONSULTAR_INSTITUICOES_BANCARIAS = "/consultar/instituicoesbancarias/listar"; public static final String CONSULTAR_LOGIN = "/consultar/fazerLogin"; public static final String CONSULTAR_PESSOA_BY_ID = "/consultar/pessoa"; public static final String CONSULTAR_TIPO_SERVIDOR = "/consultar/servidor"; public static final String MSG_SUCESSO_CADASTRO = "Operação realizada com Sucesso."; public static final String MSG_INICIO_SPINNER = "Selecione..."; public static final String MSG_PREENCHER_CAMPO = "Por favor, preencha esse campo."; public static final String MSG_PREENCHER_INSTITUICAO_FINANCIADORA = "Por favor, preencha o campo Instituição Financiadora"; public static final String ERROR_INTERNET_OFF = "Não existe conexão com a internet"; public static final String ERROR_COMUNICACAO_SERVIDOR_OFF = "Não foi possível estabelecer a conexão com o servidor."; public static final String ERROR_PROBLEMA_COMUNICACAO_SERVIDOR = "ERRO: Conexão Encerrada"; public static final String ERROR_INSTITUICAO_FINANCIADORA_NULL = "Cadastro Inválido. Instituição Financiadora Inexistente."; public static final String ERROR_PROGRAMA_INSTITUCIONAL_NULL = "Cadastro Inválido. Programa Institucional Inexistente."; public static final String ERROR_EDITAL_NULL = "Cadastro Inválido. Edital Inexistente."; public static final String ERROR_CURSO_NULL = "Cadastro Inválido. Curso Inexistente."; }
ISO-8859-1
Java
2,875
java
Constantes.java
Java
[ { "context": "lic static final String URL_WEB_SERVICE = \"http://200.129.68.181:8773/quality-manager_SERVICE\";\r\n\tpublic static fi", "end": 126, "score": 0.9996961355209351, "start": 112, "tag": "IP_ADDRESS", "value": "200.129.68.181" }, { "context": "static final String URL_INTER...
null
[]
package br.edu.ifpb.util; public class Constantes { public static final String URL_WEB_SERVICE = "http://172.16.17.32:8773/quality-manager_SERVICE"; public static final String URL_INTERNA_SERVICE = "http://192.168.1.245:8773/quality-manager_SERVICE"; public static final String URL_LOCAL_SERVICE = "http://192.168.2.100:8080/quality-manager_SERVICE"; public static final String SERVIDOR_ONLINE = "/cadastrar/servidorOnline"; public static final String CADASTRAR_INSTITUICAO_FINANCIADORA = "/cadastrar/instituicaofinanciadora"; public static final String CADASTRAR_PROGRAMA_INSTITUCIONAL = "/cadastrar/programainstitucional"; public static final String CADASTRAR_EDITAL = "/cadastrar/edital"; public static final String CADASTRAR_CURSO = "/cadastrar/curso"; public static final String CADASTRAR_INSTITUICAO_BANCARIA = "/cadastrar/instituicaobancaria"; public static final String CONSULTAR_INSTITUICOES_FINANCIADORAS = "/consultar/instituicoesfinanciadoras/listar"; public static final String CONSULTAR_PROGRAMAS_INSTITUCIONAIS = "/consultar/programasinstitucionais/listar"; public static final String CONSULTAR_EDITAIS = "/consultar/editais/listar"; public static final String CONSULTAR_CURSOS = "/consultar/cursos/listar"; public static final String CONSULTAR_COORDENADORES = "/consultar/coordenadores"; public static final String CONSULTAR_ORIENTADORES = "/consultar/orientadores/listar"; public static final String CONSULTAR_INSTITUICOES_BANCARIAS = "/consultar/instituicoesbancarias/listar"; public static final String CONSULTAR_LOGIN = "/consultar/fazerLogin"; public static final String CONSULTAR_PESSOA_BY_ID = "/consultar/pessoa"; public static final String CONSULTAR_TIPO_SERVIDOR = "/consultar/servidor"; public static final String MSG_SUCESSO_CADASTRO = "Operação realizada com Sucesso."; public static final String MSG_INICIO_SPINNER = "Selecione..."; public static final String MSG_PREENCHER_CAMPO = "Por favor, preencha esse campo."; public static final String MSG_PREENCHER_INSTITUICAO_FINANCIADORA = "Por favor, preencha o campo Instituição Financiadora"; public static final String ERROR_INTERNET_OFF = "Não existe conexão com a internet"; public static final String ERROR_COMUNICACAO_SERVIDOR_OFF = "Não foi possível estabelecer a conexão com o servidor."; public static final String ERROR_PROBLEMA_COMUNICACAO_SERVIDOR = "ERRO: Conexão Encerrada"; public static final String ERROR_INSTITUICAO_FINANCIADORA_NULL = "Cadastro Inválido. Instituição Financiadora Inexistente."; public static final String ERROR_PROGRAMA_INSTITUCIONAL_NULL = "Cadastro Inválido. Programa Institucional Inexistente."; public static final String ERROR_EDITAL_NULL = "Cadastro Inválido. Edital Inexistente."; public static final String ERROR_CURSO_NULL = "Cadastro Inválido. Curso Inexistente."; }
2,873
0.791885
0.776845
36
77.472221
35.131092
125
false
false
0
0
0
0
0
0
1.75
false
false
2
8a9158fc82d4d5e76725c8da463cef619274ead8
9,964,324,138,780
7b7fa3ddabae69b67e9cf7689223aa980bf13635
/app/src/main/java/com/stest/fragment/MusicFragment.java
dd02add8e1d910669f7b4b931069cd95f36155b6
[ "Apache-2.0" ]
permissive
GiitSmile/ImitateNetEasyCloud
https://github.com/GiitSmile/ImitateNetEasyCloud
3e0ed900dff245125f37acf08a975d1ec62e31a1
716f6c53542b020be8412c273f32d9f1d68636ed
refs/heads/master
2021-01-23T13:17:31.319000
2019-03-05T02:55:42
2019-03-05T02:55:42
56,900,510
112
33
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stest.fragment; import android.animation.ObjectAnimator; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.RelativeLayout; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.stest.adapter.MusicDetailAdapter; import com.stest.model.MusicInfoDetail; import com.stest.neteasycloud.MusicInfoActivity; import com.stest.neteasycloud.R; import com.stest.neteasycloud.SplashActivity; import com.stest.utils.SPUtils; import com.stest.view.DividerListView; import com.stest.view.NetEasyRefreshLayout; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Limuyang on 2016/7/7. */ public class MusicFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener { private View v; private MusicDetailAdapter mMusicDetailAdapter; //数据 private List<String> data; @ViewInject(R.id.lv) private DividerListView lv; @ViewInject(R.id.refresh) private NetEasyRefreshLayout refreshLayout; @ViewInject(R.id.detail_creat) private RelativeLayout creat_layout; @ViewInject(R.id.detail_collect) private RelativeLayout collect_layout; @ViewInject(R.id.creat_expand_img) private ImageView creat_expand_img; @ViewInject(R.id.collect_expand_img) private ImageView collect_expand_img; private boolean isCreatRotate = true; private boolean isCollectRotate = true; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (v != null) { ViewUtils.inject(this, v); return v; } v = inflater.inflate(R.layout.music_fragment, container, false); ViewUtils.inject(this, v); initWidgets(); return v; } //初始化 private void initWidgets() { refreshLayout.setOnRefreshListener(this); creat_layout.setOnClickListener(this); collect_layout.setOnClickListener(this); refreshLayout.setColorSchemeResources(R.color.themeColor); data = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.music_icn_data))); mMusicDetailAdapter = new MusicDetailAdapter(getActivity(), data, R.layout.music_detail_item); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { //本地音乐 case 0: Intent musicIntent = new Intent(getContext(), MusicInfoActivity.class); musicIntent.putExtra("page_number",0); startActivity(musicIntent); break; //最近播放 case 1: break; //下载管理 case 2: break; //我的歌手 case 3: Intent artistIntent = new Intent(getContext(), MusicInfoActivity.class); artistIntent.putExtra("page_number",1); startActivity(artistIntent); break; //我的电台 case 4: break; //我的MV case 5: break; } } }); if (SPUtils.getValue(getActivity(), "isFirst", "First", true)){ lv.setAdapter(mMusicDetailAdapter); refreshLayout.post(new Runnable() { @Override public void run() { refreshLayout.setRefreshing(true); } }); onRefresh(); }else { lv.setAdapter(mMusicDetailAdapter); } } @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { if (refreshLayout.isRefreshing()) { mMusicDetailAdapter = new MusicDetailAdapter(getActivity(), data, R.layout.music_detail_item); refreshLayout.setRefreshing(false); lv.setAdapter(mMusicDetailAdapter); } } }, 2500); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.detail_creat: if (isCreatRotate) { animCreat().start(); isCreatRotate = false; } else { animCreat().reverse(); isCreatRotate = true; } break; case R.id.detail_collect: if (isCollectRotate) { animCollect().start(); isCollectRotate = false; } else { animCollect().reverse(); isCollectRotate = true; } break; } } public ObjectAnimator animCreat() { ObjectAnimator anim_creat = ObjectAnimator.ofFloat(creat_expand_img, "rotation", 90, 0, 0); anim_creat.setDuration(300); return anim_creat; } public ObjectAnimator animCollect() { ObjectAnimator anim_collect = ObjectAnimator.ofFloat(collect_expand_img, "rotation", 90, 0, 0); anim_collect.setDuration(300); return anim_collect; } }
UTF-8
Java
6,001
java
MusicFragment.java
Java
[ { "context": ".Arrays;\nimport java.util.List;\n\n/**\n * Created by Limuyang on 2016/7/7.\n */\npublic class MusicFragment exten", "end": 1014, "score": 0.8501038551330566, "start": 1006, "tag": "NAME", "value": "Limuyang" } ]
null
[]
package com.stest.fragment; import android.animation.ObjectAnimator; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.RelativeLayout; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.stest.adapter.MusicDetailAdapter; import com.stest.model.MusicInfoDetail; import com.stest.neteasycloud.MusicInfoActivity; import com.stest.neteasycloud.R; import com.stest.neteasycloud.SplashActivity; import com.stest.utils.SPUtils; import com.stest.view.DividerListView; import com.stest.view.NetEasyRefreshLayout; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Limuyang on 2016/7/7. */ public class MusicFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener { private View v; private MusicDetailAdapter mMusicDetailAdapter; //数据 private List<String> data; @ViewInject(R.id.lv) private DividerListView lv; @ViewInject(R.id.refresh) private NetEasyRefreshLayout refreshLayout; @ViewInject(R.id.detail_creat) private RelativeLayout creat_layout; @ViewInject(R.id.detail_collect) private RelativeLayout collect_layout; @ViewInject(R.id.creat_expand_img) private ImageView creat_expand_img; @ViewInject(R.id.collect_expand_img) private ImageView collect_expand_img; private boolean isCreatRotate = true; private boolean isCollectRotate = true; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (v != null) { ViewUtils.inject(this, v); return v; } v = inflater.inflate(R.layout.music_fragment, container, false); ViewUtils.inject(this, v); initWidgets(); return v; } //初始化 private void initWidgets() { refreshLayout.setOnRefreshListener(this); creat_layout.setOnClickListener(this); collect_layout.setOnClickListener(this); refreshLayout.setColorSchemeResources(R.color.themeColor); data = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.music_icn_data))); mMusicDetailAdapter = new MusicDetailAdapter(getActivity(), data, R.layout.music_detail_item); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { //本地音乐 case 0: Intent musicIntent = new Intent(getContext(), MusicInfoActivity.class); musicIntent.putExtra("page_number",0); startActivity(musicIntent); break; //最近播放 case 1: break; //下载管理 case 2: break; //我的歌手 case 3: Intent artistIntent = new Intent(getContext(), MusicInfoActivity.class); artistIntent.putExtra("page_number",1); startActivity(artistIntent); break; //我的电台 case 4: break; //我的MV case 5: break; } } }); if (SPUtils.getValue(getActivity(), "isFirst", "First", true)){ lv.setAdapter(mMusicDetailAdapter); refreshLayout.post(new Runnable() { @Override public void run() { refreshLayout.setRefreshing(true); } }); onRefresh(); }else { lv.setAdapter(mMusicDetailAdapter); } } @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { if (refreshLayout.isRefreshing()) { mMusicDetailAdapter = new MusicDetailAdapter(getActivity(), data, R.layout.music_detail_item); refreshLayout.setRefreshing(false); lv.setAdapter(mMusicDetailAdapter); } } }, 2500); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.detail_creat: if (isCreatRotate) { animCreat().start(); isCreatRotate = false; } else { animCreat().reverse(); isCreatRotate = true; } break; case R.id.detail_collect: if (isCollectRotate) { animCollect().start(); isCollectRotate = false; } else { animCollect().reverse(); isCollectRotate = true; } break; } } public ObjectAnimator animCreat() { ObjectAnimator anim_creat = ObjectAnimator.ofFloat(creat_expand_img, "rotation", 90, 0, 0); anim_creat.setDuration(300); return anim_creat; } public ObjectAnimator animCollect() { ObjectAnimator anim_collect = ObjectAnimator.ofFloat(collect_expand_img, "rotation", 90, 0, 0); anim_collect.setDuration(300); return anim_collect; } }
6,001
0.581806
0.576089
175
32.982857
24.04911
123
false
false
0
0
0
0
0
0
0.674286
false
false
2
8d0d40b8639395258a1bf5a47d07131c6ef8780d
24,094,766,576,194
e414cabeaf820e99f846801778e3e6f8cddab1cf
/Algorithms.java
cb6ed9c47b8dd7d0e91e43fa8a05ff2474b34d81
[]
no_license
henrysurface/CSCE-608-Project-2-DBMS
https://github.com/henrysurface/CSCE-608-Project-2-DBMS
bc395856dcb6d8c527044b65bdcef60b79dd4de8
c9a47e0b5c9faa457f7100b927f6520bc0a2476e
refs/heads/master
2020-04-07T22:42:42.889000
2016-12-12T23:20:46
2016-12-12T23:20:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import storageManager.*; import java.util.*; import java.util.List; /** * Contains basic sorting/distinct algorithms, read/write disk operations */ public abstract class Algorithms { public static void travesal(CrossRelation relations , int level) { for (int i = 0; i < level; i++) { System.out.print(" "); } for (String str: relations.subRelation) { System.out.print(str+" "); } System.out.println(); if (relations.joinBy != null) { for (CrossRelation cr : relations.joinBy) { travesal(cr, level + 1); } } } public static CrossRelation findOptimal(List<HashMap<Set<String>, CrossRelation>> tempRelations, Set<String> finalGoal, int memSize) { if (tempRelations.get(finalGoal.size()-1).containsKey(finalGoal)) { return tempRelations.get(finalGoal.size()-1).get(finalGoal); } int block = 0; int tuple = 0; int fieldNum = 0; int minCost = Integer.MAX_VALUE; List<CrossRelation> joinBy = null; List<SetPair> permutation = cutSet(finalGoal); for (SetPair pair: permutation) { Set<String> setOne = pair.set1; Set<String> setTwo = pair.set2; CrossRelation c1 = findOptimal(tempRelations, setOne, memSize); CrossRelation c2 = findOptimal(tempRelations, setTwo, memSize); if (c1.cost + c2.cost + calcCost(memSize, c1.blockNum, c2.blockNum) < minCost) { joinBy = new ArrayList<>(); joinBy.add(c1); joinBy.add(c2); tuple = c1.tupleNum * c2.tupleNum; block = blocksAfterJoin(c1.tupleNum, c2.tupleNum, 8,c1.fieldNum + c2.fieldNum); fieldNum = c1.fieldNum + c2.fieldNum; minCost = c1.cost + c2.cost + calcCost(memSize, c1.blockNum, c2.blockNum); } } CrossRelation ret = new CrossRelation(finalGoal, block, tuple); ret.joinBy = joinBy; ret.fieldNum = fieldNum; ret.cost = minCost; tempRelations.get(finalGoal.size()-1).put(finalGoal, ret); return ret; } static class SetPair { Set<String> set1; Set<String> set2; public SetPair(Set<String> s1, Set<String> s2) { this.set1 = s1; this.set2 = s2; } public String toString() { return "[" + set1.toString() + ", " + set2.toString() + "]"; } } public static List<SetPair> cutSet(Set<String> input) { List<SetPair> result = new ArrayList<>(); for (int i = 1; i <= input.size() / 2; i++) { Set<String> tmpSet = new HashSet<>(input); Set<String> pickedSet = new HashSet<>(); helper(tmpSet, i, 0, pickedSet, result); } return result; } public static void helper(Set<String> input, int count, int startPos, Set<String> picked, List<SetPair> result) { if (count == 0) result.add(new SetPair(input, picked)); List<String> inputList = new ArrayList<>(input); for (int i = startPos; i < inputList.size(); i++) { Set<String> inputTmp = new HashSet<>(input); Set<String> pickedTmp = new HashSet<>(picked); inputTmp.remove(inputList.get(i)); pickedTmp.add(inputList.get(i)); helper(inputTmp, count - 1, i, pickedTmp, result); } } public static int blocksAfterJoin(int tupleNum1, int tupleNum2, int blockSize, int fieldPerTuple) { int totalTuples = tuplesAfterJoin(tupleNum1, tupleNum2); return totalTuples * fieldPerTuple % blockSize == 0? totalTuples * fieldPerTuple / blockSize:totalTuples * fieldPerTuple / blockSize+ 1; } public static int tuplesAfterJoin(int tupleNum1, int tupleNum2) { return tupleNum1 * tupleNum2; } public static int calcCost(int memSize, int blockNum1, int blockNum2) { if(Math.min(blockNum1, blockNum2) <= memSize) return blockNum1 + blockNum2; else return blockNum1 * blockNum2 + Math.min(blockNum1, blockNum2); } public static void removeDuplicate(ArrayList<Tuple> tuples, List<String> fieldNames) { if (tuples.isEmpty()) { System.out.println("Empty Relation"); return; } Tuple tuple = tuples.get(0); if (fieldNames.get(0).equals("*")) { fieldNames = tuple.getSchema().getFieldNames(); } int pointer1 = 1, pointer2 = 1; while (pointer2 < tuples.size()) { if(compareTuple(tuple, tuples.get(pointer2), fieldNames)!=0) { tuple = tuples.get(pointer2); tuples.set(pointer1, tuples.get(pointer2)); pointer1 += 1; } pointer2 += 1; } for (int i = tuples.size()-1; i >= pointer1; i--) { tuples.remove(i); } } public static int compareTuple(Tuple o1, Tuple o2, List<String> fieldNames) { for (String name: fieldNames){ if (o1.getField(name).type == FieldType.INT) { if (Integer.compare(o1.getField(name).integer, o2.getField(name).integer)!= 0) { return Integer.compare(o1.getField(name).integer, o2.getField(name).integer); } } else { if (o1.getField(name).str.compareTo(o2.getField(name).str) != 0) { return o1.getField(name).str.compareTo(o2.getField(name).str); } } } return 0; } public static int compareTuple(Tuple o1, Tuple o2, List<String> fieldNames, String orderBy) { if(o1.getField(orderBy).type == FieldType.INT) { if(Integer.compare(o1.getField(orderBy).integer, o2.getField(orderBy).integer)!=0) return Integer.compare(o1.getField(orderBy).integer, o2.getField(orderBy).integer); } else { if(o1.getField(orderBy).str.compareTo(o2.getField(orderBy).str)!=0) return o1.getField(orderBy).str.compareTo(o2.getField(orderBy).str); } for (String name: fieldNames){ if(!name.equalsIgnoreCase(orderBy)) { if (o1.getField(name).type == FieldType.INT) { if (Integer.compare(o1.getField(name).integer, o2.getField(name).integer) != 0) { return Integer.compare(o1.getField(name).integer, o2.getField(name).integer); } } else { if (o1.getField(name).str.compareTo(o2.getField(name).str) != 0) { return o1.getField(name).str.compareTo(o2.getField(name).str); } } } } return 0; } public static void sortInMemory(ArrayList<Tuple> tuples, final String orderBy){ System.out.println("SELECT: One pass for sorting on 1 relation\n"); final List<String> fieldNames = tuples.get(0).getSchema().getFieldNames(); Collections.sort(tuples, new Comparator<Tuple>() { @Override public int compare(Tuple o1, Tuple o2) { if(orderBy == null) { return compareTuple(o1, o2, fieldNames); } else { return compareTuple(o1, o2, fieldNames, orderBy); } } }); } public static void twoPassSort(String compareBase, Relation relation, MainMemory mem) { int currentBlockNum = 0, readBlockNum; //List<String> fieldNames = relation.getSchema().getFieldNames(); while (currentBlockNum < relation.getNumOfBlocks()) { readBlockNum = (relation.getNumOfBlocks() - currentBlockNum)>mem.getMemorySize() ?mem.getMemorySize():(relation.getNumOfBlocks() - currentBlockNum); relation.getBlocks(currentBlockNum, 0, readBlockNum); //Read a certain number of blocks into memory. ArrayList<Tuple> tupleList = mem.getTuples(0, readBlockNum); sortInMemory(tupleList, compareBase); mem.setTuples(0, tupleList); relation.setBlocks(currentBlockNum, 0, readBlockNum); currentBlockNum += readBlockNum; } } public static HashSet<String> tableInExpression(Node node) { node.contains_table = new HashSet<>(); if(node.getAttr().equalsIgnoreCase("ATTR_NAME")) { assert node.getChildren().size() > 1; node.contains_table.add(node.getChildren().get(0).getAttr()); return node.contains_table; } else { if(node.getChildren()==null||node.getChildren().size()==0) { return node.contains_table; }else { for (Node subStatement: node.getChildren()) { node.contains_table.addAll(tableInExpression(subStatement)); } return node.contains_table; } } } /** * This is just a patch. */ public static void mergeField(Node node) { /** * This function is for mergeField of several table, in a node. */ if (node.getAttr().equalsIgnoreCase("ATTR_NAME")) { List<Node> cols = node.getChildren(); StringBuilder s = new StringBuilder(); List<Node> tempBranches = new ArrayList<>(); for (Node field: cols) { s.append(field.getAttr()+"."); } s.deleteCharAt(s.length()-1); tempBranches.add(new Node(s.toString(), true)); node.setChildren(tempBranches); } else { if(node.getChildren()!=null&&node.getChildren().size()>0) { for (Node st : node.getChildren()) { mergeField(st); } } } //return statament; } }
UTF-8
Java
9,993
java
Algorithms.java
Java
[]
null
[]
import storageManager.*; import java.util.*; import java.util.List; /** * Contains basic sorting/distinct algorithms, read/write disk operations */ public abstract class Algorithms { public static void travesal(CrossRelation relations , int level) { for (int i = 0; i < level; i++) { System.out.print(" "); } for (String str: relations.subRelation) { System.out.print(str+" "); } System.out.println(); if (relations.joinBy != null) { for (CrossRelation cr : relations.joinBy) { travesal(cr, level + 1); } } } public static CrossRelation findOptimal(List<HashMap<Set<String>, CrossRelation>> tempRelations, Set<String> finalGoal, int memSize) { if (tempRelations.get(finalGoal.size()-1).containsKey(finalGoal)) { return tempRelations.get(finalGoal.size()-1).get(finalGoal); } int block = 0; int tuple = 0; int fieldNum = 0; int minCost = Integer.MAX_VALUE; List<CrossRelation> joinBy = null; List<SetPair> permutation = cutSet(finalGoal); for (SetPair pair: permutation) { Set<String> setOne = pair.set1; Set<String> setTwo = pair.set2; CrossRelation c1 = findOptimal(tempRelations, setOne, memSize); CrossRelation c2 = findOptimal(tempRelations, setTwo, memSize); if (c1.cost + c2.cost + calcCost(memSize, c1.blockNum, c2.blockNum) < minCost) { joinBy = new ArrayList<>(); joinBy.add(c1); joinBy.add(c2); tuple = c1.tupleNum * c2.tupleNum; block = blocksAfterJoin(c1.tupleNum, c2.tupleNum, 8,c1.fieldNum + c2.fieldNum); fieldNum = c1.fieldNum + c2.fieldNum; minCost = c1.cost + c2.cost + calcCost(memSize, c1.blockNum, c2.blockNum); } } CrossRelation ret = new CrossRelation(finalGoal, block, tuple); ret.joinBy = joinBy; ret.fieldNum = fieldNum; ret.cost = minCost; tempRelations.get(finalGoal.size()-1).put(finalGoal, ret); return ret; } static class SetPair { Set<String> set1; Set<String> set2; public SetPair(Set<String> s1, Set<String> s2) { this.set1 = s1; this.set2 = s2; } public String toString() { return "[" + set1.toString() + ", " + set2.toString() + "]"; } } public static List<SetPair> cutSet(Set<String> input) { List<SetPair> result = new ArrayList<>(); for (int i = 1; i <= input.size() / 2; i++) { Set<String> tmpSet = new HashSet<>(input); Set<String> pickedSet = new HashSet<>(); helper(tmpSet, i, 0, pickedSet, result); } return result; } public static void helper(Set<String> input, int count, int startPos, Set<String> picked, List<SetPair> result) { if (count == 0) result.add(new SetPair(input, picked)); List<String> inputList = new ArrayList<>(input); for (int i = startPos; i < inputList.size(); i++) { Set<String> inputTmp = new HashSet<>(input); Set<String> pickedTmp = new HashSet<>(picked); inputTmp.remove(inputList.get(i)); pickedTmp.add(inputList.get(i)); helper(inputTmp, count - 1, i, pickedTmp, result); } } public static int blocksAfterJoin(int tupleNum1, int tupleNum2, int blockSize, int fieldPerTuple) { int totalTuples = tuplesAfterJoin(tupleNum1, tupleNum2); return totalTuples * fieldPerTuple % blockSize == 0? totalTuples * fieldPerTuple / blockSize:totalTuples * fieldPerTuple / blockSize+ 1; } public static int tuplesAfterJoin(int tupleNum1, int tupleNum2) { return tupleNum1 * tupleNum2; } public static int calcCost(int memSize, int blockNum1, int blockNum2) { if(Math.min(blockNum1, blockNum2) <= memSize) return blockNum1 + blockNum2; else return blockNum1 * blockNum2 + Math.min(blockNum1, blockNum2); } public static void removeDuplicate(ArrayList<Tuple> tuples, List<String> fieldNames) { if (tuples.isEmpty()) { System.out.println("Empty Relation"); return; } Tuple tuple = tuples.get(0); if (fieldNames.get(0).equals("*")) { fieldNames = tuple.getSchema().getFieldNames(); } int pointer1 = 1, pointer2 = 1; while (pointer2 < tuples.size()) { if(compareTuple(tuple, tuples.get(pointer2), fieldNames)!=0) { tuple = tuples.get(pointer2); tuples.set(pointer1, tuples.get(pointer2)); pointer1 += 1; } pointer2 += 1; } for (int i = tuples.size()-1; i >= pointer1; i--) { tuples.remove(i); } } public static int compareTuple(Tuple o1, Tuple o2, List<String> fieldNames) { for (String name: fieldNames){ if (o1.getField(name).type == FieldType.INT) { if (Integer.compare(o1.getField(name).integer, o2.getField(name).integer)!= 0) { return Integer.compare(o1.getField(name).integer, o2.getField(name).integer); } } else { if (o1.getField(name).str.compareTo(o2.getField(name).str) != 0) { return o1.getField(name).str.compareTo(o2.getField(name).str); } } } return 0; } public static int compareTuple(Tuple o1, Tuple o2, List<String> fieldNames, String orderBy) { if(o1.getField(orderBy).type == FieldType.INT) { if(Integer.compare(o1.getField(orderBy).integer, o2.getField(orderBy).integer)!=0) return Integer.compare(o1.getField(orderBy).integer, o2.getField(orderBy).integer); } else { if(o1.getField(orderBy).str.compareTo(o2.getField(orderBy).str)!=0) return o1.getField(orderBy).str.compareTo(o2.getField(orderBy).str); } for (String name: fieldNames){ if(!name.equalsIgnoreCase(orderBy)) { if (o1.getField(name).type == FieldType.INT) { if (Integer.compare(o1.getField(name).integer, o2.getField(name).integer) != 0) { return Integer.compare(o1.getField(name).integer, o2.getField(name).integer); } } else { if (o1.getField(name).str.compareTo(o2.getField(name).str) != 0) { return o1.getField(name).str.compareTo(o2.getField(name).str); } } } } return 0; } public static void sortInMemory(ArrayList<Tuple> tuples, final String orderBy){ System.out.println("SELECT: One pass for sorting on 1 relation\n"); final List<String> fieldNames = tuples.get(0).getSchema().getFieldNames(); Collections.sort(tuples, new Comparator<Tuple>() { @Override public int compare(Tuple o1, Tuple o2) { if(orderBy == null) { return compareTuple(o1, o2, fieldNames); } else { return compareTuple(o1, o2, fieldNames, orderBy); } } }); } public static void twoPassSort(String compareBase, Relation relation, MainMemory mem) { int currentBlockNum = 0, readBlockNum; //List<String> fieldNames = relation.getSchema().getFieldNames(); while (currentBlockNum < relation.getNumOfBlocks()) { readBlockNum = (relation.getNumOfBlocks() - currentBlockNum)>mem.getMemorySize() ?mem.getMemorySize():(relation.getNumOfBlocks() - currentBlockNum); relation.getBlocks(currentBlockNum, 0, readBlockNum); //Read a certain number of blocks into memory. ArrayList<Tuple> tupleList = mem.getTuples(0, readBlockNum); sortInMemory(tupleList, compareBase); mem.setTuples(0, tupleList); relation.setBlocks(currentBlockNum, 0, readBlockNum); currentBlockNum += readBlockNum; } } public static HashSet<String> tableInExpression(Node node) { node.contains_table = new HashSet<>(); if(node.getAttr().equalsIgnoreCase("ATTR_NAME")) { assert node.getChildren().size() > 1; node.contains_table.add(node.getChildren().get(0).getAttr()); return node.contains_table; } else { if(node.getChildren()==null||node.getChildren().size()==0) { return node.contains_table; }else { for (Node subStatement: node.getChildren()) { node.contains_table.addAll(tableInExpression(subStatement)); } return node.contains_table; } } } /** * This is just a patch. */ public static void mergeField(Node node) { /** * This function is for mergeField of several table, in a node. */ if (node.getAttr().equalsIgnoreCase("ATTR_NAME")) { List<Node> cols = node.getChildren(); StringBuilder s = new StringBuilder(); List<Node> tempBranches = new ArrayList<>(); for (Node field: cols) { s.append(field.getAttr()+"."); } s.deleteCharAt(s.length()-1); tempBranches.add(new Node(s.toString(), true)); node.setChildren(tempBranches); } else { if(node.getChildren()!=null&&node.getChildren().size()>0) { for (Node st : node.getChildren()) { mergeField(st); } } } //return statament; } }
9,993
0.560092
0.545982
247
39.457489
29.777264
144
false
false
0
0
0
0
0
0
0.773279
false
false
2
7d779402997c67fc0ddf7550b4632752224c644c
20,607,253,108,424
a3308a194e33c932182fdfd6efe085480fe495fb
/src/main/java/astavie/thermallogistics/util/delegate/DelegateClientFluid.java
b27a5022cf84f4734a9cfa6c6110e806cb0ecde2
[]
no_license
kellixon/ThermalLogistics
https://github.com/kellixon/ThermalLogistics
7d3afdd5066a6d08f3f9db1538ec20b7a80a674f
cbbe6d0cfb371fbc9a38078ed55a5ebd9e09a90c
refs/heads/master
2020-04-21T07:41:15.122000
2019-02-06T11:05:14
2019-02-06T11:05:14
169,398,470
0
0
null
true
2019-02-06T11:52:49
2019-02-06T11:52:49
2019-02-06T11:05:21
2019-02-06T11:15:54
763
0
0
0
null
false
null
package astavie.thermallogistics.util.delegate; import astavie.thermallogistics.attachment.CrafterFluid; import astavie.thermallogistics.gui.client.element.ElementSlotFluid; import cofh.core.gui.GuiContainerCore; import cofh.core.gui.element.ElementBase; import cofh.core.network.PacketHandler; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraftforge.fluids.FluidStack; import java.text.NumberFormat; import java.util.List; public class DelegateClientFluid extends DelegateFluid implements IDelegateClient<FluidStack, CrafterFluid> { public static final DelegateClientFluid INSTANCE = new DelegateClientFluid(); @Override public void drawStack(GuiContainerCore gui, int x, int y, FluidStack stack) { if (stack != null) { GlStateManager.disableLighting(); gui.drawFluid(x, y, stack, 16, 16); GlStateManager.disableDepth(); GlStateManager.disableBlend(); GlStateManager.pushMatrix(); GlStateManager.scale(0.5, 0.5, 0.5); NumberFormat format = NumberFormat.getInstance(Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage().getJavaLocale()); String amount = format.format(stack.amount); gui.getFontRenderer().drawStringWithShadow(amount, (x + 16) * 2 - gui.getFontRenderer().getStringWidth(amount), (y + 12) * 2, 0xFFFFFF); GlStateManager.popMatrix(); } } @Override public void addTooltip(GuiContainerCore gui, FluidStack stack, List<String> list) { list.add(stack.getLocalizedName()); } @Override public ElementBase createSlot(GuiContainerCore gui, int x, int y, int slot, CrafterFluid crafter, boolean input) { return new ElementSlotFluid(gui, x, y, true, input ? () -> crafter.inputs[slot] : () -> crafter.outputs[slot], stack -> PacketHandler.sendToServer(crafter.getPacket(stack, input, slot))); } }
UTF-8
Java
1,834
java
DelegateClientFluid.java
Java
[]
null
[]
package astavie.thermallogistics.util.delegate; import astavie.thermallogistics.attachment.CrafterFluid; import astavie.thermallogistics.gui.client.element.ElementSlotFluid; import cofh.core.gui.GuiContainerCore; import cofh.core.gui.element.ElementBase; import cofh.core.network.PacketHandler; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraftforge.fluids.FluidStack; import java.text.NumberFormat; import java.util.List; public class DelegateClientFluid extends DelegateFluid implements IDelegateClient<FluidStack, CrafterFluid> { public static final DelegateClientFluid INSTANCE = new DelegateClientFluid(); @Override public void drawStack(GuiContainerCore gui, int x, int y, FluidStack stack) { if (stack != null) { GlStateManager.disableLighting(); gui.drawFluid(x, y, stack, 16, 16); GlStateManager.disableDepth(); GlStateManager.disableBlend(); GlStateManager.pushMatrix(); GlStateManager.scale(0.5, 0.5, 0.5); NumberFormat format = NumberFormat.getInstance(Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage().getJavaLocale()); String amount = format.format(stack.amount); gui.getFontRenderer().drawStringWithShadow(amount, (x + 16) * 2 - gui.getFontRenderer().getStringWidth(amount), (y + 12) * 2, 0xFFFFFF); GlStateManager.popMatrix(); } } @Override public void addTooltip(GuiContainerCore gui, FluidStack stack, List<String> list) { list.add(stack.getLocalizedName()); } @Override public ElementBase createSlot(GuiContainerCore gui, int x, int y, int slot, CrafterFluid crafter, boolean input) { return new ElementSlotFluid(gui, x, y, true, input ? () -> crafter.inputs[slot] : () -> crafter.outputs[slot], stack -> PacketHandler.sendToServer(crafter.getPacket(stack, input, slot))); } }
1,834
0.773719
0.764449
47
38.021278
42.313667
189
false
false
0
0
0
0
0
0
2.106383
false
false
2
e3ba6410e1ff169ac9f0ac9f5393c122ba0e7584
8,589,989,292
5c289c469b43eed5df9617ee8ce29e69d23f8ef6
/Loiane-Grone/basics/oop-exercises/src/exercise4/LibraryBook.java
59e300aa1048cf78412eee5d5787839c99c2d3e4
[]
no_license
rangel20/Java-Pequenas-Atividades
https://github.com/rangel20/Java-Pequenas-Atividades
77ebb92b972a5bfa4e3621f25d020c4ce5fed3f7
0f923b371c40a7f37cb209b2dcde283d63d66be2
refs/heads/main
2023-04-14T15:00:59.090000
2023-04-09T03:17:58
2023-04-09T03:17:58
294,838,088
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exercise4; import java.util.Date; public class LibraryBook { String title; String publisher; String language; String isbn10; String isbn13; String dimensions; int rating; Date returnindDate; boolean borrowed; }
UTF-8
Java
262
java
LibraryBook.java
Java
[]
null
[]
package exercise4; import java.util.Date; public class LibraryBook { String title; String publisher; String language; String isbn10; String isbn13; String dimensions; int rating; Date returnindDate; boolean borrowed; }
262
0.675573
0.656489
16
15.375
8.572303
26
false
false
0
0
0
0
0
0
0.6875
false
false
2
88e20bdaf8685cf5eb5711c97461e28c1c4066f4
8,589,987,629
0da01d505b3c8d8f8a816388a591d7386ae8af13
/workspace-sts-3.7.1.RELEASE/DesignPatterns/src/headfirst/composite/Waitress.java
c682109e53ad37829c979acbdba457b15a2a12b0
[]
no_license
peter-hickling/archive
https://github.com/peter-hickling/archive
e2441a556f32726a7c6a8fd19e4abe0542eabf58
cccad32a6605dd5e071ee52a5321e10086d0b437
refs/heads/master
2016-08-09T13:49:20.859000
2016-01-26T11:46:52
2016-01-26T11:46:52
50,425,230
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package headfirst.composite; import java.util.ArrayList; import java.util.Iterator; public class Waitress { // The new waitress will take in a MenuComponent and is able to print all // menus (including dessert). MenuComponent menus; public Waitress(MenuComponent menus) { this.menus = menus; } void printMenu() { menus.print(); } }
UTF-8
Java
351
java
Waitress.java
Java
[]
null
[]
package headfirst.composite; import java.util.ArrayList; import java.util.Iterator; public class Waitress { // The new waitress will take in a MenuComponent and is able to print all // menus (including dessert). MenuComponent menus; public Waitress(MenuComponent menus) { this.menus = menus; } void printMenu() { menus.print(); } }
351
0.723647
0.723647
20
16.6
18.268553
74
false
false
0
0
0
0
0
0
0.95
false
false
2
e27625171ef5a9c2d070c0a6f2ac3f186f419ded
32,169,305,089,364
acd6e4d4d79004b61b208b44bb35bb3c13b7c024
/app/src/main/java/com/inu/amadda/view/activity/SplashActivity.java
d62be2fafdc3d9d23b88bc337df96cd7884f9e07
[]
no_license
inu-appcenter/AMADDA_Android
https://github.com/inu-appcenter/AMADDA_Android
1ddb8fec9669ae308afde956c44d520471a566b7
24ba4e72237b44b47379991ee2e33ea326c06590
refs/heads/develop
2020-12-27T12:49:26.110000
2020-09-21T12:45:41
2020-09-21T12:45:41
237,907,462
2
0
null
false
2020-05-04T15:49:13
2020-02-03T07:21:15
2020-03-09T17:39:28
2020-05-04T15:49:12
818
0
0
0
Java
false
false
package com.inu.amadda.view.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.WindowManager; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.inu.amadda.R; import com.inu.amadda.etc.Constant; import com.inu.amadda.model.SuccessResponse; import com.inu.amadda.network.RetrofitInstance; import com.inu.amadda.util.PreferenceManager; import java.util.HashMap; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SplashActivity extends AppCompatActivity { private String id, pw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Handler handler = new Handler(); if (checkFirstLogin()) { handler.postDelayed(this::goToLogin, 1600); } else { requestLogin(id, pw); } } private boolean checkFirstLogin() { id = PreferenceManager.getInstance().getSharedPreference(getApplicationContext(), Constant.Preference.ID, null); pw = PreferenceManager.getInstance().getSharedPreference(getApplicationContext(), Constant.Preference.PASSWORD, null); String token = PreferenceManager.getInstance().getSharedPreference(getApplicationContext(), Constant.Preference.TOKEN, null); return id == null || pw == null || token == null; } private void goToLogin() { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); } private void requestLogin(String id, String pw){ HashMap<String, String> map = new HashMap<>(); map.put("id", id); map.put("passwd", pw); RetrofitInstance.getInstance().getService().Login(map).enqueue(new Callback<SuccessResponse>() { @Override public void onResponse(Call<SuccessResponse> call, Response<SuccessResponse> response) { int status = response.code(); if (response.isSuccessful()) { SuccessResponse successResponse = response.body(); if (successResponse != null) { if (successResponse.success) { saveUserInfo(id, pw, response.headers().get("token")); Intent intent = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent); finish(); } else { Toast.makeText(getApplicationContext(), "잠시 후 다시 시도해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); Log.d("SplashActivity", successResponse.message); } } else { Toast.makeText(getApplicationContext(), "잠시 후 다시 시도해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); } } else if (status == 400){ Toast.makeText(getApplicationContext(), "아이디 및 비밀번호를 확인해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); } else { Toast.makeText(getApplicationContext(), "잠시 후 다시 시도해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); Log.d("SplashActivity", status + ""); } } @Override public void onFailure(Call<SuccessResponse> call, Throwable t) { Toast.makeText(getApplicationContext(), "인터넷 연결 상태를 확인해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); Log.d("SplashActivity", t.getMessage()); } }); } private void saveUserInfo(String id, String pw, String token){ PreferenceManager.getInstance().putSharedPreference(getApplicationContext(), Constant.Preference.ID, id); PreferenceManager.getInstance().putSharedPreference(getApplicationContext(), Constant.Preference.PASSWORD, pw); PreferenceManager.getInstance().putSharedPreference(getApplicationContext(), Constant.Preference.TOKEN, token); Log.d("SplashActivity", "ID: " + id + ", PASSWORD: " + pw + ", TOKEN: " + token); } }
UTF-8
Java
4,687
java
SplashActivity.java
Java
[ { "context": " map.put(\"id\", id);\n map.put(\"passwd\", pw);\n\n RetrofitInstance.getInstance().getServ", "end": 1938, "score": 0.993986964225769, "start": 1936, "tag": "PASSWORD", "value": "pw" } ]
null
[]
package com.inu.amadda.view.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.WindowManager; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.inu.amadda.R; import com.inu.amadda.etc.Constant; import com.inu.amadda.model.SuccessResponse; import com.inu.amadda.network.RetrofitInstance; import com.inu.amadda.util.PreferenceManager; import java.util.HashMap; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SplashActivity extends AppCompatActivity { private String id, pw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Handler handler = new Handler(); if (checkFirstLogin()) { handler.postDelayed(this::goToLogin, 1600); } else { requestLogin(id, pw); } } private boolean checkFirstLogin() { id = PreferenceManager.getInstance().getSharedPreference(getApplicationContext(), Constant.Preference.ID, null); pw = PreferenceManager.getInstance().getSharedPreference(getApplicationContext(), Constant.Preference.PASSWORD, null); String token = PreferenceManager.getInstance().getSharedPreference(getApplicationContext(), Constant.Preference.TOKEN, null); return id == null || pw == null || token == null; } private void goToLogin() { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); } private void requestLogin(String id, String pw){ HashMap<String, String> map = new HashMap<>(); map.put("id", id); map.put("passwd", pw); RetrofitInstance.getInstance().getService().Login(map).enqueue(new Callback<SuccessResponse>() { @Override public void onResponse(Call<SuccessResponse> call, Response<SuccessResponse> response) { int status = response.code(); if (response.isSuccessful()) { SuccessResponse successResponse = response.body(); if (successResponse != null) { if (successResponse.success) { saveUserInfo(id, pw, response.headers().get("token")); Intent intent = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent); finish(); } else { Toast.makeText(getApplicationContext(), "잠시 후 다시 시도해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); Log.d("SplashActivity", successResponse.message); } } else { Toast.makeText(getApplicationContext(), "잠시 후 다시 시도해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); } } else if (status == 400){ Toast.makeText(getApplicationContext(), "아이디 및 비밀번호를 확인해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); } else { Toast.makeText(getApplicationContext(), "잠시 후 다시 시도해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); Log.d("SplashActivity", status + ""); } } @Override public void onFailure(Call<SuccessResponse> call, Throwable t) { Toast.makeText(getApplicationContext(), "인터넷 연결 상태를 확인해주세요.", Toast.LENGTH_SHORT).show(); goToLogin(); Log.d("SplashActivity", t.getMessage()); } }); } private void saveUserInfo(String id, String pw, String token){ PreferenceManager.getInstance().putSharedPreference(getApplicationContext(), Constant.Preference.ID, id); PreferenceManager.getInstance().putSharedPreference(getApplicationContext(), Constant.Preference.PASSWORD, pw); PreferenceManager.getInstance().putSharedPreference(getApplicationContext(), Constant.Preference.TOKEN, token); Log.d("SplashActivity", "ID: " + id + ", PASSWORD: " + pw + ", TOKEN: " + token); } }
4,687
0.597195
0.595003
112
39.74107
35.31358
133
false
false
0
0
0
0
0
0
0.946429
false
false
2
d663a0d4d1b0252b9e358efa9eed27f47c5cca88
30,666,066,548,722
c0765ee193a3391bd836a89fb4c5740b5b3719f2
/chapter_002/src/main/java/ru/job4j/tracker/sortByDown.java
e2c4d49fdf2dc192ad4e66a8e86df8ba924efd93
[]
no_license
Mosquitosd3/job4j
https://github.com/Mosquitosd3/job4j
b373982e5b917ba00a0844263920c8df182e0ee3
884eecab0fcde07bb4c393f7382f4c4b43904621
refs/heads/master
2021-07-16T14:23:37.533000
2021-07-11T14:22:39
2021-07-11T14:22:39
236,294,963
0
0
null
false
2020-10-13T19:04:38
2020-01-26T10:09:43
2020-07-17T10:12:12
2020-10-13T19:04:36
147
0
0
1
Java
false
false
package ru.job4j.tracker; import java.util.Comparator; public class sortByDown implements Comparator<Item> { @Override public int compare(Item itemFirst, Item itemSecond) { return itemSecond.getName().compareTo(itemFirst.getName()); } }
UTF-8
Java
259
java
sortByDown.java
Java
[]
null
[]
package ru.job4j.tracker; import java.util.Comparator; public class sortByDown implements Comparator<Item> { @Override public int compare(Item itemFirst, Item itemSecond) { return itemSecond.getName().compareTo(itemFirst.getName()); } }
259
0.72973
0.725869
10
24.9
24.394466
67
false
false
0
0
0
0
0
0
0.4
false
false
2
e01c7a52550b02754fa3e22449115408edbf525b
33,706,903,372,049
b288ed5e719ee8a0012d674569621274eba82c91
/BankAccountKata/src/main/java/com/bank/kata/business/Transaction.java
fe42af9813153f16648b055be5b148cc35cbb12c
[]
no_license
glounis/BankAccountKata
https://github.com/glounis/BankAccountKata
a064e362fa4df88ec534420cf6639ae4cb542fc6
f26b77b8a6478c873b9adbcd77c5952748392cdc
refs/heads/master
2020-03-31T17:45:19.699000
2018-10-23T13:52:39
2018-10-23T13:52:39
152,433,434
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bank.kata.business; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Transaction { @Id private long id; @Column(columnDefinition="Decimal(10,2)") private double amount; private String transactionType; private Date transactionDate; @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name="account_id" , nullable = false) private Account account; //other attributes if need ... //getters and setters public long getId() { return id; } public void setId(long id) { this.id = id; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getTransactionType() { return transactionType; } public void setTransactionType(String transactionType) { this.transactionType = transactionType; } public Date getTransactionDate() { return transactionDate; } public void setTransactionDate(Date transactionDate) { this.transactionDate = transactionDate; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } }
UTF-8
Java
1,370
java
Transaction.java
Java
[]
null
[]
package com.bank.kata.business; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Transaction { @Id private long id; @Column(columnDefinition="Decimal(10,2)") private double amount; private String transactionType; private Date transactionDate; @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name="account_id" , nullable = false) private Account account; //other attributes if need ... //getters and setters public long getId() { return id; } public void setId(long id) { this.id = id; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getTransactionType() { return transactionType; } public void setTransactionType(String transactionType) { this.transactionType = transactionType; } public Date getTransactionDate() { return transactionDate; } public void setTransactionDate(Date transactionDate) { this.transactionDate = transactionDate; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } }
1,370
0.719708
0.717518
57
22.035088
16.369596
57
false
false
0
0
0
0
0
0
1.368421
false
false
2
2e6e31bf3764a37ddcf2c990c3e3787f0baac9a1
9,466,107,951,085
1df2d203adf6a6962041e00e03d6361ab6e33b24
/MyApplication/app/src/main/java/au/com/hacklord/goodbuddy/activity/MainActivity.java
0021de449f37e8381260bcf66866557ce21497ae
[]
no_license
crazedpeanut/GoodBuddyAndroid
https://github.com/crazedpeanut/GoodBuddyAndroid
aa851322746390dc0f972b7d660f459ecfd044ff
437699b173cac3b3e443f1ab20b7e623a96fa4c5
refs/heads/master
2021-07-10T15:49:42.017000
2016-08-28T06:24:55
2016-08-28T06:24:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package au.com.hacklord.goodbuddy.activity; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import au.com.hacklord.goodbuddy.R; import au.com.hacklord.goodbuddy.fragment.BuddyFragment; import au.com.hacklord.goodbuddy.fragment.LoginFragment; import au.com.hacklord.goodbuddy.manager.UserManager; import au.com.hacklord.goodbuddy.model.AppError; import au.com.hacklord.goodbuddy.rx.IRxEvent; import au.com.hacklord.goodbuddy.session.SessionErrors; import rx.Subscriber; import rx.Subscription; public class MainActivity extends AppCompatActivity implements LoginFragment.LoginSuccessListener{ public interface SwapViewRequestListener { void onSwapViewRequest(Fragment newFrag, boolean addToBackStack); } static final String TAG = "MainActivity"; LoginFragment loginFragment; BuddyFragment buddyFragment; public SwapViewRequestListener swapViewRequestListener; View rootView; View fragmentContainer; Subscription errorSubscription; Snackbar snackbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); swapViewRequestListener = new SwapViewRequestListener() { @Override public void onSwapViewRequest(Fragment newFrag, boolean addToBackStack) { swapFragment(newFrag, addToBackStack); } }; fragmentContainer = findViewById(R.id.main_fragment_container); rootView = getWindow().getDecorView().getRootView(); initFragments(); } @Override protected void onResume() { super.onResume(); errorSubscription = SessionErrors.getInstance().getEventBus().getEvents() .subscribe(new Subscriber<IRxEvent<AppError>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.e(TAG, e.getMessage()); } @Override public void onNext(IRxEvent<AppError> appErrorIRxEvent) { displaySnackbar(appErrorIRxEvent.getData().getMessage()); } }); checkIsLoggedIn(); } @Override protected void onDestroy() { super.onDestroy(); errorSubscription.unsubscribe(); } void displaySnackbar(String message) { if(snackbar == null) { snackbar = Snackbar.make(rootView, message, Snackbar.LENGTH_LONG); } else if(snackbar.isShown()) { snackbar.dismiss(); } } void checkIsLoggedIn() { if(!UserManager.isLoggedIn()) { swapFragment(loginFragment, false); } } void initFragments() { loginFragment = LoginFragment.newInstance(); buddyFragment = BuddyFragment.newInstance(); } void swapFragment(Fragment fragment, boolean addToBackStack) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.main_fragment_container, fragment); if(addToBackStack) { fragmentTransaction.addToBackStack(null); } fragmentTransaction.commit(); } @Override public void onLoginSuccess() { swapFragment(buddyFragment, false); } }
UTF-8
Java
3,990
java
MainActivity.java
Java
[]
null
[]
package au.com.hacklord.goodbuddy.activity; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import au.com.hacklord.goodbuddy.R; import au.com.hacklord.goodbuddy.fragment.BuddyFragment; import au.com.hacklord.goodbuddy.fragment.LoginFragment; import au.com.hacklord.goodbuddy.manager.UserManager; import au.com.hacklord.goodbuddy.model.AppError; import au.com.hacklord.goodbuddy.rx.IRxEvent; import au.com.hacklord.goodbuddy.session.SessionErrors; import rx.Subscriber; import rx.Subscription; public class MainActivity extends AppCompatActivity implements LoginFragment.LoginSuccessListener{ public interface SwapViewRequestListener { void onSwapViewRequest(Fragment newFrag, boolean addToBackStack); } static final String TAG = "MainActivity"; LoginFragment loginFragment; BuddyFragment buddyFragment; public SwapViewRequestListener swapViewRequestListener; View rootView; View fragmentContainer; Subscription errorSubscription; Snackbar snackbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); swapViewRequestListener = new SwapViewRequestListener() { @Override public void onSwapViewRequest(Fragment newFrag, boolean addToBackStack) { swapFragment(newFrag, addToBackStack); } }; fragmentContainer = findViewById(R.id.main_fragment_container); rootView = getWindow().getDecorView().getRootView(); initFragments(); } @Override protected void onResume() { super.onResume(); errorSubscription = SessionErrors.getInstance().getEventBus().getEvents() .subscribe(new Subscriber<IRxEvent<AppError>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.e(TAG, e.getMessage()); } @Override public void onNext(IRxEvent<AppError> appErrorIRxEvent) { displaySnackbar(appErrorIRxEvent.getData().getMessage()); } }); checkIsLoggedIn(); } @Override protected void onDestroy() { super.onDestroy(); errorSubscription.unsubscribe(); } void displaySnackbar(String message) { if(snackbar == null) { snackbar = Snackbar.make(rootView, message, Snackbar.LENGTH_LONG); } else if(snackbar.isShown()) { snackbar.dismiss(); } } void checkIsLoggedIn() { if(!UserManager.isLoggedIn()) { swapFragment(loginFragment, false); } } void initFragments() { loginFragment = LoginFragment.newInstance(); buddyFragment = BuddyFragment.newInstance(); } void swapFragment(Fragment fragment, boolean addToBackStack) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.main_fragment_container, fragment); if(addToBackStack) { fragmentTransaction.addToBackStack(null); } fragmentTransaction.commit(); } @Override public void onLoginSuccess() { swapFragment(buddyFragment, false); } }
3,990
0.65213
0.650877
139
27.705036
24.736731
98
false
false
0
0
0
0
0
0
0.467626
false
false
2
d5cb97c006f664618f33d6fbddd6a0a803a5cfa8
16,982,300,744,904
3a40cde297447e6802cf5c138c08f026a62986f2
/ovs-driver/src/main/java/org/opendaylight/unimgr/mef/nrp/ovs/tapi/DataObjectModificationQualifier.java
0ca75d855d72db8d413cc036a5b797a8f302d210
[]
no_license
mjethanandani/unimgr
https://github.com/mjethanandani/unimgr
5e56ca76d83146e6745b70479faa46a246f0c584
059c0601d30569da4c9c61e76915274097ffb504
refs/heads/master
2022-04-09T00:23:43.391000
2019-10-04T19:28:05
2019-10-04T19:28:05
114,388,908
0
0
null
true
2017-12-15T16:12:22
2017-12-15T16:12:22
2017-05-31T22:06:29
2017-12-15T11:18:59
2,032
0
0
0
null
false
null
/* * Copyright (c) 2018 Cisco Systems Inc and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.unimgr.mef.nrp.ovs.tapi; import static org.opendaylight.unimgr.mef.nrp.ovs.util.OvsCapabilitiesService.NodeCapability.OVSDB; import static org.opendaylight.unimgr.utils.CapabilitiesService.Capability.Mode.AND; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Function; import org.opendaylight.mdsal.binding.api.DataBroker; import org.opendaylight.mdsal.binding.api.DataObjectModification; import org.opendaylight.unimgr.utils.CapabilitiesService; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint; import org.opendaylight.yangtools.yang.binding.DataObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class created to classify object according to its modification types. * * @author marek.ryznar@amartus.com */ public class DataObjectModificationQualifier { private static final Logger LOG = LoggerFactory.getLogger(DataObjectModificationQualifier.class); private CapabilitiesService capabilitiesService; public DataObjectModificationQualifier(DataBroker dataBroker) { capabilitiesService = new CapabilitiesService(dataBroker); } private Function<Node,Boolean> isOvs = node -> capabilitiesService.node(node).isSupporting(AND, OVSDB); protected void checkNodes(List<DataObjectModification<? extends DataObject>> nodes, Map<TerminationPoint,String> toAddMap, Map<TerminationPoint,String> toUpdateMap, Map<TerminationPoint,String> toDeleteMap) { Node n; for (DataObjectModification<?> node: nodes) { switch (node.getModificationType()) { //new ovs node case WRITE : n = (Node) node.getDataAfter(); if (!isOvs.apply(n) || n.getTerminationPoint() == null) { break; } String bn1 = n.augmentation(OvsdbBridgeAugmentation.class).getBridgeName().getValue(); n.getTerminationPoint().forEach(tp -> toAddMap.put(tp,bn1)); break; case SUBTREE_MODIFIED: checkTerminationPoints(node, toAddMap, toUpdateMap, toDeleteMap); break; //whole ovs-node eg. s1 deleted case DELETE: n = (Node) node.getDataBefore(); if (!isOvs.apply(n) || n.getTerminationPoint() == null) { break; } String bn2 = n.augmentation(OvsdbBridgeAugmentation.class).getBridgeName().getValue(); n.getTerminationPoint().forEach(tp -> toDeleteMap.put(tp,bn2)); break; default: LOG.debug("Not supported modification type: {}",node.getModificationType()); break; } } } private void checkTerminationPoints(DataObjectModification<?> node, Map<TerminationPoint,String> toAddMap, Map<TerminationPoint,String> toUpdateMap, Map<TerminationPoint,String> toDeleteMap) { Node n = (Node) node.getDataAfter(); if (!isOvs.apply(n)) { return ; } String bridgeName = n.augmentation(OvsdbBridgeAugmentation.class).getBridgeName().getValue(); Collection<? extends DataObjectModification<? extends DataObject>> modifiedChildren = node.getModifiedChildren(); TerminationPoint terminationPoint; for (DataObjectModification<?> tp: modifiedChildren) { if (!tp.getDataType().equals(TerminationPoint.class)) { continue; } switch (tp.getModificationType()) { //new port added eg. s1-eth7 case WRITE: terminationPoint = (TerminationPoint) tp.getDataAfter(); toAddMap.put(terminationPoint,bridgeName); break; case SUBTREE_MODIFIED: terminationPoint = (TerminationPoint) tp.getDataAfter(); if (!tp.getDataBefore().equals(tp.getDataAfter())) { toUpdateMap.put(terminationPoint,bridgeName); } break; case DELETE: terminationPoint = (TerminationPoint) tp.getDataBefore(); toDeleteMap.put(terminationPoint,bridgeName); break; default: LOG.debug("Not supported modification type: SUBTREE_MODIFIED.{}",tp.getModificationType()); break; } } } }
UTF-8
Java
5,383
java
DataObjectModificationQualifier.java
Java
[ { "context": "according to its modification types.\n *\n * @author marek.ryznar@amartus.com\n */\npublic class DataObjectModificationQualifier ", "end": 1439, "score": 0.9998468160629272, "start": 1415, "tag": "EMAIL", "value": "marek.ryznar@amartus.com" } ]
null
[]
/* * Copyright (c) 2018 Cisco Systems Inc and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.unimgr.mef.nrp.ovs.tapi; import static org.opendaylight.unimgr.mef.nrp.ovs.util.OvsCapabilitiesService.NodeCapability.OVSDB; import static org.opendaylight.unimgr.utils.CapabilitiesService.Capability.Mode.AND; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Function; import org.opendaylight.mdsal.binding.api.DataBroker; import org.opendaylight.mdsal.binding.api.DataObjectModification; import org.opendaylight.unimgr.utils.CapabilitiesService; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint; import org.opendaylight.yangtools.yang.binding.DataObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class created to classify object according to its modification types. * * @author <EMAIL> */ public class DataObjectModificationQualifier { private static final Logger LOG = LoggerFactory.getLogger(DataObjectModificationQualifier.class); private CapabilitiesService capabilitiesService; public DataObjectModificationQualifier(DataBroker dataBroker) { capabilitiesService = new CapabilitiesService(dataBroker); } private Function<Node,Boolean> isOvs = node -> capabilitiesService.node(node).isSupporting(AND, OVSDB); protected void checkNodes(List<DataObjectModification<? extends DataObject>> nodes, Map<TerminationPoint,String> toAddMap, Map<TerminationPoint,String> toUpdateMap, Map<TerminationPoint,String> toDeleteMap) { Node n; for (DataObjectModification<?> node: nodes) { switch (node.getModificationType()) { //new ovs node case WRITE : n = (Node) node.getDataAfter(); if (!isOvs.apply(n) || n.getTerminationPoint() == null) { break; } String bn1 = n.augmentation(OvsdbBridgeAugmentation.class).getBridgeName().getValue(); n.getTerminationPoint().forEach(tp -> toAddMap.put(tp,bn1)); break; case SUBTREE_MODIFIED: checkTerminationPoints(node, toAddMap, toUpdateMap, toDeleteMap); break; //whole ovs-node eg. s1 deleted case DELETE: n = (Node) node.getDataBefore(); if (!isOvs.apply(n) || n.getTerminationPoint() == null) { break; } String bn2 = n.augmentation(OvsdbBridgeAugmentation.class).getBridgeName().getValue(); n.getTerminationPoint().forEach(tp -> toDeleteMap.put(tp,bn2)); break; default: LOG.debug("Not supported modification type: {}",node.getModificationType()); break; } } } private void checkTerminationPoints(DataObjectModification<?> node, Map<TerminationPoint,String> toAddMap, Map<TerminationPoint,String> toUpdateMap, Map<TerminationPoint,String> toDeleteMap) { Node n = (Node) node.getDataAfter(); if (!isOvs.apply(n)) { return ; } String bridgeName = n.augmentation(OvsdbBridgeAugmentation.class).getBridgeName().getValue(); Collection<? extends DataObjectModification<? extends DataObject>> modifiedChildren = node.getModifiedChildren(); TerminationPoint terminationPoint; for (DataObjectModification<?> tp: modifiedChildren) { if (!tp.getDataType().equals(TerminationPoint.class)) { continue; } switch (tp.getModificationType()) { //new port added eg. s1-eth7 case WRITE: terminationPoint = (TerminationPoint) tp.getDataAfter(); toAddMap.put(terminationPoint,bridgeName); break; case SUBTREE_MODIFIED: terminationPoint = (TerminationPoint) tp.getDataAfter(); if (!tp.getDataBefore().equals(tp.getDataAfter())) { toUpdateMap.put(terminationPoint,bridgeName); } break; case DELETE: terminationPoint = (TerminationPoint) tp.getDataBefore(); toDeleteMap.put(terminationPoint,bridgeName); break; default: LOG.debug("Not supported modification type: SUBTREE_MODIFIED.{}",tp.getModificationType()); break; } } } }
5,366
0.620658
0.613598
116
45.405174
34.898121
138
false
false
0
0
0
0
0
0
0.698276
false
false
2
e51b82676fa44119c96dd32dd765c2429c29dcb5
6,167,573,093,314
e0cd93e974f1144d8a8ecef3bc0300e48949ab09
/client/src/test/java/nl/tudelft/oopp/demo/user/calendar/logic/CalendarItemDialogLogicTest.java
edfc89cf23013614676b51b2882b4cfccc160156
[]
no_license
mvdschoot/campus_reservation
https://github.com/mvdschoot/campus_reservation
01d5fc3242898ae2fb41fbccac2bdf8b6cd23241
53f48ea7787662e7a16bf61637ed1d96f6814e96
refs/heads/master
2023-08-15T07:58:38.289000
2021-09-23T15:13:03
2021-09-23T15:13:03
409,632,547
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.tudelft.oopp.demo.user.calendar.logic; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import java.awt.Color; import java.io.UnsupportedEncodingException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockserver.client.MockServerClient; import org.mockserver.integration.ClientAndServer; /** * Tests the calendarItemDialogLogic class. * Mocks a server to get custom responses and test possible cases. */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class CalendarItemDialogLogicTest { private ClientAndServer mockServer; /** * Mocks a deleteItem POST endpoint that responds with a 200 status code. */ void expectationPostTrue() { new MockServerClient("127.0.0.1", 8080) .when(request().withMethod("POST") .withPath("/deleteItem"), exactly(1)) .respond(response().withStatusCode(200)); } /** * Mocks a deleteReservation POST endpoint that responds with a 200 status code. */ void expectationPostTrue2() { new MockServerClient("127.0.0.1", 8080) .when(request().withMethod("POST") .withPath("/deleteReservation"), exactly(1)) .respond(response().withStatusCode(200)); } /** * Mocks a deleteBikeReservation POST endpoint that responds with a 200 status code. */ void expectationPostTrue3() { new MockServerClient("127.0.0.1", 8080) .when(request().withMethod("POST") .withPath("/deleteBikeReservation"), exactly(1)) .respond(response().withStatusCode(200)); } /** * Before starting the tests the server gets initialized + expectations set. */ @BeforeAll public void startServer() { mockServer = startClientAndServer(8080); expectationPostTrue(); expectationPostTrue2(); expectationPostTrue3(); } /** * After all the tests the server gets shut down. */ @AfterAll public void stopServer() { mockServer.stop(); } /** * Tests the object constructor of the class. */ @Test void objectConstructor() { assertNotNull(new CalendarItemDialogLogic()); } /** * Tests the setItemType method. */ @Test void setItemTypeTest() { CalendarItemDialogLogic.setItemType(Color.BLACK); assertFalse(CalendarItemDialogLogic.reservation); CalendarItemDialogLogic.setItemType(Color.ORANGE); assertTrue(CalendarItemDialogLogic.item); assertFalse(CalendarItemDialogLogic.reservation); assertFalse(CalendarItemDialogLogic.bikeReservation); CalendarItemDialogLogic.setItemType(Color.MAGENTA); assertTrue(CalendarItemDialogLogic.bikeReservation); CalendarItemDialogLogic.setItemType(Color.CYAN); assertTrue(CalendarItemDialogLogic.reservation); } /** * Tests the deleteItem method. */ @Test void deleteItemTest() throws UnsupportedEncodingException { assertTrue(CalendarItemDialogLogic.deleteItem(0)); assertFalse(CalendarItemDialogLogic.bikeReservation); assertFalse(CalendarItemDialogLogic.reservation); assertFalse(CalendarItemDialogLogic.item); } /** * Tests the deleteReservation method. */ @Test void deleteReservationTest() throws UnsupportedEncodingException { CalendarItemDialogLogic.reservation = true; assertTrue(CalendarItemDialogLogic.deleteReservation(0)); CalendarItemDialogLogic.bikeReservation = true; assertTrue(CalendarItemDialogLogic.deleteReservation(0)); assertFalse(CalendarItemDialogLogic.deleteReservation(0)); } }
UTF-8
Java
4,350
java
CalendarItemDialogLogicTest.java
Java
[ { "context": "ctationPostTrue() {\n new MockServerClient(\"127.0.0.1\", 8080)\n .when(request().withMetho", "end": 1215, "score": 0.9997382760047913, "start": 1206, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "tationPostTrue2() {\n new MockS...
null
[]
package nl.tudelft.oopp.demo.user.calendar.logic; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import java.awt.Color; import java.io.UnsupportedEncodingException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockserver.client.MockServerClient; import org.mockserver.integration.ClientAndServer; /** * Tests the calendarItemDialogLogic class. * Mocks a server to get custom responses and test possible cases. */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class CalendarItemDialogLogicTest { private ClientAndServer mockServer; /** * Mocks a deleteItem POST endpoint that responds with a 200 status code. */ void expectationPostTrue() { new MockServerClient("127.0.0.1", 8080) .when(request().withMethod("POST") .withPath("/deleteItem"), exactly(1)) .respond(response().withStatusCode(200)); } /** * Mocks a deleteReservation POST endpoint that responds with a 200 status code. */ void expectationPostTrue2() { new MockServerClient("127.0.0.1", 8080) .when(request().withMethod("POST") .withPath("/deleteReservation"), exactly(1)) .respond(response().withStatusCode(200)); } /** * Mocks a deleteBikeReservation POST endpoint that responds with a 200 status code. */ void expectationPostTrue3() { new MockServerClient("127.0.0.1", 8080) .when(request().withMethod("POST") .withPath("/deleteBikeReservation"), exactly(1)) .respond(response().withStatusCode(200)); } /** * Before starting the tests the server gets initialized + expectations set. */ @BeforeAll public void startServer() { mockServer = startClientAndServer(8080); expectationPostTrue(); expectationPostTrue2(); expectationPostTrue3(); } /** * After all the tests the server gets shut down. */ @AfterAll public void stopServer() { mockServer.stop(); } /** * Tests the object constructor of the class. */ @Test void objectConstructor() { assertNotNull(new CalendarItemDialogLogic()); } /** * Tests the setItemType method. */ @Test void setItemTypeTest() { CalendarItemDialogLogic.setItemType(Color.BLACK); assertFalse(CalendarItemDialogLogic.reservation); CalendarItemDialogLogic.setItemType(Color.ORANGE); assertTrue(CalendarItemDialogLogic.item); assertFalse(CalendarItemDialogLogic.reservation); assertFalse(CalendarItemDialogLogic.bikeReservation); CalendarItemDialogLogic.setItemType(Color.MAGENTA); assertTrue(CalendarItemDialogLogic.bikeReservation); CalendarItemDialogLogic.setItemType(Color.CYAN); assertTrue(CalendarItemDialogLogic.reservation); } /** * Tests the deleteItem method. */ @Test void deleteItemTest() throws UnsupportedEncodingException { assertTrue(CalendarItemDialogLogic.deleteItem(0)); assertFalse(CalendarItemDialogLogic.bikeReservation); assertFalse(CalendarItemDialogLogic.reservation); assertFalse(CalendarItemDialogLogic.item); } /** * Tests the deleteReservation method. */ @Test void deleteReservationTest() throws UnsupportedEncodingException { CalendarItemDialogLogic.reservation = true; assertTrue(CalendarItemDialogLogic.deleteReservation(0)); CalendarItemDialogLogic.bikeReservation = true; assertTrue(CalendarItemDialogLogic.deleteReservation(0)); assertFalse(CalendarItemDialogLogic.deleteReservation(0)); } }
4,350
0.674023
0.65954
129
32.728683
24.897543
88
false
false
0
0
0
0
0
0
0.395349
false
false
2
6b9f4b252861ca1e8be6ff272fd452f1d4d9eaf9
28,561,532,564,281
8b21af6b94a35c4c0df66034ac30555c244f2f3f
/src/main/java/by/epam/training/javaWEB/finalTask/controller/command/CommandProvider.java
a02f37979a11cd2db341bf15d53af52312b589c8
[]
no_license
elizaber93/JWD-FinalTask
https://github.com/elizaber93/JWD-FinalTask
a565299aa83bfb5f288d048506006020cab372d0
c9d245675544543eb859202a904d96babb59e0a7
refs/heads/main
2023-04-30T04:37:59.433000
2021-05-18T12:11:43
2021-05-18T12:11:43
344,507,270
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.epam.training.javaWEB.finalTask.controller.command; import by.epam.training.javaWEB.finalTask.controller.command.impl.*; import org.apache.log4j.Logger; import java.util.HashMap; import java.util.Map; public class CommandProvider { private final Map<CommandName, Command> commands = new HashMap<>(); public CommandProvider() { //Add all commands commands.put(CommandName.SUPPLY_ADDITION, new SupplyAddition()); commands.put(CommandName.UPDATE_PRODUCT, new UpdateProduct()); commands.put(CommandName.UPDATE_SERVICE, new UpdateService()); commands.put(CommandName.SEE_SERVICES, new SeeServiceList()); commands.put(CommandName.SERVICE_ADDITION, new ServiceAddition()); commands.put(CommandName.ADD_SERVICE, new AddService()); commands.put(CommandName.SEE_PRODUCTS, new SeeProductList()); commands.put(CommandName.ADD_PRODUCT,new AddProduct()); commands.put(CommandName.PRODUCT_ADDITION, new ProductAddition()); commands.put(CommandName.UPDATE_USER, new UpdateUser()); commands.put(CommandName.SEE_USERS,new SeeUserList()); commands.put(CommandName.ADD_ARTICLE, new AddArticle()); commands.put(CommandName.UPDATE_SUPPLIER, new UpdateSupplier()); commands.put(CommandName.SAVE_USER_DETAIL, new SaveUserDetail()); commands.put(CommandName.GOTO_EDIT_PROFILE, new GoToEditProfile()); commands.put(CommandName.LOGOUT, new LogOut()); commands.put(CommandName.GOTO, new GoTo()); commands.put(CommandName.CHANGELOC,new ChangeLoc()); commands.put(CommandName.LOGIN, new LogIn()); commands.put(CommandName.REGISTRATION, new Registration()); commands.put(CommandName.ADD_SUPPlY, new AddSupply()); commands.put(CommandName.ADD_SUPPLIER, new AddSupplier()); commands.put(CommandName.SEE_SUPPLIERS, new SeeSupplierList()); } public Command takeCommand(String name) { CommandName commandName; commandName = CommandName.valueOf(name.toUpperCase()); return commands.get(commandName); } }
UTF-8
Java
2,122
java
CommandProvider.java
Java
[]
null
[]
package by.epam.training.javaWEB.finalTask.controller.command; import by.epam.training.javaWEB.finalTask.controller.command.impl.*; import org.apache.log4j.Logger; import java.util.HashMap; import java.util.Map; public class CommandProvider { private final Map<CommandName, Command> commands = new HashMap<>(); public CommandProvider() { //Add all commands commands.put(CommandName.SUPPLY_ADDITION, new SupplyAddition()); commands.put(CommandName.UPDATE_PRODUCT, new UpdateProduct()); commands.put(CommandName.UPDATE_SERVICE, new UpdateService()); commands.put(CommandName.SEE_SERVICES, new SeeServiceList()); commands.put(CommandName.SERVICE_ADDITION, new ServiceAddition()); commands.put(CommandName.ADD_SERVICE, new AddService()); commands.put(CommandName.SEE_PRODUCTS, new SeeProductList()); commands.put(CommandName.ADD_PRODUCT,new AddProduct()); commands.put(CommandName.PRODUCT_ADDITION, new ProductAddition()); commands.put(CommandName.UPDATE_USER, new UpdateUser()); commands.put(CommandName.SEE_USERS,new SeeUserList()); commands.put(CommandName.ADD_ARTICLE, new AddArticle()); commands.put(CommandName.UPDATE_SUPPLIER, new UpdateSupplier()); commands.put(CommandName.SAVE_USER_DETAIL, new SaveUserDetail()); commands.put(CommandName.GOTO_EDIT_PROFILE, new GoToEditProfile()); commands.put(CommandName.LOGOUT, new LogOut()); commands.put(CommandName.GOTO, new GoTo()); commands.put(CommandName.CHANGELOC,new ChangeLoc()); commands.put(CommandName.LOGIN, new LogIn()); commands.put(CommandName.REGISTRATION, new Registration()); commands.put(CommandName.ADD_SUPPlY, new AddSupply()); commands.put(CommandName.ADD_SUPPLIER, new AddSupplier()); commands.put(CommandName.SEE_SUPPLIERS, new SeeSupplierList()); } public Command takeCommand(String name) { CommandName commandName; commandName = CommandName.valueOf(name.toUpperCase()); return commands.get(commandName); } }
2,122
0.708765
0.708294
47
44.148937
27.863634
75
false
false
0
0
0
0
0
0
1.191489
false
false
2
8ee9220c36e9380bb273f92bc74d6a84dd9206fb
4,398,046,571,354
321bcb51cdd570148ce45d575d613c81ca8bee5b
/app/src/main/java/com/example/mkhade/todoapp/MainActivity.java
dbf6ca2a5a5c53081db8d56893926c974bf4ac8d
[ "Apache-2.0" ]
permissive
mug797/ToDoApp
https://github.com/mug797/ToDoApp
99ac08cebc190ff2902b4b2c0e3efe7ee0ffd141
e9fe0415a78ddc5ba970b1a546898794f2b2a9da
refs/heads/master
2021-01-19T04:48:52.044000
2016-09-28T08:07:39
2016-09-28T08:07:39
69,438,869
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mkhade.todoapp; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; ArrayList<String> items; ArrayAdapter<String> itemsAdapter; ListView lvItems; private final int CODE_GET_EDITED_NAME = 7; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = "MyPrefs" ; private final int ITEM_ADD = 1; private final int ITEM_MODIFIED = 2; private final int ITEM_REMOVED = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lvItems = (ListView) findViewById(R.id.lvItems); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); readItems(); itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); lvItems.setAdapter(itemsAdapter); setupListViewListener(); } private void readItems() { Set<String> h_set = sharedpreferences.getStringSet("key", null); if (h_set != null) items = new ArrayList<String>(h_set); else items = new ArrayList<String>(); } private void writeItems(String newItem, int position, int action){ itemsAdapter.notifyDataSetChanged(); if (newItem.equals("")) return; switch (action) { case ITEM_ADD: if (!items.contains(newItem)) items.add(newItem); else { Toast.makeText(this, newItem +" : already present! :-)", Toast.LENGTH_SHORT).show(); } break; case ITEM_MODIFIED: items.set(position, newItem); break; case ITEM_REMOVED: items.remove(newItem); break; default: Log.e(TAG, "Unrecognised action"); assert(false); } } @Override protected void onPause() { super.onPause(); SharedPreferences.Editor editor = sharedpreferences.edit(); Set<String> h_set = new HashSet<String>(); h_set.addAll(items); editor.putStringSet("key", h_set); editor.commit(); } public void onAddItem(View v){ EditText etNewText = (EditText) findViewById(R.id.etNewItem); String itemText = etNewText.getText().toString(); etNewText.setText(""); writeItems(itemText, -1, ITEM_ADD); Log.wtf(TAG, ""+Thread.currentThread().getStackTrace()[2].getLineNumber()); } private void setupListViewListener(){ lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { TextView txt = (TextView) parent.getChildAt(position- lvItems.getFirstVisiblePosition()); writeItems(txt.getText().toString(), position, ITEM_REMOVED); Log.wtf(TAG, ""+ txt.getText().toString() + ": " + position + " :" + Thread.currentThread().getStackTrace()[2].getLineNumber()); return true; } }); lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, EditItemActivity.class); intent.putExtra("position", position); TextView txt = (TextView) parent.getChildAt(position - lvItems.getFirstVisiblePosition()); intent.putExtra("item_name", txt.getText().toString()); startActivityForResult(intent, CODE_GET_EDITED_NAME); } }); }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == RESULT_OK && requestCode == CODE_GET_EDITED_NAME) { String original_item_name = data.getExtras().getString("original_name"); String edited_item_name = data.getExtras().getString("edited_name"); int position = data.getExtras().getInt("position"); Toast.makeText(this, "Modified " + original_item_name + " to " + edited_item_name, Toast.LENGTH_SHORT).show(); writeItems(edited_item_name, position, ITEM_MODIFIED); } } private void printItemsArray(){ int pos = 0; for (String i:items) { Log.wtf(TAG, "Item = " + ++pos + " : " + i); } } }
UTF-8
Java
5,304
java
MainActivity.java
Java
[ { "context": "package com.example.mkhade.todoapp;\n\nimport android.app.Activity;\nimport and", "end": 26, "score": 0.9500360488891602, "start": 20, "tag": "USERNAME", "value": "mkhade" } ]
null
[]
package com.example.mkhade.todoapp; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; ArrayList<String> items; ArrayAdapter<String> itemsAdapter; ListView lvItems; private final int CODE_GET_EDITED_NAME = 7; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = "MyPrefs" ; private final int ITEM_ADD = 1; private final int ITEM_MODIFIED = 2; private final int ITEM_REMOVED = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lvItems = (ListView) findViewById(R.id.lvItems); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); readItems(); itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); lvItems.setAdapter(itemsAdapter); setupListViewListener(); } private void readItems() { Set<String> h_set = sharedpreferences.getStringSet("key", null); if (h_set != null) items = new ArrayList<String>(h_set); else items = new ArrayList<String>(); } private void writeItems(String newItem, int position, int action){ itemsAdapter.notifyDataSetChanged(); if (newItem.equals("")) return; switch (action) { case ITEM_ADD: if (!items.contains(newItem)) items.add(newItem); else { Toast.makeText(this, newItem +" : already present! :-)", Toast.LENGTH_SHORT).show(); } break; case ITEM_MODIFIED: items.set(position, newItem); break; case ITEM_REMOVED: items.remove(newItem); break; default: Log.e(TAG, "Unrecognised action"); assert(false); } } @Override protected void onPause() { super.onPause(); SharedPreferences.Editor editor = sharedpreferences.edit(); Set<String> h_set = new HashSet<String>(); h_set.addAll(items); editor.putStringSet("key", h_set); editor.commit(); } public void onAddItem(View v){ EditText etNewText = (EditText) findViewById(R.id.etNewItem); String itemText = etNewText.getText().toString(); etNewText.setText(""); writeItems(itemText, -1, ITEM_ADD); Log.wtf(TAG, ""+Thread.currentThread().getStackTrace()[2].getLineNumber()); } private void setupListViewListener(){ lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { TextView txt = (TextView) parent.getChildAt(position- lvItems.getFirstVisiblePosition()); writeItems(txt.getText().toString(), position, ITEM_REMOVED); Log.wtf(TAG, ""+ txt.getText().toString() + ": " + position + " :" + Thread.currentThread().getStackTrace()[2].getLineNumber()); return true; } }); lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, EditItemActivity.class); intent.putExtra("position", position); TextView txt = (TextView) parent.getChildAt(position - lvItems.getFirstVisiblePosition()); intent.putExtra("item_name", txt.getText().toString()); startActivityForResult(intent, CODE_GET_EDITED_NAME); } }); }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == RESULT_OK && requestCode == CODE_GET_EDITED_NAME) { String original_item_name = data.getExtras().getString("original_name"); String edited_item_name = data.getExtras().getString("edited_name"); int position = data.getExtras().getInt("position"); Toast.makeText(this, "Modified " + original_item_name + " to " + edited_item_name, Toast.LENGTH_SHORT).show(); writeItems(edited_item_name, position, ITEM_MODIFIED); } } private void printItemsArray(){ int pos = 0; for (String i:items) { Log.wtf(TAG, "Item = " + ++pos + " : " + i); } } }
5,304
0.625189
0.623492
143
36.0979
29.171141
145
false
false
0
0
0
0
0
0
0.811189
false
false
2
f1e7f8578d2451f7a1fd3f78bd779530b7c9e8a1
4,398,046,573,162
bff1c1e4ff0113b183e65ff5eda249f832948921
/src/test/java/fr/pragmaticmemory/fileProcessing/routeProvider/StringListReaderTest.java
280ce24fe506e833eda01ebc5444c8f0c099848f
[]
no_license
PragmaticMemory/PragmaticMemory
https://github.com/PragmaticMemory/PragmaticMemory
df26d0819f0573adbd3d506d3be76be149997744
4a83af459b666bd9508606f2075844a442f6c6ee
refs/heads/master
2016-09-10T00:15:17.898000
2014-12-19T15:44:37
2014-12-19T15:44:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.pragmaticmemory.fileProcessing.routeProvider; import java.io.BufferedReader; import java.io.IOException; import java.util.Arrays; import junit.framework.Assert; import junit.framework.TestCase; public class StringListReaderTest extends TestCase { static final String LINE_1 = "Première ligne"; // 0 - 14 (\n) static final String LINE_2 = "Seconde ligne"; // 15 - 28 (\n) static final String LINE_3 = "Troisième ligne"; // 29 - 44 (\n) static final StringListReader STRING_LIST_READER = new StringListReader(Arrays.<String>asList(LINE_1, LINE_2, LINE_3)); // public static void main(String[] args) throws IOException { // char[] cbuffer = new char[100]; // StringReader stringReader = new StringReader(LINE_1); // int read = stringReader.read(cbuffer, 3, 14); // int read2 = stringReader.read(cbuffer, 3, 1); // stringReader.reset(); // int read3 = stringReader.read(cbuffer, 3, 14); // System.out.println(read); // System.out.println(read2); // System.out.println(read3); // System.out.println(cbuffer); // } @Override public void setUp() throws Exception { STRING_LIST_READER.reset(); } public void testBufferedReaderReadLine() throws Exception { BufferedReader bufferedReader = new BufferedReader(STRING_LIST_READER); Assert.assertEquals(LINE_1, bufferedReader.readLine()); Assert.assertEquals(LINE_2, bufferedReader.readLine()); Assert.assertEquals(LINE_3, bufferedReader.readLine()); } public void testRead() throws Exception { assetRead(8, "Première", 1, 8); assetRead(7, " ligne\n", 0, 7); assetRead(13, "Seconde ligne", 0, 13); assetRead(1, "\n", 0, 1); assetRead(16, "Troisième ligne\n", 0, 16); STRING_LIST_READER.reset(); assetRead(8, "Première", 1, 8); assetRead(14, " ligne\nSeconde", 1, 14); STRING_LIST_READER.reset(); assetRead(45, "Première ligne\nSeconde ligne\nTroisième ligne\n", 0, 100); } private void assetRead(int expectedRead, String expectedString, int offset, int length) throws IOException { char[] cBuffer = new char[offset + length]; int read = STRING_LIST_READER.read(cBuffer, offset, length); Assert.assertEquals(expectedString, new String(cBuffer).substring(offset, offset + read)); Assert.assertEquals(expectedRead, read); } }
ISO-8859-1
Java
2,669
java
StringListReaderTest.java
Java
[]
null
[]
package fr.pragmaticmemory.fileProcessing.routeProvider; import java.io.BufferedReader; import java.io.IOException; import java.util.Arrays; import junit.framework.Assert; import junit.framework.TestCase; public class StringListReaderTest extends TestCase { static final String LINE_1 = "Première ligne"; // 0 - 14 (\n) static final String LINE_2 = "Seconde ligne"; // 15 - 28 (\n) static final String LINE_3 = "Troisième ligne"; // 29 - 44 (\n) static final StringListReader STRING_LIST_READER = new StringListReader(Arrays.<String>asList(LINE_1, LINE_2, LINE_3)); // public static void main(String[] args) throws IOException { // char[] cbuffer = new char[100]; // StringReader stringReader = new StringReader(LINE_1); // int read = stringReader.read(cbuffer, 3, 14); // int read2 = stringReader.read(cbuffer, 3, 1); // stringReader.reset(); // int read3 = stringReader.read(cbuffer, 3, 14); // System.out.println(read); // System.out.println(read2); // System.out.println(read3); // System.out.println(cbuffer); // } @Override public void setUp() throws Exception { STRING_LIST_READER.reset(); } public void testBufferedReaderReadLine() throws Exception { BufferedReader bufferedReader = new BufferedReader(STRING_LIST_READER); Assert.assertEquals(LINE_1, bufferedReader.readLine()); Assert.assertEquals(LINE_2, bufferedReader.readLine()); Assert.assertEquals(LINE_3, bufferedReader.readLine()); } public void testRead() throws Exception { assetRead(8, "Première", 1, 8); assetRead(7, " ligne\n", 0, 7); assetRead(13, "Seconde ligne", 0, 13); assetRead(1, "\n", 0, 1); assetRead(16, "Troisième ligne\n", 0, 16); STRING_LIST_READER.reset(); assetRead(8, "Première", 1, 8); assetRead(14, " ligne\nSeconde", 1, 14); STRING_LIST_READER.reset(); assetRead(45, "Première ligne\nSeconde ligne\nTroisième ligne\n", 0, 100); } private void assetRead(int expectedRead, String expectedString, int offset, int length) throws IOException { char[] cBuffer = new char[offset + length]; int read = STRING_LIST_READER.read(cBuffer, offset, length); Assert.assertEquals(expectedString, new String(cBuffer).substring(offset, offset + read)); Assert.assertEquals(expectedRead, read); } }
2,669
0.60556
0.579639
65
39.953846
30.21229
112
false
false
0
0
0
0
0
0
1.261539
false
false
2
dd6a37b5e135d32b9ef50ef4b40325d801fba6f0
34,574,486,734,955
f307f8b22428f03df6ccee87df282e658941db6d
/src/com/onebus/model/Bus.java
0a710e3162c88f9515eb59106880aebdd4aa9d6d
[ "Apache-2.0" ]
permissive
Mrsunsunshine/FrontOne
https://github.com/Mrsunsunshine/FrontOne
8f459b44b0e2f568f182686e2fac6e492dc86999
ac68f498d208fcc387e1aabba3eb76cc0539902c
refs/heads/master
2021-01-10T16:30:19.412000
2018-03-12T08:56:59
2018-03-12T08:56:59
48,114,655
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.onebus.model; import java.io.Serializable; public class Bus implements Serializable{ /** * */ private static final long serialVersionUID = -4717927168879916028L; private int id; private String number; //车牌号 private String type; //车的类型 private String company; private String busLine; private int price; private String arriveTime; private String distance; private float speed; private double latitude; private double longitude; public String getArriveTime() { return arriveTime; } public void setArriveTime(String arriveTime) { this.arriveTime = arriveTime; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public float getSpeed() { return speed; } public void setSpeed(float speed) { this.speed = speed; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getBusLine() { return busLine; } public void setBusLine(String busLine) { this.busLine = busLine; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Bus [id=" + id + ", number=" + number + ", type=" + type + ", company=" + company + ", busLine=" + busLine + ", price=" + price + ", speed=" + speed + ", latitude=" + latitude + ", longitude=" + longitude + "]"; } }
UTF-8
Java
2,087
java
Bus.java
Java
[]
null
[]
package com.onebus.model; import java.io.Serializable; public class Bus implements Serializable{ /** * */ private static final long serialVersionUID = -4717927168879916028L; private int id; private String number; //车牌号 private String type; //车的类型 private String company; private String busLine; private int price; private String arriveTime; private String distance; private float speed; private double latitude; private double longitude; public String getArriveTime() { return arriveTime; } public void setArriveTime(String arriveTime) { this.arriveTime = arriveTime; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public float getSpeed() { return speed; } public void setSpeed(float speed) { this.speed = speed; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getBusLine() { return busLine; } public void setBusLine(String busLine) { this.busLine = busLine; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Bus [id=" + id + ", number=" + number + ", type=" + type + ", company=" + company + ", busLine=" + busLine + ", price=" + price + ", speed=" + speed + ", latitude=" + latitude + ", longitude=" + longitude + "]"; } }
2,087
0.671491
0.662325
123
15.853659
16.484871
68
false
false
0
0
0
0
0
0
1.487805
false
false
2
f77a7db363a6f9cc06bfd2ca8525b69a27ef168b
36,112,085,031,648
207d6d85a89eab4e9bd91a37b5d35b24b5e25ddf
/net/src/main/java/com/grechur/net/ApiException.java
7f83108ca04de6c99cb1f84605f52f4db60c5c08
[]
no_license
Jochur/WanAndroidMVVM
https://github.com/Jochur/WanAndroidMVVM
c0bbba9574214685b9da0b7485c9a87388cb485c
cadd1a9eef991c136f7a758a667212178fd0528d
refs/heads/master
2022-11-26T03:58:04.447000
2020-08-02T17:21:21
2020-08-02T17:21:21
262,548,016
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.grechur.net; /** * Created by han on 2017/3/1. */ public class ApiException extends RuntimeException{ private int mCode; private String mMessage; public ApiException(Throwable throwable,int code){ super(throwable); mCode=code; } public ApiException(Throwable throwable,int code,String message){ super(throwable); mCode=code; mMessage=message; } public ApiException(int code,String message){ super(message); mCode=code; mMessage=message; } public int getCode(){ return mCode; } public String getMessage(){ return mMessage; } public void setCode(int code){ this.mCode=code; } public void setMessage(String message){ this.mMessage=message; } }
UTF-8
Java
822
java
ApiException.java
Java
[ { "context": "package com.grechur.net;\n\n/**\n * Created by han on 2017/3/1.\n */\n\npublic class ApiException exten", "end": 47, "score": 0.9874633550643921, "start": 44, "tag": "USERNAME", "value": "han" } ]
null
[]
package com.grechur.net; /** * Created by han on 2017/3/1. */ public class ApiException extends RuntimeException{ private int mCode; private String mMessage; public ApiException(Throwable throwable,int code){ super(throwable); mCode=code; } public ApiException(Throwable throwable,int code,String message){ super(throwable); mCode=code; mMessage=message; } public ApiException(int code,String message){ super(message); mCode=code; mMessage=message; } public int getCode(){ return mCode; } public String getMessage(){ return mMessage; } public void setCode(int code){ this.mCode=code; } public void setMessage(String message){ this.mMessage=message; } }
822
0.618005
0.610706
41
19.04878
17.062227
69
false
false
0
0
0
0
0
0
0.463415
false
false
2
58f1e08af0b6c74790d63ec0b737b25473de28d0
3,994,319,616,170
74c04d985f1543cb53c7a19ed572c8decba4f815
/src/main/java/at/porscheinformatik/seleniumcomponents/VisibleSeleniumComponent.java
3aad5ddbf244c7e9687135b35c4ed7d5515eeb1f
[ "MIT" ]
permissive
sappa-saikumar/selenium-components
https://github.com/sappa-saikumar/selenium-components
6d95ca78676217a6abae9e156ac59b642fd2a869
41969665aa2df9bf9b1a86c0b2de5e3270457ae8
refs/heads/master
2023-03-18T00:21:30.872000
2021-03-08T10:35:20
2021-03-08T10:35:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.porscheinformatik.seleniumcomponents; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; /** * A {@link SeleniumComponent} that is visible * * @author ham */ public interface VisibleSeleniumComponent extends SeleniumComponent { /** * Returns true if a {@link WebElement} described by this component is visible. By default it checks, if the element * is visible. This method has no timeout, it does not wait for the component to become existent. <br> * <br> * It it NO good idea, to check for invisibility. If the component is not visible, Selenium always waits for some * time. This causes tests to run slowly and timeouts to fail. * * @return true if the component is visible */ default boolean isVisible() { try { return SeleniumUtils.retryOnStale(() -> { WebElement element = element(); boolean visible = element.isDisplayed(); if (!visible) { LOG.hintAt("Element not visible: %s", describe()); } return visible; }); } catch (NoSuchElementException e) { LOG.hintAt("Element not found: %s", describe()); return false; } } default void waitUntilVisible(double timeoutInSeconds) { SeleniumAsserts.assertIsVisible(timeoutInSeconds, this); } }
UTF-8
Java
1,492
java
VisibleSeleniumComponent.java
Java
[ { "context": "k SeleniumComponent} that is visible\n *\n * @author ham\n */\npublic interface VisibleSeleniumComponent ext", "end": 209, "score": 0.999276876449585, "start": 206, "tag": "USERNAME", "value": "ham" } ]
null
[]
package at.porscheinformatik.seleniumcomponents; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; /** * A {@link SeleniumComponent} that is visible * * @author ham */ public interface VisibleSeleniumComponent extends SeleniumComponent { /** * Returns true if a {@link WebElement} described by this component is visible. By default it checks, if the element * is visible. This method has no timeout, it does not wait for the component to become existent. <br> * <br> * It it NO good idea, to check for invisibility. If the component is not visible, Selenium always waits for some * time. This causes tests to run slowly and timeouts to fail. * * @return true if the component is visible */ default boolean isVisible() { try { return SeleniumUtils.retryOnStale(() -> { WebElement element = element(); boolean visible = element.isDisplayed(); if (!visible) { LOG.hintAt("Element not visible: %s", describe()); } return visible; }); } catch (NoSuchElementException e) { LOG.hintAt("Element not found: %s", describe()); return false; } } default void waitUntilVisible(double timeoutInSeconds) { SeleniumAsserts.assertIsVisible(timeoutInSeconds, this); } }
1,492
0.607909
0.607909
52
27.692308
30.943832
120
false
false
0
0
0
0
0
0
0.346154
false
false
2
e891aa44724976c9b6b00ef9f546f7a849f633ff
23,407,571,794,455
d5e073db2967f89c77d86bf043025df201a5327c
/src/main/java/com/aidn5/chatcleaner/ChatCleaner.java
00139764168e1d6111fd733303e2b51766ce539e
[]
no_license
aidn3/ChatCleaner
https://github.com/aidn3/ChatCleaner
191a48714bc3110493aef151538935a3dc4370e2
450ccde3a19e2cd2e96f54eac7b7e57f2683fbdd
refs/heads/master
2020-03-24T13:37:27.953000
2018-09-01T21:01:13
2018-09-01T21:01:13
142,747,993
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aidn5.chatcleaner; import com.aidn5.chatcleaner.config.Config; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; @Mod(modid = Config.MODID, version = Config.VERSION, name = Config.MOD_NAME, clientSideOnly = true, guiFactory = "com.aidn5.chatcleaner.gui.GuiFactory") public class ChatCleaner { public static Handler_ Handler_; @EventHandler public void init(FMLInitializationEvent event) { Handler_ = new Handler_(); if (Handler_.prepare()) { MinecraftForge.EVENT_BUS.register(this); } } @SubscribeEvent(priority = EventPriority.LOWEST) public void onPlayerChatReceive(ClientChatReceivedEvent event) { if (event.type != 0) return; String message = event.message.getUnformattedText(); if (Handler_.matchRegex(message)) { event.setCanceled(true); } } @SubscribeEvent public void playerLoggedIn(FMLNetworkEvent.ClientConnectedToServerEvent event) { try { Minecraft mc = Minecraft.getMinecraft(); boolean b = mc.getCurrentServerData().serverIP.toLowerCase().contains("hypixel.net"); Handler_.onHypixel = b; } catch (Exception ignore) {} } @SubscribeEvent public void onLoggedOut(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) { Handler_.onHypixel = false; } @SubscribeEvent public void onGameTick(TickEvent.ClientTickEvent event) { Handler_.looper.doTick(); } @SubscribeEvent public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { if (event.modID.equals(Config.MODID)) { Handler_.guiSettings.onConfigChange(); } } }
UTF-8
Java
2,110
java
ChatCleaner.java
Java
[]
null
[]
package com.aidn5.chatcleaner; import com.aidn5.chatcleaner.config.Config; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; @Mod(modid = Config.MODID, version = Config.VERSION, name = Config.MOD_NAME, clientSideOnly = true, guiFactory = "com.aidn5.chatcleaner.gui.GuiFactory") public class ChatCleaner { public static Handler_ Handler_; @EventHandler public void init(FMLInitializationEvent event) { Handler_ = new Handler_(); if (Handler_.prepare()) { MinecraftForge.EVENT_BUS.register(this); } } @SubscribeEvent(priority = EventPriority.LOWEST) public void onPlayerChatReceive(ClientChatReceivedEvent event) { if (event.type != 0) return; String message = event.message.getUnformattedText(); if (Handler_.matchRegex(message)) { event.setCanceled(true); } } @SubscribeEvent public void playerLoggedIn(FMLNetworkEvent.ClientConnectedToServerEvent event) { try { Minecraft mc = Minecraft.getMinecraft(); boolean b = mc.getCurrentServerData().serverIP.toLowerCase().contains("hypixel.net"); Handler_.onHypixel = b; } catch (Exception ignore) {} } @SubscribeEvent public void onLoggedOut(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) { Handler_.onHypixel = false; } @SubscribeEvent public void onGameTick(TickEvent.ClientTickEvent event) { Handler_.looper.doTick(); } @SubscribeEvent public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { if (event.modID.equals(Config.MODID)) { Handler_.guiSettings.onConfigChange(); } } }
2,110
0.78673
0.784834
65
31.461538
29.814854
152
false
false
0
0
0
0
0
0
1.415385
false
false
2
bcdfe9ced3fb735c127672acff773ae1ae4aab52
30,185,030,186,689
b55109e36f35eda6cb84bfbe67cf2f363ace235e
/Client/src/VO/FinanceDocVO.java
e6a83e9eb23248ae60d7a2dc0fc3186db93cd5c1
[]
no_license
JonySheep/XiangXiangDeng
https://github.com/JonySheep/XiangXiangDeng
cb87e65e24080302f3f135e9e22f23735fe424d5
4ad25e3781d30050c5c7e0b29767e07477cae750
refs/heads/master
2021-04-30T12:18:09.803000
2018-02-12T16:51:37
2018-02-12T16:51:37
121,271,929
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package VO; import PO.FinanceDocPO; import Presentation.DocUI.CheckingDoc.Previewable; import Util.DocType; /** * 财务类单据VO的父类. */ public abstract class FinanceDocVO extends DocVO implements Previewable{ public FinanceDocVO(String prKey, String id, UserForDocVO operator, DocType type) { super(prKey, id, operator, type); } public abstract FinanceDocPO toPO(); @Override public String getComment() { return ""; } }
UTF-8
Java
476
java
FinanceDocVO.java
Java
[]
null
[]
package VO; import PO.FinanceDocPO; import Presentation.DocUI.CheckingDoc.Previewable; import Util.DocType; /** * 财务类单据VO的父类. */ public abstract class FinanceDocVO extends DocVO implements Previewable{ public FinanceDocVO(String prKey, String id, UserForDocVO operator, DocType type) { super(prKey, id, operator, type); } public abstract FinanceDocPO toPO(); @Override public String getComment() { return ""; } }
476
0.702174
0.702174
22
19.90909
23.975193
87
false
false
0
0
0
0
0
0
0.590909
false
false
2
8d2246ded124b27c17d87d0544b26dde0a9a9de9
7,902,739,892,673
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_19e51df4bc21efee71041d18e2deafed68e2512d/DFSFilename/2_19e51df4bc21efee71041d18e2deafed68e2512d_DFSFilename_s.java
718220948e549c75f959548719e5a4680a41f76e
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
public class DFSFilename { public static final String kPrefixString = "/dfs/"; private int node; private String path; public DFSFilename(String fileName) { if (!fileName.startsWith(kPrefixString)) throw new IllegalArgumentException("Invalid DFS filename"); int nodeIdEnd = fileName.indexOf('/', kPrefixString.length()); if (nodeIdEnd == -1 || fileName.length() == nodeIdEnd) throw new IllegalArgumentException("No path beyond the node id!"); try { node = Integer.parseInt( fileName.substring(kPrefixString.length(), nodeIdEnd)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Node ID is nonnumeric!"); } path = fileName.substring(nodeIdEnd + 1); } public int getOwningServer() { return node; } public String getPath() { return path; } @Override public String toString() { return kPrefixString + Integer.toString(node) + path; } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof DFSFilename)) return false; return ((DFSFilename) other).node == node && ((DFSFilename) other).path.equals(path); } }
UTF-8
Java
1,309
java
2_19e51df4bc21efee71041d18e2deafed68e2512d_DFSFilename_s.java
Java
[]
null
[]
public class DFSFilename { public static final String kPrefixString = "/dfs/"; private int node; private String path; public DFSFilename(String fileName) { if (!fileName.startsWith(kPrefixString)) throw new IllegalArgumentException("Invalid DFS filename"); int nodeIdEnd = fileName.indexOf('/', kPrefixString.length()); if (nodeIdEnd == -1 || fileName.length() == nodeIdEnd) throw new IllegalArgumentException("No path beyond the node id!"); try { node = Integer.parseInt( fileName.substring(kPrefixString.length(), nodeIdEnd)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Node ID is nonnumeric!"); } path = fileName.substring(nodeIdEnd + 1); } public int getOwningServer() { return node; } public String getPath() { return path; } @Override public String toString() { return kPrefixString + Integer.toString(node) + path; } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof DFSFilename)) return false; return ((DFSFilename) other).node == node && ((DFSFilename) other).path.equals(path); } }
1,309
0.6356
0.634072
53
23.64151
22.613316
73
false
false
0
0
0
0
0
0
0.358491
false
false
2
477206b916ee80e81ab0402d2170d8e80f701ba6
403,726,956,354
6c11faa77cdc88e0db0695abc47bfb8d241cd166
/alice/src/main/java/com/thoughtworks/capability/gtb/alice/controller/HelloController.java
3848dbd1e85486d5e16ecc48ed7aba68a638db95
[]
no_license
cx-Zh/Practice_docker
https://github.com/cx-Zh/Practice_docker
e94aab45e3557cab40c09fa095c379ce579cb262
8e5fefdd237cb2e352cb9e290f40140de5487cfa
refs/heads/master
2022-10-18T17:44:35.135000
2020-06-07T03:13:01
2020-06-07T03:13:01
270,176,592
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thoughtworks.capability.gtb.alice.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.ResponseEntity; @RestController public class HelloController { @Autowired private RestTemplate restTemplate; @GetMapping("/hello") public String hello() { final String url = "http://bob:8081/hello"; String result = restTemplate.getForObject(url, String.class); // ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); // String result = response.getBody(); return result; } }
UTF-8
Java
887
java
HelloController.java
Java
[]
null
[]
package com.thoughtworks.capability.gtb.alice.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.ResponseEntity; @RestController public class HelloController { @Autowired private RestTemplate restTemplate; @GetMapping("/hello") public String hello() { final String url = "http://bob:8081/hello"; String result = restTemplate.getForObject(url, String.class); // ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); // String result = response.getBody(); return result; } }
887
0.789177
0.784667
29
29.586206
27.438354
103
false
false
0
0
0
0
0
0
0.62069
false
false
2
6e5afb842cdb0cf964a630fe8cd03c097f760c15
29,807,073,083,284
f70901d3a25a7090cedbf3cfd9c0e46ed1a34f18
/src/src/main/java/com/tms/dao/ReportGenerationdao.java
33cc2dd07b934a411be3030176a94db3e99d395f
[]
no_license
egjava/tms
https://github.com/egjava/tms
b1eb27ffe36a05902590c744f85abe83738bd770
25d34d09244b3d392421163a49fde6494e66017a
refs/heads/master
2022-07-02T01:28:03.208000
2019-11-28T07:32:37
2019-11-28T07:32:37
224,570,013
0
0
null
false
2022-06-21T02:20:19
2019-11-28T04:31:12
2019-11-28T07:33:16
2022-06-21T02:20:18
1,162
0
0
2
JavaScript
false
false
package com.tms.dao; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.apache.log4j.Logger; import com.tms.bean.Report; import com.tms.bean.ReportGeneration; import com.tms.database.ConnectionHelper; import com.tms.util.DateUtil; import com.tms.util.Queries; public class ReportGenerationdao { final static Logger logger = Logger.getLogger(ReportGenerationdao.class); DateUtil dateUtil = new DateUtil(); public List<ReportGeneration> generateReportBI(ReportGeneration bins) { List<ReportGeneration> reportBI = new ArrayList<ReportGeneration>(); List<Date> activityDate = new ArrayList<Date>(); List<Integer> activityID = new ArrayList<Integer>(); List<Integer> cptcode = new ArrayList<Integer>(); List<String> aName = new ArrayList<String>(); Date fromDate= null; Date toDate = null; String activityDt=""; float rate =0; float waiver =0; float netcharge =0; //float total=0; int clientid=0; Connection c = null; PreparedStatement ps = null; ResultSet rs = null; try{ c = ConnectionHelper.getConnection(); if(bins.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bins.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bins.getNameid()); ps.setInt(2, bins.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bins.setClientid(clientid); logger.debug("Query:"+Queries.getQuery("fetchForCNameBI")); ps = c.prepareStatement(Queries.getQuery("fetchForCNameBI")); ps.setInt(1, bins.getNameid()); rs = ps.executeQuery(); while (rs.next()) { bins.setCfirstname(rs.getString("firstname")); bins.setClastname(rs.getString("lastname")); bins.setCmiddlename(rs.getString("middlename")); } String clientName = bins.getCfirstname() + " " +bins.getCmiddlename() + " " +bins.getClastname(); bins.setClientname( clientName); //To get address for the client logger.debug("Query:"+Queries.getQuery("fetchForCAddressBI")); ps = c.prepareStatement(Queries.getQuery("fetchForCAddressBI")); ps.setInt(1, bins.getClientid()); rs = ps.executeQuery(); while (rs.next()) { bins.setCaddress1(rs.getString("address1")); bins.setCaddress2(rs.getString("address2")); bins.setCcity(rs.getString("city")); bins.setCstate(rs.getString("state")); bins.setCzipcode(rs.getInt("zip")); } //To get first diagnosis code for a client ps = c.prepareStatement(Queries.getQuery("fetchForCdiagnosisBI")); ps.setInt(1, bins.getClientid()); rs = ps.executeQuery(); while (rs.next()) { bins.setDiagnosiscode(rs.getString("name")); } //To get Therapist Name and address logger.debug("Query:"+Queries.getQuery("fetchForNameBI")); ps = c.prepareStatement(Queries.getQuery("fetchForNameBI")); ps.setInt(1, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setFirstname(rs.getString("firstname")); bins.setLastname(rs.getString("lastname")); bins.setMiddlename(rs.getString("middlename")); } String therapistName = bins.getFirstname() + " " +bins.getMiddlename() + " " +bins.getLastname(); bins.setTherapistname(therapistName); logger.debug("Query:"+Queries.getQuery("fetchForAddressBI")); ps = c.prepareStatement(Queries.getQuery("fetchForAddressBI")); ps.setInt(1, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setAddress1(rs.getString("address1")); bins.setAddress2(rs.getString("address2")); bins.setCity(rs.getString("city")); bins.setState(rs.getString("state")); bins.setZipcode(rs.getInt("zip")); } //To get Therapist Mobile and EIN, License Number logger.debug("Query:"+Queries.getQuery("fetchForContactBI")); ps = c.prepareStatement(Queries.getQuery("fetchForContactBI")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setEin(rs.getString("ein")); bins.setLicense(rs.getString("license")); bins.setMobile(rs.getString("mobile")); } reportBI.add(bins); logger.debug("Query:"+Queries.getQuery("genRepBIActivity")); ps = c.prepareStatement(Queries.getQuery("genRepBIActivity")); ps.setInt(1, bins.getClientid()); ps.setInt(2, bins.getTherapistid()); fromDate = dateUtil.convertDate(bins.getFromdate()); ps.setDate(3, fromDate); toDate = dateUtil.convertDate(bins.getTodate()); ps.setDate(4, toDate); rs= ps.executeQuery(); while (rs.next()) { activityDate.add(rs.getDate("activitydate")); activityID.add(rs.getInt("activityid")); cptcode.add(rs.getInt("cptcode")); aName.add(rs.getString("activityname")); } ReportGeneration bInsurance[] = new ReportGeneration[activityID.size()]; for(int i=0;i<activityID.size();i++){ bInsurance[i] = new ReportGeneration(); logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, activityID.get(i)); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { rate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setInt(3, activityID.get(i)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netcharge = rate - waiver; //total += netcharge; activityDt = dateUtil.convertStringToDate(activityDate.get(i)); bInsurance[i].setActivityDate(activityDt); bInsurance[i].setCptcode(cptcode.get(i)); bInsurance[i].setNetcharge(netcharge); reportBI.add(bInsurance[i]); rate=0;waiver=0;netcharge=0; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportBI; } public List<ReportGeneration> generateReportBS(ReportGeneration bins) { List<ReportGeneration> reportBS = new ArrayList<ReportGeneration>(); List<Date> activityDate = new ArrayList<Date>(); List<Integer> activityID = new ArrayList<Integer>(); List<Integer> priorActivityID = new ArrayList<Integer>(); List<Integer> cptcode = new ArrayList<Integer>(); List<String> aName = new ArrayList<String>(); List<Date> paymentDate = new ArrayList<Date>(); List<Integer> payActivityid = new ArrayList<Integer>(); List<String> payActivityname = new ArrayList<String>(); List<Float> fullPayment = new ArrayList<Float>(); List<Integer> payonlyactivityid = new ArrayList<Integer>(); List<Date> payonlypaymentdate = new ArrayList<Date>(); List<Float> payonlyamount = new ArrayList<Float>(); boolean payAtyID=false; float rate =0; float waiver =0; float netcharge =0; float payment=0; float priorCharge=0; float priorWaiver=0; float priorNetcharge=0; float priorRate=0; float priorPayment=0; float priorBalance=0; int clientid=0; float balance=0; int repBSSize =0; boolean priorAtyID=false; boolean payOnly = false; boolean payOnlyActivityid = false; boolean priorBal = false; Connection c = null; PreparedStatement ps = null; ResultSet rs = null; DecimalFormat df = new DecimalFormat("###.##"); df.setMaximumFractionDigits(2); Date fromDate = null; Date toDate = null; String activityDt = ""; String paymentDt = ""; String priorDt= null; String payonlyPaymentDt = ""; String payonlyActivityName = ""; try{ c = ConnectionHelper.getConnection(); if(bins.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bins.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bins.getNameid()); ps.setInt(2, bins.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bins.setClientid(clientid); logger.debug("Query:"+Queries.getQuery("fetchForCNameBI")); ps = c.prepareStatement(Queries.getQuery("fetchForCNameBI")); ps.setInt(1, bins.getNameid()); rs = ps.executeQuery(); while (rs.next()) { bins.setCfirstname(rs.getString("firstname")); bins.setClastname(rs.getString("lastname")); bins.setCmiddlename(rs.getString("middlename")); } String clientName = bins.getCfirstname() + " " +bins.getCmiddlename() + " " +bins.getClastname(); bins.setClientname( clientName); //To get address for the client logger.debug("Query:"+Queries.getQuery("fetchForCAddressBI")); ps = c.prepareStatement(Queries.getQuery("fetchForCAddressBI")); ps.setInt(1, bins.getClientid()); rs = ps.executeQuery(); while (rs.next()) { bins.setCaddress1(rs.getString("address1")); bins.setCaddress2(rs.getString("address2")); bins.setCcity(rs.getString("city")); bins.setCstate(rs.getString("state")); bins.setCzipcode(rs.getInt("zip")); } //To get Therapist Name and address logger.debug("Query:"+Queries.getQuery("fetchForNameBI")); ps = c.prepareStatement(Queries.getQuery("fetchForNameBI")); ps.setInt(1, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setFirstname(rs.getString("firstname")); bins.setLastname(rs.getString("lastname")); bins.setMiddlename(rs.getString("middlename")); } String therapistName = bins.getFirstname() + " " +bins.getMiddlename() + " " +bins.getLastname(); bins.setTherapistname(therapistName); logger.debug("Query:"+Queries.getQuery("fetchForAddressBI")); ps = c.prepareStatement(Queries.getQuery("fetchForAddressBI")); ps.setInt(1, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setAddress1(rs.getString("address1")); bins.setAddress2(rs.getString("address2")); bins.setCity(rs.getString("city")); bins.setState(rs.getString("state")); bins.setZipcode(rs.getInt("zip")); } //To get Therapist Mobile and EIN, License Number logger.debug("Query:"+Queries.getQuery("fetchForContactBI")); ps = c.prepareStatement(Queries.getQuery("fetchForContactBI")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setEin(rs.getString("ein")); bins.setLicense(rs.getString("license")); bins.setMobile(rs.getString("mobile")); } reportBS.add(bins); logger.debug("Query:"+Queries.getQuery("genRepBIActivity")); ps = c.prepareStatement(Queries.getQuery("genRepBIActivity")); ps.setInt(1, bins.getClientid()); ps.setInt(2, bins.getTherapistid()); fromDate = dateUtil.convertDate(bins.getFromdate()); toDate = dateUtil.convertDate(bins.getTodate()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs= ps.executeQuery(); while (rs.next()) { activityDate.add(rs.getDate("activitydate")); activityID.add(rs.getInt("activityid")); cptcode.add(rs.getInt("cptcode")); aName.add(rs.getString("activityname")); } //Check if there is any prior balance logger.debug("Query:"+Queries.getQuery("fetch_prioractivity")); ps = c.prepareStatement(Queries.getQuery("fetch_prioractivity")); ps.setInt(1,bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setDate(3, fromDate); rs= ps.executeQuery(); while (rs.next()) { priorActivityID.add(rs.getInt("activityid")); } /*2 if(priorActivityID.size() >= 1){ repBSSize = activityID.size()+1;} else repBSSize = activityID.size();*/ //To display Any Payments made between the selected date logger.debug("Query:"+Queries.getQuery("fetch_fullpayment")); ps = c.prepareStatement(Queries.getQuery("fetch_fullpayment")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { payActivityid.add(rs.getInt("activityid")); fullPayment.add(rs.getFloat("payment")); //paymentDt = dateUtil.convertStringToDate(rs.getDate("paymentdate")); paymentDate.add(rs.getDate("paymentdate")); payActivityname.add(rs.getString("activityname")); } if(activityID.size()<payActivityid.size()){ payAtyID = true; for(int i=0;i<activityID.size();i++){ for(int k=0;k<payActivityid.size();k++){ if(activityID.get(i) == payActivityid.get(k)){ payActivityid.remove(i); fullPayment.remove(i); paymentDate.remove(i); payActivityname.remove(i); } } } } //If any payment made on any other date other than activity date logger.debug("Query:"+Queries.getQuery("fetch_paymentbwdate")); ps = c.prepareStatement(Queries.getQuery("fetch_paymentbwdate")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); ps.setInt(5, bins.getTherapistid()); ps.setInt(6, bins.getClientid()); ps.setDate(7, fromDate); ps.setDate(8, toDate); rs = ps.executeQuery(); while (rs.next()) { payonlyactivityid.add(rs.getInt("activityid")); payonlyamount.add(rs.getFloat("amount")); payonlypaymentdate.add(rs.getDate("paymentdate")); } if(priorActivityID.size() >= 1){ repBSSize = activityID.size()+1; priorAtyID = true;} else repBSSize = activityID.size(); if(payAtyID){ repBSSize = repBSSize + payActivityid.size(); } if(payonlyactivityid.size() >=1){ repBSSize = repBSSize + payonlyactivityid.size(); } ReportGeneration bSummary[] = new ReportGeneration[repBSSize]; /*1 if(payAtyID){ for(int l=0;l<payActivityid.size();l++) { bSummary[l] = new ReportGeneration(); bSummary[l].setActivityname(payActivityname.get(l)+"- P/O"); paymentDt = dateUtil.convertStringToDate(paymentDate.get(l)); bSummary[l].setActivityDate(paymentDt); bSummary[l].setNetcharge(0); bSummary[l].setPayment(Float.parseFloat(df.format(fullPayment.get(l)))); bSummary[l].setBalance(Float.parseFloat(df.format(-fullPayment.get(l)))); reportBS.add(bSummary[l]); } }*/ for(int i=0;i<repBSSize;i++){ if(i< activityID.size()){ bSummary[i] = new ReportGeneration(); logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, activityID.get(i)); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { rate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setInt(3, activityID.get(i)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netcharge = rate - waiver; logger.debug("Query:"+Queries.getQuery("fetch_paidamount")); ps = c.prepareStatement(Queries.getQuery("fetch_paidamount")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setInt(3, activityID.get(i)); ps.setDate(4, activityDate.get(i)); // ps.setDate(4, fromDate); // ps.setDate(5, toDate); rs = ps.executeQuery(); while (rs.next()) { payment = rs.getFloat("payment"); } balance = netcharge - payment; activityDt = dateUtil.convertStringToDate(activityDate.get(i)); bSummary[i].setActivityDate(activityDt); bSummary[i].setActivityname(aName.get(i)); bSummary[i].setNetcharge(netcharge); bSummary[i].setPayment(Float.parseFloat(df.format(payment))); bSummary[i].setBalance(Float.parseFloat(df.format(balance))); reportBS.add(bSummary[i]); rate=0;waiver=0;netcharge=0;payment=0;balance=0; } // else if( priorAtyID && !priorBal){ //This is for Prior Balance priorBal = true; for(int k=0;k<priorActivityID.size();k++){ logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, priorActivityID.get(k)); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { priorRate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setInt(3, priorActivityID.get(k)); rs = ps.executeQuery(); while (rs.next()) { priorWaiver = rs.getFloat("waiver"); } priorCharge = priorRate - priorWaiver; priorNetcharge += priorCharge; priorRate =0;priorWaiver=0;priorCharge=0; } logger.debug("Query:"+Queries.getQuery("fetch_priorbalance")); ps = c.prepareStatement(Queries.getQuery("fetch_priorbalance")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setDate(3, fromDate); rs = ps.executeQuery(); while (rs.next()) { priorPayment = rs.getFloat("payment"); } priorBalance = priorNetcharge - priorPayment; DateFormat dateFormat= new SimpleDateFormat("yyyy/MM/dd"); Calendar cal = Calendar.getInstance(); cal.setTime(fromDate); cal.add(Calendar.DATE, -1); String dateInString = dateFormat.format(cal.getTime()); java.util.Date date = dateFormat.parse(dateInString); Date priorDate = new Date(date.getTime()); bSummary[i] = new ReportGeneration(); priorDt = dateUtil.convertStringToDate(priorDate); bSummary[i].setActivityDate(priorDt); bSummary[i].setActivityname("Prior Balance"); bSummary[i].setNetcharge(0); bSummary[i].setPayment(0); bSummary[i].setBalance(Float.parseFloat(df.format(priorBalance))); reportBS.add(bSummary[i]); priorBalance=0;priorPayment=0;priorNetcharge=0; } if(payAtyID && !payOnly){ payOnly = true; for(int l=0;l<payActivityid.size();l++) { bSummary[l] = new ReportGeneration(); bSummary[l].setActivityname(payActivityname.get(l)+"- P/O"); paymentDt = dateUtil.convertStringToDate(paymentDate.get(l)); bSummary[l].setActivityDate(paymentDt); bSummary[l].setNetcharge(0); bSummary[l].setPayment(Float.parseFloat(df.format(fullPayment.get(l)))); bSummary[l].setBalance(Float.parseFloat(df.format(-fullPayment.get(l)))); reportBS.add(bSummary[l]); } } if(payonlyactivityid.size() >=1 && !payOnlyActivityid){ payOnlyActivityid = true; for(int l=0;l<payonlyactivityid.size();l++) { payonlyActivityName =""; bSummary[l] =new ReportGeneration(); logger.debug("Query:"+Queries.getQuery("fetch_activityname")); ps = c.prepareStatement(Queries.getQuery("fetch_activityname")); ps.setInt(1, payonlyactivityid.get(l)); rs = ps.executeQuery(); while (rs.next()) { payonlyActivityName=rs.getString("activityname"); } bSummary[l].setActivityname(payonlyActivityName +"- P/O"); payonlyPaymentDt = dateUtil.convertStringToDate(payonlypaymentdate.get(l)); bSummary[l].setActivityDate(payonlyPaymentDt); bSummary[l].setNetcharge(0); bSummary[l].setPayment(Float.parseFloat(df.format(payonlyamount.get(l)))); bSummary[l].setBalance(Float.parseFloat(df.format(-payonlyamount.get(l)))); reportBS.add(bSummary[l]); } } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportBS; } public List<ReportGeneration> generateReportTOT(ReportGeneration bTOT) { List<ReportGeneration> reportTOT = new ArrayList<ReportGeneration>(); List<Integer> clientIdList = new ArrayList<Integer>(); List<Integer> nameIdList = new ArrayList<Integer>(); List<Integer> priorActivityID = null; List<Integer> activityIDList = null; DateUtil dateUtil = new DateUtil(); DecimalFormat df = new DecimalFormat("###.##"); df.setMaximumFractionDigits(2); Connection c = null; PreparedStatement ps = null; ResultSet rs = null; int clientid=0; String firstName=""; String lastName=""; String clientName=""; String therapistName=""; int repActTOTSize =0; float charge=0; float netCharge=0; float waiver=0; float netWaiver=0; float payment=0; float netPayment=0; float grossCharge =0; float totbal =0; float balance=0; float priorBalance=0; float priorWaiver=0; float priorPayment=0; float priorCharge =0; float priorRate=0; float priorNetcharge=0; Date fromDate= null; Date toDate=null; int nameid=0; try{ c = ConnectionHelper.getConnection(); nameid = bTOT.getNameid(); fromDate= dateUtil.convertDate(bTOT.getFromdate()); toDate = dateUtil.convertDate(bTOT.getTodate()); if(nameid == 0){ if(bTOT.getFlagid() == 0){ //Get all the Clients logger.debug("Query:"+Queries.getQuery("fetchForTMClientid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientid")); ps.setInt(1, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } else{ //Get all the Clients with flagid logger.debug("Query:"+Queries.getQuery("fetchForTMClientidWFlag")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientidWFlag")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bTherapistMoney[] = new ReportGeneration[clientIdList.size()]; for(int i=0;i<clientIdList.size();i++){ bTherapistMoney[i] = new ReportGeneration(); //Get The Name of all Clients logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, nameIdList.get(i)); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } clientName = firstName+" "+lastName; bTherapistMoney[i].setClientname(clientName); bTherapistMoney[i].setTherapistname(therapistName); bTherapistMoney[i].setFromdate(bTOT.getFromdate()); bTherapistMoney[i].setTodate(bTOT.getTodate()); //Get The Activity of a Client activityIDList = new ArrayList<Integer>(); priorActivityID = new ArrayList<Integer>(); logger.debug("Query:"+Queries.getQuery("fetchForTMActivity")); ps = c.prepareStatement(Queries.getQuery("fetchForTMActivity")); ps.setInt(1, clientIdList.get(i)); ps.setInt(2, bTOT.getTherapistid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { activityIDList.add(rs.getInt("activityid")); } //Check if there is any prior balance logger.debug("Query:"+Queries.getQuery("fetch_prioractivity")); ps = c.prepareStatement(Queries.getQuery("fetch_prioractivity")); ps.setInt(1,bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setDate(3, fromDate); rs= ps.executeQuery(); while (rs.next()) { priorActivityID.add(rs.getInt("activityid")); } if(priorActivityID.size() >= 1){ repActTOTSize = activityIDList.size()+1;} else{ repActTOTSize = activityIDList.size();} netPayment=0;netCharge=0;netWaiver=0; for(int k=0;k<repActTOTSize;k++){ if(k<activityIDList.size()){ //Get The Rate for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMRate")); ps = c.prepareStatement(Queries.getQuery("fetchForTMRate")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { charge = rs.getFloat("rate"); } netCharge += charge; //Get The waiver for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMWaiver")); ps = c.prepareStatement(Queries.getQuery("fetchForTMWaiver")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setInt(3, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netWaiver += waiver; charge=0;waiver=0; } else{ //This is for Prior Balance for(int l=0;l<priorActivityID.size();l++){ logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, priorActivityID.get(l)); ps.setInt(2, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { priorRate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setInt(3, priorActivityID.get(l)); rs = ps.executeQuery(); while (rs.next()) { priorWaiver = rs.getFloat("waiver"); } priorCharge = priorRate - priorWaiver; priorNetcharge += priorCharge; priorRate =0;priorWaiver=0;priorCharge=0; } logger.debug("Query:"+Queries.getQuery("fetch_priorbalance")); ps = c.prepareStatement(Queries.getQuery("fetch_priorbalance")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setDate(3, fromDate); rs = ps.executeQuery(); while (rs.next()) { priorPayment = rs.getFloat("payment"); } priorBalance = priorNetcharge - priorPayment; } } //Get The Payment for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMPayment")); ps = c.prepareStatement(Queries.getQuery("fetchForTMPayment")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setDate(3,fromDate); ps.setDate(4,toDate); rs = ps.executeQuery(); while (rs.next()) { netPayment = rs.getFloat("payment"); } bTherapistMoney[i].setNetcharge(Float.parseFloat(df.format(netCharge))); bTherapistMoney[i].setNetwaiver(Float.parseFloat(df.format(netWaiver))); bTherapistMoney[i].setNetpayment(Float.parseFloat(df.format(netPayment))); grossCharge = netCharge - netWaiver; balance = grossCharge - netPayment; totbal = balance + priorBalance; bTherapistMoney[i].setBalance(Float.parseFloat(df.format(totbal))); bTherapistMoney[i].setPriorBalance(Float.parseFloat(df.format(priorBalance))); reportTOT.add(bTherapistMoney[i]); priorBalance=0;priorPayment=0;priorNetcharge=0; } }//This is for an individual client else{ if(bTOT.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bTOT.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bTOT.getNameid()); ps.setInt(2, bTOT.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bTOT.setClientid(clientid); activityIDList = new ArrayList<Integer>(); priorActivityID = new ArrayList<Integer>(); //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bTherapistMoney = new ReportGeneration(); if(clientid != 0){ //Get The Name of the client logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, bTOT.getNameid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } clientName = firstName+" "+lastName; //Get The Activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMActivity")); ps = c.prepareStatement(Queries.getQuery("fetchForTMActivity")); ps.setInt(1, bTOT.getClientid()); ps.setInt(2, bTOT.getTherapistid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { activityIDList.add(rs.getInt("activityid")); } //Check if there is any prior balance logger.debug("Query:"+Queries.getQuery("fetch_prioractivity")); ps = c.prepareStatement(Queries.getQuery("fetch_prioractivity")); ps.setInt(1,bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setDate(3, fromDate); rs= ps.executeQuery(); while (rs.next()) { priorActivityID.add(rs.getInt("activityid")); } if(priorActivityID.size() >= 1){ repActTOTSize = activityIDList.size()+1;} else{ repActTOTSize = activityIDList.size();} netPayment=0;netCharge=0;netWaiver=0; for(int k=0;k<repActTOTSize;k++){ if(k<activityIDList.size()){ //Get The Rate for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMRate")); ps = c.prepareStatement(Queries.getQuery("fetchForTMRate")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { charge = rs.getFloat("rate"); } netCharge += charge; //Get The waiver for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMWaiver")); ps = c.prepareStatement(Queries.getQuery("fetchForTMWaiver")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setInt(3, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netWaiver += waiver; charge=0;waiver=0; } else{ //This is for Prior Balance for(int l=0;l<priorActivityID.size();l++){ logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, priorActivityID.get(l)); ps.setInt(2, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { priorRate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setInt(3, priorActivityID.get(l)); rs = ps.executeQuery(); while (rs.next()) { priorWaiver = rs.getFloat("waiver"); } priorCharge = priorRate - priorWaiver; priorNetcharge += priorCharge; priorRate =0;priorWaiver=0;priorCharge=0; } logger.debug("Query:"+Queries.getQuery("fetch_priorbalance")); ps = c.prepareStatement(Queries.getQuery("fetch_priorbalance")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setDate(3, fromDate); rs = ps.executeQuery(); while (rs.next()) { priorPayment = rs.getFloat("payment"); } priorBalance = priorNetcharge - priorPayment; } } //Get The Payment for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMPayment")); ps = c.prepareStatement(Queries.getQuery("fetchForTMPayment")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setDate(3,fromDate); ps.setDate(4,toDate); rs = ps.executeQuery(); while (rs.next()) { netPayment = rs.getFloat("payment"); } bTherapistMoney.setClientname(clientName); bTherapistMoney.setTherapistname(therapistName); bTherapistMoney.setFromdate(bTOT.getFromdate()); bTherapistMoney.setTodate(bTOT.getTodate()); bTherapistMoney.setNetcharge(Float.parseFloat(df.format(netCharge))); bTherapistMoney.setNetwaiver(Float.parseFloat(df.format(netWaiver))); bTherapistMoney.setNetpayment(Float.parseFloat(df.format(netPayment))); grossCharge = netCharge - netWaiver; balance = grossCharge - netPayment; totbal = balance + priorBalance; bTherapistMoney.setBalance(Float.parseFloat(df.format(totbal))); bTherapistMoney.setPriorBalance(Float.parseFloat(df.format(priorBalance))); reportTOT.add(bTherapistMoney); } else{ bTherapistMoney.setTherapistname(therapistName); bTherapistMoney.setClientname(" - "); bTherapistMoney.setFromdate(bTOT.getFromdate()); bTherapistMoney.setTodate(bTOT.getTodate()); reportTOT.add(bTherapistMoney); } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportTOT; } public List<ReportGeneration> generateReportTM(ReportGeneration bTM) { List<ReportGeneration> reportTM = new ArrayList<ReportGeneration>(); List<Integer> clientIdList = new ArrayList<Integer>(); List<Integer> nameIdList = new ArrayList<Integer>(); List<Integer> activityIDList = null; DateUtil dateUtil = new DateUtil(); DecimalFormat df = new DecimalFormat("###.##"); df.setMaximumFractionDigits(2); Connection c = null; PreparedStatement ps = null; ResultSet rs = null; int clientid=0; String firstName=""; String lastName=""; String clientName=""; String therapistName=""; float charge=0; float netCharge=0; float waiver=0; float netWaiver=0; float payment=0; float netPayment=0; Date fromDate= null; Date toDate=null; int nameid=0; try{ c = ConnectionHelper.getConnection(); nameid = bTM.getNameid(); fromDate= dateUtil.convertDate(bTM.getFromdate()); toDate = dateUtil.convertDate(bTM.getTodate()); if(nameid == 0){ if(bTM.getFlagid() == 0){ //Get all the Clients logger.debug("Query:"+Queries.getQuery("fetchForTMClientid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientid")); ps.setInt(1, bTM.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } else{ //Get all the Clients with flagid logger.debug("Query:"+Queries.getQuery("fetchForTMClientidWFlag")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientidWFlag")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, bTM.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bTM.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bTherapistMoney[] = new ReportGeneration[clientIdList.size()]; for(int i=0;i<clientIdList.size();i++){ bTherapistMoney[i] = new ReportGeneration(); //Get The Name of all Clients logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, nameIdList.get(i)); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } clientName = firstName+" "+lastName; bTherapistMoney[i].setClientname(clientName); bTherapistMoney[i].setTherapistname(therapistName); bTherapistMoney[i].setFromdate(bTM.getFromdate()); bTherapistMoney[i].setTodate(bTM.getTodate()); //Get The Activity of a Client activityIDList = new ArrayList<Integer>(); logger.debug("Query:"+Queries.getQuery("fetchForTMActivity")); ps = c.prepareStatement(Queries.getQuery("fetchForTMActivity")); ps.setInt(1, clientIdList.get(i)); ps.setInt(2, bTM.getTherapistid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { activityIDList.add(rs.getInt("activityid")); } netPayment=0;netCharge=0;netWaiver=0; for(int k=0;k<activityIDList.size();k++){ //Get The Rate for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMRate")); ps = c.prepareStatement(Queries.getQuery("fetchForTMRate")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { charge = rs.getFloat("rate"); } netCharge += charge; //Get The waiver for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMWaiver")); ps = c.prepareStatement(Queries.getQuery("fetchForTMWaiver")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setInt(3, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netWaiver += waiver; charge=0;waiver=0; } //Get The Payment for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMPayment")); ps = c.prepareStatement(Queries.getQuery("fetchForTMPayment")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setDate(3,fromDate); ps.setDate(4,toDate); rs = ps.executeQuery(); while (rs.next()) { netPayment = rs.getFloat("payment"); } bTherapistMoney[i].setNetcharge(Float.parseFloat(df.format(netCharge))); bTherapistMoney[i].setNetwaiver(Float.parseFloat(df.format(netWaiver))); bTherapistMoney[i].setNetpayment(Float.parseFloat(df.format(netPayment))); reportTM.add(bTherapistMoney[i]); } } else{ if(bTM.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bTM.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bTM.getNameid()); ps.setInt(2, bTM.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bTM.setClientid(clientid); activityIDList = new ArrayList<Integer>(); //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bTM.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bTherapistMoney = new ReportGeneration(); if(clientid != 0){ //Get The Name of the client logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, bTM.getNameid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } clientName = firstName+" "+lastName; //Get The Activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMActivity")); ps = c.prepareStatement(Queries.getQuery("fetchForTMActivity")); ps.setInt(1, bTM.getClientid()); ps.setInt(2, bTM.getTherapistid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { activityIDList.add(rs.getInt("activityid")); } for(int k=0;k<activityIDList.size();k++){ //Get The Rate for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMRate")); ps = c.prepareStatement(Queries.getQuery("fetchForTMRate")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { charge = rs.getFloat("rate"); } netCharge += charge; //Get The waiver for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMWaiver")); ps = c.prepareStatement(Queries.getQuery("fetchForTMWaiver")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, bTM.getClientid()); ps.setInt(3, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netWaiver += waiver; charge=0;waiver=0; } //Get The Payment for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMICPayment")); ps = c.prepareStatement(Queries.getQuery("fetchForTMICPayment")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, bTM.getClientid()); //ps.setInt(3, activityIDList.get(k)); ps.setDate(3,fromDate); ps.setDate(4,toDate); rs = ps.executeQuery(); while (rs.next()) { netPayment = rs.getFloat("payment"); } bTherapistMoney.setClientname(clientName); bTherapistMoney.setTherapistname(therapistName); bTherapistMoney.setFromdate(bTM.getFromdate()); bTherapistMoney.setTodate(bTM.getTodate()); bTherapistMoney.setNetcharge(Float.parseFloat(df.format(netCharge))); bTherapistMoney.setNetwaiver(Float.parseFloat(df.format(netWaiver))); bTherapistMoney.setNetpayment(Float.parseFloat(df.format(netPayment))); reportTM.add(bTherapistMoney); } else{ bTherapistMoney.setTherapistname(therapistName); bTherapistMoney.setClientname(" - "); bTherapistMoney.setFromdate(bTM.getFromdate()); bTherapistMoney.setTodate(bTM.getTodate()); reportTM.add(bTherapistMoney); } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportTM; } public List<ReportGeneration> generateReportCL(ReportGeneration bCL) { List<ReportGeneration> reportCL = new ArrayList<ReportGeneration>(); List<Integer> clientIdList = new ArrayList<Integer>(); List<Integer> nameIdList = new ArrayList<Integer>(); Connection c = null; PreparedStatement ps = null; ResultSet rs = null; int clientid=0; String firstName=""; String lastName=""; String lastNameUpTo4Char = ""; String clientName=""; String therapistName=""; String mobile=""; int nameid=0; try{ c = ConnectionHelper.getConnection(); nameid = bCL.getNameid(); if(nameid == 0){ if(bCL.getFlagid() == 0){ //Get all the Clients logger.debug("Query:"+Queries.getQuery("fetchForTMClientid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientid")); ps.setInt(1, bCL.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } else{ //Get all the Clients with flagid logger.debug("Query:"+Queries.getQuery("fetchForTMClientidWFlag")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientidWFlag")); ps.setInt(1, bCL.getTherapistid()); ps.setInt(2, bCL.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bCL.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bClientList[] = new ReportGeneration[clientIdList.size()]; for(int i=0;i<clientIdList.size();i++){ bClientList[i] = new ReportGeneration(); //Get The Name of all Clients logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, nameIdList.get(i)); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } if(lastName!=null) lastNameUpTo4Char = lastName.substring(0, Math.min(lastName.length(), 4)); clientName = firstName+" "+lastNameUpTo4Char; bClientList[i].setClientname(clientName); bClientList[i].setTherapistname(therapistName); //Get The Mobile Number of all Clients logger.debug("Query:"+Queries.getQuery("fetchForCLMobile")); ps = c.prepareStatement(Queries.getQuery("fetchForCLMobile")); ps.setInt(1, clientIdList.get(i)); rs = ps.executeQuery(); while (rs.next()) { mobile = rs.getString("mobile"); } bClientList[i].setMobile(mobile); reportCL.add(bClientList[i]); } } else{ if(bCL.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bCL.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bCL.getNameid()); ps.setInt(2, bCL.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bCL.setClientid(clientid); //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bCL.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bClientList = new ReportGeneration(); if(clientid != 0){ //Get The Name of the client logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, bCL.getNameid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } if(lastName!=null) lastNameUpTo4Char = lastName.substring(0, Math.min(lastName.length(), 4)); clientName = firstName+" "+lastNameUpTo4Char; //Get The Mobile Number of all Clients logger.debug("Query:"+Queries.getQuery("fetchForCLMobile")); ps = c.prepareStatement(Queries.getQuery("fetchForCLMobile")); ps.setInt(1, clientid); rs = ps.executeQuery(); while (rs.next()) { mobile = rs.getString("mobile"); } bClientList.setMobile(mobile); bClientList.setClientname(clientName); bClientList.setTherapistname(therapistName); reportCL.add(bClientList); } else{ bClientList.setTherapistname(therapistName); bClientList.setClientname(" - "); bClientList.setMobile("-"); reportCL.add(bClientList); } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportCL; } }
UTF-8
Java
62,727
java
ReportGenerationdao.java
Java
[ { "context": " rs.getString(\"lastname\");\n\t\t\t}\n\t\t\ttherapistName = firstName+\" \"+lastName;\n\t\t\t\n\t\t\t\n \t \t\tReportGeneration bTh", "end": 30438, "score": 0.7115079164505005, "start": 30429, "tag": "NAME", "value": "firstName" }, { "context": "String(\"lastname\");...
null
[]
package com.tms.dao; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.apache.log4j.Logger; import com.tms.bean.Report; import com.tms.bean.ReportGeneration; import com.tms.database.ConnectionHelper; import com.tms.util.DateUtil; import com.tms.util.Queries; public class ReportGenerationdao { final static Logger logger = Logger.getLogger(ReportGenerationdao.class); DateUtil dateUtil = new DateUtil(); public List<ReportGeneration> generateReportBI(ReportGeneration bins) { List<ReportGeneration> reportBI = new ArrayList<ReportGeneration>(); List<Date> activityDate = new ArrayList<Date>(); List<Integer> activityID = new ArrayList<Integer>(); List<Integer> cptcode = new ArrayList<Integer>(); List<String> aName = new ArrayList<String>(); Date fromDate= null; Date toDate = null; String activityDt=""; float rate =0; float waiver =0; float netcharge =0; //float total=0; int clientid=0; Connection c = null; PreparedStatement ps = null; ResultSet rs = null; try{ c = ConnectionHelper.getConnection(); if(bins.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bins.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bins.getNameid()); ps.setInt(2, bins.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bins.setClientid(clientid); logger.debug("Query:"+Queries.getQuery("fetchForCNameBI")); ps = c.prepareStatement(Queries.getQuery("fetchForCNameBI")); ps.setInt(1, bins.getNameid()); rs = ps.executeQuery(); while (rs.next()) { bins.setCfirstname(rs.getString("firstname")); bins.setClastname(rs.getString("lastname")); bins.setCmiddlename(rs.getString("middlename")); } String clientName = bins.getCfirstname() + " " +bins.getCmiddlename() + " " +bins.getClastname(); bins.setClientname( clientName); //To get address for the client logger.debug("Query:"+Queries.getQuery("fetchForCAddressBI")); ps = c.prepareStatement(Queries.getQuery("fetchForCAddressBI")); ps.setInt(1, bins.getClientid()); rs = ps.executeQuery(); while (rs.next()) { bins.setCaddress1(rs.getString("address1")); bins.setCaddress2(rs.getString("address2")); bins.setCcity(rs.getString("city")); bins.setCstate(rs.getString("state")); bins.setCzipcode(rs.getInt("zip")); } //To get first diagnosis code for a client ps = c.prepareStatement(Queries.getQuery("fetchForCdiagnosisBI")); ps.setInt(1, bins.getClientid()); rs = ps.executeQuery(); while (rs.next()) { bins.setDiagnosiscode(rs.getString("name")); } //To get Therapist Name and address logger.debug("Query:"+Queries.getQuery("fetchForNameBI")); ps = c.prepareStatement(Queries.getQuery("fetchForNameBI")); ps.setInt(1, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setFirstname(rs.getString("firstname")); bins.setLastname(rs.getString("lastname")); bins.setMiddlename(rs.getString("middlename")); } String therapistName = bins.getFirstname() + " " +bins.getMiddlename() + " " +bins.getLastname(); bins.setTherapistname(therapistName); logger.debug("Query:"+Queries.getQuery("fetchForAddressBI")); ps = c.prepareStatement(Queries.getQuery("fetchForAddressBI")); ps.setInt(1, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setAddress1(rs.getString("address1")); bins.setAddress2(rs.getString("address2")); bins.setCity(rs.getString("city")); bins.setState(rs.getString("state")); bins.setZipcode(rs.getInt("zip")); } //To get Therapist Mobile and EIN, License Number logger.debug("Query:"+Queries.getQuery("fetchForContactBI")); ps = c.prepareStatement(Queries.getQuery("fetchForContactBI")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setEin(rs.getString("ein")); bins.setLicense(rs.getString("license")); bins.setMobile(rs.getString("mobile")); } reportBI.add(bins); logger.debug("Query:"+Queries.getQuery("genRepBIActivity")); ps = c.prepareStatement(Queries.getQuery("genRepBIActivity")); ps.setInt(1, bins.getClientid()); ps.setInt(2, bins.getTherapistid()); fromDate = dateUtil.convertDate(bins.getFromdate()); ps.setDate(3, fromDate); toDate = dateUtil.convertDate(bins.getTodate()); ps.setDate(4, toDate); rs= ps.executeQuery(); while (rs.next()) { activityDate.add(rs.getDate("activitydate")); activityID.add(rs.getInt("activityid")); cptcode.add(rs.getInt("cptcode")); aName.add(rs.getString("activityname")); } ReportGeneration bInsurance[] = new ReportGeneration[activityID.size()]; for(int i=0;i<activityID.size();i++){ bInsurance[i] = new ReportGeneration(); logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, activityID.get(i)); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { rate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setInt(3, activityID.get(i)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netcharge = rate - waiver; //total += netcharge; activityDt = dateUtil.convertStringToDate(activityDate.get(i)); bInsurance[i].setActivityDate(activityDt); bInsurance[i].setCptcode(cptcode.get(i)); bInsurance[i].setNetcharge(netcharge); reportBI.add(bInsurance[i]); rate=0;waiver=0;netcharge=0; } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportBI; } public List<ReportGeneration> generateReportBS(ReportGeneration bins) { List<ReportGeneration> reportBS = new ArrayList<ReportGeneration>(); List<Date> activityDate = new ArrayList<Date>(); List<Integer> activityID = new ArrayList<Integer>(); List<Integer> priorActivityID = new ArrayList<Integer>(); List<Integer> cptcode = new ArrayList<Integer>(); List<String> aName = new ArrayList<String>(); List<Date> paymentDate = new ArrayList<Date>(); List<Integer> payActivityid = new ArrayList<Integer>(); List<String> payActivityname = new ArrayList<String>(); List<Float> fullPayment = new ArrayList<Float>(); List<Integer> payonlyactivityid = new ArrayList<Integer>(); List<Date> payonlypaymentdate = new ArrayList<Date>(); List<Float> payonlyamount = new ArrayList<Float>(); boolean payAtyID=false; float rate =0; float waiver =0; float netcharge =0; float payment=0; float priorCharge=0; float priorWaiver=0; float priorNetcharge=0; float priorRate=0; float priorPayment=0; float priorBalance=0; int clientid=0; float balance=0; int repBSSize =0; boolean priorAtyID=false; boolean payOnly = false; boolean payOnlyActivityid = false; boolean priorBal = false; Connection c = null; PreparedStatement ps = null; ResultSet rs = null; DecimalFormat df = new DecimalFormat("###.##"); df.setMaximumFractionDigits(2); Date fromDate = null; Date toDate = null; String activityDt = ""; String paymentDt = ""; String priorDt= null; String payonlyPaymentDt = ""; String payonlyActivityName = ""; try{ c = ConnectionHelper.getConnection(); if(bins.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bins.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bins.getNameid()); ps.setInt(2, bins.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bins.setClientid(clientid); logger.debug("Query:"+Queries.getQuery("fetchForCNameBI")); ps = c.prepareStatement(Queries.getQuery("fetchForCNameBI")); ps.setInt(1, bins.getNameid()); rs = ps.executeQuery(); while (rs.next()) { bins.setCfirstname(rs.getString("firstname")); bins.setClastname(rs.getString("lastname")); bins.setCmiddlename(rs.getString("middlename")); } String clientName = bins.getCfirstname() + " " +bins.getCmiddlename() + " " +bins.getClastname(); bins.setClientname( clientName); //To get address for the client logger.debug("Query:"+Queries.getQuery("fetchForCAddressBI")); ps = c.prepareStatement(Queries.getQuery("fetchForCAddressBI")); ps.setInt(1, bins.getClientid()); rs = ps.executeQuery(); while (rs.next()) { bins.setCaddress1(rs.getString("address1")); bins.setCaddress2(rs.getString("address2")); bins.setCcity(rs.getString("city")); bins.setCstate(rs.getString("state")); bins.setCzipcode(rs.getInt("zip")); } //To get Therapist Name and address logger.debug("Query:"+Queries.getQuery("fetchForNameBI")); ps = c.prepareStatement(Queries.getQuery("fetchForNameBI")); ps.setInt(1, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setFirstname(rs.getString("firstname")); bins.setLastname(rs.getString("lastname")); bins.setMiddlename(rs.getString("middlename")); } String therapistName = bins.getFirstname() + " " +bins.getMiddlename() + " " +bins.getLastname(); bins.setTherapistname(therapistName); logger.debug("Query:"+Queries.getQuery("fetchForAddressBI")); ps = c.prepareStatement(Queries.getQuery("fetchForAddressBI")); ps.setInt(1, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setAddress1(rs.getString("address1")); bins.setAddress2(rs.getString("address2")); bins.setCity(rs.getString("city")); bins.setState(rs.getString("state")); bins.setZipcode(rs.getInt("zip")); } //To get Therapist Mobile and EIN, License Number logger.debug("Query:"+Queries.getQuery("fetchForContactBI")); ps = c.prepareStatement(Queries.getQuery("fetchForContactBI")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { bins.setEin(rs.getString("ein")); bins.setLicense(rs.getString("license")); bins.setMobile(rs.getString("mobile")); } reportBS.add(bins); logger.debug("Query:"+Queries.getQuery("genRepBIActivity")); ps = c.prepareStatement(Queries.getQuery("genRepBIActivity")); ps.setInt(1, bins.getClientid()); ps.setInt(2, bins.getTherapistid()); fromDate = dateUtil.convertDate(bins.getFromdate()); toDate = dateUtil.convertDate(bins.getTodate()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs= ps.executeQuery(); while (rs.next()) { activityDate.add(rs.getDate("activitydate")); activityID.add(rs.getInt("activityid")); cptcode.add(rs.getInt("cptcode")); aName.add(rs.getString("activityname")); } //Check if there is any prior balance logger.debug("Query:"+Queries.getQuery("fetch_prioractivity")); ps = c.prepareStatement(Queries.getQuery("fetch_prioractivity")); ps.setInt(1,bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setDate(3, fromDate); rs= ps.executeQuery(); while (rs.next()) { priorActivityID.add(rs.getInt("activityid")); } /*2 if(priorActivityID.size() >= 1){ repBSSize = activityID.size()+1;} else repBSSize = activityID.size();*/ //To display Any Payments made between the selected date logger.debug("Query:"+Queries.getQuery("fetch_fullpayment")); ps = c.prepareStatement(Queries.getQuery("fetch_fullpayment")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { payActivityid.add(rs.getInt("activityid")); fullPayment.add(rs.getFloat("payment")); //paymentDt = dateUtil.convertStringToDate(rs.getDate("paymentdate")); paymentDate.add(rs.getDate("paymentdate")); payActivityname.add(rs.getString("activityname")); } if(activityID.size()<payActivityid.size()){ payAtyID = true; for(int i=0;i<activityID.size();i++){ for(int k=0;k<payActivityid.size();k++){ if(activityID.get(i) == payActivityid.get(k)){ payActivityid.remove(i); fullPayment.remove(i); paymentDate.remove(i); payActivityname.remove(i); } } } } //If any payment made on any other date other than activity date logger.debug("Query:"+Queries.getQuery("fetch_paymentbwdate")); ps = c.prepareStatement(Queries.getQuery("fetch_paymentbwdate")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); ps.setInt(5, bins.getTherapistid()); ps.setInt(6, bins.getClientid()); ps.setDate(7, fromDate); ps.setDate(8, toDate); rs = ps.executeQuery(); while (rs.next()) { payonlyactivityid.add(rs.getInt("activityid")); payonlyamount.add(rs.getFloat("amount")); payonlypaymentdate.add(rs.getDate("paymentdate")); } if(priorActivityID.size() >= 1){ repBSSize = activityID.size()+1; priorAtyID = true;} else repBSSize = activityID.size(); if(payAtyID){ repBSSize = repBSSize + payActivityid.size(); } if(payonlyactivityid.size() >=1){ repBSSize = repBSSize + payonlyactivityid.size(); } ReportGeneration bSummary[] = new ReportGeneration[repBSSize]; /*1 if(payAtyID){ for(int l=0;l<payActivityid.size();l++) { bSummary[l] = new ReportGeneration(); bSummary[l].setActivityname(payActivityname.get(l)+"- P/O"); paymentDt = dateUtil.convertStringToDate(paymentDate.get(l)); bSummary[l].setActivityDate(paymentDt); bSummary[l].setNetcharge(0); bSummary[l].setPayment(Float.parseFloat(df.format(fullPayment.get(l)))); bSummary[l].setBalance(Float.parseFloat(df.format(-fullPayment.get(l)))); reportBS.add(bSummary[l]); } }*/ for(int i=0;i<repBSSize;i++){ if(i< activityID.size()){ bSummary[i] = new ReportGeneration(); logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, activityID.get(i)); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { rate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setInt(3, activityID.get(i)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netcharge = rate - waiver; logger.debug("Query:"+Queries.getQuery("fetch_paidamount")); ps = c.prepareStatement(Queries.getQuery("fetch_paidamount")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setInt(3, activityID.get(i)); ps.setDate(4, activityDate.get(i)); // ps.setDate(4, fromDate); // ps.setDate(5, toDate); rs = ps.executeQuery(); while (rs.next()) { payment = rs.getFloat("payment"); } balance = netcharge - payment; activityDt = dateUtil.convertStringToDate(activityDate.get(i)); bSummary[i].setActivityDate(activityDt); bSummary[i].setActivityname(aName.get(i)); bSummary[i].setNetcharge(netcharge); bSummary[i].setPayment(Float.parseFloat(df.format(payment))); bSummary[i].setBalance(Float.parseFloat(df.format(balance))); reportBS.add(bSummary[i]); rate=0;waiver=0;netcharge=0;payment=0;balance=0; } // else if( priorAtyID && !priorBal){ //This is for Prior Balance priorBal = true; for(int k=0;k<priorActivityID.size();k++){ logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, priorActivityID.get(k)); ps.setInt(2, bins.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { priorRate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setInt(3, priorActivityID.get(k)); rs = ps.executeQuery(); while (rs.next()) { priorWaiver = rs.getFloat("waiver"); } priorCharge = priorRate - priorWaiver; priorNetcharge += priorCharge; priorRate =0;priorWaiver=0;priorCharge=0; } logger.debug("Query:"+Queries.getQuery("fetch_priorbalance")); ps = c.prepareStatement(Queries.getQuery("fetch_priorbalance")); ps.setInt(1, bins.getTherapistid()); ps.setInt(2, bins.getClientid()); ps.setDate(3, fromDate); rs = ps.executeQuery(); while (rs.next()) { priorPayment = rs.getFloat("payment"); } priorBalance = priorNetcharge - priorPayment; DateFormat dateFormat= new SimpleDateFormat("yyyy/MM/dd"); Calendar cal = Calendar.getInstance(); cal.setTime(fromDate); cal.add(Calendar.DATE, -1); String dateInString = dateFormat.format(cal.getTime()); java.util.Date date = dateFormat.parse(dateInString); Date priorDate = new Date(date.getTime()); bSummary[i] = new ReportGeneration(); priorDt = dateUtil.convertStringToDate(priorDate); bSummary[i].setActivityDate(priorDt); bSummary[i].setActivityname("Prior Balance"); bSummary[i].setNetcharge(0); bSummary[i].setPayment(0); bSummary[i].setBalance(Float.parseFloat(df.format(priorBalance))); reportBS.add(bSummary[i]); priorBalance=0;priorPayment=0;priorNetcharge=0; } if(payAtyID && !payOnly){ payOnly = true; for(int l=0;l<payActivityid.size();l++) { bSummary[l] = new ReportGeneration(); bSummary[l].setActivityname(payActivityname.get(l)+"- P/O"); paymentDt = dateUtil.convertStringToDate(paymentDate.get(l)); bSummary[l].setActivityDate(paymentDt); bSummary[l].setNetcharge(0); bSummary[l].setPayment(Float.parseFloat(df.format(fullPayment.get(l)))); bSummary[l].setBalance(Float.parseFloat(df.format(-fullPayment.get(l)))); reportBS.add(bSummary[l]); } } if(payonlyactivityid.size() >=1 && !payOnlyActivityid){ payOnlyActivityid = true; for(int l=0;l<payonlyactivityid.size();l++) { payonlyActivityName =""; bSummary[l] =new ReportGeneration(); logger.debug("Query:"+Queries.getQuery("fetch_activityname")); ps = c.prepareStatement(Queries.getQuery("fetch_activityname")); ps.setInt(1, payonlyactivityid.get(l)); rs = ps.executeQuery(); while (rs.next()) { payonlyActivityName=rs.getString("activityname"); } bSummary[l].setActivityname(payonlyActivityName +"- P/O"); payonlyPaymentDt = dateUtil.convertStringToDate(payonlypaymentdate.get(l)); bSummary[l].setActivityDate(payonlyPaymentDt); bSummary[l].setNetcharge(0); bSummary[l].setPayment(Float.parseFloat(df.format(payonlyamount.get(l)))); bSummary[l].setBalance(Float.parseFloat(df.format(-payonlyamount.get(l)))); reportBS.add(bSummary[l]); } } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportBS; } public List<ReportGeneration> generateReportTOT(ReportGeneration bTOT) { List<ReportGeneration> reportTOT = new ArrayList<ReportGeneration>(); List<Integer> clientIdList = new ArrayList<Integer>(); List<Integer> nameIdList = new ArrayList<Integer>(); List<Integer> priorActivityID = null; List<Integer> activityIDList = null; DateUtil dateUtil = new DateUtil(); DecimalFormat df = new DecimalFormat("###.##"); df.setMaximumFractionDigits(2); Connection c = null; PreparedStatement ps = null; ResultSet rs = null; int clientid=0; String firstName=""; String lastName=""; String clientName=""; String therapistName=""; int repActTOTSize =0; float charge=0; float netCharge=0; float waiver=0; float netWaiver=0; float payment=0; float netPayment=0; float grossCharge =0; float totbal =0; float balance=0; float priorBalance=0; float priorWaiver=0; float priorPayment=0; float priorCharge =0; float priorRate=0; float priorNetcharge=0; Date fromDate= null; Date toDate=null; int nameid=0; try{ c = ConnectionHelper.getConnection(); nameid = bTOT.getNameid(); fromDate= dateUtil.convertDate(bTOT.getFromdate()); toDate = dateUtil.convertDate(bTOT.getTodate()); if(nameid == 0){ if(bTOT.getFlagid() == 0){ //Get all the Clients logger.debug("Query:"+Queries.getQuery("fetchForTMClientid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientid")); ps.setInt(1, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } else{ //Get all the Clients with flagid logger.debug("Query:"+Queries.getQuery("fetchForTMClientidWFlag")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientidWFlag")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bTherapistMoney[] = new ReportGeneration[clientIdList.size()]; for(int i=0;i<clientIdList.size();i++){ bTherapistMoney[i] = new ReportGeneration(); //Get The Name of all Clients logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, nameIdList.get(i)); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } clientName = firstName+" "+lastName; bTherapistMoney[i].setClientname(clientName); bTherapistMoney[i].setTherapistname(therapistName); bTherapistMoney[i].setFromdate(bTOT.getFromdate()); bTherapistMoney[i].setTodate(bTOT.getTodate()); //Get The Activity of a Client activityIDList = new ArrayList<Integer>(); priorActivityID = new ArrayList<Integer>(); logger.debug("Query:"+Queries.getQuery("fetchForTMActivity")); ps = c.prepareStatement(Queries.getQuery("fetchForTMActivity")); ps.setInt(1, clientIdList.get(i)); ps.setInt(2, bTOT.getTherapistid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { activityIDList.add(rs.getInt("activityid")); } //Check if there is any prior balance logger.debug("Query:"+Queries.getQuery("fetch_prioractivity")); ps = c.prepareStatement(Queries.getQuery("fetch_prioractivity")); ps.setInt(1,bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setDate(3, fromDate); rs= ps.executeQuery(); while (rs.next()) { priorActivityID.add(rs.getInt("activityid")); } if(priorActivityID.size() >= 1){ repActTOTSize = activityIDList.size()+1;} else{ repActTOTSize = activityIDList.size();} netPayment=0;netCharge=0;netWaiver=0; for(int k=0;k<repActTOTSize;k++){ if(k<activityIDList.size()){ //Get The Rate for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMRate")); ps = c.prepareStatement(Queries.getQuery("fetchForTMRate")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { charge = rs.getFloat("rate"); } netCharge += charge; //Get The waiver for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMWaiver")); ps = c.prepareStatement(Queries.getQuery("fetchForTMWaiver")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setInt(3, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netWaiver += waiver; charge=0;waiver=0; } else{ //This is for Prior Balance for(int l=0;l<priorActivityID.size();l++){ logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, priorActivityID.get(l)); ps.setInt(2, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { priorRate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setInt(3, priorActivityID.get(l)); rs = ps.executeQuery(); while (rs.next()) { priorWaiver = rs.getFloat("waiver"); } priorCharge = priorRate - priorWaiver; priorNetcharge += priorCharge; priorRate =0;priorWaiver=0;priorCharge=0; } logger.debug("Query:"+Queries.getQuery("fetch_priorbalance")); ps = c.prepareStatement(Queries.getQuery("fetch_priorbalance")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setDate(3, fromDate); rs = ps.executeQuery(); while (rs.next()) { priorPayment = rs.getFloat("payment"); } priorBalance = priorNetcharge - priorPayment; } } //Get The Payment for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMPayment")); ps = c.prepareStatement(Queries.getQuery("fetchForTMPayment")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setDate(3,fromDate); ps.setDate(4,toDate); rs = ps.executeQuery(); while (rs.next()) { netPayment = rs.getFloat("payment"); } bTherapistMoney[i].setNetcharge(Float.parseFloat(df.format(netCharge))); bTherapistMoney[i].setNetwaiver(Float.parseFloat(df.format(netWaiver))); bTherapistMoney[i].setNetpayment(Float.parseFloat(df.format(netPayment))); grossCharge = netCharge - netWaiver; balance = grossCharge - netPayment; totbal = balance + priorBalance; bTherapistMoney[i].setBalance(Float.parseFloat(df.format(totbal))); bTherapistMoney[i].setPriorBalance(Float.parseFloat(df.format(priorBalance))); reportTOT.add(bTherapistMoney[i]); priorBalance=0;priorPayment=0;priorNetcharge=0; } }//This is for an individual client else{ if(bTOT.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bTOT.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bTOT.getNameid()); ps.setInt(2, bTOT.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bTOT.setClientid(clientid); activityIDList = new ArrayList<Integer>(); priorActivityID = new ArrayList<Integer>(); //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bTherapistMoney = new ReportGeneration(); if(clientid != 0){ //Get The Name of the client logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, bTOT.getNameid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } clientName = firstName+" "+lastName; //Get The Activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMActivity")); ps = c.prepareStatement(Queries.getQuery("fetchForTMActivity")); ps.setInt(1, bTOT.getClientid()); ps.setInt(2, bTOT.getTherapistid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { activityIDList.add(rs.getInt("activityid")); } //Check if there is any prior balance logger.debug("Query:"+Queries.getQuery("fetch_prioractivity")); ps = c.prepareStatement(Queries.getQuery("fetch_prioractivity")); ps.setInt(1,bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setDate(3, fromDate); rs= ps.executeQuery(); while (rs.next()) { priorActivityID.add(rs.getInt("activityid")); } if(priorActivityID.size() >= 1){ repActTOTSize = activityIDList.size()+1;} else{ repActTOTSize = activityIDList.size();} netPayment=0;netCharge=0;netWaiver=0; for(int k=0;k<repActTOTSize;k++){ if(k<activityIDList.size()){ //Get The Rate for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMRate")); ps = c.prepareStatement(Queries.getQuery("fetchForTMRate")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { charge = rs.getFloat("rate"); } netCharge += charge; //Get The waiver for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMWaiver")); ps = c.prepareStatement(Queries.getQuery("fetchForTMWaiver")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setInt(3, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netWaiver += waiver; charge=0;waiver=0; } else{ //This is for Prior Balance for(int l=0;l<priorActivityID.size();l++){ logger.debug("Query:"+Queries.getQuery("fetch_rate")); ps = c.prepareStatement(Queries.getQuery("fetch_rate")); ps.setInt(1, priorActivityID.get(l)); ps.setInt(2, bTOT.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { priorRate = rs.getFloat("amount"); } logger.debug("Query:"+Queries.getQuery("fetch_waiver")); ps = c.prepareStatement(Queries.getQuery("fetch_waiver")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setInt(3, priorActivityID.get(l)); rs = ps.executeQuery(); while (rs.next()) { priorWaiver = rs.getFloat("waiver"); } priorCharge = priorRate - priorWaiver; priorNetcharge += priorCharge; priorRate =0;priorWaiver=0;priorCharge=0; } logger.debug("Query:"+Queries.getQuery("fetch_priorbalance")); ps = c.prepareStatement(Queries.getQuery("fetch_priorbalance")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setDate(3, fromDate); rs = ps.executeQuery(); while (rs.next()) { priorPayment = rs.getFloat("payment"); } priorBalance = priorNetcharge - priorPayment; } } //Get The Payment for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMPayment")); ps = c.prepareStatement(Queries.getQuery("fetchForTMPayment")); ps.setInt(1, bTOT.getTherapistid()); ps.setInt(2, bTOT.getClientid()); ps.setDate(3,fromDate); ps.setDate(4,toDate); rs = ps.executeQuery(); while (rs.next()) { netPayment = rs.getFloat("payment"); } bTherapistMoney.setClientname(clientName); bTherapistMoney.setTherapistname(therapistName); bTherapistMoney.setFromdate(bTOT.getFromdate()); bTherapistMoney.setTodate(bTOT.getTodate()); bTherapistMoney.setNetcharge(Float.parseFloat(df.format(netCharge))); bTherapistMoney.setNetwaiver(Float.parseFloat(df.format(netWaiver))); bTherapistMoney.setNetpayment(Float.parseFloat(df.format(netPayment))); grossCharge = netCharge - netWaiver; balance = grossCharge - netPayment; totbal = balance + priorBalance; bTherapistMoney.setBalance(Float.parseFloat(df.format(totbal))); bTherapistMoney.setPriorBalance(Float.parseFloat(df.format(priorBalance))); reportTOT.add(bTherapistMoney); } else{ bTherapistMoney.setTherapistname(therapistName); bTherapistMoney.setClientname(" - "); bTherapistMoney.setFromdate(bTOT.getFromdate()); bTherapistMoney.setTodate(bTOT.getTodate()); reportTOT.add(bTherapistMoney); } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportTOT; } public List<ReportGeneration> generateReportTM(ReportGeneration bTM) { List<ReportGeneration> reportTM = new ArrayList<ReportGeneration>(); List<Integer> clientIdList = new ArrayList<Integer>(); List<Integer> nameIdList = new ArrayList<Integer>(); List<Integer> activityIDList = null; DateUtil dateUtil = new DateUtil(); DecimalFormat df = new DecimalFormat("###.##"); df.setMaximumFractionDigits(2); Connection c = null; PreparedStatement ps = null; ResultSet rs = null; int clientid=0; String firstName=""; String lastName=""; String clientName=""; String therapistName=""; float charge=0; float netCharge=0; float waiver=0; float netWaiver=0; float payment=0; float netPayment=0; Date fromDate= null; Date toDate=null; int nameid=0; try{ c = ConnectionHelper.getConnection(); nameid = bTM.getNameid(); fromDate= dateUtil.convertDate(bTM.getFromdate()); toDate = dateUtil.convertDate(bTM.getTodate()); if(nameid == 0){ if(bTM.getFlagid() == 0){ //Get all the Clients logger.debug("Query:"+Queries.getQuery("fetchForTMClientid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientid")); ps.setInt(1, bTM.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } else{ //Get all the Clients with flagid logger.debug("Query:"+Queries.getQuery("fetchForTMClientidWFlag")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientidWFlag")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, bTM.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bTM.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bTherapistMoney[] = new ReportGeneration[clientIdList.size()]; for(int i=0;i<clientIdList.size();i++){ bTherapistMoney[i] = new ReportGeneration(); //Get The Name of all Clients logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, nameIdList.get(i)); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } clientName = firstName+" "+lastName; bTherapistMoney[i].setClientname(clientName); bTherapistMoney[i].setTherapistname(therapistName); bTherapistMoney[i].setFromdate(bTM.getFromdate()); bTherapistMoney[i].setTodate(bTM.getTodate()); //Get The Activity of a Client activityIDList = new ArrayList<Integer>(); logger.debug("Query:"+Queries.getQuery("fetchForTMActivity")); ps = c.prepareStatement(Queries.getQuery("fetchForTMActivity")); ps.setInt(1, clientIdList.get(i)); ps.setInt(2, bTM.getTherapistid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { activityIDList.add(rs.getInt("activityid")); } netPayment=0;netCharge=0;netWaiver=0; for(int k=0;k<activityIDList.size();k++){ //Get The Rate for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMRate")); ps = c.prepareStatement(Queries.getQuery("fetchForTMRate")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { charge = rs.getFloat("rate"); } netCharge += charge; //Get The waiver for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMWaiver")); ps = c.prepareStatement(Queries.getQuery("fetchForTMWaiver")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setInt(3, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netWaiver += waiver; charge=0;waiver=0; } //Get The Payment for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMPayment")); ps = c.prepareStatement(Queries.getQuery("fetchForTMPayment")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, clientIdList.get(i)); ps.setDate(3,fromDate); ps.setDate(4,toDate); rs = ps.executeQuery(); while (rs.next()) { netPayment = rs.getFloat("payment"); } bTherapistMoney[i].setNetcharge(Float.parseFloat(df.format(netCharge))); bTherapistMoney[i].setNetwaiver(Float.parseFloat(df.format(netWaiver))); bTherapistMoney[i].setNetpayment(Float.parseFloat(df.format(netPayment))); reportTM.add(bTherapistMoney[i]); } } else{ if(bTM.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bTM.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bTM.getNameid()); ps.setInt(2, bTM.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bTM.setClientid(clientid); activityIDList = new ArrayList<Integer>(); //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bTM.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bTherapistMoney = new ReportGeneration(); if(clientid != 0){ //Get The Name of the client logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, bTM.getNameid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } clientName = firstName+" "+lastName; //Get The Activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMActivity")); ps = c.prepareStatement(Queries.getQuery("fetchForTMActivity")); ps.setInt(1, bTM.getClientid()); ps.setInt(2, bTM.getTherapistid()); ps.setDate(3, fromDate); ps.setDate(4, toDate); rs = ps.executeQuery(); while (rs.next()) { activityIDList.add(rs.getInt("activityid")); } for(int k=0;k<activityIDList.size();k++){ //Get The Rate for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMRate")); ps = c.prepareStatement(Queries.getQuery("fetchForTMRate")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { charge = rs.getFloat("rate"); } netCharge += charge; //Get The waiver for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMWaiver")); ps = c.prepareStatement(Queries.getQuery("fetchForTMWaiver")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, bTM.getClientid()); ps.setInt(3, activityIDList.get(k)); rs = ps.executeQuery(); while (rs.next()) { waiver = rs.getFloat("waiver"); } netWaiver += waiver; charge=0;waiver=0; } //Get The Payment for activity of a Client logger.debug("Query:"+Queries.getQuery("fetchForTMICPayment")); ps = c.prepareStatement(Queries.getQuery("fetchForTMICPayment")); ps.setInt(1, bTM.getTherapistid()); ps.setInt(2, bTM.getClientid()); //ps.setInt(3, activityIDList.get(k)); ps.setDate(3,fromDate); ps.setDate(4,toDate); rs = ps.executeQuery(); while (rs.next()) { netPayment = rs.getFloat("payment"); } bTherapistMoney.setClientname(clientName); bTherapistMoney.setTherapistname(therapistName); bTherapistMoney.setFromdate(bTM.getFromdate()); bTherapistMoney.setTodate(bTM.getTodate()); bTherapistMoney.setNetcharge(Float.parseFloat(df.format(netCharge))); bTherapistMoney.setNetwaiver(Float.parseFloat(df.format(netWaiver))); bTherapistMoney.setNetpayment(Float.parseFloat(df.format(netPayment))); reportTM.add(bTherapistMoney); } else{ bTherapistMoney.setTherapistname(therapistName); bTherapistMoney.setClientname(" - "); bTherapistMoney.setFromdate(bTM.getFromdate()); bTherapistMoney.setTodate(bTM.getTodate()); reportTM.add(bTherapistMoney); } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportTM; } public List<ReportGeneration> generateReportCL(ReportGeneration bCL) { List<ReportGeneration> reportCL = new ArrayList<ReportGeneration>(); List<Integer> clientIdList = new ArrayList<Integer>(); List<Integer> nameIdList = new ArrayList<Integer>(); Connection c = null; PreparedStatement ps = null; ResultSet rs = null; int clientid=0; String firstName=""; String lastName=""; String lastNameUpTo4Char = ""; String clientName=""; String therapistName=""; String mobile=""; int nameid=0; try{ c = ConnectionHelper.getConnection(); nameid = bCL.getNameid(); if(nameid == 0){ if(bCL.getFlagid() == 0){ //Get all the Clients logger.debug("Query:"+Queries.getQuery("fetchForTMClientid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientid")); ps.setInt(1, bCL.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } else{ //Get all the Clients with flagid logger.debug("Query:"+Queries.getQuery("fetchForTMClientidWFlag")); ps = c.prepareStatement(Queries.getQuery("fetchForTMClientidWFlag")); ps.setInt(1, bCL.getTherapistid()); ps.setInt(2, bCL.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientIdList.add(rs.getInt("clientid")); nameIdList.add(rs.getInt("name_id")); } } //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bCL.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bClientList[] = new ReportGeneration[clientIdList.size()]; for(int i=0;i<clientIdList.size();i++){ bClientList[i] = new ReportGeneration(); //Get The Name of all Clients logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, nameIdList.get(i)); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } if(lastName!=null) lastNameUpTo4Char = lastName.substring(0, Math.min(lastName.length(), 4)); clientName = firstName+" "+lastNameUpTo4Char; bClientList[i].setClientname(clientName); bClientList[i].setTherapistname(therapistName); //Get The Mobile Number of all Clients logger.debug("Query:"+Queries.getQuery("fetchForCLMobile")); ps = c.prepareStatement(Queries.getQuery("fetchForCLMobile")); ps.setInt(1, clientIdList.get(i)); rs = ps.executeQuery(); while (rs.next()) { mobile = rs.getString("mobile"); } bClientList[i].setMobile(mobile); reportCL.add(bClientList[i]); } } else{ if(bCL.getFlagid() == 0){ logger.debug("Query:"+Queries.getQuery("fetchForReport_clientid")); ps = c.prepareStatement(Queries.getQuery("fetchForReport_clientid")); ps.setInt(1, bCL.getNameid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } else{ logger.debug("Query:"+Queries.getQuery("fetchForReportclientWflagid")); ps = c.prepareStatement(Queries.getQuery("fetchForReportclientWflagid")); ps.setInt(1, bCL.getNameid()); ps.setInt(2, bCL.getFlagid()); rs = ps.executeQuery(); while (rs.next()) { clientid = rs.getInt("clientid"); } } bCL.setClientid(clientid); //Get Therapist Name logger.debug("Query:"+Queries.getQuery("fetchForTMTherapist")); ps = c.prepareStatement(Queries.getQuery("fetchForTMTherapist")); ps.setInt(1, bCL.getTherapistid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } therapistName = firstName+" "+lastName; ReportGeneration bClientList = new ReportGeneration(); if(clientid != 0){ //Get The Name of the client logger.debug("Query:"+Queries.getQuery("fetchForTMNameid")); ps = c.prepareStatement(Queries.getQuery("fetchForTMNameid")); ps.setInt(1, bCL.getNameid()); rs = ps.executeQuery(); while (rs.next()) { firstName = rs.getString("firstname"); lastName = rs.getString("lastname"); } if(lastName!=null) lastNameUpTo4Char = lastName.substring(0, Math.min(lastName.length(), 4)); clientName = firstName+" "+lastNameUpTo4Char; //Get The Mobile Number of all Clients logger.debug("Query:"+Queries.getQuery("fetchForCLMobile")); ps = c.prepareStatement(Queries.getQuery("fetchForCLMobile")); ps.setInt(1, clientid); rs = ps.executeQuery(); while (rs.next()) { mobile = rs.getString("mobile"); } bClientList.setMobile(mobile); bClientList.setClientname(clientName); bClientList.setTherapistname(therapistName); reportCL.add(bClientList); } else{ bClientList.setTherapistname(therapistName); bClientList.setClientname(" - "); bClientList.setMobile("-"); reportCL.add(bClientList); } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { ConnectionHelper.close(c); } return reportCL; } }
62,727
0.525212
0.519824
1,620
37.720371
22.83008
114
false
false
0
0
0
0
0
0
2.711728
false
false
2
017be0266f05589878c1f19d3626e458b9f6cc9f
20,392,504,789,189
27548bfd4f26f5d8b458b50e2914563d5ab99374
/src/codegen/org.ect.codegen.v2.proxy/src/org/ect/codegen/v2/proxy/gen/java/ProxyJavaGenerator.java
10ef889eed20a4de78e6ca2df87cdf0e9cf0a9c4
[]
no_license
behnaaz/extensible-coordination-tools
https://github.com/behnaaz/extensible-coordination-tools
bafa0b2ba810bf6a9ac5478133330b430993c753
16d447a241ad87096d45f657b8efb832f133414a
refs/heads/master
2021-01-17T04:45:53.202000
2016-05-20T14:55:53
2016-05-20T14:55:53
39,437,821
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ect.codegen.v2.proxy.gen.java; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.ect.codegen.v2.core.gen.AbstractGenerator; import org.ect.codegen.v2.core.gen.Files; import org.ect.codegen.v2.core.gen.java.AbstractJavaGenerator; import org.ect.codegen.v2.core.gen.java.CoreJavaGenerator; import org.ect.codegen.v2.core.gen.java.CoreJavaGeneratorDefaults; import org.ect.codegen.v2.proxy.descr.java.AbstractParty; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; public class ProxyJavaGenerator<P extends AbstractParty<?>> extends AbstractJavaGenerator<P> { // // FIELDS // /** * The cached result of <code>tryGenerate()</code>. * * @see #tryGenerate() */ private Map<String, String> tryGenerateResult; /** * The cached result of <code>tryGenerateSimAut()</code>. * * @see #tryGenerateSimAut() */ private Map<String, String> tryGenerateSimAutResult; // // CONSTRUCTORS // /** * Invokes: <code>super(party,stgFiles,srcDirs,libDirs)</code>. * * @see AbstractGenerator#AbstractGenerator(Object, Collection, Collection, * Collection) */ public ProxyJavaGenerator(final P party, final Collection<File> stgFiles, final Collection<File> srcDirs, final Collection<File> libDirs) { super(party, stgFiles, srcDirs, libDirs); } // // METHODS - PUBLIC // /** * <em>Inherited documentation:</em> * * <p> * {@inheritDoc} * </p> */ @Override public boolean canGenerate() { try { tryGenerate(); return true; } catch (final Exception e) { return false; } } /** * <em>Inherited documentation:</em> * * <p> * {@inheritDoc} * </p> */ @Override public Map<String, String> generate() { /* Validate state. */ if (!canGenerate()) throw new IllegalStateException("!canGenerate()"); /* Try to generate. */ try { return tryGenerate(); } /* Catch. */ catch (final Exception e) { throw new RuntimeException(e); } } // // METHODS - PRIVATE // /** * Tries to generate code for the subject of this generator. * * <p> * Returns a map from names of generated files to their content. * </p> * * @return A map from strings to strings. Never <code>null</code>. * @throws Exception * If something goes wrong. */ private Map<String, String> tryGenerate() throws Exception { if (tryGenerateResult == null) { /* Get the template. */ ST template = null; for (final STGroup g : super.loadTemplates()) if ((template = g.getInstanceOf("proxyClass")) != null) break; /* Prepare the subject. */ final P party = super.getSubject(); /* Prepare the template. */ template.add("party", party); /* Generate. */ tryGenerateResult = new HashMap<String, String>(); tryGenerateResult.putAll(tryGenerateSimAut()); tryGenerateResult.put(party.getClassName().toString() + ".java", template.render()); } return tryGenerateResult; } /** * Tries to generate code for the simulation automaton of the subject of * this generator. * * <p> * Returns a map from names of generated files to their content. * </p> * * @return A map from strings to strings. Never <code>null</code>. * @throws Exception * If something goes wrong. */ private final Map<String, String> tryGenerateSimAut() throws Exception { if (tryGenerateSimAutResult == null) { /* Get defaults. */ final Collection<File> stgFiles = Files .tryFindReadableFilesAt(CoreJavaGeneratorDefaults .findStgLocations()); final Collection<File> srcDirs = Files .tryFindReadableDirsAt(CoreJavaGeneratorDefaults .findSrcLocations()); final Collection<File> libDirs = Files .tryFindReadableDirsAt(CoreJavaGeneratorDefaults .findLibLocations()); /* Generate. */ tryGenerateSimAutResult = new CoreJavaGenerator(super.getSubject() .getSimAut(), stgFiles, srcDirs, libDirs).generate(); } return tryGenerateSimAutResult; } }
UTF-8
Java
4,220
java
ProxyJavaGenerator.java
Java
[]
null
[]
package org.ect.codegen.v2.proxy.gen.java; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.ect.codegen.v2.core.gen.AbstractGenerator; import org.ect.codegen.v2.core.gen.Files; import org.ect.codegen.v2.core.gen.java.AbstractJavaGenerator; import org.ect.codegen.v2.core.gen.java.CoreJavaGenerator; import org.ect.codegen.v2.core.gen.java.CoreJavaGeneratorDefaults; import org.ect.codegen.v2.proxy.descr.java.AbstractParty; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; public class ProxyJavaGenerator<P extends AbstractParty<?>> extends AbstractJavaGenerator<P> { // // FIELDS // /** * The cached result of <code>tryGenerate()</code>. * * @see #tryGenerate() */ private Map<String, String> tryGenerateResult; /** * The cached result of <code>tryGenerateSimAut()</code>. * * @see #tryGenerateSimAut() */ private Map<String, String> tryGenerateSimAutResult; // // CONSTRUCTORS // /** * Invokes: <code>super(party,stgFiles,srcDirs,libDirs)</code>. * * @see AbstractGenerator#AbstractGenerator(Object, Collection, Collection, * Collection) */ public ProxyJavaGenerator(final P party, final Collection<File> stgFiles, final Collection<File> srcDirs, final Collection<File> libDirs) { super(party, stgFiles, srcDirs, libDirs); } // // METHODS - PUBLIC // /** * <em>Inherited documentation:</em> * * <p> * {@inheritDoc} * </p> */ @Override public boolean canGenerate() { try { tryGenerate(); return true; } catch (final Exception e) { return false; } } /** * <em>Inherited documentation:</em> * * <p> * {@inheritDoc} * </p> */ @Override public Map<String, String> generate() { /* Validate state. */ if (!canGenerate()) throw new IllegalStateException("!canGenerate()"); /* Try to generate. */ try { return tryGenerate(); } /* Catch. */ catch (final Exception e) { throw new RuntimeException(e); } } // // METHODS - PRIVATE // /** * Tries to generate code for the subject of this generator. * * <p> * Returns a map from names of generated files to their content. * </p> * * @return A map from strings to strings. Never <code>null</code>. * @throws Exception * If something goes wrong. */ private Map<String, String> tryGenerate() throws Exception { if (tryGenerateResult == null) { /* Get the template. */ ST template = null; for (final STGroup g : super.loadTemplates()) if ((template = g.getInstanceOf("proxyClass")) != null) break; /* Prepare the subject. */ final P party = super.getSubject(); /* Prepare the template. */ template.add("party", party); /* Generate. */ tryGenerateResult = new HashMap<String, String>(); tryGenerateResult.putAll(tryGenerateSimAut()); tryGenerateResult.put(party.getClassName().toString() + ".java", template.render()); } return tryGenerateResult; } /** * Tries to generate code for the simulation automaton of the subject of * this generator. * * <p> * Returns a map from names of generated files to their content. * </p> * * @return A map from strings to strings. Never <code>null</code>. * @throws Exception * If something goes wrong. */ private final Map<String, String> tryGenerateSimAut() throws Exception { if (tryGenerateSimAutResult == null) { /* Get defaults. */ final Collection<File> stgFiles = Files .tryFindReadableFilesAt(CoreJavaGeneratorDefaults .findStgLocations()); final Collection<File> srcDirs = Files .tryFindReadableDirsAt(CoreJavaGeneratorDefaults .findSrcLocations()); final Collection<File> libDirs = Files .tryFindReadableDirsAt(CoreJavaGeneratorDefaults .findLibLocations()); /* Generate. */ tryGenerateSimAutResult = new CoreJavaGenerator(super.getSubject() .getSimAut(), stgFiles, srcDirs, libDirs).generate(); } return tryGenerateSimAutResult; } }
4,220
0.645024
0.642891
173
22.393064
22.475584
76
false
false
0
0
0
0
0
0
1.745665
false
false
2
7be734c4dce74ef9f40414e2b731862d199eef95
23,733,989,343,848
712da17b1422d64882deed75d378914d3c4eba72
/laba19-20/Generatooorrr.java
cdc8a9f6c2ef99a1eb45a2f87d9528ab9535a6a7
[]
no_license
Romell-rom/Laba13-14
https://github.com/Romell-rom/Laba13-14
6a2f337d650b962c62c4aedcecf6bb0ec261c5df
f27fe3ee9af544e3b1038d06ce6e66ca1d1894da
refs/heads/main
2023-02-05T08:12:19.002000
2020-12-22T11:14:02
2020-12-22T11:14:02
306,589,672
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package laba19-20; import java.util.*; public class Generate { private final ArrayList<String> numbers = new ArrayList<>(); private final HashSet<String> numbers_hash = new HashSet<String>(); private final Set<String> numbers_tree = new TreeSet<>(); public void beatifulplates(){ String[] letter = {"А", "В", "Е", "К", "М", "Н", "О", "Р", "С", "Т", "У", "Х"}; for (int i=1;i<=199;i++){ for(int j=1; j<=9; j++) for (String s : letter) { String arr = s + (j) + (j) + (j) + s + s + (i); numbers.add(arr); numbers_hash.add(arr); numbers_tree.add(arr); } } for (int i=1;i<=199;i++){ for(int l=1; l<=9; l++) for (int j = 0; j < letter.length; j++) { for (int h = 0; h < letter.length; h++) { for (int k = 0; k < letter.length; k++) { String arr = letter[j] + (l) + (l) + (l) + letter[h] + letter[k] + (i); numbers.add(arr); numbers_hash.add(arr); numbers_tree.add(arr); } } } } } public void search(String plate){ boolean search; long startTime = System.nanoTime(); search = numbers.contains(plate); long estimatedTime = System.nanoTime() - startTime; if (search){ System.out.println("Найден, поиск занял "+estimatedTime+"нс"); } else System.out.println("Не найден, поиск занял "+estimatedTime+"нс"); Collections.sort(numbers); int x; startTime = System.nanoTime(); x=Collections.binarySearch(numbers,plate); estimatedTime = System.nanoTime() - startTime; if (x>0 && x<= numbers.size()){ System.out.println("Найден, поиск занял "+estimatedTime+"нс"); } else System.out.println("Не найден, поиск занял "+estimatedTime+"нс"); startTime = System.nanoTime(); search = numbers_hash.contains(plate); estimatedTime = System.nanoTime() - startTime; if (search){ System.out.println("Найден, поиск занял "+estimatedTime+"нс"); } else System.out.println("Не найден, поиск занял "+estimatedTime+"нс"); startTime = System.nanoTime(); search =(numbers_tree.contains(plate)); estimatedTime = System.nanoTime() - startTime; if (search){ System.out.println("Найден, поиск занял "+estimatedTime+"нс"); } else System.out.println("Не найден, поиск занял "+estimatedTime+"нс"); } }
UTF-8
Java
2,993
java
Generatooorrr.java
Java
[]
null
[]
package laba19-20; import java.util.*; public class Generate { private final ArrayList<String> numbers = new ArrayList<>(); private final HashSet<String> numbers_hash = new HashSet<String>(); private final Set<String> numbers_tree = new TreeSet<>(); public void beatifulplates(){ String[] letter = {"А", "В", "Е", "К", "М", "Н", "О", "Р", "С", "Т", "У", "Х"}; for (int i=1;i<=199;i++){ for(int j=1; j<=9; j++) for (String s : letter) { String arr = s + (j) + (j) + (j) + s + s + (i); numbers.add(arr); numbers_hash.add(arr); numbers_tree.add(arr); } } for (int i=1;i<=199;i++){ for(int l=1; l<=9; l++) for (int j = 0; j < letter.length; j++) { for (int h = 0; h < letter.length; h++) { for (int k = 0; k < letter.length; k++) { String arr = letter[j] + (l) + (l) + (l) + letter[h] + letter[k] + (i); numbers.add(arr); numbers_hash.add(arr); numbers_tree.add(arr); } } } } } public void search(String plate){ boolean search; long startTime = System.nanoTime(); search = numbers.contains(plate); long estimatedTime = System.nanoTime() - startTime; if (search){ System.out.println("Найден, поиск занял "+estimatedTime+"нс"); } else System.out.println("Не найден, поиск занял "+estimatedTime+"нс"); Collections.sort(numbers); int x; startTime = System.nanoTime(); x=Collections.binarySearch(numbers,plate); estimatedTime = System.nanoTime() - startTime; if (x>0 && x<= numbers.size()){ System.out.println("Найден, поиск занял "+estimatedTime+"нс"); } else System.out.println("Не найден, поиск занял "+estimatedTime+"нс"); startTime = System.nanoTime(); search = numbers_hash.contains(plate); estimatedTime = System.nanoTime() - startTime; if (search){ System.out.println("Найден, поиск занял "+estimatedTime+"нс"); } else System.out.println("Не найден, поиск занял "+estimatedTime+"нс"); startTime = System.nanoTime(); search =(numbers_tree.contains(plate)); estimatedTime = System.nanoTime() - startTime; if (search){ System.out.println("Найден, поиск занял "+estimatedTime+"нс"); } else System.out.println("Не найден, поиск занял "+estimatedTime+"нс"); } }
2,993
0.488512
0.481442
78
35.26923
25.612333
100
false
false
0
0
0
0
0
0
0.910256
false
false
2
119b24d843c40f9dbeb290504e7328af0a287d57
25,761,213,885,289
17d45abeef6286b1fcff82cd3fad7a6a8d719592
/trunk/rund.FUNKER/src/de/fhaugsburg/rundfunker/rundspieler/util/RenderTimerHandler.java
c26e661d258ef581f47e8c51cd44edcd4df9d3c8
[]
no_license
BackupTheBerlios/rundfunker
https://github.com/BackupTheBerlios/rundfunker
095a393400baa34aff8c570b79d37a5c739c738f
74085fe601a3b943222d2d9f2a52759d37ed6964
refs/heads/master
2020-12-25T19:26:15.105000
2007-03-11T23:48:17
2007-03-11T23:48:17
40,746,415
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.fhaugsburg.rundfunker.rundspieler.util; import java.util.Timer; import java.util.TimerTask; import de.fhaugsburg.rundfunker.rundspieler.view.Screen; public class RenderTimerHandler{ private Timer t; private TimerTask renderTimer; private Screen screen; private long period; boolean isRunning = false; public RenderTimerHandler(Screen screen, long period){ this.screen=screen; this.period=period; t = new Timer(); } public void startRenderTimer(){ if(isRunning) return; isRunning=true; renderTimer= new TimerTask(){ public void run() { screen.render(); } public boolean cancel(){ isRunning=false; return super.cancel(); } }; t.scheduleAtFixedRate(renderTimer, 400, period); } public void stopRenderTimer(){ if(!isRunning) return; isRunning=false; renderTimer.cancel() ; } }
UTF-8
Java
996
java
RenderTimerHandler.java
Java
[]
null
[]
package de.fhaugsburg.rundfunker.rundspieler.util; import java.util.Timer; import java.util.TimerTask; import de.fhaugsburg.rundfunker.rundspieler.view.Screen; public class RenderTimerHandler{ private Timer t; private TimerTask renderTimer; private Screen screen; private long period; boolean isRunning = false; public RenderTimerHandler(Screen screen, long period){ this.screen=screen; this.period=period; t = new Timer(); } public void startRenderTimer(){ if(isRunning) return; isRunning=true; renderTimer= new TimerTask(){ public void run() { screen.render(); } public boolean cancel(){ isRunning=false; return super.cancel(); } }; t.scheduleAtFixedRate(renderTimer, 400, period); } public void stopRenderTimer(){ if(!isRunning) return; isRunning=false; renderTimer.cancel() ; } }
996
0.61747
0.614458
48
18.75
16.976086
56
false
false
0
0
0
0
0
0
1.541667
false
false
2
fd6ef2a5bd6a69accf297d6a4dcda84ffa987bc6
21,466,246,613,541
fd4d74bafe8bbb59e1b0bd299159bce34977b1b6
/src/main/java/br/edu/ufcg/cccpharma/product/ProductController.java
6dec60c23be0c4af4c6ccfab2d275e12b0a3fa65
[]
no_license
jadsonluan/CCCPharmaServer
https://github.com/jadsonluan/CCCPharmaServer
421596bb7f06234f1fce50f8de181b1a5d714549
7c5b554dfb8143bb1382460d727e5981e2e3f78f
refs/heads/master
2020-05-31T11:06:47.808000
2018-12-17T11:39:19
2018-12-17T11:39:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.edu.ufcg.cccpharma.product; import org.springframework.http.HttpStatus; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * A ProductController object is responsible to manage the product objects of * the CCCPharma system based on the requests received. Once that the operations * are usually delegated to the service attribute, the main purposes of this * controller are to invoke the proper services based on the received requests * and to define the response status used on them. * * @author Douglas Pereira de Lima * @author Fanny Batista Vieira * @author Mateus de Lima Oliveira * @author Matheus Alves dos Santos * * @since 2018-11-12 * @version 1.0 * */ @RestController @RequestMapping("/products") public class ProductController { @Autowired private ProductService productService; /** * Creates a new Product object in the system and returns it after that. Also, * uses the HTTP status 201. * * @param product The product to be created in the system. * * @return The registered Product object. * */ @PostMapping @ResponseStatus(HttpStatus.CREATED) public Product save(@RequestBody Product product) { return this.productService.save(product); } /** * Returns the Product object whose identifier code was given as parameter. If * the given code does not match one of the products in the system, this method * will return null. Also, uses the HTTP status 200. * * @param code The identifier code of the requested product. * * @return The Product object whose identifier code was given, if it exists. * Null, otherwise. * */ @GetMapping("/{code}") @ResponseStatus(HttpStatus.OK) public Product findByCode(@PathVariable String code) { return this.productService.findByCode(code); } /** * Returns a list containing all the Product objects whose name attribute value * is the name given as parameter. Uses the HTTP status 200. * * @param name The name of the products being requested. * * @return A list of Products whose name is the one given. * */ @GetMapping("/name/{name}") @ResponseStatus(HttpStatus.OK) public Product findByName(@PathVariable String name) { return this.productService.findByName(name); } /** * Returns a list containing all the Product objects in the system. Uses the * HTTP status 200. * * @return A list of all the Products. * */ @GetMapping @ResponseStatus(HttpStatus.OK) public Page<Product> findAll(Pageable pageable) { return this.productService.findAll(pageable); } /** * Updates the Product object in the system whose identifier code is the same * that the Product given as parameter and returns it after that. If the given * Product does not match one of the products in the system, it will be * registered and returned. Uses the HTTP status 200. * * @param product The product to be updated in the system. * * @return The updated (or created) Product object. * */ @PutMapping @ResponseStatus(HttpStatus.OK) public Product update(@RequestBody Product product) { return this.productService.save(product); } /** * Deletes the Product object whose identifier code was given as parameter. If * the given code does not match one of the products in the system, nothing * happens. Also, uses the HTTP status 200. * * @param code The identifier code of the product to be deleted. * */ @DeleteMapping("/{code}") @ResponseStatus(HttpStatus.OK) public void deleteByCode(@PathVariable String code) { this.productService.deleteByCode(code); } /** * Deletes all the Product objects in the system. Also, uses the HTTP status * 200. */ @DeleteMapping @ResponseStatus(HttpStatus.OK) public void deleteAll() { this.productService.deleteAll(); } }
UTF-8
Java
4,442
java
ProductController.java
Java
[ { "context": "e the response status used on them.\n * \n * @author Douglas Pereira de Lima\n * @author Fanny Batista Vieira\n * @author Mateus", "end": 1200, "score": 0.9998902082443237, "start": 1177, "tag": "NAME", "value": "Douglas Pereira de Lima" }, { "context": "\n * \n * @auth...
null
[]
package br.edu.ufcg.cccpharma.product; import org.springframework.http.HttpStatus; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * A ProductController object is responsible to manage the product objects of * the CCCPharma system based on the requests received. Once that the operations * are usually delegated to the service attribute, the main purposes of this * controller are to invoke the proper services based on the received requests * and to define the response status used on them. * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * * @since 2018-11-12 * @version 1.0 * */ @RestController @RequestMapping("/products") public class ProductController { @Autowired private ProductService productService; /** * Creates a new Product object in the system and returns it after that. Also, * uses the HTTP status 201. * * @param product The product to be created in the system. * * @return The registered Product object. * */ @PostMapping @ResponseStatus(HttpStatus.CREATED) public Product save(@RequestBody Product product) { return this.productService.save(product); } /** * Returns the Product object whose identifier code was given as parameter. If * the given code does not match one of the products in the system, this method * will return null. Also, uses the HTTP status 200. * * @param code The identifier code of the requested product. * * @return The Product object whose identifier code was given, if it exists. * Null, otherwise. * */ @GetMapping("/{code}") @ResponseStatus(HttpStatus.OK) public Product findByCode(@PathVariable String code) { return this.productService.findByCode(code); } /** * Returns a list containing all the Product objects whose name attribute value * is the name given as parameter. Uses the HTTP status 200. * * @param name The name of the products being requested. * * @return A list of Products whose name is the one given. * */ @GetMapping("/name/{name}") @ResponseStatus(HttpStatus.OK) public Product findByName(@PathVariable String name) { return this.productService.findByName(name); } /** * Returns a list containing all the Product objects in the system. Uses the * HTTP status 200. * * @return A list of all the Products. * */ @GetMapping @ResponseStatus(HttpStatus.OK) public Page<Product> findAll(Pageable pageable) { return this.productService.findAll(pageable); } /** * Updates the Product object in the system whose identifier code is the same * that the Product given as parameter and returns it after that. If the given * Product does not match one of the products in the system, it will be * registered and returned. Uses the HTTP status 200. * * @param product The product to be updated in the system. * * @return The updated (or created) Product object. * */ @PutMapping @ResponseStatus(HttpStatus.OK) public Product update(@RequestBody Product product) { return this.productService.save(product); } /** * Deletes the Product object whose identifier code was given as parameter. If * the given code does not match one of the products in the system, nothing * happens. Also, uses the HTTP status 200. * * @param code The identifier code of the product to be deleted. * */ @DeleteMapping("/{code}") @ResponseStatus(HttpStatus.OK) public void deleteByCode(@PathVariable String code) { this.productService.deleteByCode(code); } /** * Deletes all the Product objects in the system. Also, uses the HTTP status * 200. */ @DeleteMapping @ResponseStatus(HttpStatus.OK) public void deleteAll() { this.productService.deleteAll(); } }
4,376
0.744935
0.737956
141
30.503546
27.018414
80
false
false
0
0
0
0
0
0
0.957447
false
false
2
3099ed911e9ee4c3cc150876873cb2b6df5ae92d
34,840,774,731,240
667c5303eca510ae9afa7333a822db71fb8430db
/명태우/javaTest/src/javaObject/ServerClass.java
2fd4b58e0a0ab5002f7dd618d2a89d34b5a9d9fc
[]
no_license
Hyeong-Won/Golfzon_JavaStudy
https://github.com/Hyeong-Won/Golfzon_JavaStudy
3c331bcb9e425325e3cd42c6d15489b6cdada65f
8c0ff23777bb014df81b1821e6ccd108876f9edc
refs/heads/master
2020-04-27T04:27:43.279000
2019-05-21T04:18:03
2019-05-21T04:18:03
174,055,899
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javaObject; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.Scanner; import javaObject.CommonModule.ROLE; public class ServerClass { public static ArrayList<Character> arrCharacterList = null; public static Character objCharacter1P = null; public static Character objCharacter2P = null; //입출력 선언 public static InputStream objInStream = null; public static DataInputStream objDataInStream = null; public static OutputStream objOutStram = null; public static DataOutputStream objDataOutStram = null; public static void main(String[] args) { int intRetVal = 0; int intInMsg = 0; String strInMsg = null; //서버 소켓 선언 ServerSocket objServerSocket = null; Socket objSocket = null; try { //캐릭터 리스트 arrCharacterList = new ArrayList<Character>(); //샘플 케릭터 생성 arrCharacterList = makeCharacterSample(); System.out.println("서버 시작"); //클라이언트 연결 objServerSocket = new ServerSocket(9000); objSocket = objServerSocket.accept(); System.out.println("클라이언트 연결 : " + objSocket); //입출력 설정 objInStream = objSocket.getInputStream(); objDataInStream = new DataInputStream(objInStream); objOutStram = objSocket.getOutputStream(); objDataOutStram = new DataOutputStream(objOutStram); objDataOutStram.writeUTF(CommonModule.MENU); objDataOutStram.flush(); while (intRetVal == 0) { //데이터 수신 strInMsg = objDataInStream.readUTF(); System.out.println("메뉴 :" + strInMsg); intInMsg = Integer.parseInt(strInMsg); switch (intInMsg) { case 1: //캐릭터 리스트 조회 intRetVal = getCharacterList(); break; case 2: objCharacter1P = new Character(); objCharacter2P = new Character(); //캐릭터 선택 intRetVal = selectCharacter(); break; case 3: //캐릭터 선택 체크 if (checkSelectCharacter()) { //캐릭터 결투 intRetVal = fightCharacter(); } objDataOutStram.writeUTF("종료"); objDataOutStram.flush(); break; default: //종료 intRetVal = 10; objDataOutStram.writeUTF("종료"); objDataOutStram.flush(); System.out.println("그만~~~"); break; } } System.out.println("종료 " + intRetVal); objServerSocket.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (objDataOutStram != null) { objDataOutStram.close(); } if (objOutStram != null) { objOutStram.close(); } if (objDataInStream != null) { objDataInStream.close(); } if (objInStream != null) { objInStream.close(); } if (objSocket != null) { objSocket.close(); } if (objServerSocket != null) { objServerSocket.close(); } } catch (Exception e) { e.printStackTrace(); } } } //캐릭터 생성(샘플) private static ArrayList<Character> makeCharacterSample() { ArrayList<Character> arrCharacterList = new ArrayList<Character>(); Character objCharacter = null; objCharacter = new Character(); objCharacter.makeCharacter("전사", ROLE.Tanker.ordinal(), 100, 70, 30); arrCharacterList.add(objCharacter); objCharacter = new Character(); objCharacter.makeCharacter("도적", ROLE.Dealer.ordinal(), 70, 150, 30); arrCharacterList.add(objCharacter); objCharacter = new Character(); objCharacter.makeCharacter("법사", ROLE.Nucker.ordinal(), 30, 70, 150); arrCharacterList.add(objCharacter); objCharacter = new Character(); objCharacter.makeCharacter("사제", ROLE.Healer.ordinal(), 30, 30, 150); arrCharacterList.add(objCharacter); return arrCharacterList; } //캐릭터 리스트 public static int getCharacterList() { int intRetVal = 0; //문자열 클래스 사용 StringBuilder strSBCharacter = null; try { strSBCharacter = new StringBuilder(); strSBCharacter.append("----------------------------------------------------------------------------------------------------\n"); strSBCharacter.append("\t\t캐릭터 리스트\n"); for (int i = 0; i < arrCharacterList.size(); i++) { strSBCharacter.append("번호: " + i); strSBCharacter.append(", 이름: " + arrCharacterList.get(i).strName); strSBCharacter.append(", 역활: " + arrCharacterList.get(i).strRole); strSBCharacter.append(", 생명력: " + arrCharacterList.get(i).intHealthPoint); strSBCharacter.append(", 마나: " + arrCharacterList.get(i).intManaPoint); strSBCharacter.append(", 공격력: " + arrCharacterList.get(i).intPower); strSBCharacter.append(", 방어력: " + arrCharacterList.get(i).intDefensive); strSBCharacter.append("\n"); } strSBCharacter.append("----------------------------------------------------------------------------------------------------\n"); strSBCharacter.append(CommonModule.MENU); //데이터 전송 objDataOutStram.writeUTF(strSBCharacter.toString()); objDataOutStram.flush(); } catch (Exception e) { intRetVal = 99; e.printStackTrace(); } return intRetVal; } //캐릭터 선택 public static int selectCharacter() { int intRetVal = 0; int intIndex1P = 0; int intIndex2P = 0; StringBuilder strSBCharacter = null; Random objRandom = null; try { strSBCharacter = new StringBuilder(); objRandom = new Random(); //데이터 전송 objDataOutStram.writeUTF("\t1P 캐릭터를 선택하시오?(캐릭터 번호) : "); objDataOutStram.flush(); //데이터 수신 intIndex1P = Integer.parseInt(objDataInStream.readUTF()); System.out.println("\t캐릭터 : " + intIndex1P); //상대 선택용 intIndex2P = objRandom.nextInt(arrCharacterList.size()); //캐릭터 선택 objCharacter1P = arrCharacterList.get(intIndex1P); objCharacter2P = arrCharacterList.get(intIndex2P); strSBCharacter.append("\t1P 캐릭터 : " + objCharacter1P.printCharacter()); strSBCharacter.append("\t2P 캐릭터 : " + objCharacter2P.printCharacter()); strSBCharacter.append("----------------------------------------------------------------------------------------------------"); strSBCharacter.append(CommonModule.MENU); //데이터 전송 objDataOutStram.writeUTF(strSBCharacter.toString()); objDataOutStram.flush(); } catch (Exception e) { intRetVal = 99; e.printStackTrace(); } return intRetVal; } //캐릭터 선택 여부 public static boolean checkSelectCharacter() { boolean blnSelectCharacter = false; StringBuilder strSBCharacter = null; try { strSBCharacter = new StringBuilder(); if (objCharacter1P == null || objCharacter2P == null) { blnSelectCharacter = false; strSBCharacter.append("캐릭터 선택부터 ~~~"); } else { blnSelectCharacter = true; strSBCharacter.append("----------------------------------------------------------------------------------------------------"); strSBCharacter.append("1P => 이름: " + objCharacter1P.strName + ", 역활: " + objCharacter1P.strRole); strSBCharacter.append("2P => 이름: " + objCharacter2P.strName + ", 역활: " + objCharacter2P.strRole); strSBCharacter.append("----------------------------------------------------------------------------------------------------"); } //데이터 전송 //objDataOutStram.writeUTF(strSBCharacter.toString()); //objDataOutStram.flush(); } catch (Exception e) { e.printStackTrace(); } return blnSelectCharacter; } //캐릭터 결투 public static int fightCharacter() { int intRetVal = 0; try { while (objCharacter1P.intHealthPoint > 0 && objCharacter2P.intHealthPoint > 0) { if (objCharacter1P.intHealthPoint > 0) { castAction(objCharacter1P, objCharacter2P, 1); } if (objCharacter2P.intHealthPoint > 0) { castAction(objCharacter2P, objCharacter1P, 2); } } intRetVal = 10; //데이터 전송 // objDataOutStram.writeUTF(Integer.toString(intRetVal)); // objDataOutStram.flush(); } catch (Exception e) { intRetVal = 99; e.printStackTrace(); } finally { objCharacter1P = null; objCharacter2P = null; } return intRetVal; } //캐릭터 액션 public static void castAction(Character objCharacter4Att, Character objCharacter4Def, int intPlayer) { int intAction = 0; int intActionNo = 0; Cast objCast = null; StringBuilder strSBCharacter = null; ArrayList<HashMap<String, String>> arrSkillList = null; Random objRandom = null; try { strSBCharacter = new StringBuilder(); arrSkillList = new ArrayList<HashMap<String, String>>(); objRandom = new Random(); //각 역활의 시전 클래스 - 추상 클래스 switch(objCharacter4Att.intRole) { case 0: objCast = new Cast4Tanker(); break; case 1: objCast = new Cast4Dealer(); break; case 2: objCast = new Cast4Nucker(); break; case 3: default: objCast = new Cast4Healer(); break; } //스킬 세팅 arrSkillList = objCast.getSkill(); if (intPlayer == 1) { strSBCharacter.append("1 공격\n"); //스킬 설명 출력 for (int i = 0; i < arrSkillList.size(); i++) { intActionNo = i + 2; strSBCharacter.append(intActionNo + " 스킬 " + arrSkillList.get(i).get("name") + " -> " + arrSkillList.get(i).get("desc") + "\n"); } strSBCharacter.append(objCharacter4Att.strName + "선택 하시오\n"); //데이터 전송 objDataOutStram.writeUTF(strSBCharacter.toString()); objDataOutStram.flush(); //데이터 수신 intAction = Integer.parseInt(objDataInStream.readUTF()); System.out.println("\t1P 액션 : " + intAction); } else { intAction = objRandom.nextInt(3) + 1; System.out.println("\t2P 액션 : " + intAction); } //초기화 strSBCharacter.setLength(0); if (intAction == 1) { //공격 strSBCharacter.append("\t공격 : " + objCharacter4Att.strName + " -> " + objCharacter4Def.strName + "\n"); objCast.castAttack(objCharacter4Att, objCharacter4Def); } else if (intAction == 2) { //스킬 시전 - 추상 메서드 objCast.castSkill(arrSkillList.get(0).get("name"), objCharacter4Att, objCharacter4Def); strSBCharacter.append("\t스킬 - " + arrSkillList.get(0).get("name") + " : " + objCharacter4Att.strName + " -> " + objCharacter4Def.strName + "\n"); } else if(intAction == 3) { //스킬 시전 - 추상 메서드 objCast.castSkill(arrSkillList.get(1).get("name"), objCharacter4Att, objCharacter4Def); strSBCharacter.append("\t스킬 - " + arrSkillList.get(1).get("name") + " : " + objCharacter4Att.strName + " -> " + objCharacter4Def.strName + "\n"); } strSBCharacter.append("----------------------------------------------------------------------------------------------------"); strSBCharacter.append("\t1P 캐릭터 : " + objCharacter1P.printCharacter()); strSBCharacter.append("\t2P 캐릭터 : " + objCharacter2P.printCharacter()); strSBCharacter.append("----------------------------------------------------------------------------------------------------"); if (objCharacter1P.intHealthPoint > 0 && objCharacter2P.intHealthPoint <= 0) { strSBCharacter.append("\n\t\t1P 승리~~!!!"); } else if (objCharacter2P.intHealthPoint > 0 && objCharacter1P.intHealthPoint <= 0) { strSBCharacter.append("\n\t\t2P 승리~~!!!"); } strSBCharacter.append("\n계속하려면 아무키나 누르세요"); //데이터 전송 objDataOutStram.writeUTF(strSBCharacter.toString()); objDataOutStram.flush(); //데이터 수신 intAction = Integer.parseInt(objDataInStream.readUTF()); } catch (Exception e) { e.printStackTrace(); } return; } }
UTF-8
Java
16,043
java
ServerClass.java
Java
[]
null
[]
package javaObject; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.Scanner; import javaObject.CommonModule.ROLE; public class ServerClass { public static ArrayList<Character> arrCharacterList = null; public static Character objCharacter1P = null; public static Character objCharacter2P = null; //입출력 선언 public static InputStream objInStream = null; public static DataInputStream objDataInStream = null; public static OutputStream objOutStram = null; public static DataOutputStream objDataOutStram = null; public static void main(String[] args) { int intRetVal = 0; int intInMsg = 0; String strInMsg = null; //서버 소켓 선언 ServerSocket objServerSocket = null; Socket objSocket = null; try { //캐릭터 리스트 arrCharacterList = new ArrayList<Character>(); //샘플 케릭터 생성 arrCharacterList = makeCharacterSample(); System.out.println("서버 시작"); //클라이언트 연결 objServerSocket = new ServerSocket(9000); objSocket = objServerSocket.accept(); System.out.println("클라이언트 연결 : " + objSocket); //입출력 설정 objInStream = objSocket.getInputStream(); objDataInStream = new DataInputStream(objInStream); objOutStram = objSocket.getOutputStream(); objDataOutStram = new DataOutputStream(objOutStram); objDataOutStram.writeUTF(CommonModule.MENU); objDataOutStram.flush(); while (intRetVal == 0) { //데이터 수신 strInMsg = objDataInStream.readUTF(); System.out.println("메뉴 :" + strInMsg); intInMsg = Integer.parseInt(strInMsg); switch (intInMsg) { case 1: //캐릭터 리스트 조회 intRetVal = getCharacterList(); break; case 2: objCharacter1P = new Character(); objCharacter2P = new Character(); //캐릭터 선택 intRetVal = selectCharacter(); break; case 3: //캐릭터 선택 체크 if (checkSelectCharacter()) { //캐릭터 결투 intRetVal = fightCharacter(); } objDataOutStram.writeUTF("종료"); objDataOutStram.flush(); break; default: //종료 intRetVal = 10; objDataOutStram.writeUTF("종료"); objDataOutStram.flush(); System.out.println("그만~~~"); break; } } System.out.println("종료 " + intRetVal); objServerSocket.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (objDataOutStram != null) { objDataOutStram.close(); } if (objOutStram != null) { objOutStram.close(); } if (objDataInStream != null) { objDataInStream.close(); } if (objInStream != null) { objInStream.close(); } if (objSocket != null) { objSocket.close(); } if (objServerSocket != null) { objServerSocket.close(); } } catch (Exception e) { e.printStackTrace(); } } } //캐릭터 생성(샘플) private static ArrayList<Character> makeCharacterSample() { ArrayList<Character> arrCharacterList = new ArrayList<Character>(); Character objCharacter = null; objCharacter = new Character(); objCharacter.makeCharacter("전사", ROLE.Tanker.ordinal(), 100, 70, 30); arrCharacterList.add(objCharacter); objCharacter = new Character(); objCharacter.makeCharacter("도적", ROLE.Dealer.ordinal(), 70, 150, 30); arrCharacterList.add(objCharacter); objCharacter = new Character(); objCharacter.makeCharacter("법사", ROLE.Nucker.ordinal(), 30, 70, 150); arrCharacterList.add(objCharacter); objCharacter = new Character(); objCharacter.makeCharacter("사제", ROLE.Healer.ordinal(), 30, 30, 150); arrCharacterList.add(objCharacter); return arrCharacterList; } //캐릭터 리스트 public static int getCharacterList() { int intRetVal = 0; //문자열 클래스 사용 StringBuilder strSBCharacter = null; try { strSBCharacter = new StringBuilder(); strSBCharacter.append("----------------------------------------------------------------------------------------------------\n"); strSBCharacter.append("\t\t캐릭터 리스트\n"); for (int i = 0; i < arrCharacterList.size(); i++) { strSBCharacter.append("번호: " + i); strSBCharacter.append(", 이름: " + arrCharacterList.get(i).strName); strSBCharacter.append(", 역활: " + arrCharacterList.get(i).strRole); strSBCharacter.append(", 생명력: " + arrCharacterList.get(i).intHealthPoint); strSBCharacter.append(", 마나: " + arrCharacterList.get(i).intManaPoint); strSBCharacter.append(", 공격력: " + arrCharacterList.get(i).intPower); strSBCharacter.append(", 방어력: " + arrCharacterList.get(i).intDefensive); strSBCharacter.append("\n"); } strSBCharacter.append("----------------------------------------------------------------------------------------------------\n"); strSBCharacter.append(CommonModule.MENU); //데이터 전송 objDataOutStram.writeUTF(strSBCharacter.toString()); objDataOutStram.flush(); } catch (Exception e) { intRetVal = 99; e.printStackTrace(); } return intRetVal; } //캐릭터 선택 public static int selectCharacter() { int intRetVal = 0; int intIndex1P = 0; int intIndex2P = 0; StringBuilder strSBCharacter = null; Random objRandom = null; try { strSBCharacter = new StringBuilder(); objRandom = new Random(); //데이터 전송 objDataOutStram.writeUTF("\t1P 캐릭터를 선택하시오?(캐릭터 번호) : "); objDataOutStram.flush(); //데이터 수신 intIndex1P = Integer.parseInt(objDataInStream.readUTF()); System.out.println("\t캐릭터 : " + intIndex1P); //상대 선택용 intIndex2P = objRandom.nextInt(arrCharacterList.size()); //캐릭터 선택 objCharacter1P = arrCharacterList.get(intIndex1P); objCharacter2P = arrCharacterList.get(intIndex2P); strSBCharacter.append("\t1P 캐릭터 : " + objCharacter1P.printCharacter()); strSBCharacter.append("\t2P 캐릭터 : " + objCharacter2P.printCharacter()); strSBCharacter.append("----------------------------------------------------------------------------------------------------"); strSBCharacter.append(CommonModule.MENU); //데이터 전송 objDataOutStram.writeUTF(strSBCharacter.toString()); objDataOutStram.flush(); } catch (Exception e) { intRetVal = 99; e.printStackTrace(); } return intRetVal; } //캐릭터 선택 여부 public static boolean checkSelectCharacter() { boolean blnSelectCharacter = false; StringBuilder strSBCharacter = null; try { strSBCharacter = new StringBuilder(); if (objCharacter1P == null || objCharacter2P == null) { blnSelectCharacter = false; strSBCharacter.append("캐릭터 선택부터 ~~~"); } else { blnSelectCharacter = true; strSBCharacter.append("----------------------------------------------------------------------------------------------------"); strSBCharacter.append("1P => 이름: " + objCharacter1P.strName + ", 역활: " + objCharacter1P.strRole); strSBCharacter.append("2P => 이름: " + objCharacter2P.strName + ", 역활: " + objCharacter2P.strRole); strSBCharacter.append("----------------------------------------------------------------------------------------------------"); } //데이터 전송 //objDataOutStram.writeUTF(strSBCharacter.toString()); //objDataOutStram.flush(); } catch (Exception e) { e.printStackTrace(); } return blnSelectCharacter; } //캐릭터 결투 public static int fightCharacter() { int intRetVal = 0; try { while (objCharacter1P.intHealthPoint > 0 && objCharacter2P.intHealthPoint > 0) { if (objCharacter1P.intHealthPoint > 0) { castAction(objCharacter1P, objCharacter2P, 1); } if (objCharacter2P.intHealthPoint > 0) { castAction(objCharacter2P, objCharacter1P, 2); } } intRetVal = 10; //데이터 전송 // objDataOutStram.writeUTF(Integer.toString(intRetVal)); // objDataOutStram.flush(); } catch (Exception e) { intRetVal = 99; e.printStackTrace(); } finally { objCharacter1P = null; objCharacter2P = null; } return intRetVal; } //캐릭터 액션 public static void castAction(Character objCharacter4Att, Character objCharacter4Def, int intPlayer) { int intAction = 0; int intActionNo = 0; Cast objCast = null; StringBuilder strSBCharacter = null; ArrayList<HashMap<String, String>> arrSkillList = null; Random objRandom = null; try { strSBCharacter = new StringBuilder(); arrSkillList = new ArrayList<HashMap<String, String>>(); objRandom = new Random(); //각 역활의 시전 클래스 - 추상 클래스 switch(objCharacter4Att.intRole) { case 0: objCast = new Cast4Tanker(); break; case 1: objCast = new Cast4Dealer(); break; case 2: objCast = new Cast4Nucker(); break; case 3: default: objCast = new Cast4Healer(); break; } //스킬 세팅 arrSkillList = objCast.getSkill(); if (intPlayer == 1) { strSBCharacter.append("1 공격\n"); //스킬 설명 출력 for (int i = 0; i < arrSkillList.size(); i++) { intActionNo = i + 2; strSBCharacter.append(intActionNo + " 스킬 " + arrSkillList.get(i).get("name") + " -> " + arrSkillList.get(i).get("desc") + "\n"); } strSBCharacter.append(objCharacter4Att.strName + "선택 하시오\n"); //데이터 전송 objDataOutStram.writeUTF(strSBCharacter.toString()); objDataOutStram.flush(); //데이터 수신 intAction = Integer.parseInt(objDataInStream.readUTF()); System.out.println("\t1P 액션 : " + intAction); } else { intAction = objRandom.nextInt(3) + 1; System.out.println("\t2P 액션 : " + intAction); } //초기화 strSBCharacter.setLength(0); if (intAction == 1) { //공격 strSBCharacter.append("\t공격 : " + objCharacter4Att.strName + " -> " + objCharacter4Def.strName + "\n"); objCast.castAttack(objCharacter4Att, objCharacter4Def); } else if (intAction == 2) { //스킬 시전 - 추상 메서드 objCast.castSkill(arrSkillList.get(0).get("name"), objCharacter4Att, objCharacter4Def); strSBCharacter.append("\t스킬 - " + arrSkillList.get(0).get("name") + " : " + objCharacter4Att.strName + " -> " + objCharacter4Def.strName + "\n"); } else if(intAction == 3) { //스킬 시전 - 추상 메서드 objCast.castSkill(arrSkillList.get(1).get("name"), objCharacter4Att, objCharacter4Def); strSBCharacter.append("\t스킬 - " + arrSkillList.get(1).get("name") + " : " + objCharacter4Att.strName + " -> " + objCharacter4Def.strName + "\n"); } strSBCharacter.append("----------------------------------------------------------------------------------------------------"); strSBCharacter.append("\t1P 캐릭터 : " + objCharacter1P.printCharacter()); strSBCharacter.append("\t2P 캐릭터 : " + objCharacter2P.printCharacter()); strSBCharacter.append("----------------------------------------------------------------------------------------------------"); if (objCharacter1P.intHealthPoint > 0 && objCharacter2P.intHealthPoint <= 0) { strSBCharacter.append("\n\t\t1P 승리~~!!!"); } else if (objCharacter2P.intHealthPoint > 0 && objCharacter1P.intHealthPoint <= 0) { strSBCharacter.append("\n\t\t2P 승리~~!!!"); } strSBCharacter.append("\n계속하려면 아무키나 누르세요"); //데이터 전송 objDataOutStram.writeUTF(strSBCharacter.toString()); objDataOutStram.flush(); //데이터 수신 intAction = Integer.parseInt(objDataInStream.readUTF()); } catch (Exception e) { e.printStackTrace(); } return; } }
16,043
0.462621
0.452715
424
35.183964
28.470261
161
false
false
0
0
0
0
0
0
0.563679
false
false
2
bb348ac957d8c868243d91e6e309e2766dd58e74
35,570,919,175,526
7185db9638106ac9fd1f866f53e6ee4154355125
/boss/core/src/com/mygdx/game/Entities/UnitEntity.java
cd617d054a229a19b112dafb56b95cca929e7e27
[]
no_license
Ramshell/game-design
https://github.com/Ramshell/game-design
e8f1ded8f8bcd8f4c41662b2719f820b949078a8
fb57ab90ecf29244996c26f6e157b4e384dc138c
refs/heads/master
2021-01-22T19:41:55.552000
2018-06-27T21:17:01
2018-06-27T21:17:01
100,714,657
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mygdx.game.Entities; import box2dLight.PointLight; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.utils.Array; import com.mygdx.game.Components.*; import com.mygdx.game.Components.WorldObjects.*; import com.mygdx.game.Mappers.ResourceMapper; import com.mygdx.game.OOP.WorldMapObject; import com.mygdx.game.Play; public class UnitEntity extends Entity{ public UnitEntity(PlayerComponent player, WorldObjectComponent wo, float posX, float posY, int initialState, AnimationComponent anim, HealthComponent healthComponent, int id, Play play, float visibility, float maxSpeed){ VelocityComponent velocityComponent = new VelocityComponent(); velocityComponent.maxSpeed = maxSpeed; StateComponent state = new StateComponent(); state.set(initialState); TextureComponent t = new TextureComponent(); LightComponent lightComponent = new LightComponent(); lightComponent.light = new PointLight(play.rayHandler, 64, new Color(1,1,1,1), visibility, posX * ResourceMapper.tileWidth + ResourceMapper.tileWidth / 2, posY * ResourceMapper.tileHeight + ResourceMapper.tileHeight / 2); lightComponent.visibility = visibility; t.region = anim.animations.get(initialState).getKeyFrame(0); add(wo).add(t).add(anim).add(state).add(new WorldPositionComponent(posX * ResourceMapper.tileWidth,posY * ResourceMapper.tileHeight)) .add(velocityComponent).add(player).add(healthComponent).add(new DynamicWOComponent(wo.bounds, posX * ResourceMapper.tileWidth, posY * ResourceMapper.tileHeight)) .add(lightComponent); } }
UTF-8
Java
1,822
java
UnitEntity.java
Java
[]
null
[]
package com.mygdx.game.Entities; import box2dLight.PointLight; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.utils.Array; import com.mygdx.game.Components.*; import com.mygdx.game.Components.WorldObjects.*; import com.mygdx.game.Mappers.ResourceMapper; import com.mygdx.game.OOP.WorldMapObject; import com.mygdx.game.Play; public class UnitEntity extends Entity{ public UnitEntity(PlayerComponent player, WorldObjectComponent wo, float posX, float posY, int initialState, AnimationComponent anim, HealthComponent healthComponent, int id, Play play, float visibility, float maxSpeed){ VelocityComponent velocityComponent = new VelocityComponent(); velocityComponent.maxSpeed = maxSpeed; StateComponent state = new StateComponent(); state.set(initialState); TextureComponent t = new TextureComponent(); LightComponent lightComponent = new LightComponent(); lightComponent.light = new PointLight(play.rayHandler, 64, new Color(1,1,1,1), visibility, posX * ResourceMapper.tileWidth + ResourceMapper.tileWidth / 2, posY * ResourceMapper.tileHeight + ResourceMapper.tileHeight / 2); lightComponent.visibility = visibility; t.region = anim.animations.get(initialState).getKeyFrame(0); add(wo).add(t).add(anim).add(state).add(new WorldPositionComponent(posX * ResourceMapper.tileWidth,posY * ResourceMapper.tileHeight)) .add(velocityComponent).add(player).add(healthComponent).add(new DynamicWOComponent(wo.bounds, posX * ResourceMapper.tileWidth, posY * ResourceMapper.tileHeight)) .add(lightComponent); } }
1,822
0.72393
0.718441
35
51.057144
35.721897
170
false
false
0
0
0
0
0
0
1.2
false
false
2
573ac91af0a4690669ee9788803d34273fcf7ea1
15,195,594,352,701
0d65115b366829d98a4c6321de05e3f4786e56eb
/BOJ/11004.java
c44fa5f993237d75d2b199055f3af909b92e0e41
[]
no_license
Jeje01/PS
https://github.com/Jeje01/PS
03f3b7caf25f79a8127fb6b6edb402e50440b456
eb8e7b5586deb1455a971af1ef72b93332d5ffdc
refs/heads/master
2023-04-10T01:33:08.797000
2023-03-28T10:46:26
2023-03-28T10:46:26
226,119,508
0
6
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * K번째 수 * 정렬, 입출력 * 684,908 kb * 3,756 ms */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class Main { static BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder output = new StringBuilder(); static StringTokenizer tokens; static ArrayList<Integer> list = new ArrayList<Integer>(); public static void main(String[] args) throws IOException { tokens = new StringTokenizer(input.readLine(), " "); int N = Integer.parseInt(tokens.nextToken()); int K = Integer.parseInt(tokens.nextToken()); tokens = new StringTokenizer(input.readLine(), " "); for(int i=0; i<N; i++) { list.add(Integer.parseInt(tokens.nextToken())); } Collections.sort(list); output.append(list.get(K-1)).append("\n"); System.out.println(output.toString()); } }
UTF-8
Java
977
java
11004.java
Java
[]
null
[]
/** * K번째 수 * 정렬, 입출력 * 684,908 kb * 3,756 ms */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class Main { static BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); static StringBuilder output = new StringBuilder(); static StringTokenizer tokens; static ArrayList<Integer> list = new ArrayList<Integer>(); public static void main(String[] args) throws IOException { tokens = new StringTokenizer(input.readLine(), " "); int N = Integer.parseInt(tokens.nextToken()); int K = Integer.parseInt(tokens.nextToken()); tokens = new StringTokenizer(input.readLine(), " "); for(int i=0; i<N; i++) { list.add(Integer.parseInt(tokens.nextToken())); } Collections.sort(list); output.append(list.get(K-1)).append("\n"); System.out.println(output.toString()); } }
977
0.718002
0.705515
34
27.264706
21.921396
84
false
false
0
0
0
0
0
0
1.588235
false
false
2
15e8a1339ab470891e1ecfa82b4e79bcd15866fe
29,454,885,778,592
2db32e9cd192be9bbc620c74af1598ee64857a76
/src/main/java/com/istoliarchuk/app/mvc/controller/IssueController.java
cd8bc6c08b192dd1e4cf1cc6a596d7e8f580c34d
[]
no_license
ryaj/btsys_v3
https://github.com/ryaj/btsys_v3
1744f01649eb5db225eab38e07db85d81c56ecb2
c94b126c8fc6447499fc7cbfd56111e949053d8a
refs/heads/master
2020-03-04T10:22:29.538000
2018-03-19T17:04:16
2018-03-19T17:04:16
64,020,297
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.istoliarchuk.app.mvc.controller; import com.istoliarchuk.app.domain.entity.Issue; import com.istoliarchuk.app.domain.service.IssueService; import com.istoliarchuk.app.domain.service.TypeListService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("issues") public class IssueController extends BaseController { private IssueService issueService; private TypeListService typeListService; @Autowired public IssueController(IssueService issueService, TypeListService typeListService1) { super(typeListService1); this.issueService = issueService; } @GetMapping public String getAll(Model model) { model.addAttribute("issues", issueService.getAll()); return "issues"; } @GetMapping("/new") public String newWorkflow(Model model) { return "issueNew"; } @GetMapping("/{id}") public String getIssueById(@PathVariable int id, Model model) { Issue issue = issueService.getById(id); if (issue != null) { //IssueWorkflow workflow = issueService.getWorkflow(issue); //model.addAttribute("workflow", workflow); model.addAttribute("issue", issue); return "issueView"; } else return "404"; } }
UTF-8
Java
1,600
java
IssueController.java
Java
[]
null
[]
package com.istoliarchuk.app.mvc.controller; import com.istoliarchuk.app.domain.entity.Issue; import com.istoliarchuk.app.domain.service.IssueService; import com.istoliarchuk.app.domain.service.TypeListService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("issues") public class IssueController extends BaseController { private IssueService issueService; private TypeListService typeListService; @Autowired public IssueController(IssueService issueService, TypeListService typeListService1) { super(typeListService1); this.issueService = issueService; } @GetMapping public String getAll(Model model) { model.addAttribute("issues", issueService.getAll()); return "issues"; } @GetMapping("/new") public String newWorkflow(Model model) { return "issueNew"; } @GetMapping("/{id}") public String getIssueById(@PathVariable int id, Model model) { Issue issue = issueService.getById(id); if (issue != null) { //IssueWorkflow workflow = issueService.getWorkflow(issue); //model.addAttribute("workflow", workflow); model.addAttribute("issue", issue); return "issueView"; } else return "404"; } }
1,600
0.713125
0.71
51
30.372549
23.512167
89
false
false
0
0
0
0
0
0
0.54902
false
false
2
fd6764d85c7acabf2be150dab30318b315a7e935
3,058,016,775,787
e8ef37a30d9b038504a4a133b9ea405460f579d4
/tommy/TobySpringEx/src/main/java/me/devsign/toby/config/SpringConfig.java
e4ca8459a3e11a1c5cd4c16c6b6ce92945da3eff
[]
no_license
team-pitch/TobySpring
https://github.com/team-pitch/TobySpring
7a2a6ce935faed83b0cb8dc4aab60f903227cf29
1645b6ccfa1a6c2717b67b4209ba334bc9ddcdde
refs/heads/main
2023-07-12T11:47:41.017000
2021-08-24T14:14:25
2021-08-24T14:14:25
384,964,522
0
0
null
false
2021-08-24T14:14:26
2021-07-11T14:10:20
2021-08-23T14:38:32
2021-08-24T14:14:25
159
0
4
0
Java
false
false
package me.devsign.toby.config; import me.devsign.toby.dao.JdbcContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class SpringConfig { private final DataSource dataSource; @Autowired public SpringConfig(DataSource dataSource) { this.dataSource = dataSource; } @Bean public JdbcContext jdbcContext() { JdbcContext jdbcContext = new JdbcContext(); jdbcContext.setDataSource(this.dataSource); return jdbcContext; } }
UTF-8
Java
664
java
SpringConfig.java
Java
[]
null
[]
package me.devsign.toby.config; import me.devsign.toby.dao.JdbcContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class SpringConfig { private final DataSource dataSource; @Autowired public SpringConfig(DataSource dataSource) { this.dataSource = dataSource; } @Bean public JdbcContext jdbcContext() { JdbcContext jdbcContext = new JdbcContext(); jdbcContext.setDataSource(this.dataSource); return jdbcContext; } }
664
0.751506
0.751506
25
25.559999
20.95916
62
false
false
0
0
0
0
0
0
0.44
false
false
2
73c29758bd40eee36cd0a60c75ede1677c35b6a1
23,768,349,018,981
44fbcb4feea71ec991433eef2e224f05b08e6cbf
/src/main/java/com/alany/other/ThreadPoolExecutor.java
b78e37c04083e9de4d35a312b50a0f1ef71dc14c
[]
no_license
Alanyx/SpringBootWeb
https://github.com/Alanyx/SpringBootWeb
23d95a73aeb7d4557ab09a7a14af47236ae75e30
fa2ad8f54854e423c6706ad5cc4fd30cff48d33c
refs/heads/master
2021-06-06T20:15:08.476000
2020-07-07T05:22:39
2020-07-07T05:22:39
138,147,303
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alany.other; import com.alany.other.http.http.HttpClientUtil; import com.alany.other.http.http.HttpConstants; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.*; /** * Created by yinxing on 2018/8/8. */ public class ThreadPoolExecutor { protected Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 异步调用上报接口 * * @param url * @param stringMap */ public void asynchronousCall(String url, Map<String, Object> stringMap) { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("asynchronousCall-pool-%d").build(); //Common Thread Pool ExecutorService pool = new java.util.concurrent.ThreadPoolExecutor(15, 200, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new java.util.concurrent.ThreadPoolExecutor.AbortPolicy()); pool.execute(new Runnable() { @Override public void run() { try { HttpClientUtil.doGet(url, stringMap, HttpConstants.DEFAULT); } catch (Exception e) { logger.info("http上报solr失败!"); } } }); pool.shutdown();//gracefully shutdown // 不建议这么做 // ExecutorService fixedThreadPool = Executors.newFixedThreadPool(15); // fixedThreadPool.execute(new Runnable() { // @Override // public void run() { // try { // HttpClientUtil.doGet(url, stringMap, HttpConstants.HttpClientConfig.DEFAULT); // } catch (Exception e) { // logger.info("http上报solr失败!"); // } // } // }); } public static void main(String[] args) throws InterruptedException { java.util.concurrent.ThreadPoolExecutor poolExecutor = new java.util.concurrent.ThreadPoolExecutor(6, 10, 30, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()); Runnable myRunnable = new Runnable() { @Override public void run() { try { Thread.sleep(2000); System.out.println(Thread.currentThread().getName() + "run"); } catch (Exception e) { e.printStackTrace(); } } }; poolExecutor.execute(myRunnable); poolExecutor.execute(myRunnable); poolExecutor.execute(myRunnable); System.out.println("======先开3个线程======"); System.out.println("核心线程数:" + poolExecutor.getCorePoolSize()); System.out.println("线程池数:" + poolExecutor.getPoolSize()); System.out.println("队列任务数:" + poolExecutor.getQueue().size()); poolExecutor.execute(myRunnable); poolExecutor.execute(myRunnable); poolExecutor.execute(myRunnable); System.out.println("---再开三个---"); System.out.println("核心线程数" + poolExecutor.getCorePoolSize()); System.out.println("线程池数" + poolExecutor.getPoolSize()); System.out.println("队列任务数" + poolExecutor.getQueue().size()); Thread.sleep(10000); System.out.println("----8秒之后----"); System.out.println("核心线程数" + poolExecutor.getCorePoolSize()); System.out.println("线程池数" + poolExecutor.getPoolSize()); System.out.println("队列任务数" + poolExecutor.getQueue().size()); } public static void asynchronousCall(String s) { //有多种选择 参见:https://blog.csdn.net/qq_20160723/article/details/78131201 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(15); fixedThreadPool.execute(new Runnable() { @Override public void run() { try { //待异步调用的代码 } catch (Exception e) { } } }); } }
UTF-8
Java
4,213
java
ThreadPoolExecutor.java
Java
[ { "context": "\nimport java.util.concurrent.*;\n\n/**\n * Created by yinxing on 2018/8/8.\n */\npublic class ThreadPoolExecutor ", "end": 323, "score": 0.9995328783988953, "start": 316, "tag": "USERNAME", "value": "yinxing" }, { "context": "ing s) {\n //有多种选择 参见:https://blog.c...
null
[]
package com.alany.other; import com.alany.other.http.http.HttpClientUtil; import com.alany.other.http.http.HttpConstants; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.*; /** * Created by yinxing on 2018/8/8. */ public class ThreadPoolExecutor { protected Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 异步调用上报接口 * * @param url * @param stringMap */ public void asynchronousCall(String url, Map<String, Object> stringMap) { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("asynchronousCall-pool-%d").build(); //Common Thread Pool ExecutorService pool = new java.util.concurrent.ThreadPoolExecutor(15, 200, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new java.util.concurrent.ThreadPoolExecutor.AbortPolicy()); pool.execute(new Runnable() { @Override public void run() { try { HttpClientUtil.doGet(url, stringMap, HttpConstants.DEFAULT); } catch (Exception e) { logger.info("http上报solr失败!"); } } }); pool.shutdown();//gracefully shutdown // 不建议这么做 // ExecutorService fixedThreadPool = Executors.newFixedThreadPool(15); // fixedThreadPool.execute(new Runnable() { // @Override // public void run() { // try { // HttpClientUtil.doGet(url, stringMap, HttpConstants.HttpClientConfig.DEFAULT); // } catch (Exception e) { // logger.info("http上报solr失败!"); // } // } // }); } public static void main(String[] args) throws InterruptedException { java.util.concurrent.ThreadPoolExecutor poolExecutor = new java.util.concurrent.ThreadPoolExecutor(6, 10, 30, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()); Runnable myRunnable = new Runnable() { @Override public void run() { try { Thread.sleep(2000); System.out.println(Thread.currentThread().getName() + "run"); } catch (Exception e) { e.printStackTrace(); } } }; poolExecutor.execute(myRunnable); poolExecutor.execute(myRunnable); poolExecutor.execute(myRunnable); System.out.println("======先开3个线程======"); System.out.println("核心线程数:" + poolExecutor.getCorePoolSize()); System.out.println("线程池数:" + poolExecutor.getPoolSize()); System.out.println("队列任务数:" + poolExecutor.getQueue().size()); poolExecutor.execute(myRunnable); poolExecutor.execute(myRunnable); poolExecutor.execute(myRunnable); System.out.println("---再开三个---"); System.out.println("核心线程数" + poolExecutor.getCorePoolSize()); System.out.println("线程池数" + poolExecutor.getPoolSize()); System.out.println("队列任务数" + poolExecutor.getQueue().size()); Thread.sleep(10000); System.out.println("----8秒之后----"); System.out.println("核心线程数" + poolExecutor.getCorePoolSize()); System.out.println("线程池数" + poolExecutor.getPoolSize()); System.out.println("队列任务数" + poolExecutor.getQueue().size()); } public static void asynchronousCall(String s) { //有多种选择 参见:https://blog.csdn.net/qq_20160723/article/details/78131201 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(15); fixedThreadPool.execute(new Runnable() { @Override public void run() { try { //待异步调用的代码 } catch (Exception e) { } } }); } }
4,213
0.585299
0.57189
111
35.279278
27.856186
136
false
false
0
0
0
0
0
0
0.54955
false
false
2
3fc29f0084a9641c897bebc2ad92652caa16a6db
23,768,349,018,004
e55e896f72f9f304c1b5f154e9ffb2a74b8b456e
/DS_8_proj1/src/com/java/proj/MyDate.java
ba8d2d8f59dcbfcec95090678448f5ffa051880a
[]
no_license
SeonghwanKim13109/ds
https://github.com/SeonghwanKim13109/ds
9ce253de42939206fa99dc9e36f96574843a7fa9
51820c0e4561ea39632aaf2374447606b4c2968f
refs/heads/master
2020-03-21T13:09:50.297000
2018-07-19T06:46:19
2018-07-19T06:46:19
138,591,068
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.java.proj; public class MyDate { private int day; private int month; private int year; public int getDay() { return day; } public int getMonth() { return month; } public int getYear() { return year; } public MyDate(int year, int month, int day) { super(); this.day = day; this.month = month; this.year = year; } @Override public String toString() { // TODO Auto-generated method stub return year + "/" + month + "/" + day; } @Override public boolean equals(Object mydate) { // TODO Auto-generated method stub MyDate temp = (MyDate) mydate; if (this.year == temp.getYear() && this.month == temp.getMonth() && this.day == temp.getDay()) return true; return false; } public boolean isIn(MyDate begin, MyDate end) { if (this.year > end.getYear() || this.year<begin.getYear()) return false; else { if (this.month > begin.getMonth() && this.month < end.getMonth()) return true; else if (this.month == begin.getMonth() && this.day > begin.getDay()) return true; else if (this.month == end.getMonth() && this.day < end.getDay()) return true; } return false; } public boolean isIn(MyDate expire) { if (this.month < expire.getMonth()) return true; else if (this.month == expire.getMonth() && this.day < expire.getDay()) return true; return false; } }
UTF-8
Java
1,357
java
MyDate.java
Java
[]
null
[]
package com.java.proj; public class MyDate { private int day; private int month; private int year; public int getDay() { return day; } public int getMonth() { return month; } public int getYear() { return year; } public MyDate(int year, int month, int day) { super(); this.day = day; this.month = month; this.year = year; } @Override public String toString() { // TODO Auto-generated method stub return year + "/" + month + "/" + day; } @Override public boolean equals(Object mydate) { // TODO Auto-generated method stub MyDate temp = (MyDate) mydate; if (this.year == temp.getYear() && this.month == temp.getMonth() && this.day == temp.getDay()) return true; return false; } public boolean isIn(MyDate begin, MyDate end) { if (this.year > end.getYear() || this.year<begin.getYear()) return false; else { if (this.month > begin.getMonth() && this.month < end.getMonth()) return true; else if (this.month == begin.getMonth() && this.day > begin.getDay()) return true; else if (this.month == end.getMonth() && this.day < end.getDay()) return true; } return false; } public boolean isIn(MyDate expire) { if (this.month < expire.getMonth()) return true; else if (this.month == expire.getMonth() && this.day < expire.getDay()) return true; return false; } }
1,357
0.639646
0.639646
64
20.203125
21.341114
96
false
false
0
0
0
0
0
0
1.90625
false
false
2
b161de1546e57534d3b8e72766e86904ce450924
28,020,366,705,838
3825a7774dcb51fba858baaa1e3bfcc6b572c90c
/src/main/java/com/example/Bibliotheque/entity/film.java
1a44b24e665b3c00c79e4acd96a805fe7639093a
[]
no_license
jeremyMontanes/BibliothequeSpringBoot
https://github.com/jeremyMontanes/BibliothequeSpringBoot
a28eea049ca4d1ea27ea2162339e804910496dc3
8b0d1f20a5c8d17c97f0a0c713bf3b655afb5cba
refs/heads/master
2023-03-24T20:28:33.523000
2021-03-23T18:46:14
2021-03-23T18:46:14
350,818,671
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.Bibliotheque.entity; import com.example.Bibliotheque.interfaceEntity.SuperObject; public class film extends SuperObject { }
UTF-8
Java
158
java
film.java
Java
[]
null
[]
package com.example.Bibliotheque.entity; import com.example.Bibliotheque.interfaceEntity.SuperObject; public class film extends SuperObject { }
158
0.772152
0.772152
7
20.571428
23.224724
60
false
false
0
0
0
0
0
0
0.285714
false
false
2