blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
e675bd99c71dbf6d24f1f9b04df473f12f1320c2
c885ef92397be9d54b87741f01557f61d3f794f3
/tests-without-trycatch/Gson-15/com.google.gson.stream.JsonWriter/BBC-F0-opt-100/12/com/google/gson/stream/JsonWriter_ESTest.java
683dd4c34427fed534ddf3110f00009c6619fb93
[ "CC-BY-4.0", "MIT" ]
permissive
pderakhshanfar/EMSE-BBC-experiment
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
fea1a92c2e7ba7080b8529e2052259c9b697bbda
refs/heads/main
2022-11-25T00:39:58.983828
2022-04-12T16:04:26
2022-04-12T16:04:26
309,335,889
0
1
null
2021-11-05T11:18:43
2020-11-02T10:30:38
null
UTF-8
Java
false
false
35,037
java
/* * This file was automatically generated by EvoSuite * Wed Oct 20 23:49:13 GMT 2021 */ package com.google.gson.stream; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true) public class JsonWriter_ESTest extends JsonWriter_ESTest_scaffolding { @Test(timeout = 4000) public void test00() throws Throwable { StringWriter stringWriter0 = new StringWriter(2677); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.beginArray(); jsonWriter0.name("2"); // Undeclared exception! // try { jsonWriter0.value(true); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test01() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.beginArray(); // Undeclared exception! // try { jsonWriter0.endObject(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test02() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setSerializeNulls(false); jsonWriter0.value(false); assertEquals("false", stringWriter0.toString()); } @Test(timeout = 4000) public void test03() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); jsonWriter0.value("5}g[Y6k]O%;kgG-Pd"); assertEquals("\"5}g[Y6k]O%;kgG-Pd\"", stringWriter0.toString()); } @Test(timeout = 4000) public void test04() throws Throwable { StringWriter stringWriter0 = new StringWriter(2677); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); jsonWriter0.value("["); assertEquals("\"[\"", stringWriter0.toString()); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test05() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setSerializeNulls(false); jsonWriter0.value("5}g[Y6m]OH;kgG[P'"); assertEquals("\"5}g[Y6m]OH;kgG[P'\"", stringWriter0.toString()); } @Test(timeout = 4000) public void test06() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); Long long0 = new Long((-1L)); jsonWriter0.value((Number) long0); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test07() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); assertTrue(jsonWriter0.getSerializeNulls()); jsonWriter0.setSerializeNulls(false); Long long0 = new Long(0L); jsonWriter0.value((Number) long0); assertFalse(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test08() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); Boolean boolean0 = Boolean.valueOf("["); jsonWriter0.setLenient(true); jsonWriter0.value(boolean0); assertEquals("false", stringWriter0.toString()); } @Test(timeout = 4000) public void test09() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); Boolean boolean0 = Boolean.valueOf((String) null); jsonWriter0.value(boolean0); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test10() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setSerializeNulls(false); Boolean boolean0 = Boolean.valueOf(true); jsonWriter0.value(boolean0); assertEquals("true", stringWriter0.toString()); assertFalse(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test11() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); jsonWriter0.value((-655L)); assertEquals("-655", stringWriter0.toString()); } @Test(timeout = 4000) public void test12() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); jsonWriter0.value((-1519L)); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test13() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setSerializeNulls(false); jsonWriter0.value((-1L)); assertEquals("-1", stringWriter0.toString()); assertFalse(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test14() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); jsonWriter0.value((-1546.49663912)); assertEquals("-1546.49663912", stringWriter0.toString()); } @Test(timeout = 4000) public void test15() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); jsonWriter0.value((-1198.5623593883759)); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test16() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setSerializeNulls(false); jsonWriter0.value(1.0); assertEquals("1.0", stringWriter0.toString()); assertFalse(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test17() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); jsonWriter0.nullValue(); assertEquals("null", stringWriter0.toString()); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test18() throws Throwable { StringWriter stringWriter0 = new StringWriter(2677); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); jsonWriter0.nullValue(); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test19() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); jsonWriter0.name("&"); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test20() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); jsonWriter0.jsonValue("'YZ5.,7uG)FKx"); assertEquals("'YZ5.,7uG)FKx", stringWriter0.toString()); } @Test(timeout = 4000) public void test21() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); jsonWriter1.setSerializeNulls(false); jsonWriter1.name("L{S-QMadY"); jsonWriter1.jsonValue("L{S-QMadY"); assertFalse(jsonWriter1.getSerializeNulls()); } @Test(timeout = 4000) public void test22() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); jsonWriter0.isLenient(); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test23() throws Throwable { StringWriter stringWriter0 = new StringWriter(2677); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); boolean boolean0 = jsonWriter0.isHtmlSafe(); assertTrue(boolean0); } @Test(timeout = 4000) public void test24() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); assertTrue(jsonWriter0.getSerializeNulls()); jsonWriter0.setSerializeNulls(false); boolean boolean0 = jsonWriter0.getSerializeNulls(); assertFalse(boolean0); } @Test(timeout = 4000) public void test25() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); jsonWriter0.setLenient(true); JsonWriter jsonWriter2 = jsonWriter1.name("4n"); jsonWriter1.value(false); jsonWriter2.endObject(); assertEquals("{\"4n\":false}", stringWriter0.toString()); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test26() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); JsonWriter jsonWriter2 = jsonWriter1.name("^L{S-QMadY"); jsonWriter2.setHtmlSafe(true); jsonWriter2.value(false); jsonWriter2.endObject(); assertEquals("{\"^L{S-QMadY\":false}", stringWriter0.toString()); } @Test(timeout = 4000) public void test27() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); JsonWriter jsonWriter2 = jsonWriter1.name("4n"); jsonWriter1.value(false); jsonWriter2.setSerializeNulls(false); jsonWriter2.endObject(); assertEquals("{\"4n\":false}", stringWriter0.toString()); } @Test(timeout = 4000) public void test28() throws Throwable { StringWriter stringWriter0 = new StringWriter(2677); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginArray(); jsonWriter0.setHtmlSafe(true); jsonWriter1.endArray(); assertTrue(jsonWriter1.isHtmlSafe()); } @Test(timeout = 4000) public void test29() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginArray(); jsonWriter1.setSerializeNulls(false); jsonWriter1.endArray(); assertEquals("[]", stringWriter0.toString()); assertFalse(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test30() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); jsonWriter0.beginObject(); assertEquals("{", stringWriter0.toString()); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test31() throws Throwable { StringWriter stringWriter0 = new StringWriter(2677); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); jsonWriter0.beginObject(); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test32() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setSerializeNulls(false); jsonWriter0.beginObject(); assertEquals("{", stringWriter0.toString()); assertFalse(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test33() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); jsonWriter0.beginArray(); assertEquals("[", stringWriter0.toString()); } @Test(timeout = 4000) public void test34() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setHtmlSafe(true); jsonWriter0.beginArray(); assertTrue(jsonWriter0.isHtmlSafe()); } @Test(timeout = 4000) public void test35() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.name(""); // Undeclared exception! // try { jsonWriter1.value(false); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test36() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); Double double0 = new Double((-1.0)); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); // Undeclared exception! // try { jsonWriter1.value((Number) double0); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test37() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); Boolean boolean0 = new Boolean("iX\""); // Undeclared exception! // try { jsonWriter1.value(boolean0); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test38() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.value("0WAz~3Qb>;}`J54$7D"); // Undeclared exception! // try { jsonWriter1.value((-2424L)); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // JSON must have only one top-level value. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test39() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.value(false); // Undeclared exception! // try { jsonWriter1.value(1.0); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // JSON must have only one top-level value. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test40() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); // Undeclared exception! // try { jsonWriter0.setIndent((String) null); // fail("Expecting exception: NullPointerException"); // } catch(NullPointerException e) { // // // // no message in exception (getMessage() returned null) // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test41() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.nullValue(); // Undeclared exception! // try { jsonWriter1.jsonValue((String) null); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // JSON must have only one top-level value. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test42() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); jsonWriter1.name("4n"); jsonWriter1.value(false); // Undeclared exception! // try { jsonWriter0.beginObject(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test43() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); jsonWriter1.name("4n"); jsonWriter0.beginObject(); assertEquals("{\"4n\":{", stringWriter0.toString()); } @Test(timeout = 4000) public void test44() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.beginArray(); jsonWriter0.setLenient(true); jsonWriter0.endArray(); jsonWriter0.value((Number) null); assertEquals("[]null", stringWriter0.toString()); } @Test(timeout = 4000) public void test45() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.value(false); // Undeclared exception! // try { jsonWriter0.value(""); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // JSON must have only one top-level value. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test46() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); jsonWriter1.name("L{S-QMadY"); jsonWriter1.jsonValue("L{S-QMadY"); // Undeclared exception! // try { jsonWriter1.nullValue(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test47() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.beginObject(); // Undeclared exception! // try { jsonWriter0.beginObject(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test48() throws Throwable { StringWriter stringWriter0 = new StringWriter(2677); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.beginArray(); JsonWriter jsonWriter1 = jsonWriter0.value("["); jsonWriter1.beginObject(); assertEquals("[\"[\",{", stringWriter0.toString()); } @Test(timeout = 4000) public void test49() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); JsonWriter jsonWriter2 = jsonWriter1.name("ylw;k9U|EUS[@eNIv5"); Boolean boolean0 = Boolean.valueOf((String) null); JsonWriter jsonWriter3 = jsonWriter2.value(boolean0); JsonWriter jsonWriter4 = jsonWriter3.name("ylw;k9U|EUS[@eNIv5"); jsonWriter4.value(true); assertEquals("{\"ylw;k9U|EUS[@eNIv5\":false,\"ylw;k9U|EUS[@eNIv5\":true", stringWriter0.toString()); } @Test(timeout = 4000) public void test50() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); jsonWriter1.name("java.lang.Long@0000000003"); jsonWriter0.setIndent("java.lang.Long@0000000003"); JsonWriter jsonWriter2 = jsonWriter1.jsonValue("java.lang.Long@0000000003"); assertFalse(jsonWriter2.isLenient()); } @Test(timeout = 4000) public void test51() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.value("^I3NSURCW7\"wC"); assertEquals("\"^I3NSURCW7\\\"wC\"", stringWriter0.toString()); } @Test(timeout = 4000) public void test52() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.value("\u2028"); // Undeclared exception! // try { jsonWriter0.beginArray(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // JSON must have only one top-level value. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test53() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginObject(); JsonWriter jsonWriter2 = jsonWriter1.name("java.lang.Long@0000000003"); jsonWriter2.setHtmlSafe(true); JsonWriter jsonWriter3 = jsonWriter1.jsonValue("java.lang.Long@0000000003"); assertTrue(jsonWriter3.getSerializeNulls()); } @Test(timeout = 4000) public void test54() throws Throwable { StringWriter stringWriter0 = new StringWriter(9); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); // try { jsonWriter0.close(); // fail("Expecting exception: IOException"); // } catch(IOException e) { // // // // Incomplete document // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test55() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.value("-Infinity"); jsonWriter0.close(); jsonWriter1.close(); assertEquals("\"-Infinity\"", stringWriter0.toString()); } @Test(timeout = 4000) public void test56() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.beginArray(); // try { jsonWriter0.close(); // fail("Expecting exception: IOException"); // } catch(IOException e) { // // // // Incomplete document // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test57() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.value("6{JdHFjEGAaG@,[?SE"); jsonWriter0.close(); // Undeclared exception! // try { jsonWriter1.flush(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // JsonWriter is closed. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test58() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.flush(); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test59() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.value((Boolean) null); assertEquals("null", stringWriter0.toString()); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test60() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.name("&"); // Undeclared exception! // try { jsonWriter0.nullValue(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test61() throws Throwable { StringWriter stringWriter0 = new StringWriter(2677); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.value((String) null); assertEquals("null", stringWriter0.toString()); } @Test(timeout = 4000) public void test62() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.value("6{JdHFjEGAaG@,[?SE"); jsonWriter0.close(); // Undeclared exception! // try { jsonWriter1.name("6{JdHFjEGAaG@,[?SE"); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // JsonWriter is closed. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test63() throws Throwable { StringWriter stringWriter0 = new StringWriter(0); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.name("Nesting problem."); // Undeclared exception! // try { jsonWriter0.name("gN6vIhep['k|uQ"); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // no message in exception (getMessage() returned null) // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test64() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); // Undeclared exception! // try { jsonWriter0.name((String) null); // fail("Expecting exception: NullPointerException"); // } catch(NullPointerException e) { // // // // name == null // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test65() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.name("Mh"); jsonWriter1.setSerializeNulls(false); jsonWriter1.nullValue(); jsonWriter1.nullValue(); jsonWriter1.close(); // Undeclared exception! // try { jsonWriter0.beginObject(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // JsonWriter is closed. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test66() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginArray(); JsonWriter jsonWriter2 = jsonWriter1.beginArray(); JsonWriter jsonWriter3 = jsonWriter2.beginArray(); JsonWriter jsonWriter4 = jsonWriter3.beginArray(); JsonWriter jsonWriter5 = jsonWriter2.beginArray(); JsonWriter jsonWriter6 = jsonWriter1.beginArray(); JsonWriter jsonWriter7 = jsonWriter6.beginArray(); JsonWriter jsonWriter8 = jsonWriter7.beginArray(); JsonWriter jsonWriter9 = jsonWriter6.beginArray(); jsonWriter9.beginArray(); jsonWriter0.beginArray(); jsonWriter1.beginArray(); jsonWriter3.beginArray(); JsonWriter jsonWriter10 = jsonWriter2.beginArray(); jsonWriter8.beginArray(); jsonWriter0.beginArray(); jsonWriter8.beginArray(); jsonWriter4.beginArray(); jsonWriter4.beginArray(); JsonWriter jsonWriter11 = jsonWriter7.beginArray(); jsonWriter5.beginArray(); JsonWriter jsonWriter12 = jsonWriter9.beginArray(); jsonWriter12.beginArray(); jsonWriter11.beginArray(); JsonWriter jsonWriter13 = jsonWriter3.beginArray(); jsonWriter13.beginArray(); jsonWriter12.beginArray(); JsonWriter jsonWriter14 = jsonWriter13.beginArray(); jsonWriter14.beginArray(); jsonWriter0.beginArray(); jsonWriter7.beginArray(); jsonWriter10.beginArray(); assertEquals("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[", stringWriter0.toString()); } @Test(timeout = 4000) public void test67() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setIndent(""); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test68() throws Throwable { JsonWriter jsonWriter0 = null; // try { jsonWriter0 = new JsonWriter((Writer) null); // fail("Expecting exception: NullPointerException"); // } catch(NullPointerException e) { // // // // out == null // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test69() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); JsonWriter jsonWriter1 = jsonWriter0.beginArray(); JsonWriter jsonWriter2 = jsonWriter1.name("java.lang.Float@0000000002"); // Undeclared exception! // try { jsonWriter2.endArray(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Dangling name: java.lang.Float@0000000002 // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test70() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); // Undeclared exception! // try { jsonWriter0.endObject(); // fail("Expecting exception: IllegalStateException"); // } catch(IllegalStateException e) { // // // // Nesting problem. // // // verifyException("com.google.gson.stream.JsonWriter", e); // } } @Test(timeout = 4000) public void test71() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); boolean boolean0 = jsonWriter0.getSerializeNulls(); assertTrue(boolean0); } @Test(timeout = 4000) public void test72() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.isLenient(); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test73() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.isHtmlSafe(); assertTrue(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test74() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setSerializeNulls(false); jsonWriter0.beginArray(); assertEquals("[", stringWriter0.toString()); assertFalse(jsonWriter0.getSerializeNulls()); } @Test(timeout = 4000) public void test75() throws Throwable { StringWriter stringWriter0 = new StringWriter(); JsonWriter jsonWriter0 = new JsonWriter(stringWriter0); jsonWriter0.setLenient(true); Short short0 = new Short((short) (-2284)); jsonWriter0.value((Number) short0); assertTrue(jsonWriter0.isLenient()); } }
8dd1cf4a0e8a826c5bd3cddef7d57717bd7f66b9
6101f5df0bb7478db5b4bf31dff68b5981ddfb70
/TemplateDesignPattern/EvaluareDaune.java
2b84b6ab7dded8b9b5e5366680ba8a4a50ca17b6
[]
no_license
lauraharaba/SoftwareQualityAndTesting
6ca8f64698e1c0384052505049273ce9fbaa38c3
08a531dd2dc312ccb0cad8197463be0d09b679a8
refs/heads/master
2020-03-18T11:42:03.971981
2018-06-12T20:25:25
2018-06-12T20:25:25
134,686,602
0
0
null
null
null
null
UTF-8
Java
false
false
471
java
package TemplateDesignPattern; public abstract class EvaluareDaune { public abstract void deplasare(); public abstract void identificareDaune(); public abstract void consultareAnalisti(); public abstract void consultareFirmaAsiguratoare(); public abstract void evaluareFinalaDaune(); public void evalueazaDaune() { deplasare(); identificareDaune(); consultareAnalisti(); consultareFirmaAsiguratoare(); evaluareFinalaDaune(); } }
455fda7be326899a05a5aed1c4e0fbfd2479c043
3f06624cada2af6cfb3c30fb04ac321b7e0d5a07
/src/main/java/com/data/pet/serviceimpl/PetServiceImpl.java
22ebd620bc902a5ab572449a2c71e4f758550fdc
[]
no_license
hari-1998/petMicroservice
6e3ced1677c4a08a0ddc0999365d430dbd28e503
2af7e667282f3f0dc6be7f58704792b1ccfc6785
refs/heads/master
2023-08-29T21:52:50.656494
2021-11-14T12:27:26
2021-11-14T12:27:26
427,111,462
0
0
null
null
null
null
UTF-8
Java
false
false
2,311
java
package com.data.pet.serviceimpl; import com.data.pet.constant.ErrorEnum; import com.data.pet.model.Pet; import com.data.pet.repository.PetRepository; import com.data.pet.service.PetService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import java.util.Optional; @Service public class PetServiceImpl implements PetService { @Autowired private PetRepository petRepository; @Override public Pet addPet(Pet pet) { boolean isPresent = petRepository.findById(pet.getId()).isPresent(); if(!isPresent){ Pet response = petRepository.save(pet); return response; } else{ throw new ResponseStatusException(HttpStatus.NOT_FOUND, ErrorEnum.ERROR404.getMessage()); } } @Override public Iterable<Pet> getAllPets() { Iterable<Pet> data = petRepository.findAll(); return data; } @Override public Pet getPetById(Long id) { boolean isPresent = petRepository.findById(id).isPresent(); if(isPresent){ Optional<Pet> response = petRepository.findById(id); Pet data = response.get(); return data; } else{ throw new ResponseStatusException(HttpStatus.NOT_FOUND, ErrorEnum.ERROR404.getMessage()); } } @Override public Pet updatePetById(Long id, Pet pet) { boolean isPresent = petRepository.findById(pet.getId()).isPresent(); if(isPresent && id == pet.getId()) { Pet response = petRepository.save(pet); return response; } else{ throw new ResponseStatusException(HttpStatus.NOT_FOUND, ErrorEnum.ERROR404.getMessage()); } } @Override public Pet deletePetById(Long id) { boolean isPresent = petRepository.findById(id).isPresent(); if(isPresent){ Pet response = petRepository.findById(id).get(); petRepository.deleteById(id); return response; } else{ throw new ResponseStatusException(HttpStatus.NOT_FOUND, ErrorEnum.ERROR404.getMessage()); } } }
56519fd8d5512a8f9f3e512e59198a41e792e8ce
cba210b186ac4814264f4e56b8ac00d3e2bf7a95
/Java高并发编程详解/示例代码/Java高并发编程详解/src/chapter26/Test.java
97adf0a591a43039ca32d5444c33ee19ddeec20d
[]
no_license
GoToSleepEarly/BigData-CloudComputing
3d6970cff29afa3da21364fd582296b25be641cf
127780bd73be2a8aaffbd3fab13f8fb1c136e322
refs/heads/master
2020-04-29T10:15:57.875072
2020-02-16T16:13:18
2020-02-16T16:13:18
176,055,472
2
0
null
null
null
null
GB18030
Java
false
false
942
java
package chapter26; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import static java.util.concurrent.ThreadLocalRandom.current; /** * 5个工人生产, 8个工人消费 */ public class Test { public static void main(String[] args) { final ProductionChannel channel = new ProductionChannel(5); AtomicInteger productionNo = new AtomicInteger() ; IntStream.range(1,8).forEach(i->{ new Thread(()->{ while (true) { channel.offerProduction(new Production(productionNo.getAndIncrement())); try { TimeUnit.SECONDS.sleep(current().nextInt(10)); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); }); } }
f90ee3d26ebf76e92a2a9f3ac32c596e4b9ad33f
8f8c6076bc3ded01c05280b7e63a7f8c477c7561
/file-parser/src/main/java/gov/nist/healthcare/iz/darq/parser/type/DqString.java
9c586c349f517e4d6389037e99d72ad3b3ee6962
[]
no_license
usnistgov/iz-darq
bb26c60c8eb18c153034261062702782d0c29e02
ea6fdaea150ee5be0f39739c38095440eb1e340d
refs/heads/master
2023-09-01T16:31:56.146152
2023-08-08T17:57:10
2023-08-08T17:57:10
114,279,587
0
1
null
2022-12-16T09:00:01
2017-12-14T17:43:46
Java
UTF-8
Java
false
false
805
java
package gov.nist.healthcare.iz.darq.parser.type; import gov.nist.healthcare.iz.darq.parser.exception.InvalidValueException; import org.apache.commons.lang3.RandomStringUtils; public class DqString extends DataUnit<String> { private final String dummyValue; public DqString(String payload, String dummy) throws InvalidValueException { super(payload); this.dummyValue = dummy; } @Override public String validate(String payload) throws InvalidValueException { return payload; } @Override protected String dummy(int n) { if(n == -1) return this.dummyValue; else { return RandomStringUtils.random(n); } } @Override protected String empty() { return ""; } @Override protected void validatePlaceHolder(DescriptorType placeholder) throws InvalidValueException { } }
6d34f2c79d4961f80498a48e2a86255cb2242c2f
754d8224c37177a125ddb23f8e42041d64d3afa1
/src/proj/service/AttendanceLogService.java
2735afc59d82d108e5bacb619c4f179af66808de
[]
no_license
stephen1807/SEP1
39a44bb7adaeb1ca923b9467c87205817b8b0f8d
8a833f239a845797668d2c90aaccfecc026e6fc8
refs/heads/master
2016-08-09T05:20:33.568766
2015-05-28T07:33:34
2015-05-28T07:33:34
36,053,499
0
3
null
null
null
null
UTF-8
Java
false
false
2,236
java
package proj.service; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import proj.obj.AttendanceLog; import java.util.List; /** * Created by Stephen on 2015/05/20. * Ver 1.0 */ public class AttendanceLogService { private static AttendanceLogService ourInstance = new AttendanceLogService(); public static AttendanceLogService getInstance() { return ourInstance; } SessionFactory factory; private AttendanceLogService() { try { Configuration configuration = new Configuration(); configuration.configure("proj/resources/sep1.cfg.xml"); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); factory = configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public void insertAttendanceLog(AttendanceLog newAL) { Session session = factory.openSession(); Transaction tr = null; try { tr = session.beginTransaction(); session.save(newAL); tr.commit(); } catch (HibernateException e) { if (tr != null) tr.rollback(); e.printStackTrace(); } finally { session.close(); } } public List<AttendanceLog> getAttendanceLog(int employeeID){ Session session = factory.openSession(); Transaction tr = null; List<AttendanceLog> result = null; try { tr = session.beginTransaction(); result = (List<AttendanceLog>) session.createQuery("FROM AttendanceLog where employeeid = ?").setParameter(0, employeeID).list(); tr.commit(); } catch (HibernateException e){ if (tr != null) tr.rollback(); e.printStackTrace(); } finally { session.close(); } return result; } }
2e5021eb920834b8c99c548c87eedb7b622cadd6
b2f07f3e27b2162b5ee6896814f96c59c2c17405
/com/sun/org/apache/xalan/internal/xsltc/runtime/ErrorMessages_zh_TW.java
77e87bd160e08b9b4913f368cf9eab19bd9d1238
[]
no_license
weiju-xi/RT-JAR-CODE
e33d4ccd9306d9e63029ddb0c145e620921d2dbd
d5b2590518ffb83596a3aa3849249cf871ab6d4e
refs/heads/master
2021-09-08T02:36:06.675911
2018-03-06T05:27:49
2018-03-06T05:27:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,597
java
/* */ package com.sun.org.apache.xalan.internal.xsltc.runtime; /* */ /* */ import java.util.ListResourceBundle; /* */ /* */ public class ErrorMessages_zh_TW extends ListResourceBundle /* */ { /* */ public Object[][] getContents() /* */ { /* 90 */ return new Object[][] { { "RUN_TIME_INTERNAL_ERR", "''{0}'' 中的執行階段內部錯誤" }, { "RUN_TIME_COPY_ERR", "執行 <xsl:copy> 時發生執行階段錯誤" }, { "DATA_CONVERSION_ERR", "從 ''{0}'' 至 ''{1}'' 的轉換無效。" }, { "EXTERNAL_FUNC_ERR", "XSLTC 不支援外部函數 ''{0}''。" }, { "EQUALITY_EXPR_ERR", "相等性表示式中的引數類型不明。" }, { "INVALID_ARGUMENT_ERR", "呼叫 ''{1}'' 中的引數類型 ''{0}'' 無效" }, { "FORMAT_NUMBER_ERR", "嘗試使用樣式 ''{1}'' 格式化數字 ''{0}''。" }, { "ITERATOR_CLONE_ERR", "無法複製重複程式 ''{0}''。" }, { "AXIS_SUPPORT_ERR", "不支援軸 ''{0}'' 的重複程式。" }, { "TYPED_AXIS_SUPPORT_ERR", "不支援類型軸 ''{0}'' 的重複程式。" }, { "STRAY_ATTRIBUTE_ERR", "屬性 ''{0}'' 在元素之外。" }, { "STRAY_NAMESPACE_ERR", "命名空間宣告 ''{0}''=''{1}'' 超出元素外。" }, { "NAMESPACE_PREFIX_ERR", "字首 ''{0}'' 的命名空間尚未宣告。" }, { "DOM_ADAPTER_INIT_ERR", "使用錯誤的來源 DOM 類型建立 DOMAdapter。" }, { "PARSER_DTD_SUPPORT_ERR", "您正在使用的 SAX 剖析器不會處理 DTD 宣告事件。" }, { "NAMESPACES_SUPPORT_ERR", "您正在使用的 SAX 剖析器不支援 XML 命名空間。" }, { "CANT_RESOLVE_RELATIVE_URI_ERR", "無法解析 URI 參照 ''{0}''。" }, { "UNSUPPORTED_XSL_ERR", "不支援的 XSL 元素 ''{0}''" }, { "UNSUPPORTED_EXT_ERR", "無法辨識的 XSLTC 擴充套件 ''{0}''" }, { "UNKNOWN_TRANSLET_VERSION_ERR", "建立指定 translet ''{0}'' 的 XSLTC 版本比使用中 XSLTC 執行階段的版本較新。您必須重新編譯樣式表,或使用較新的 XSLTC 版本來執行此 translet。" }, { "INVALID_QNAME_ERR", "值必須為 QName 的屬性,具有值 ''{0}''" }, { "INVALID_NCNAME_ERR", "值必須為 NCName 的屬性,具有值 ''{0}''" }, { "UNALLOWED_EXTENSION_FUNCTION_ERR", "當安全處理功能設為真時,不允許使用擴充套件函數 ''{0}''。" }, { "UNALLOWED_EXTENSION_ELEMENT_ERR", "當安全處理功能設為真時,不允許使用擴充套件元素 ''{0}''。" } }; /* */ } /* */ } /* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar * Qualified Name: com.sun.org.apache.xalan.internal.xsltc.runtime.ErrorMessages_zh_TW * JD-Core Version: 0.6.2 */
674ade935b229717df811478956cb745b21092be
6c1a851e66bcd99e0dcd5905b0e37ea5bffc8471
/Lista 2 - 2018.2 (Funk)/L2Q6 - A Fórmula Perfeita.java
7e5d4f23633fbc6adddccbeff6dedc558cf903f0
[]
no_license
joaovaladares/ListasIP-2018.2
364b70649ba693cb4f372df49e56132339580820
aa2eb244a64d40a1c9dd2fa8e51b7870b485afd4
refs/heads/master
2020-04-02T05:06:21.172071
2018-10-26T02:08:51
2018-10-26T02:08:51
154,052,691
0
0
null
null
null
null
UTF-8
Java
false
false
976
java
import java.io.*; import java.util.*; public class HuxleyCode { public static void main(String args[]) { double tang, termos, fatorialInicial = 3, potenciaInicial = 2, contador =1, controle, vodka, tangform = 0, fatorial = 1; Scanner in = new Scanner(System.in); tang = in.nextInt(); termos = in.nextInt(); if(termos == 0){ tangform = tang; } while (termos > 1){ fatorial = 1; controle = fatorialInicial; while (controle > 1){ fatorial = fatorial * controle; controle -= 1; } tangform = tangform - ((Math.pow(-1, contador)) * (Math.pow(tang, potenciaInicial)) / (fatorial)); termos -= 1; fatorialInicial += 2; potenciaInicial += 2; contador += 1; } vodka = Math.abs(tang - tangform); System.out.printf("%.3f", vodka); } }
77a027a3089aab8e14b8ce46120f7f28435a75c8
3b888b743df83c9e067728870c53af74546c0635
/gms/src/test/java/TestEquipmentService.java
210d7aee435d9fc5fa8a260e4b516376cd172d1e
[]
no_license
RoseTomato/GDOU-GMS
b8a49e2c16c1307033d2be85b1f06a8dac4ec03b
495d720bdac7775d68ae6b3331357fb47b23b1c8
refs/heads/master
2021-01-17T06:01:00.436025
2016-06-16T01:47:06
2016-06-16T01:47:06
46,345,385
0
0
null
null
null
null
UTF-8
Java
false
false
741
java
import love.drose.gms.models.Equipment; import love.drose.gms.services.EquipmentService; import love.drose.gms.utils.Page; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Created by lovedrose on 1/20/16. */ public class TestEquipmentService extends BaseTest { @Autowired private EquipmentService equipmentService; @Test public void test() { Equipment equipment = equipmentService.findByNameWithTotalIsNotNull("篮球"); System.out.println(equipment); } @Test public void testFindPageDataWithTotalIsNotNull() { Page page = equipmentService.findPageDataWithTotalIsNotNull(1, 20); System.out.println(page.getList().size()); } }
e7275953210315fc1bf05833728fef360c1a73a0
f1a9635f989ce60a08aad8b7e0924383cb072369
/app/src/main/java/com/gj/weidusore/bean/UserInfoLogin.java
9abb2e085d406c61ae175c8feb26de5c82e8f163
[]
no_license
GJ-Jay/WeiDuSore
686ece319c894e2f8ede8bd6eeb7c1f9c91dd6ca
c740d659cba5b9654726c2cdf5b5ce0066567ae3
refs/heads/master
2020-04-16T12:12:15.860118
2019-01-20T04:00:10
2019-01-20T04:00:10
165,568,680
0
0
null
null
null
null
UTF-8
Java
false
false
1,987
java
package com.gj.weidusore.bean; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Generated; /** * 登录注册的bean类 */ @Entity public class UserInfoLogin { @Id long userId; private String headPic; private String nickName; private String phone; private String sessionId; private int sex; private int status;//记录本地用户登录状态,用于直接登录和退出,1:登录,0:未登录或退出 @Generated(hash = 956452759) public UserInfoLogin(long userId, String headPic, String nickName, String phone, String sessionId, int sex, int status) { this.userId = userId; this.headPic = headPic; this.nickName = nickName; this.phone = phone; this.sessionId = sessionId; this.sex = sex; this.status = status; } @Generated(hash = 1482791127) public UserInfoLogin() { } public String getHeadPic() { return headPic; } public void setHeadPic(String headPic) { this.headPic = headPic; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } }
020f1855eac799df5414fc40690cb1ce4d6f9439
dd32f11708b286143eb9eb58dca60a523501190f
/gulimall-member/src/main/java/com/hb/gulimall/member/controller/GrowthChangeHistoryController.java
8baf7ce8ff1c7d7e25ff243ec2903193b36cb67a
[]
no_license
aboutmoon/gulimall
854bcb6477d2b3d3cae0eef6bfb5a87d7d471b35
9e87146141cb75e8a44430b8827a00c8ebb142a5
refs/heads/master
2022-12-05T05:49:40.330225
2020-08-27T11:32:39
2020-08-27T11:32:39
286,908,916
0
0
null
null
null
null
UTF-8
Java
false
false
2,154
java
package com.hb.gulimall.member.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.hb.gulimall.member.entity.GrowthChangeHistoryEntity; import com.hb.gulimall.member.service.GrowthChangeHistoryService; import com.hb.common.utils.PageUtils; import com.hb.common.utils.R; /** * 成长值变化历史记录 * * @author hb * @email [email protected] * @date 2020-08-26 13:45:10 */ @RestController @RequestMapping("member/growthchangehistory") public class GrowthChangeHistoryController { @Autowired private GrowthChangeHistoryService growthChangeHistoryService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = growthChangeHistoryService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id){ GrowthChangeHistoryEntity growthChangeHistory = growthChangeHistoryService.getById(id); return R.ok().put("growthChangeHistory", growthChangeHistory); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody GrowthChangeHistoryEntity growthChangeHistory){ growthChangeHistoryService.save(growthChangeHistory); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody GrowthChangeHistoryEntity growthChangeHistory){ growthChangeHistoryService.updateById(growthChangeHistory); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] ids){ growthChangeHistoryService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
0c34b45bb74a6047ef20b4180ca1e37eeabe841f
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/3/3_7104d5b2d093d2b8e5a134ccf84c95f98a55c7b3/PixelDrawing/3_7104d5b2d093d2b8e5a134ccf84c95f98a55c7b3_PixelDrawing_t.java
aaefb2820ceec105c7f3214c75371acf0488f067
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
137,845
java
/* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: PixelDrawing.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Electric(tm) 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.user.redisplay; import com.sun.electric.database.geometry.DBMath; import com.sun.electric.database.geometry.EGraphics; import com.sun.electric.database.geometry.GenMath; import com.sun.electric.database.geometry.Orientation; import com.sun.electric.database.geometry.Poly; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.Export; import com.sun.electric.database.id.CellId; import com.sun.electric.database.prototype.NodeProto; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.topology.ArcInst; import com.sun.electric.database.topology.Connection; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.database.variable.EditWindow0; import com.sun.electric.database.variable.TextDescriptor; import com.sun.electric.database.variable.VarContext; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.Layer; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.PrimitivePort; import com.sun.electric.technology.Technology; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.tool.Job; import com.sun.electric.tool.user.GraphicsPreferences; import com.sun.electric.tool.user.User; import com.sun.electric.tool.user.ui.EditWindow; import com.sun.electric.tool.user.ui.LayerVisibility; import com.sun.electric.tool.user.ui.WindowFrame; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.font.LineMetrics; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.SwingUtilities; /** * This class manages an offscreen display for an associated EditWindow. * It renders an Image for copying to the display. * <P> * Every offscreen display consists of two parts: the transparent layers and the opaque image. * To tell how a layer is displayed, look at the "transparentLayer" field of its "EGraphics" object. * When this is nonzero, the layer is drawn transparent. * When this is zero, use the "red, green, blue" fields for the opaque color. * <P> * The opaque image is a full-color Image that is the size of the EditWindow. * Any layers that are marked "opaque" are drawn in full color in the image. * Colors are not combined in the opaque image: every color placed in it overwrites the previous color. * For this reason, opaque colors are often stipple patterns, so that they won't completely obscure other * opaque layers. * <P> * The transparent layers are able to combine with each other. * Typically, the more popular layers are made transparent (metal, poly, active, etc.) * For every transparent layer, there is a 1-bit deep bitmap that is the size of the EditWindow. * The bitmap is an array of "byte []" pointers, one for every Y coordinate in the EditWindow. * Each array contains the bits for that row, packed 8 per byte. * All of this information is in the "layerBitMaps" field, which is triply indexed. * <P> * Thus, to find bit (x,y) of transparent layer T, first lookup the appropriate transparent layer, * ("layerBitMaps[T]"). * Then, for that layer, find the array of bytes for the appropriate row * (by indexing the the Y coordinate into the rowstart array, "layerBitMaps[T][y]"). * Next, figure out which byte has the bit (by dividing the X coordinate by 8: "layerBitMaps[T][y][x>>3]"). * Finally, determine which bit to use (by using the low 3 bits of the X coordinate, * layerBitMaps[T][y][x>>3] & (1 << (x&7)) ). * <P> * Transparent layers are not allocated until needed. Thus, if there are 5 possible transparent layers, * but only 2 are used, then only two bitplanes will be created. * <P> * Each technology declares the number of possible transparent layers that it can generate. * In addition, it must provide a color map for describing every combination of transparent layer. * This map is, of course, 2-to-the-number-of-possible-transparent-layers long. * <P> * The expected number of transparent layers is taken from the current technology. If the user switches * the current technology, but draws something from a different technology, then the drawn circuitry * may make use of transparent layers that don't exist in the current technology. In such a case, * the transparent request is made opaque. * <P> * When all rendering is done, the full-color image is composited with the transparent layers to produce * the final image. * This is done by scanning the full-color image for any entries that were not filled-in. * These are then replaced by the transparent color at that point. * The transparent color is computed by looking at the bits in every transparent bitmap and * constructing an index. This is looked-up in the color table and the appropriate color is used. * If no transparent layers are set, the background color is used. * <P> * There are a number of efficiencies implemented here. * <UL> * <LI><B>Setting bits directly into the offscreen memory</B>. * Although Java's Swing package has a rendering model, it was found to be 3 times slower than * setting bits directly in the offscreen memory.</LI> * <LI><B>Tiny nodes and arcs are approximated</B>. * When a node or arc will be only 1 or 2 pixels in size on the screen, it is not necessary * to actually compute the edges of all of its parts. Instead, a single pixel of color is placed. * The color is taken from all of the layers that compose the node or arc. * For arcs that are long but only 1 pixel wide, a line is drawn in the same manner. * This optimization adds another factor of 2 to the speed of display.</LI> * <LI><B>Expanded cell contents are cached</B>. * When a cell is expanded, and its contents is drawn, the contents are preserved so that they * need be rendered only once. Subsequent instances of that expanded cell are able to be instantly drawn. * There are a number of extra considerations here: * <UL> * <LI>Cell instances can appear in any orientation. Therefore, the cache of drawn cells must * include the orientation.</LI> * <LI>Cached cells are retained as long as the current scale is maintained. But when zooming * in and out, the cache is cleared.</LI> * <LI>Cell instances may appear at different levels of the hierarchy, with different other circuitry over * them. For example, an instance may have been rendered at one level of hierarchy, and other items at that * same level then rendered over it. It is then no longer possible to copy those bits when the instance * appears again at another place in the hierarchy because it has been altered by neighboring circuitry. * The same problem happens when cell instances overlap. Therefore, it is necessary to render each expanded * cell instance into its own offscreen map, with its own separate opaque and transparent layers (which allows * it to be composited properly when re-instantiated). Thus, a new PixelDrawing" object is created for each * cached cell.</LI> * <LI>Subpixel alignment may not be the same for each cached instance. This turns out not to be * a problem, because at such zoomed-out scales, it is impossible to see individual objects anyway.</LI> * <LI>Large cell instances should not be cached. When zoomed-in, an expanded cell instance could * be many megabytes in size, and only a portion of it appears on the screen. Therefore, large cell * instances are not cached, but drawn directly. It is assumed that there will be few such instances. * The rule currently is that any cell whose width is greater than half of the display size AND whose * height is greater than half of the display size is too large to cache.</LI> * <LI>If an instance only appears once, it is not cached. This requires a preprocessing step to scan * the hierarchy and count the number of times that a particular cell-transformation is used. During * rendering, if the count is only 1, it is not cached. The exception to this rule is if the screen * is redisplayed without a change of magnification (during panning, for example). In such a case, * all cells will eventually be cached because, even those used once are being displayed with each redraw. </LI> * <LI>Texture patterns don't line-up. When drawing texture pattern to the final buffer, it is easy * to use the screen coordinates to index the pattern map, causing all of them to line-up. * Any two adjoining objects that use the same pattern will have their patterns line-up smoothly. * However, when caching cell instances, it is not possible to know where the contents will be placed * on the screen, and so the texture patterns rendered into the cache cannot be aligned globally. * To solve this, there are additional bitmaps created for every Patterned-Opaque-Layer (POL). * When rendering on a layer that is patterned and opaque, the bitmap is dynamically allocated * and filled (all bits are filled on the bitmap, not just those in the pattern). * When combining lower-level cell images with higher-level ones, these POLs are copied, too. * When compositing at the top level, however, the POLs are converted back to patterns, so that they line-up.</LI> * </UL> * </UL> * */ public class PixelDrawing { /** Text smaller than this will not be drawn. */ public static final int MINIMUMTEXTSIZE = 5; /** Text larger than this is granular. */ public static final int MAXIMUMTEXTSIZE = 100; /** Number of singleton cells to cache when redisplaying. */ public static final int SINGLETONSTOADD = 5; private static class PolySeg { private int fx,fy, tx,ty, direction, increment; private PolySeg nextedge; private PolySeg nextactive; } // statistics stuff private static final boolean TAKE_STATS = true; private static int tinyCells, tinyPrims, totalCells, renderedCells, totalPrims, tinyArcs, linedArcs, totalArcs; private static int offscreensCreated, offscreenPixelsCreated, offscreensUsed, offscreenPixelsUsed, cellsRendered; private static final boolean DEBUGRENDERTIMING = false; private static long renderTextTime; private static long renderPolyTime; private static class ExpandedCellKey { private Cell cell; private Orientation orient; private ExpandedCellKey(Cell cell, Orientation orient) { this.cell = cell; this.orient = orient; } @Override public boolean equals(Object obj) { if (obj instanceof ExpandedCellKey) { ExpandedCellKey that = (ExpandedCellKey)obj; return this.cell == that.cell && this.orient.equals(that.orient); } return false; } @Override public int hashCode() { return cell.hashCode()^orient.hashCode(); } } /** * This class holds information about expanded cell instances. * For efficiency, Electric remembers the bits in an expanded cell instance * and uses them when another expanded instance appears elsewhere. * Of course, the orientation of the instance matters, so each combination of * cell and orientation forms a "cell cache". The Cell Cache is stored in the * "wnd" field (which has its own PixelDrawing object). */ private static class ExpandedCellInfo { private boolean singleton; private int instanceCount; private PixelDrawing offscreen; ExpandedCellInfo() { singleton = true; offscreen = null; } } /** the size of the EditWindow */ private final Dimension sz; /** the scale of the EditWindow */ private double scale; /** the VarContext of the EditWindow */ private VarContext varContext = VarContext.globalContext; /** the X origin of the cell in display coordinates. */ private double originX; /** the Y origin of the cell in display coordinates. */ private double originY; /** 0: color display, 1: color printing, 2: B&W printing */ private int nowPrinting; /** the area of the cell to draw, in DB units */ private Rectangle2D drawBounds; /** whether any layers are highlighted/dimmed */ boolean highlightingLayers; /** true if the last display was a full-instantiate */ private boolean lastFullInstantiate = false; /** A List of NodeInsts to the cell being in-place edited. */private List<NodeInst> inPlaceNodePath; /** true if text can be drawn (not too zoomed-out) */ private boolean canDrawText; /** maximum size before an object is too small */ private static double maxObjectSize; /** half of maximum object size */ private static double halfMaxObjectSize; /** temporary objects (saves reallocation) */ private final Point tempPt1 = new Point(), tempPt2 = new Point(); /** temporary objects (saves reallocation) */ private final Point tempPt3 = new Point(), tempPt4 = new Point(); // the full-depth image /** the offscreen opaque image of the window */ private final BufferedImage img; /** opaque layer of the window */ private final int [] opaqueData; /** size of the opaque layer of the window */ private final int total; /** the background color of the offscreen image */ private int backgroundColor; /** the "unset" color of the offscreen image */ private int backgroundValue; /** cache of port colors */ private HashMap<PrimitivePort,EGraphics> portGraphicsCache = new HashMap<PrimitivePort,EGraphics>(); // the transparent bitmaps /** the offscreen maps for transparent layers */ private byte [][][] layerBitMaps; /** row pointers for transparent layers */ private byte [][] compositeRows; /** the number of transparent layers */ int numLayerBitMaps; /** the number of bytes per row in offscreen maps */ private final int numBytesPerRow; /** the number of offscreen transparent maps made */ private int numLayerBitMapsCreated; /** the technology of the window */ private Technology curTech; // the patterned opaque bitmaps private static class PatternedOpaqueLayer { private byte[][] layerBitMap; PatternedOpaqueLayer(int height, int numBytesPerRow) { layerBitMap = new byte[height][numBytesPerRow]; } } /** the map from layers to Patterned Opaque bitmaps */ private Map<Layer,PatternedOpaqueLayer> patternedOpaqueLayers = new HashMap<Layer,PatternedOpaqueLayer>(); /** the top-level window being rendered */ private boolean renderedWindow; /** whether to occasionally update the display. */ private boolean periodicRefresh; /** keeps track of when to update the display. */ private int objectCount; /** keeps track of when to update the display. */ private long lastRefreshTime; /** the EditWindow being drawn */ private EditWindow wnd; /** the size of the top-level EditWindow */ private static Dimension topSz; /** the last Technology that had transparent layers */ private static Technology techWithLayers = null; /** list of cell expansions. */ private static Map<ExpandedCellKey,ExpandedCellInfo> expandedCells = null; /** Set of changed cells. */ private static final Set<CellId> changedCells = new HashSet<CellId>(); /** scale of cell expansions. */ private static double expandedScale = 0; /** number of extra cells to render this time */ private static int numberToReconcile; /** zero rectangle */ private static final Rectangle2D CENTERRECT = new Rectangle2D.Double(0, 0, 0, 0); static GraphicsPreferences gp; static LayerVisibility lv; static EGraphics textGraphics = new EGraphics(false, false, null, 0, 0,0,0, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}); private static EGraphics gridGraphics = textGraphics; static EGraphics instanceGraphics = textGraphics; private int clipLX, clipHX, clipLY, clipHY; private final EditWindow0 dummyWnd = new EditWindow0() { public VarContext getVarContext() { return varContext; } public double getScale() { return scale; } public double getGlobalTextScale() { return wnd.getGlobalTextScale(); } }; static class Drawing extends AbstractDrawing { private final int displayAlgorithm = User.getDisplayAlgorithm(); private final boolean useCellGreekingImages = User.isUseCellGreekingImages(); private final double greekSizeLimit = User.getGreekSizeLimit(); private final double greekCellSizeLimit = User.getGreekCellSizeLimit(); private final VectorDrawing vd = new VectorDrawing(useCellGreekingImages); private volatile PixelDrawing offscreen; Drawing(EditWindow wnd) { super(wnd); } @Override public boolean paintComponent(Graphics2D g, LayerVisibility lv, Dimension sz) { assert SwingUtilities.isEventDispatchThread(); assert sz.equals(wnd.getSize()); PixelDrawing offscreen = this.offscreen; if (offscreen == null || !offscreen.getSize().equals(sz)) return false; // show the image g.drawImage(offscreen.getBufferedImage(), 0, 0, wnd); return true; } @Override public void render(Dimension sz, WindowFrame.DisplayAttributes da, GraphicsPreferences gp, boolean fullInstantiate, Rectangle2D bounds) { PixelDrawing.gp = gp; PixelDrawing offscreen_ = this.offscreen; if (offscreen_ == null || !offscreen_.getSize().equals(sz)) this.offscreen = offscreen_ = new PixelDrawing(sz); this.da = da; boolean isPixelDrawing = displayAlgorithm == 0; offscreen_.drawImage(this, fullInstantiate, bounds, isPixelDrawing, greekSizeLimit, greekCellSizeLimit); } @Override public void abortRendering() { if (displayAlgorithm > 0) vd.abortRendering(); } } // ************************************* TOP LEVEL ************************************* /** * Constructor creates an offscreen PixelDrawing object. * @param sz the size of an offscreen PixelDrawinf object. */ public PixelDrawing(Dimension sz) { this.sz = new Dimension(sz); clipLX = 0; clipHX = sz.width - 1; clipLY = 0; clipHY = sz.height - 1; // allocate pointer to the opaque image img = new BufferedImage(sz.width, sz.height, BufferedImage.TYPE_INT_RGB); WritableRaster raster = img.getRaster(); DataBufferInt dbi = (DataBufferInt)raster.getDataBuffer(); opaqueData = dbi.getData(); total = sz.height * sz.width; numBytesPerRow = (sz.width + 7) / 8; renderedWindow = true; } public PixelDrawing(double scale, Rectangle screenBounds) { this.scale = scale; this.originX = -screenBounds.x; this.originY = screenBounds.y + screenBounds.height; this.sz = new Dimension(screenBounds.width, screenBounds.height); clipLX = 0; clipHX = sz.width - 1; clipLY = 0; clipHY = sz.height - 1; // allocate pointer to the opaque image img = null; total = sz.height * sz.width; opaqueData = new int[total]; numBytesPerRow = (sz.width + 7) / 8; // initialize the data clearImage(null); } void initOrigin(double scale, double offx, double offy) { this.scale = scale; this.originX = sz.width/2 - offx*scale; this.originY = sz.height/2 + offy*scale; } void initDrawing(double scale) { clearImage(null); initOrigin(scale, 0, 0); } /** * Method to set the printing mode used for all drawing. * @param mode the printing mode: 0=color display (default), 1=color printing, 2=B&W printing. */ public void setPrintingMode(int mode) { nowPrinting = mode; } /** * Method to override the background color. * Must be called before "drawImage()". * This is used by printing, which forces the background to be white. * @param bg the background color to use. */ public void setBackgroundColor(Color bg) { backgroundColor = bg.getRGB() & 0xFFFFFF; } /** * Method for obtaining the rendered image after "drawImage" has finished. * @return an Image for this edit window. */ public BufferedImage getBufferedImage() { return img; } /** * Method for obtaining the RGB array of the rendered image after "drawImage" has finished. * @return an RGB array for this edit window. */ int[] getOpaqueData() { return opaqueData; } /** * Method for obtaining the size of the offscreen bitmap. * @return the size of the offscreen bitmap. */ public Dimension getSize() { return sz; } /** * Method to clear the cache of expanded subcells. * This is used by layer visibility which, when changed, causes everything to be redrawn. */ public static void clearSubCellCache() { expandedCells = new HashMap<ExpandedCellKey,ExpandedCellInfo>(); } /** * This is the entry point for rendering. * It displays a cell in this offscreen window. * @param fullInstantiate true to display to the bottom of the hierarchy (for peeking). * @param drawLimitBounds the area in the cell to display (null to show all). * The rendered Image can then be obtained with "getImage()". */ private void drawImage(Drawing drawing, boolean fullInstantiate, Rectangle2D drawLimitBounds, boolean isPixelDrawing, double greekSizeLimit, double greekCellSizeLimit) { long startTime = 0; long initialUsed = 0; if (TAKE_STATS) { startTime = System.currentTimeMillis(); initialUsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); tinyCells = tinyPrims = totalCells = renderedCells = totalPrims = tinyArcs = linedArcs = totalArcs = 0; offscreensCreated = offscreenPixelsCreated = offscreensUsed = offscreenPixelsUsed = cellsRendered = 0; } if (fullInstantiate != lastFullInstantiate) { clearSubCellCache(); lastFullInstantiate = fullInstantiate; } EditWindow wnd = drawing.wnd; Cell cell = wnd.getInPlaceEditTopCell(); inPlaceNodePath = wnd.getInPlaceEditNodePath(); double width = sz.width/scale; double height = sz.height/scale; drawBounds = new Rectangle2D.Double(drawing.da.offX - width/2, drawing.da.offY - height/2, width, height); // set colors to use textGraphics = textGraphics.withColor(gp.getColor(User.ColorPrefType.TEXT)); gridGraphics = gridGraphics.withColor(gp.getColor(User.ColorPrefType.GRID)); instanceGraphics = instanceGraphics.withColor(gp.getColor(User.ColorPrefType.INSTANCE)); portGraphicsCache.clear(); // initialize the cache of expanded cell displays if (expandedScale != drawing.da.scale) { clearSubCellCache(); expandedScale = drawing.da.scale; } varContext = wnd.getVarContext(); initOrigin(expandedScale, drawing.da.offX, drawing.da.offY); canDrawText = expandedScale > 1; maxObjectSize = 2 / expandedScale; halfMaxObjectSize = maxObjectSize / 2; // remember the true window size (since recursive calls may cache individual cells that are smaller) topSz = sz; // see if any layers are being highlighted/dimmed lv = wnd.getLayerVisibility(); highlightingLayers = false; for(Iterator<Layer> it = Technology.getCurrent().getLayers(); it.hasNext(); ) { Layer layer = it.next(); if (lv.isHighlighted(layer)) { highlightingLayers = true; break; } } // initialize rendering into the offscreen image Rectangle renderBounds = null; if (drawLimitBounds != null) { renderBounds = databaseToScreen(drawLimitBounds); clipLX = Math.max(renderBounds.x, 0); clipHX = Math.min(renderBounds.x + renderBounds.width, sz.width) - 1; clipLY = Math.max(renderBounds.y, 0); clipHY = Math.min(renderBounds.y + renderBounds.height, sz.height) - 1; } else { clipLX = 0; clipHX = sz.width - 1; clipLY = 0; clipHY = sz.height - 1; } clearImage(renderBounds); periodicRefresh = true; this.wnd = wnd; objectCount = 0; lastRefreshTime = System.currentTimeMillis(); Set<CellId> changedCellsCopy; synchronized (changedCells) { changedCellsCopy = new HashSet<CellId>(changedCells); changedCells.clear(); } forceRedraw(changedCellsCopy); VectorCache.theCache.forceRedraw(); if (isPixelDrawing) { // reset cached cell counts numberToReconcile = SINGLETONSTOADD; for(ExpandedCellInfo count : expandedCells.values()) count.instanceCount = 0; // determine which cells should be cached (must have at least 2 instances) countCell(cell, drawLimitBounds, fullInstantiate, Orientation.IDENT, DBMath.MATID); // now render it all drawCell(cell, drawLimitBounds, fullInstantiate, Orientation.IDENT, DBMath.MATID, wnd.getCell()); } else { drawing.vd.render(this, scale, new Point2D.Double(drawing.da.offX, drawing.da.offY), cell, fullInstantiate, inPlaceNodePath, wnd.getCell(), renderBounds, varContext, greekSizeLimit, greekCellSizeLimit); } // merge transparent image into opaque one synchronized(img) { // if a grid is requested, overlay it if (cell != null && wnd.isGrid()) drawGrid(wnd, drawing.da); // combine transparent and opaque colors into a final image composite(renderBounds); } if (TAKE_STATS && isPixelDrawing) { long endTime = System.currentTimeMillis(); long curUsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long memConsumed = curUsed - initialUsed; System.out.println("Took "+com.sun.electric.database.text.TextUtils.getElapsedTime(endTime-startTime)+ ", rendered "+cellsRendered+" cells, used "+offscreensUsed+" ("+offscreenPixelsUsed+" pixels) cached cells, created "+ offscreensCreated+" ("+offscreenPixelsCreated+" pixels) new cell caches (my size is "+total+" pixels), memory used="+memConsumed); System.out.println(" Cells ("+totalCells+") "+tinyCells+" are tiny;"+ " Primitives ("+totalPrims+") "+tinyPrims+" are tiny;"+ " Arcs ("+totalArcs+") "+tinyArcs+" are tiny, "+linedArcs+" are lines"); } } /** * This is the entry point for rendering. * It displays a cell in this offscreen window. * The rendered Image can then be obtained with "getImage()". */ public void printImage(double scale, Point2D offset, Cell cell, VarContext varContext, GraphicsPreferences gp) { this.gp = gp; clearSubCellCache(); lastFullInstantiate = false; expandedScale = this.scale = scale; // set colors to use textGraphics = textGraphics.withColor(gp.getColor(User.ColorPrefType.TEXT)); gridGraphics = gridGraphics.withColor(gp.getColor(User.ColorPrefType.GRID)); instanceGraphics = instanceGraphics.withColor(gp.getColor(User.ColorPrefType.INSTANCE)); portGraphicsCache.clear(); if (wnd != null) varContext = wnd.getVarContext(); initOrigin(scale, offset.getX(), offset.getY()); canDrawText = expandedScale > 1; maxObjectSize = 2 / expandedScale; halfMaxObjectSize = maxObjectSize / 2; // remember the true window size (since recursive calls may cache individual cells that are smaller) topSz = sz; // see if any layers are being highlighted/dimmed highlightingLayers = false; for(Iterator<Layer> it = Technology.getCurrent().getLayers(); it.hasNext(); ) { Layer layer = it.next(); if (lv.isHighlighted(layer)) { highlightingLayers = true; break; } } // initialize rendering into the offscreen image clipLX = 0; clipHX = sz.width - 1; clipLY = 0; clipHY = sz.height - 1; clearImage(null); Set<CellId> changedCellsCopy; synchronized (changedCells) { changedCellsCopy = new HashSet<CellId>(changedCells); changedCells.clear(); } forceRedraw(changedCellsCopy); VectorCache.theCache.forceRedraw(); if (User.getDisplayAlgorithm() == 0) { // reset cached cell counts numberToReconcile = SINGLETONSTOADD; for(ExpandedCellInfo count : expandedCells.values()) count.instanceCount = 0; // determine which cells should be cached (must have at least 2 instances) countCell(cell, null, false, Orientation.IDENT, DBMath.MATID); // now render it all drawCell(cell, null, false, Orientation.IDENT, DBMath.MATID, cell); } else { VectorDrawing vd = new VectorDrawing(User.isUseCellGreekingImages()); vd.render(this, scale, offset, cell, false, null, null, null, varContext, User.getGreekSizeLimit(), User.getGreekCellSizeLimit()); } // merge transparent image into opaque one synchronized(img) { // combine transparent and opaque colors into a final image composite(null); } } // ************************************* INTERMEDIATE CONTROL LEVEL ************************************* /** * Method to erase the offscreen data in this PixelDrawing. * This is called before any rendering is done. * @param bounds the area of the image to actually draw (null to draw all). */ public void clearImage(Rectangle bounds) { // pickup new technology if it changed initForTechnology(); backgroundValue = gp.getColor(User.ColorPrefType.BACKGROUND).getRGB(); backgroundColor = backgroundValue & GraphicsPreferences.RGB_MASK; // erase the transparent bitmaps for(int i=0; i<numLayerBitMaps; i++) { byte [][] layerBitMap = layerBitMaps[i]; if (layerBitMap == null) continue; for(int y=0; y<sz.height; y++) { byte [] row = layerBitMap[y]; for(int x=0; x<numBytesPerRow; x++) row[x] = 0; } } // erase the patterned opaque layer bitmaps assert patternedOpaqueLayers.isEmpty(); // empty at top level for(Iterator<PatternedOpaqueLayer> it = patternedOpaqueLayers.values().iterator(); it.hasNext(); ) { PatternedOpaqueLayer pol = it.next(); byte [][] layerBitMap = pol.layerBitMap; for(int y=0; y<sz.height; y++) { byte [] row = layerBitMap[y]; for(int x=0; x<numBytesPerRow; x++) row[x] = 0; } } // erase opaque image if (bounds == null) { // erase the entire image for(int i=0; i<total; i++) opaqueData[i] = backgroundValue; } else { // erase only part of the image int lx = bounds.x; int hx = lx + bounds.width; int ly = bounds.y; int hy = ly + bounds.height; if (lx < 0) lx = 0; if (hx >= sz.width) hx = sz.width - 1; if (ly < 0) ly = 0; if (hy >= sz.height) hy = sz.height - 1; for(int y=ly; y<=hy; y++) { int baseIndex = y * sz.width; for(int x=lx; x<=hx; x++) opaqueData[baseIndex + x] = backgroundValue; } } } /** * Method to complete rendering by combining the transparent and opaque imagery. * This is called after all rendering is done. * @return the offscreen Image with the final display. */ public Image composite(Rectangle bounds) { // merge in the transparent layers if (numLayerBitMapsCreated > 0) { // get the technology's color map Color [] colorMap = gp.getColorMap(curTech); // adjust the colors if any of the transparent layers are dimmed boolean dimmedTransparentLayers = false; for(Iterator<Layer> it = curTech.getLayers(); it.hasNext(); ) { Layer layer = it.next(); if (!highlightingLayers || lv.isHighlighted(layer)) continue; if (gp.getGraphics(layer).getTransparentLayer() == 0) continue; dimmedTransparentLayers = true; break; } if (dimmedTransparentLayers) { Color [] newColorMap = new Color[colorMap.length]; int numTransparents = curTech.getNumTransparentLayers(); boolean [] dimLayer = new boolean[numTransparents]; for(int i=0; i<numTransparents; i++) dimLayer[i] = true; for(Iterator<Layer> it = curTech.getLayers(); it.hasNext(); ) { Layer layer = it.next(); if (!lv.isHighlighted(layer)) continue; int tIndex = gp.getGraphics(layer).getTransparentLayer(); if (tIndex == 0) continue; dimLayer[tIndex-1] = false; } for(int i=0; i<colorMap.length; i++) { newColorMap[i] = colorMap[i]; if (i == 0) continue; boolean dimThisEntry = true; for(int j=0; j<numTransparents; j++) { if ((i & (1<<j)) != 0) { if (!dimLayer[j]) { dimThisEntry = false; break; } } } if (dimThisEntry) { newColorMap[i] = new Color(dimColor(colorMap[i].getRGB())); } else { newColorMap[i] = new Color(brightenColor(colorMap[i].getRGB())); } } colorMap = newColorMap; } // determine range int lx = 0, hx = sz.width-1; int ly = 0, hy = sz.height-1; if (bounds != null) { lx = bounds.x; hx = lx + bounds.width; ly = bounds.y; hy = ly + bounds.height; if (lx < 0) lx = 0; if (hx >= sz.width) hx = sz.width - 1; if (ly < 0) ly = 0; if (hy >= sz.height) hy = sz.height - 1; } for(int y=ly; y<=hy; y++) { for(int i=0; i<numLayerBitMaps; i++) { byte [][] layerBitMap = layerBitMaps[i]; if (layerBitMap == null) compositeRows[i] = null; else { compositeRows[i] = layerBitMap[y]; } } int baseIndex = y * sz.width; for(int x=lx; x<=hx; x++) { int index = baseIndex + x; int pixelValue = opaqueData[index]; // the value of Alpha starts at 0xFF, which means "background" // opaque drawing typically sets it to 0, which means "filled" // Text drawing can antialias by setting the edge values in the range 0-254 // where the lower the value, the more saturated the color (so 0 means all color, 254 means little color) int alpha = (pixelValue >> 24) & 0xFF; if (alpha != 0) { // aggregate the transparent bitplanes at this pixel int bits = 0; int entry = x >> 3; int maskBit = 1 << (x & 7); for(int i=0; i<numLayerBitMaps; i++) { if (compositeRows[i] == null) continue; int byt = compositeRows[i][entry]; if ((byt & maskBit) != 0) bits |= (1<<i); } // determine the transparent color to draw int newColor = backgroundColor; if (bits != 0) { // set a transparent color newColor = colorMap[bits].getRGB() & 0xFFFFFF; } // if alpha blending, merge with the opaque data if (alpha != 0xFF) { newColor = alphaBlend(pixelValue, newColor, alpha); } opaqueData[index] = newColor; } } } } else { // nothing in transparent layers: make sure background color is right if (bounds == null) { // handle the entire image for(int i=0; i<total; i++) { int pixelValue = opaqueData[i]; if (pixelValue == backgroundValue) opaqueData[i] = backgroundColor; else { if ((pixelValue&0xFF000000) != 0) { int alpha = (pixelValue >> 24) & 0xFF; opaqueData[i] = alphaBlend(pixelValue, backgroundColor, alpha); } } } } else { // handle a partial image int lx = bounds.x; int hx = lx + bounds.width; int ly = bounds.y; int hy = ly + bounds.height; if (lx < 0) lx = 0; if (hx >= sz.width) hx = sz.width - 1; if (ly < 0) ly = 0; if (hy >= sz.height) hy = sz.height - 1; for(int y=ly; y<=hy; y++) { int baseIndex = y * sz.width; for(int x=lx; x<=hx; x++) { int index = baseIndex + x; int pixelValue = opaqueData[index]; if (pixelValue == backgroundValue) opaqueData[index] = backgroundColor; else { if ((pixelValue&0xFF000000) != 0) { int alpha = (pixelValue >> 24) & 0xFF; opaqueData[index] = alphaBlend(pixelValue, backgroundColor, alpha); } } } } } } return img; } /** * Method to draw the grid into the offscreen buffer */ private void drawGrid(EditWindow wnd, WindowFrame.DisplayAttributes da) { double spacingX = wnd.getGridXSpacing(); double spacingY = wnd.getGridYSpacing(); if (spacingX == 0 || spacingY == 0) return; double boldSpacingX = spacingX * User.getDefGridXBoldFrequency(); double boldSpacingY = spacingY * User.getDefGridYBoldFrequency(); double boldSpacingThreshX = spacingX / 4; double boldSpacingThreshY = spacingY / 4; // screen extent Rectangle2D displayable = displayableBounds(da.getIntoCellTransform()); double lX = displayable.getMinX(); double lY = displayable.getMaxY(); double hX = displayable.getMaxX(); double hY = displayable.getMinY(); double scaleX = sz.width / (hX - lX); double scaleY = sz.height / (lY - hY); // initial grid location double x1 = DBMath.toNearest(lX, spacingX); double y1 = DBMath.toNearest(lY, spacingY); // adjust grid placement according to scale boolean allBoldDots = false; if (spacingX * scaleX < 5 || spacingY * scaleY < 5) { // normal grid is too fine: only show the "bold dots" x1 = DBMath.toNearest(x1, boldSpacingX); spacingX = boldSpacingX; y1 = DBMath.toNearest(y1, boldSpacingY); spacingY = boldSpacingY; // if even the bold dots are too close, don't draw a grid if (spacingX * scaleX < 10 || spacingY * scaleY < 10) return; } else if (spacingX * scaleX > 75 && spacingY * scaleY > 75) { // if zoomed-out far enough, show all bold dots allBoldDots = true; } // draw the grid Point2D.Double tmpPt = new Point2D.Double(); AffineTransform outofCellTransform = da.getOutofCellTransform(); int col = gp.getColor(User.ColorPrefType.GRID).getRGB() & GraphicsPreferences.RGB_MASK; for(double i = y1; i > hY; i -= spacingY) { double boldValueY = i; if (i < 0) boldValueY -= boldSpacingThreshY/2; else boldValueY += boldSpacingThreshY/2; boolean everyTenY = Math.abs(boldValueY) % boldSpacingY < boldSpacingThreshY; for(double j = x1; j < hX; j += spacingX) { tmpPt.setLocation(j, i); outofCellTransform.transform(tmpPt, tmpPt); databaseToScreen(tmpPt.getX(), tmpPt.getY(), tempPt1); int x = tempPt1.x; int y = tempPt1.y; if (x < 0 || x >= sz.width) continue; if (y < 0 || y >= sz.height) continue; double boldValueX = j; if (j < 0) boldValueX -= boldSpacingThreshX/2; else boldValueX += boldSpacingThreshX/2; boolean everyTenX = Math.abs(boldValueX) % boldSpacingX < boldSpacingThreshX; if (allBoldDots && everyTenX && everyTenY) { int boxLX = x-2; if (boxLX < 0) boxLX = 0; int boxHX = x+2; if (boxHX >= sz.width) boxHX = sz.width-1; int boxLY = y-2; if (boxLY < 0) boxLY = 0; int boxHY = y+2; if (boxHY >= sz.height) boxHY = sz.height-1; drawBox(boxLX, boxHX, boxLY, boxHY, null, gridGraphics, false); if (x > 1) opaqueData[y * sz.width + (x-2)] = col; if (x < sz.width-2) opaqueData[y * sz.width + (x+2)] = col; if (y > 1) opaqueData[(y-2) * sz.width + x] = col; if (y < sz.height-2) opaqueData[(y+2) * sz.width + x] = col; continue; } // special case every 10 grid points in each direction if (allBoldDots || (everyTenX && everyTenY)) { opaqueData[y * sz.width + x] = col; if (x > 0) opaqueData[y * sz.width + (x-1)] = col; if (x < sz.width-1) opaqueData[y * sz.width + (x+1)] = col; if (y > 0) opaqueData[(y-1) * sz.width + x] = col; if (y < sz.height-1) opaqueData[(y+1) * sz.width + x] = col; continue; } // just a single dot opaqueData[y * sz.width + x] = col; } } if (User.isGridAxesShown()) { tmpPt.setLocation(0, 0); outofCellTransform.transform(tmpPt, tmpPt); databaseToScreen(tmpPt.getX(), tmpPt.getY(), tempPt1); int x = tempPt1.x; int y = tempPt1.y; if (x >= 0 && x < sz.width) drawSolidLine(x, 0, x, sz.height-1, null, col); if (y >= 0 && y < sz.height) drawSolidLine(0, y, sz.width-1, y, null, col); } } /** * Method to return a rectangle in database coordinates that covers the viewable extent of this window. * @return a rectangle that describes the viewable extent of this window (database coordinates). */ private Rectangle2D displayableBounds(AffineTransform intoCellTransform) { Point2D low = new Point2D.Double(); screenToDatabase(0, 0, low); intoCellTransform.transform(low, low); Point2D high = new Point2D.Double(); screenToDatabase(sz.width-1, sz.height-1, high); intoCellTransform.transform(high, high); double lowX = Math.min(low.getX(), high.getX()); double lowY = Math.min(low.getY(), high.getY()); double sizeX = Math.abs(high.getX()-low.getX()); double sizeY = Math.abs(high.getY()-low.getY()); Rectangle2D bounds = new Rectangle2D.Double(lowX, lowY, sizeX, sizeY); return bounds; } private void initForTechnology() { // allocate pointers to the overlappable layers Technology tech = Technology.getCurrent(); if (tech == null) return; int transLayers = gp.getNumTransparentLayers(tech); if (tech == curTech && numLayerBitMaps == transLayers) return; if (transLayers != 0) { techWithLayers = curTech = tech; } if (curTech == null) curTech = techWithLayers; if (curTech == null) return; numLayerBitMaps = gp.getNumTransparentLayers(curTech); layerBitMaps = new byte[numLayerBitMaps][][]; compositeRows = new byte[numLayerBitMaps][]; for(int i=0; i<numLayerBitMaps; i++) layerBitMaps[i] = null; numLayerBitMapsCreated = 0; } private void periodicRefresh() { // handle refreshing if (periodicRefresh) { objectCount++; if (objectCount > 100) { objectCount = 0; long currentTime = System.currentTimeMillis(); if (currentTime - lastRefreshTime > 1000) { wnd.repaint(); } } } } // ************************************* HIERARCHY TRAVERSAL ************************************* /** * Method to draw the contents of a cell, transformed through "prevTrans". */ private void drawCell(Cell cell, Rectangle2D drawLimitBounds, boolean fullInstantiate, Orientation orient, AffineTransform prevTrans, Cell topCell) { renderedCells++; renderPolyTime = 0; renderTextTime = 0; // draw all arcs for(Iterator<ArcInst> arcs = cell.getArcs(); arcs.hasNext(); ) { ArcInst ai = arcs.next(); // if limiting drawing, reject when out of area if (drawLimitBounds != null) { Rectangle2D curBounds = ai.getBounds(); Rectangle2D bounds = new Rectangle2D.Double(curBounds.getX(), curBounds.getY(), curBounds.getWidth(), curBounds.getHeight()); DBMath.transformRect(bounds, prevTrans); if (!DBMath.rectsIntersect(bounds, drawLimitBounds)) continue; } drawArc(ai, prevTrans, false); } // draw all nodes for(Iterator<NodeInst> nodes = cell.getNodes(); nodes.hasNext(); ) { NodeInst ni = nodes.next(); // if limiting drawing, reject when out of area if (drawLimitBounds != null) { Rectangle2D curBounds = ni.getBounds(); Rectangle2D bounds = new Rectangle2D.Double(curBounds.getX(), curBounds.getY(), curBounds.getWidth(), curBounds.getHeight()); DBMath.transformRect(bounds, prevTrans); if (!DBMath.rectsIntersect(bounds, drawLimitBounds)) continue; } drawNode(ni, orient, prevTrans, topCell, drawLimitBounds, fullInstantiate, false); } // show cell variables if at the top level boolean topLevel = true; if (topCell != null) topLevel = (cell == topCell); if (canDrawText && topLevel && gp.isTextVisibilityOn(TextDescriptor.TextType.CELL)) { // show displayable variables on the instance Poly[] polys = cell.getDisplayableVariables(CENTERRECT, dummyWnd, true); drawPolys(polys, prevTrans, false); } if (DEBUGRENDERTIMING) { System.out.println("Total time to render polys: "+TextUtils.getElapsedTime(renderPolyTime)); System.out.println("Total time to render text: "+TextUtils.getElapsedTime(renderTextTime)); } } /** * Method to draw a NodeInst into the offscreen image. * @param ni the NodeInst to draw. * @param trans the transformation of the NodeInst to the display. * @param topCell the Cell at the top-level of display. * @param drawLimitBounds bounds in which to draw. * @param fullInstantiate true to draw to the bottom of the hierarchy ("peek" mode). * @param forceVisible true if layer visibility information should be ignored and force the drawing */ private void drawNode(NodeInst ni, Orientation orient, AffineTransform trans, Cell topCell, Rectangle2D drawLimitBounds, boolean fullInstantiate, boolean forceVisible) { NodeProto np = ni.getProto(); AffineTransform localTrans = ni.rotateOut(trans); boolean topLevel = true; if (topCell != null) topLevel = (ni.getParent() == topCell); // draw the node if (ni.isCellInstance()) { // cell instance totalCells++; // if (objWidth < maxObjectSize) // { // tinyCells++; // return; // } // see if it is on the screen Cell subCell = (Cell)np; Orientation subOrient = orient.concatenate(ni.getOrient()); AffineTransform subTrans = ni.translateOut(localTrans); Rectangle2D cellBounds = subCell.getBounds(); Poly poly = new Poly(cellBounds); poly.transform(subTrans); cellBounds = poly.getBounds2D(); Rectangle screenBounds = databaseToScreen(cellBounds); if (screenBounds.width <= 0 || screenBounds.height <= 0) { tinyCells++; return; } if (screenBounds.x >= sz.width || screenBounds.x+screenBounds.width <= 0) return; if (screenBounds.y >= sz.height || screenBounds.y+screenBounds.height <= 0) return; boolean expanded = ni.isExpanded(); if (fullInstantiate) expanded = true; // if not expanded, but viewing this cell in-place, expand it if (!expanded) { if (inPlaceNodePath != null) { for(int pathIndex=0; pathIndex<inPlaceNodePath.size(); pathIndex++) { NodeInst niOnPath = inPlaceNodePath.get(pathIndex); if (niOnPath.getProto() == subCell) { expanded = true; break; } } } } // two ways to draw a cell instance if (expanded) { // show the contents of the cell if (!expandedCellCached(subCell, subOrient, subTrans, topCell, drawLimitBounds, fullInstantiate)) { // just draw it directly cellsRendered++; varContext = varContext.push(ni); drawCell(subCell, drawLimitBounds, fullInstantiate, subOrient, subTrans, topCell); varContext.pop(); } } else { // draw the black box of the instance drawUnexpandedCell(ni, poly); } if (canDrawText) showCellPorts(ni, trans, expanded); // draw any displayable variables on the instance if (canDrawText && gp.isTextVisibilityOn(TextDescriptor.TextType.NODE)) { Poly[] polys = ni.getDisplayableVariables(dummyWnd); drawPolys(polys, localTrans, false); } } else { // primitive: see if it can be drawn if (topLevel || (!ni.isVisInside() && np != Generic.tech().cellCenterNode)) { // see if the node is completely clipped from the screen Point2D ctr = ni.getTrueCenter(); trans.transform(ctr, ctr); double halfWidth = Math.max(ni.getXSize(), ni.getYSize()) / 2; double ctrX = ctr.getX(); double ctrY = ctr.getY(); if (renderedWindow && drawBounds != null) { Rectangle2D databaseBounds = drawBounds; if (ctrX + halfWidth < databaseBounds.getMinX()) return; if (ctrX - halfWidth > databaseBounds.getMaxX()) return; if (ctrY + halfWidth < databaseBounds.getMinY()) return; if (ctrY - halfWidth > databaseBounds.getMaxY()) return; } PrimitiveNode prim = (PrimitiveNode)np; totalPrims++; if (!prim.isCanBeZeroSize() && halfWidth < halfMaxObjectSize && !forceVisible) { // draw a tiny primitive by setting a single dot from each layer tinyPrims++; databaseToScreen(ctrX, ctrY, tempPt1); if (tempPt1.x >= 0 && tempPt1.x < sz.width && tempPt1.y >= 0 && tempPt1.y < sz.height) { drawTinyLayers(prim.getLayerIterator(), tempPt1.x, tempPt1.y); } return; } EditWindow0 nodeWnd = dummyWnd; if (!forceVisible && (!canDrawText || !gp.isTextVisibilityOn(TextDescriptor.TextType.NODE))) nodeWnd = null; if (prim == Generic.tech().invisiblePinNode) { if (!gp.isTextVisibilityOn(TextDescriptor.TextType.ANNOTATION)) nodeWnd = null; } Technology tech = prim.getTechnology(); drawPolys(tech.getShapeOfNode(ni, false, false, null), localTrans, forceVisible); drawPolys(ni.getDisplayableVariables(nodeWnd), localTrans, forceVisible); } } // draw any exports from the node if (canDrawText && topLevel && gp.isTextVisibilityOn(TextDescriptor.TextType.EXPORT)) { int exportDisplayLevel = gp.exportDisplayLevel; Iterator<Export> it = ni.getExports(); while (it.hasNext()) { Export e = it.next(); if (np instanceof PrimitiveNode && !lv.isVisible((PrimitiveNode)np)) continue; Poly poly = e.getNamePoly(); poly.transform(trans); Rectangle2D rect = (Rectangle2D)poly.getBounds2D().clone(); if (exportDisplayLevel == 2) { // draw port as a cross drawCross(poly, textGraphics, false); } else { // draw port as text TextDescriptor descript = poly.getTextDescriptor(); Poly.Type type = descript.getPos().getPolyType(); String portName = e.getName(); if (exportDisplayLevel == 1) { // use shorter port name portName = e.getShortName(); } databaseToScreen(poly.getCenterX(), poly.getCenterY(), tempPt1); Rectangle textRect = new Rectangle(tempPt1); type = Poly.rotateType(type, ni); drawText(textRect, type, descript, portName, null, textGraphics, false); } // draw variables on the export Poly[] polys = e.getDisplayableVariables(rect, dummyWnd, true); drawPolys(polys, localTrans, false); } } } /** * Method to render an ArcInst into the offscreen image. * @param ai the ArcInst to draw. * @param trans the transformation of the ArcInst to the display. * @param forceVisible true to ignore layer visibility and draw all layers. */ private void drawArc(ArcInst ai, AffineTransform trans, boolean forceVisible) { // if the arc is tiny, just approximate it with a single dot Rectangle2D arcBounds = ai.getBounds(); double arcSize = Math.max(arcBounds.getWidth(), arcBounds.getHeight()); totalArcs++; if (!forceVisible) { if (arcSize < maxObjectSize) { tinyArcs++; return; } if (ai.getGridFullWidth() > 0) { arcSize = Math.min(arcBounds.getWidth(), arcBounds.getHeight()); if (arcSize < maxObjectSize) { linedArcs++; // draw a tiny arc by setting a single dot from each layer Point2D headEnd = new Point2D.Double(ai.getHeadLocation().getX(), ai.getHeadLocation().getY()); trans.transform(headEnd, headEnd); databaseToScreen(headEnd.getX(), headEnd.getY(), tempPt1); Point2D tailEnd = new Point2D.Double(ai.getTailLocation().getX(), ai.getTailLocation().getY()); trans.transform(tailEnd, tailEnd); databaseToScreen(tailEnd.getX(), tailEnd.getY(), tempPt2); ArcProto prim = ai.getProto(); drawTinyArc(prim.getLayerIterator(), tempPt1, tempPt2); return; } } } // see if the arc is completely clipped from the screen Rectangle2D dbBounds = new Rectangle2D.Double(arcBounds.getX(), arcBounds.getY(), arcBounds.getWidth(), arcBounds.getHeight()); Poly p = new Poly(dbBounds); p.transform(trans); dbBounds = p.getBounds2D(); if (drawBounds != null && !DBMath.rectsIntersect(drawBounds, dbBounds)) return; // draw the arc ArcProto ap = ai.getProto(); Technology tech = ap.getTechnology(); drawPolys(tech.getShapeOfArc(ai), trans, forceVisible); if (canDrawText && gp.isTextVisibilityOn(TextDescriptor.TextType.ARC)) drawPolys(ai.getDisplayableVariables(dummyWnd), trans, forceVisible); } private void showCellPorts(NodeInst ni, AffineTransform trans, boolean expanded) { // show the ports that are not further exported or connected int numPorts = ni.getProto().getNumPorts(); boolean[] shownPorts = new boolean[numPorts]; for(Iterator<Connection> it = ni.getConnections(); it.hasNext();) { Connection con = it.next(); PortInst pi = con.getPortInst(); Export e = (Export)pi.getPortProto(); if (!e.isAlwaysDrawn()) shownPorts[pi.getPortIndex()] = true; } for(Iterator<Export> it = ni.getExports(); it.hasNext();) { Export exp = it.next(); PortInst pi = exp.getOriginalPort(); Export e = (Export)pi.getPortProto(); if (!e.isAlwaysDrawn()) shownPorts[pi.getPortIndex()] = true; } int portDisplayLevel = gp.portDisplayLevel; for(int i = 0; i < numPorts; i++) { if (shownPorts[i]) continue; Export pp = (Export)ni.getProto().getPort(i); Poly portPoly = ni.getShapeOfPort(pp); if (portPoly == null) continue; portPoly.transform(trans); EGraphics portGraphics = expanded ? textGraphics : getPortGraphics(pp.getBasePort()); if (portDisplayLevel == 2) { // draw port as a cross drawCross(portPoly, portGraphics, false); } else { // draw port as text if (gp.isTextVisibilityOn(TextDescriptor.TextType.PORT)) { // combine all features of port text with color of the port TextDescriptor descript = portPoly.getTextDescriptor(); TextDescriptor portDescript = pp.getTextDescriptor(Export.EXPORT_NAME).withColorIndex(descript.getColorIndex()); Poly.Type type = descript.getPos().getPolyType(); String portName = pp.getName(); if (portDisplayLevel == 1) { // use shorter port name portName = pp.getShortName(); } databaseToScreen(portPoly.getCenterX(), portPoly.getCenterY(), tempPt1); Rectangle rect = new Rectangle(tempPt1); drawText(rect, type, portDescript, portName, null, portGraphics, false); } } } } private void drawUnexpandedCell(NodeInst ni, Poly poly) { // draw the instance outline Point2D [] points = poly.getPoints(); for(int i=0; i<points.length; i++) { int lastI = i - 1; if (lastI < 0) lastI = points.length - 1; Point2D lastPt = points[lastI]; Point2D thisPt = points[i]; databaseToScreen(lastPt.getX(), lastPt.getY(), tempPt1); databaseToScreen(thisPt.getX(), thisPt.getY(), tempPt2); drawLine(tempPt1, tempPt2, null, instanceGraphics, 0, false); } // draw the instance name if (canDrawText && gp.isTextVisibilityOn(TextDescriptor.TextType.INSTANCE)) { Rectangle2D bounds = poly.getBounds2D(); Rectangle rect = databaseToScreen(bounds); TextDescriptor descript = ni.getTextDescriptor(NodeInst.NODE_PROTO); NodeProto np = ni.getProto(); drawText(rect, Poly.Type.TEXTBOX, descript, np.describe(false), null, textGraphics, false); } } private void drawTinyLayers(Iterator<Layer> layerIterator, int x, int y) { for(Iterator<Layer> it = layerIterator; it.hasNext(); ) { Layer layer = it.next(); if (layer == null) continue; byte [][] layerBitMap = null; int col = 0; EGraphics graphics = gp.getGraphics(layer); if (graphics != null) { if (nowPrinting != 0 ? graphics.isPatternedOnPrinter() : graphics.isPatternedOnDisplay()) { int [] pattern = graphics.getPattern(); if (pattern != null) { int pat = pattern[y&15]; if (pat == 0 || (pat & (0x8000 >> (x&15))) == 0) continue; } } int layerNum = graphics.getTransparentLayer() - 1; if (layerNum < numLayerBitMaps) layerBitMap = getLayerBitMap(layerNum); col = graphics.getRGB(); } // set the bit if (layerBitMap == null) { int index = y * sz.width + x; int alpha = (opaqueData[index] >> 24) & 0xFF; if (alpha == 0xFF) opaqueData[index] = col; } else { layerBitMap[y][x>>3] |= (1 << (x&7)); } } } private void drawTinyArc(Iterator<Layer> layerIterator, Point head, Point tail) { for(Iterator<Layer> it = layerIterator; it.hasNext(); ) { Layer layer = it.next(); if (layer == null) continue; EGraphics graphics = gp.getGraphics(layer); byte [][] layerBitMap = null; if (graphics != null) { int layerNum = graphics.getTransparentLayer() - 1; if (layerNum < numLayerBitMaps) layerBitMap = getLayerBitMap(layerNum); } drawLine(head, tail, layerBitMap, graphics, 0, !lv.isHighlighted(layer)); } } // ************************************* CELL CACHING ************************************* /** * @return true if the cell is properly handled and need no further processing. * False to render the contents recursively. */ private boolean expandedCellCached(Cell subCell, Orientation orient, AffineTransform origTrans, Cell topCell, Rectangle2D drawLimitBounds, boolean fullInstantiate) { // if there is no global for remembering cached cells, do not cache if (expandedCells == null) return false; // do not cache icons: they can be redrawn each time if (subCell.isIcon()) return false; ExpandedCellKey expansionKey = new ExpandedCellKey(subCell, orient); ExpandedCellInfo expandedCellCount = expandedCells.get(expansionKey); if (expandedCellCount != null) { // if this combination is not used multiple times, do not cache it if (expandedCellCount.singleton && expandedCellCount.instanceCount < 2 && expandedCellCount.offscreen == null) { if (numberToReconcile > 0) { numberToReconcile--; expandedCellCount.singleton = false; } else return false; } } if (expandedCellCount == null || expandedCellCount.offscreen == null) { // compute the cell's location on the screen Rectangle2D cellBounds = new Rectangle2D.Double(); cellBounds.setRect(subCell.getBounds()); Rectangle2D textBounds = subCell.getTextBounds(dummyWnd); if (textBounds != null) cellBounds.add(textBounds); AffineTransform rotTrans = orient.pureRotate(); DBMath.transformRect(cellBounds, rotTrans); int lX = (int)Math.floor(cellBounds.getMinX()*scale); int hX = (int)Math.ceil(cellBounds.getMaxX()*scale); int lY = (int)Math.floor(cellBounds.getMinY()*scale); int hY = (int)Math.ceil(cellBounds.getMaxY()*scale); Rectangle screenBounds = new Rectangle(lX, lY, hX - lX, hY - lY); if (screenBounds.width <= 0 || screenBounds.height <= 0) return true; // do not cache if the cell is too large (creates immense offscreen buffers) if (screenBounds.width >= topSz.width/2 && screenBounds.height >= topSz.height/2) return false; // if this is the first use, create the offscreen buffer if (expandedCellCount == null) { expandedCellCount = new ExpandedCellInfo(); expandedCells.put(expansionKey, expandedCellCount); } expandedCellCount.offscreen = new PixelDrawing(scale, screenBounds); expandedCellCount.offscreen.drawCell(subCell, null, fullInstantiate, orient, rotTrans, topCell); offscreensCreated++; offscreenPixelsCreated += expandedCellCount.offscreen.total; } // copy out of the offscreen buffer into the main buffer databaseToScreen(origTrans.getTranslateX(), origTrans.getTranslateY(), tempPt1); copyBits(expandedCellCount.offscreen, tempPt1.x, tempPt1.y); offscreensUsed++; offscreenPixelsUsed += expandedCellCount.offscreen.total; return true; } /** * Recursive method to count the number of times that a cell-transformation is used */ private void countCell(Cell cell, Rectangle2D drawLimitBounds, boolean fullInstantiate, Orientation orient, AffineTransform prevTrans) { // look for subcells for(Iterator<NodeInst> nodes = cell.getNodes(); nodes.hasNext(); ) { NodeInst ni = nodes.next(); if (!ni.isCellInstance()) continue; // if limiting drawing, reject when out of area if (drawLimitBounds != null) { Rectangle2D curBounds = ni.getBounds(); Rectangle2D bounds = new Rectangle2D.Double(curBounds.getX(), curBounds.getY(), curBounds.getWidth(), curBounds.getHeight()); DBMath.transformRect(bounds, prevTrans); if (!DBMath.rectsIntersect(bounds, drawLimitBounds)) return; } countNode(ni, drawLimitBounds, fullInstantiate, orient, prevTrans); } } /** * Recursive method to count the number of times that a cell-transformation is used */ private void countNode(NodeInst ni, Rectangle2D drawLimitBounds, boolean fullInstantiate, Orientation orient, AffineTransform trans) { // if the node is tiny, it will be approximated double objWidth = Math.max(ni.getXSize(), ni.getYSize()); if (objWidth < maxObjectSize) return; // transform into the subcell Orientation subOrient = orient.concatenate(ni.getOrient()); AffineTransform subTrans = ni.transformOut(trans); // compute where this cell lands on the screen NodeProto np = ni.getProto(); Cell subCell = (Cell)np; Rectangle2D cellBounds = subCell.getBounds(); Poly poly = new Poly(cellBounds); poly.transform(subTrans); cellBounds = poly.getBounds2D(); Rectangle screenBounds = databaseToScreen(cellBounds); if (screenBounds.width <= 0 || screenBounds.height <= 0) return; if (screenBounds.x > sz.width || screenBounds.x+screenBounds.width < 0) return; if (screenBounds.y > sz.height || screenBounds.y+screenBounds.height < 0) return; // only interested in expanded instances boolean expanded = ni.isExpanded(); if (fullInstantiate) expanded = true; // if not expanded, but viewing this cell in-place, expand it if (!expanded) { if (inPlaceNodePath != null) { for(int pathIndex=0; pathIndex<inPlaceNodePath.size(); pathIndex++) { NodeInst niOnPath = inPlaceNodePath.get(pathIndex); if (niOnPath.getProto() == subCell) { expanded = true; break; } } } } if (!expanded) return; if (screenBounds.width < sz.width/2 || screenBounds.height <= sz.height/2) { // construct the cell name that combines with the transformation ExpandedCellKey expansionKey = new ExpandedCellKey(subCell, subOrient); ExpandedCellInfo expansionCount = expandedCells.get(expansionKey); if (expansionCount == null) { expansionCount = new ExpandedCellInfo(); expansionCount.instanceCount = 1; expandedCells.put(expansionKey, expansionCount); } else { expansionCount.instanceCount++; if (expansionCount.instanceCount > 1) return; } } // now recurse countCell(subCell, null, fullInstantiate, subOrient, subTrans); } public static void forceRedraw(Cell cell) { synchronized (changedCells) { changedCells.add(cell.getId()); } } private static void forceRedraw(Set<CellId> changedCells) { // if there is no global for remembering cached cells, do not cache if (expandedCells == null) return; List<ExpandedCellKey> keys = new ArrayList<ExpandedCellKey>(); for(ExpandedCellKey eck : expandedCells.keySet() ) keys.add(eck); for(ExpandedCellKey expansionKey : keys) { if (changedCells.contains(expansionKey.cell.getId())) expandedCells.remove(expansionKey); } } /** * Method to copy the offscreen bits for a cell into the offscreen bits for the entire screen. */ private void copyBits(PixelDrawing srcOffscreen, int centerX, int centerY) { if (srcOffscreen == null) return; Dimension dim = srcOffscreen.sz; int cornerX = centerX - (int)srcOffscreen.originX; int cornerY = centerY - (int)srcOffscreen.originY; int minSrcX = Math.max(0, clipLX - cornerX); int maxSrcX = Math.min(dim.width - 1, clipHX - cornerX); int minSrcY = Math.max(0, clipLY - cornerY); int maxSrcY = Math.min(dim.height - 1, clipHY - cornerY); if (minSrcX > maxSrcX || minSrcY > maxSrcY) return; if (Job.getDebug() && numLayerBitMaps != srcOffscreen.numLayerBitMaps) System.out.println("Possible mixture of technologies in PixelDrawing.copyBits"); // copy the opaque and transparent layers for (int srcY = minSrcY; srcY <= maxSrcY; srcY++) { int destY = srcY + cornerY; assert destY >= clipLY && destY <= clipHY; if (destY < 0 || destY >= sz.height) continue; int srcBase = srcY * dim.width; int destBase = destY * sz.width; for (int srcX = minSrcX; srcX <= maxSrcX; srcX++) { int destX = srcX + cornerX; assert destX >= clipLX && destX <= clipHX; if (destX < 0 || destX >= sz.width) continue; int srcColor = srcOffscreen.opaqueData[srcBase + srcX]; if (srcColor != backgroundValue) opaqueData[destBase + destX] = srcColor; } } for (int i = 0; i < numLayerBitMaps; i++) { // out of range. Possible mixture of technologies. if (i >= srcOffscreen.numLayerBitMaps) break; byte [][] srcLayerBitMap = srcOffscreen.layerBitMaps[i]; if (srcLayerBitMap == null) continue; byte [][] destLayerBitMap = getLayerBitMap(i); for (int srcY = minSrcY; srcY <= maxSrcY; srcY++) { int destY = srcY + cornerY; assert destY >= clipLY && destY <= clipHY; if (destY < 0 || destY >= sz.height) continue; byte [] srcRow = srcLayerBitMap[srcY]; byte [] destRow = destLayerBitMap[destY]; for (int srcX = minSrcX; srcX <= maxSrcX; srcX++) { int destX = srcX + cornerX; assert destX >= clipLX && destX <= clipHX; if (destX < 0 || destX >= sz.width) continue; if ((srcRow[srcX>>3] & (1<<(srcX&7))) != 0) destRow[destX>>3] |= (1 << (destX&7)); } } } // copy the patterned opaque layers for(Layer layer : srcOffscreen.patternedOpaqueLayers.keySet()) { PatternedOpaqueLayer polSrc = srcOffscreen.patternedOpaqueLayers.get(layer); byte [][] srcLayerBitMap = polSrc.layerBitMap; if (srcLayerBitMap == null) continue; if (renderedWindow) { // this is the top-level of display: convert patterned opaque to patterns EGraphics desc = gp.getGraphics(layer); int col = desc.getRGB(); int [] pattern = desc.getPattern(); // setup pattern for this row for (int srcY = minSrcY; srcY <= maxSrcY; srcY++) { int destY = srcY + cornerY; assert destY >= clipLY && destY <= clipHY; if (destY < 0 || destY >= sz.height) continue; int destBase = destY * sz.width; int pat = pattern[destY&15]; if (pat == 0) continue; byte [] srcRow = srcLayerBitMap[srcY]; for (int srcX = minSrcX; srcX <= maxSrcX; srcX++) { int destX = srcX + cornerX; assert destX >= clipLX && destX <= clipHX; if (destX < 0 || destX >= sz.width) continue; if ((srcRow[srcX>>3] & (1<<(srcX&7))) != 0) { if ((pat & (0x8000 >> (destX&15))) != 0) opaqueData[destBase + destX] = col; } } } } else { // a lower level being copied to a low level: just copy the patterned opaque layers PatternedOpaqueLayer polDest = patternedOpaqueLayers.get(layer); if (polDest == null) { polDest = new PatternedOpaqueLayer(sz.height, numBytesPerRow); patternedOpaqueLayers.put(layer, polDest); } byte [][] destLayerBitMap = polDest.layerBitMap; for(int srcY = minSrcY; srcY <= maxSrcY; srcY++) { int destY = srcY + cornerY; assert destY >= clipLY && destY <= clipHY; if (destY < 0 || destY >= sz.height) continue; byte [] srcRow = srcLayerBitMap[srcY]; byte [] destRow = destLayerBitMap[destY]; for (int srcX = minSrcX; srcX <= maxSrcX; srcX++) { int destX = srcX + cornerX; assert destX >= clipLX && destX <= clipHX; if (destX < 0 || destX >= sz.width) continue; if ((srcRow[srcX>>3] & (1<<(srcX&7))) != 0) destRow[destX>>3] |= (1 << (destX&7)); } } } } } // ************************************* RENDERING POLY SHAPES ************************************* /** * A class representing a rectangular array of pixels. References * to pixels outside of the bounding rectangle may result in an * exception being thrown, or may result in references to unintended * elements of the Raster's associated DataBuffer. It is the user's * responsibility to avoid accessing such pixels. */ static interface ERaster { /** * Method to fill a box [lX,hX] x [lY,hY]. * Both low and high coordiantes are inclusive. * Filling might be patterned. * @param lX left X coordinate * @param hX right X coordiante * @param lY top Y coordinate * @param hY bottom Y coordiante */ public void fillBox(int lX, int hX, int lY, int hY); /** * Method to fill a horizontal scanline [lX,hX] x [y]. * Both low and high coordiantes are inclusive. * Filling might be patterned. * @param y Y coordinate * @param lX left X coordinate * @param hX right X coordiante */ public void fillHorLine(int y, int lX, int hX); /** * Method to fill a verticaltal scanline [x] x [lY,hY]. * Both low and bigh coordiantes are inclusive. * Filling might be patterned. * @param x X coordinate * @param lY top Y coordinate * @param hY bottom Y coordiante */ public void fillVerLine(int x, int lY, int hY); /** * Method to fill a point. * Filling might be patterned. * @param x X coordinate * @param y Y coordinate */ public void fillPoint(int x, int y); /** * Method to draw a horizontal line [lX,hX] x [y]. * Both low and high coordiantes are inclusive. * Drawing is always solid. * @param y Y coordinate * @param lX left X coordinate * @param hX right X coordiante */ public void drawHorLine(int y, int lX, int hX); /** * Method to draw a vertical line [x] x [lY,hY]. * Both low and high coordiantes are inclusive. * Drawing is always solid. * @param x X coordinate * @param lY top Y coordinate * @param hY bottom Y coordiante */ public void drawVerLine(int x, int lY, int hY); /** * Method to draw a point. * @param x X coordinate * @param y Y coordinate */ public void drawPoint(int x, int y); /** * Method to return Electric Outline style for this ERaster. * @return Electric Outline style for this ERaster or null for no outline. */ public EGraphics.Outline getOutline(); } // ************************************* RENDERING POLY SHAPES ************************************* /** * Method to draw polygon "poly", transformed through "trans". */ private void drawPolys(Poly[] polys, AffineTransform trans, boolean forceVisible) { if (polys == null) return; for(int i = 0; i < polys.length; i++) { // get the polygon and transform it Poly poly = polys[i]; if (poly == null) continue; Layer layer = poly.getLayer(); EGraphics graphics = poly.getGraphicsOverride(); if (graphics == null && layer != null) graphics = gp.getGraphics(layer); boolean dimmed = false; if (layer != null) { if (!forceVisible && !lv.isVisible(layer)) continue; dimmed = !lv.isHighlighted(layer); } // transform the bounds poly.transform(trans); // render the polygon if (DEBUGRENDERTIMING) { long startTime = System.currentTimeMillis(); renderPoly(poly, graphics, dimmed); renderPolyTime += (System.currentTimeMillis() - startTime); } else { renderPoly(poly, graphics, dimmed); } // handle refreshing periodicRefresh(); } } byte [][] getLayerBitMap(int layerNum) { if (layerNum < 0) return null; byte [][] layerBitMap = layerBitMaps[layerNum]; if (layerBitMap != null) return layerBitMap; // allocate this bitplane dynamically return newLayerBitMap(layerNum); } private byte [][] newLayerBitMap(int layerNum) { byte [][] layerBitMap= new byte[sz.height][]; for(int y=0; y<sz.height; y++) { byte [] row = new byte[numBytesPerRow]; for(int x=0; x<numBytesPerRow; x++) row[x] = 0; layerBitMap[y] = row; } layerBitMaps[layerNum] = layerBitMap; numLayerBitMapsCreated++; return layerBitMap; } /** * Render a Poly to the offscreen buffer. */ private void renderPoly(Poly poly, EGraphics graphics, boolean dimmed) { byte [][] layerBitMap = null; if (graphics != null) { int layerNum = graphics.getTransparentLayer() - 1; if (layerNum < numLayerBitMaps) layerBitMap = getLayerBitMap(layerNum); } Poly.Type style = poly.getStyle(); // only do this for lower-level (cached cells) if (!renderedWindow) { // for fills, handle patterned opaque layers specially if (style == Poly.Type.FILLED || style == Poly.Type.DISC) { // see if it is opaque if (layerBitMap == null) { // see if it is patterned if (nowPrinting != 0 ? graphics.isPatternedOnPrinter() : graphics.isPatternedOnDisplay()) { Layer layer = poly.getLayer(); PatternedOpaqueLayer pol = patternedOpaqueLayers.get(layer); if (pol == null) { pol = new PatternedOpaqueLayer(sz.height, numBytesPerRow); patternedOpaqueLayers.put(layer, pol); } layerBitMap = pol.layerBitMap; graphics = null; } } } } // now draw it Point2D [] points = poly.getPoints(); if (style == Poly.Type.FILLED) { Rectangle2D bounds = poly.getBox(); if (bounds != null) { // convert coordinates databaseToScreen(bounds.getMinX(), bounds.getMinY(), tempPt1); databaseToScreen(bounds.getMaxX(), bounds.getMaxY(), tempPt2); int lX = Math.min(tempPt1.x, tempPt2.x); int hX = Math.max(tempPt1.x, tempPt2.x); int lY = Math.min(tempPt1.y, tempPt2.y); int hY = Math.max(tempPt1.y, tempPt2.y); // do clipping if (lX < 0) lX = 0; if (hX >= sz.width) hX = sz.width-1; if (lY < 0) lY = 0; if (hY >= sz.height) hY = sz.height-1; // draw the box drawBox(lX, hX, lY, hY, layerBitMap, graphics, dimmed); return; } Point [] intPoints = new Point[points.length]; for(int i=0; i<points.length; i++) { intPoints[i] = new Point(); databaseToScreen(points[i].getX(), points[i].getY(), intPoints[i]); } Point [] clippedPoints = GenMath.clipPoly(intPoints, 0, sz.width-1, 0, sz.height-1); drawPolygon(clippedPoints, layerBitMap, graphics, dimmed); return; } if (style == Poly.Type.CROSSED) { databaseToScreen(points[0].getX(), points[0].getY(), tempPt1); databaseToScreen(points[1].getX(), points[1].getY(), tempPt2); databaseToScreen(points[2].getX(), points[2].getY(), tempPt3); databaseToScreen(points[3].getX(), points[3].getY(), tempPt4); drawLine(tempPt1, tempPt2, layerBitMap, graphics, 0, dimmed); drawLine(tempPt2, tempPt3, layerBitMap, graphics, 0, dimmed); drawLine(tempPt3, tempPt4, layerBitMap, graphics, 0, dimmed); drawLine(tempPt4, tempPt1, layerBitMap, graphics, 0, dimmed); drawLine(tempPt1, tempPt3, layerBitMap, graphics, 0, dimmed); drawLine(tempPt2, tempPt4, layerBitMap, graphics, 0, dimmed); return; } if (style.isText()) { Rectangle2D bounds = poly.getBounds2D(); Rectangle rect = databaseToScreen(bounds); TextDescriptor descript = poly.getTextDescriptor(); String str = poly.getString(); drawText(rect, style, descript, str, layerBitMap, graphics, dimmed); return; } if (style == Poly.Type.CLOSED || style == Poly.Type.OPENED || style == Poly.Type.OPENEDT1 || style == Poly.Type.OPENEDT2 || style == Poly.Type.OPENEDT3) { int lineType = 0; if (style == Poly.Type.OPENEDT1) lineType = 1; else if (style == Poly.Type.OPENEDT2) lineType = 2; else if (style == Poly.Type.OPENEDT3) lineType = 3; for(int j=1; j<points.length; j++) { Point2D oldPt = points[j-1]; Point2D newPt = points[j]; databaseToScreen(oldPt.getX(), oldPt.getY(), tempPt1); databaseToScreen(newPt.getX(), newPt.getY(), tempPt2); drawLine(tempPt1, tempPt2, layerBitMap, graphics, lineType, dimmed); } if (style == Poly.Type.CLOSED) { Point2D oldPt = points[points.length-1]; Point2D newPt = points[0]; databaseToScreen(oldPt.getX(), oldPt.getY(), tempPt1); databaseToScreen(newPt.getX(), newPt.getY(), tempPt2); drawLine(tempPt1, tempPt2, layerBitMap, graphics, lineType, dimmed); } return; } if (style == Poly.Type.VECTORS) { for(int j=0; j<points.length; j+=2) { Point2D oldPt = points[j]; Point2D newPt = points[j+1]; databaseToScreen(oldPt.getX(), oldPt.getY(), tempPt1); databaseToScreen(newPt.getX(), newPt.getY(), tempPt2); drawLine(tempPt1, tempPt2, layerBitMap, graphics, 0, dimmed); } return; } if (style == Poly.Type.CIRCLE) { Point2D center = points[0]; Point2D edge = points[1]; databaseToScreen(center.getX(), center.getY(), tempPt1); databaseToScreen(edge.getX(), edge.getY(), tempPt2); drawCircle(tempPt1, tempPt2, layerBitMap, graphics, dimmed); return; } if (style == Poly.Type.THICKCIRCLE) { Point2D center = points[0]; Point2D edge = points[1]; databaseToScreen(center.getX(), center.getY(), tempPt1); databaseToScreen(edge.getX(), edge.getY(), tempPt2); drawThickCircle(tempPt1, tempPt2, layerBitMap, graphics, dimmed); return; } if (style == Poly.Type.DISC) { Point2D center = points[0]; Point2D edge = points[1]; databaseToScreen(center.getX(), center.getY(), tempPt1); databaseToScreen(edge.getX(), edge.getY(), tempPt2); drawDisc(tempPt1, tempPt2, layerBitMap, graphics, dimmed); return; } if (style == Poly.Type.CIRCLEARC || style == Poly.Type.THICKCIRCLEARC) { Point2D center = points[0]; Point2D edge1 = points[1]; Point2D edge2 = points[2]; databaseToScreen(center.getX(), center.getY(), tempPt1); databaseToScreen(edge1.getX(), edge1.getY(), tempPt2); databaseToScreen(edge2.getX(), edge2.getY(), tempPt3); drawCircleArc(tempPt1, tempPt2, tempPt3, style == Poly.Type.THICKCIRCLEARC, layerBitMap, graphics, dimmed); return; } if (style == Poly.Type.CROSS) { // draw the cross drawCross(poly, graphics, dimmed); return; } if (style == Poly.Type.BIGCROSS) { // draw the big cross Point2D center = points[0]; databaseToScreen(center.getX(), center.getY(), tempPt1); int size = 5; drawLine(new Point(tempPt1.x-size, tempPt1.y), new Point(tempPt1.x+size, tempPt1.y), layerBitMap, graphics, 0, dimmed); drawLine(new Point(tempPt1.x, tempPt1.y-size), new Point(tempPt1.x, tempPt1.y+size), layerBitMap, graphics, 0, dimmed); return; } } // ************************************* BOX DRAWING ************************************* EGraphics getPortGraphics(PrimitivePort basePort) { EGraphics portGraphics = portGraphicsCache.get(basePort); if (portGraphics == null) { Color graColor = basePort.getPortColor(gp); if (graColor != null) { portGraphics = textGraphics.withColor(graColor); portGraphicsCache.put(basePort, portGraphics); } } return portGraphics; } int getTheColor(EGraphics desc, boolean dimmed) { if (nowPrinting == 2) return 0; int col = desc.getRGB(); if (highlightingLayers) { if (dimmed) col = dimColor(col); else col = brightenColor(col); } return col; } private double [] hsvTempArray = new double[3]; /** * Method to dim a color by reducing its saturation. * @param col the color as a 24-bit integer. * @return the dimmed color, a 24-bit integer. */ private int dimColor(int col) { int r = col & 0xFF; int g = (col >> 8) & 0xFF; int b = (col >> 16) & 0xFF; fromRGBtoHSV(r, g, b, hsvTempArray); hsvTempArray[1] *= 0.2; col = fromHSVtoRGB(hsvTempArray[0], hsvTempArray[1], hsvTempArray[2]); return col; } /** * Method to brighten a color by increasing its saturation. * @param col the color as a 24-bit integer. * @return the brightened color, a 24-bit integer. */ private int brightenColor(int col) { int r = col & 0xFF; int g = (col >> 8) & 0xFF; int b = (col >> 16) & 0xFF; fromRGBtoHSV(r, g, b, hsvTempArray); hsvTempArray[1] *= 1.5; if (hsvTempArray[1] > 1) hsvTempArray[1] = 1; col = fromHSVtoRGB(hsvTempArray[0], hsvTempArray[1], hsvTempArray[2]); return col; } /** * Method to convert a red/green/blue color to a hue/saturation/intensity color. * Why not use Color.RGBtoHSB? It doesn't work as well. */ private void fromRGBtoHSV(int ir, int ig, int ib, double [] hsi) { double r = ir / 255.0f; double g = ig / 255.0f; double b = ib / 255.0f; // "i" is maximum of "r", "g", and "b" hsi[2] = Math.max(Math.max(r, g), b); // "x" is minimum of "r", "g", and "b" double x = Math.min(Math.min(r, g), b); // "saturation" is (i-x)/i if (hsi[2] == 0.0) hsi[1] = 0.0; else hsi[1] = (hsi[2] - x) / hsi[2]; // hue is quadrant-based hsi[0] = 0.0; if (hsi[1] != 0.0) { double rdot = (hsi[2] - r) / (hsi[2] - x); double gdot = (hsi[2] - g) / (hsi[2] - x); double bdot = (hsi[2] - b) / (hsi[2] - x); if (b == x && r == hsi[2]) hsi[0] = (1.0 - gdot) / 6.0; else if (b == x && g == hsi[2]) hsi[0] = (1.0 + rdot) / 6.0; else if (r == x && g == hsi[2]) hsi[0] = (3.0 - bdot) / 6.0; else if (r == x && b == hsi[2]) hsi[0] = (3.0 + gdot) / 6.0; else if (g == x && b == hsi[2]) hsi[0] = (5.0 - rdot) / 6.0; else if (g == x && r == hsi[2]) hsi[0] = (5.0 + bdot) / 6.0; else System.out.println("Cannot convert (" + ir + "," + ig + "," + ib + "), for x=" + x + " i=" + hsi[2] + " s=" + hsi[1]); } } /** * Method to convert a hue/saturation/intensity color to a red/green/blue color. * Why not use Color.HSBtoRGB? It doesn't work as well. */ private int fromHSVtoRGB(double h, double s, double v) { h = h * 6.0; int i = (int)h; double f = h - i; double m = v * (1.0 - s); double n = v * (1.0 - s * f); double k = v * (1.0 - s * (1.0 - f)); int r = 0, g = 0, b = 0; switch (i) { case 0: r = (int)(v*255.0); g = (int)(k*255.0); b = (int)(m*255.0); break; case 1: r = (int)(n*255.0); g = (int)(v*255.0); b = (int)(m*255.0); break; case 2: r = (int)(m*255.0); g = (int)(v*255.0); b = (int)(k*255.0); break; case 3: r = (int)(m*255.0); g = (int)(n*255.0); b = (int)(v*255.0); break; case 4: r = (int)(k*255.0); g = (int)(m*255.0); b = (int)(v*255.0); break; case 5: r = (int)(v*255.0); g = (int)(m*255.0); b = (int)(n*255.0); break; } if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { System.out.println("(" + h + "," + s + "," + v + ") -> (" + r + "," + g + "," + b + ") (i=" + i + ")"); if (r < 0) r = 0; if (r > 255) r = 255; if (g < 0) g = 0; if (g > 255) g = 255; if (b < 0) b = 0; if (b > 255) b = 255; } return (b << 16) | (g << 8) | r; } /** * Method to draw a box on the off-screen buffer. */ void drawBox(int lX, int hX, int lY, int hY, byte [][] layerBitMap, EGraphics desc, boolean dimmed) { // get color and pattern information int col = 0; int [] pattern = null; if (desc != null) { col = getTheColor(desc, dimmed); if (nowPrinting != 0 ? desc.isPatternedOnPrinter() : desc.isPatternedOnDisplay()) pattern = desc.getPattern(); } // different code for patterned and solid if (pattern == null) { // solid fill if (layerBitMap == null) { // solid fill in opaque area for(int y=lY; y<=hY; y++) { int baseIndex = y * sz.width + lX; for(int x=lX; x<=hX; x++) { int index = baseIndex++; int alpha = (opaqueData[index] >> 24) & 0xFF; if (alpha == 0xFF) opaqueData[index] = col; } } } else { // solid fill in transparent layers for(int y=lY; y<=hY; y++) { byte [] row = layerBitMap[y]; for(int x=lX; x<=hX; x++) row[x>>3] |= (1 << (x&7)); } } } else { // patterned fill if (layerBitMap == null) { // patterned fill in opaque area for(int y=lY; y<=hY; y++) { // setup pattern for this row int pat = pattern[y&15]; if (pat == 0) continue; int baseIndex = y * sz.width; for(int x=lX; x<=hX; x++) { if ((pat & (0x8000 >> (x&15))) != 0) opaqueData[baseIndex + x] = col; } } } else { // patterned fill in transparent layers for(int y=lY; y<=hY; y++) { // setup pattern for this row int pat = pattern[y&15]; if (pat == 0) continue; byte [] row = layerBitMap[y]; for(int x=lX; x<=hX; x++) { if ((pat & (0x8000 >> (x&15))) != 0) row[x>>3] |= (1 << (x&7)); } } } EGraphics.Outline o = desc.getOutlined(); if (o != EGraphics.Outline.NOPAT) { drawOutline(lX, lY, lX, hY, layerBitMap, col, o.getPattern(), o.getLen()); drawOutline(lX, hY, hX, hY, layerBitMap, col, o.getPattern(), o.getLen()); drawOutline(hX, hY, hX, lY, layerBitMap, col, o.getPattern(), o.getLen()); drawOutline(hX, lY, lX, lY, layerBitMap, col, o.getPattern(), o.getLen()); if (o.getThickness() != 1) { for(int i=1; i<o.getThickness(); i++) { if (lX+i < sz.width) drawOutline(lX+i, lY, lX+i, hY, layerBitMap, col, o.getPattern(), o.getLen()); if (hY-i >= 0) drawOutline(lX, hY-i, hX, hY-i, layerBitMap, col, o.getPattern(), o.getLen()); if (hX-i >= 0) drawOutline(hX-i, hY, hX-i, lY, layerBitMap, col, o.getPattern(), o.getLen()); if (lY+i < sz.height) drawOutline(hX, lY+i, lX, lY+i, layerBitMap, col, o.getPattern(), o.getLen()); } } } } } // ************************************* LINE DRAWING ************************************* /** * Method to draw a line on the off-screen buffer. */ void drawLine(Point pt1, Point pt2, byte [][] layerBitMap, EGraphics desc, int texture, boolean dimmed) { // first clip the line if (GenMath.clipLine(pt1, pt2, 0, sz.width-1, 0, sz.height-1)) return; int col = 0; if (desc != null) col = getTheColor(desc, dimmed); // now draw with the proper line type switch (texture) { case 0: drawSolidLine(pt1.x, pt1.y, pt2.x, pt2.y, layerBitMap, col); break; case 1: drawPatLine(pt1.x, pt1.y, pt2.x, pt2.y, layerBitMap, col, 0x88, 8); break; case 2: drawPatLine(pt1.x, pt1.y, pt2.x, pt2.y, layerBitMap, col, 0xE7, 8); break; case 3: drawThickLine(pt1.x, pt1.y, pt2.x, pt2.y, layerBitMap, col); break; } } private void drawCross(Poly poly, EGraphics graphics, boolean dimmed) { Point2D [] points = poly.getPoints(); databaseToScreen(points[0].getX(), points[0].getY(), tempPt1); int size = 3; drawLine(new Point(tempPt1.x-size, tempPt1.y), new Point(tempPt1.x+size, tempPt1.y), null, graphics, 0, dimmed); drawLine(new Point(tempPt1.x, tempPt1.y-size), new Point(tempPt1.x, tempPt1.y+size), null, graphics, 0, dimmed); } private void drawSolidLine(int x1, int y1, int x2, int y2, byte [][] layerBitMap, int col) { // initialize the Bresenham algorithm int dx = Math.abs(x2-x1); int dy = Math.abs(y2-y1); if (dx > dy) { // initialize for lines that increment along X int incr1 = 2 * dy; int incr2 = 2 * (dy - dx); int d = incr2; int x, y, xend, yend, yincr; if (x1 > x2) { x = x2; y = y2; xend = x1; yend = y1; } else { x = x1; y = y1; xend = x2; yend = y2; } if (yend < y) yincr = -1; else yincr = 1; if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else layerBitMap[y][x>>3] |= (1 << (x&7)); // draw line that increments along X while (x < xend) { x++; if (d < 0) d += incr1; else { y += yincr; d += incr2; } if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else layerBitMap[y][x>>3] |= (1 << (x&7)); } } else { // initialize for lines that increment along Y int incr1 = 2 * dx; int incr2 = 2 * (dx - dy); int d = incr2; int x, y, xend, yend, xincr; if (y1 > y2) { x = x2; y = y2; xend = x1; yend = y1; } else { x = x1; y = y1; xend = x2; yend = y2; } if (xend < x) xincr = -1; else xincr = 1; if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else layerBitMap[y][x>>3] |= (1 << (x&7)); // draw line that increments along X while (y < yend) { y++; if (d < 0) d += incr1; else { x += xincr; d += incr2; } if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else layerBitMap[y][x>>3] |= (1 << (x&7)); } } } private void drawOutline(int x1, int y1, int x2, int y2, byte [][] layerBitMap, int col, int pattern, int len) { tempPt3.x = x1; tempPt3.y = y1; tempPt4.x = x2; tempPt4.y = y2; // first clip the line if (GenMath.clipLine(tempPt3, tempPt4, 0, sz.width-1, 0, sz.height-1)) return; drawPatLine(tempPt3.x, tempPt3.y, tempPt4.x, tempPt4.y, layerBitMap, col, pattern, len); } private void drawPatLine(int x1, int y1, int x2, int y2, byte [][] layerBitMap, int col, int pattern, int len) { // initialize counter for line style int i = 0; // initialize the Bresenham algorithm int dx = Math.abs(x2-x1); int dy = Math.abs(y2-y1); if (dx > dy) { // initialize for lines that increment along X int incr1 = 2 * dy; int incr2 = 2 * (dy - dx); int d = incr2; int x, y, xend, yend, yincr; if (x1 > x2) { x = x2; y = y2; xend = x1; yend = y1; } else { x = x1; y = y1; xend = x2; yend = y2; } if (yend < y) yincr = -1; else yincr = 1; if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else layerBitMap[y][x>>3] |= (1 << (x&7)); // draw line that increments along X while (x < xend) { x++; if (d < 0) d += incr1; else { y += yincr; d += incr2; } i++; if (i == len) i = 0; if ((pattern & (1 << i)) == 0) continue; if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else layerBitMap[y][x>>3] |= (1 << (x&7)); } } else { // initialize for lines that increment along Y int incr1 = 2 * dx; int incr2 = 2 * (dx - dy); int d = incr2; int x, y, xend, yend, xincr; if (y1 > y2) { x = x2; y = y2; xend = x1; yend = y1; } else { x = x1; y = y1; xend = x2; yend = y2; } if (xend < x) xincr = -1; else xincr = 1; if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else layerBitMap[y][x>>3] |= (1 << (x&7)); // draw line that increments along X while (y < yend) { y++; if (d < 0) d += incr1; else { x += xincr; d += incr2; } i++; if (i == len) i = 0; if ((pattern & (1 << i)) == 0) continue; if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else layerBitMap[y][x>>3] |= (1 << (x&7)); } } } private void drawThickLine(int x1, int y1, int x2, int y2, byte [][] layerBitMap, int col) { // initialize the Bresenham algorithm int dx = Math.abs(x2-x1); int dy = Math.abs(y2-y1); if (dx > dy) { // initialize for lines that increment along X int incr1 = 2 * dy; int incr2 = 2 * (dy - dx); int d = incr2; int x, y, xend, yend, yincr; if (x1 > x2) { x = x2; y = y2; xend = x1; yend = y1; } else { x = x1; y = y1; xend = x2; yend = y2; } if (yend < y) yincr = -1; else yincr = 1; drawThickPoint(x, y, layerBitMap, col); // draw line that increments along X while (x < xend) { x++; if (d < 0) d += incr1; else { y += yincr; d += incr2; } drawThickPoint(x, y, layerBitMap, col); } } else { // initialize for lines that increment along Y int incr1 = 2 * dx; int incr2 = 2 * (dx - dy); int d = incr2; int x, y, xend, yend, xincr; if (y1 > y2) { x = x2; y = y2; xend = x1; yend = y1; } else { x = x1; y = y1; xend = x2; yend = y2; } if (xend < x) xincr = -1; else xincr = 1; drawThickPoint(x, y, layerBitMap, col); // draw line that increments along X while (y < yend) { y++; if (d < 0) d += incr1; else { x += xincr; d += incr2; } drawThickPoint(x, y, layerBitMap, col); } } } // ************************************* POLYGON DRAWING ************************************* /** * Method to draw a polygon on the off-screen buffer. */ void drawPolygon(Point [] points, byte [][] layerBitMap, EGraphics desc, boolean dimmed) { // get color and pattern information int col = 0; int [] pattern = null; if (desc != null) { col = getTheColor(desc, dimmed); if (nowPrinting != 0 ? desc.isPatternedOnPrinter() : desc.isPatternedOnDisplay()) pattern = desc.getPattern(); } // fill in internal structures PolySeg edgelist = null; PolySeg [] polySegs = new PolySeg[points.length]; for(int i=0; i<points.length; i++) { polySegs[i] = new PolySeg(); if (i == 0) { polySegs[i].fx = points[points.length-1].x; polySegs[i].fy = points[points.length-1].y; } else { polySegs[i].fx = points[i-1].x; polySegs[i].fy = points[i-1].y; } polySegs[i].tx = points[i].x; polySegs[i].ty = points[i].y; } for(int i=0; i<points.length; i++) { // compute the direction of this edge int j = polySegs[i].ty - polySegs[i].fy; if (j > 0) polySegs[i].direction = 1; else if (j < 0) polySegs[i].direction = -1; else polySegs[i].direction = 0; // compute the X increment of this edge if (j == 0) polySegs[i].increment = 0; else { polySegs[i].increment = polySegs[i].tx - polySegs[i].fx; if (polySegs[i].increment != 0) polySegs[i].increment = (polySegs[i].increment * 65536 - j + 1) / j; } polySegs[i].tx <<= 16; polySegs[i].fx <<= 16; // make sure "from" is above "to" if (polySegs[i].fy > polySegs[i].ty) { j = polySegs[i].tx; polySegs[i].tx = polySegs[i].fx; polySegs[i].fx = j; j = polySegs[i].ty; polySegs[i].ty = polySegs[i].fy; polySegs[i].fy = j; } // insert this edge into the edgelist, sorted by ascending "fy" if (edgelist == null) { edgelist = polySegs[i]; polySegs[i].nextedge = null; } else { // insert by ascending "fy" if (edgelist.fy > polySegs[i].fy) { polySegs[i].nextedge = edgelist; edgelist = polySegs[i]; } else for(PolySeg a = edgelist; a != null; a = a.nextedge) { if (a.nextedge == null || a.nextedge.fy > polySegs[i].fy) { // insert after this polySegs[i].nextedge = a.nextedge; a.nextedge = polySegs[i]; break; } } } } // scan polygon and render int ycur = 0; PolySeg active = null; while (active != null || edgelist != null) { if (active == null) { active = edgelist; active.nextactive = null; edgelist = edgelist.nextedge; ycur = active.fy; } // introduce edges from edge list into active list while (edgelist != null && edgelist.fy <= ycur) { // insert "edgelist" into active list, sorted by "fx" coordinate if (active.fx > edgelist.fx || (active.fx == edgelist.fx && active.increment > edgelist.increment)) { edgelist.nextactive = active; active = edgelist; edgelist = edgelist.nextedge; } else for(PolySeg a = active; a != null; a = a.nextactive) { if (a.nextactive == null || a.nextactive.fx > edgelist.fx || (a.nextactive.fx == edgelist.fx && a.nextactive.increment > edgelist.increment)) { // insert after this edgelist.nextactive = a.nextactive; a.nextactive = edgelist; edgelist = edgelist.nextedge; break; } } } // generate regions to be filled in on current scan line int wrap = 0; PolySeg left = active; for(PolySeg edge = active; edge != null; edge = edge.nextactive) { wrap = wrap + edge.direction; if (wrap == 0) { int j = (left.fx + 32768) >> 16; int k = (edge.fx + 32768) >> 16; if (pattern != null) { int pat = pattern[ycur & 15]; if (pat != 0) { if (layerBitMap == null) { int baseIndex = ycur * sz.width; for(int x=j; x<=k; x++) { if ((pat & (1 << (15-(x&15)))) != 0) { int index = baseIndex + x; opaqueData[index] = col; } } } else { byte [] row = layerBitMap[ycur]; for(int x=j; x<=k; x++) { if ((pat & (1 << (15-(x&15)))) != 0) row[x>>3] |= (1 << (x&7)); } } } } else { if (layerBitMap == null) { int baseIndex = ycur * sz.width; for(int x=j; x<=k; x++) { opaqueData[baseIndex + x] = col; } } else { byte [] row = layerBitMap[ycur]; for(int x=j; x<=k; x++) { row[x>>3] |= (1 << (x&7)); } } } left = edge.nextactive; } } ycur++; // update edges in active list PolySeg lastedge = null; for(PolySeg edge = active; edge != null; edge = edge.nextactive) { if (ycur >= edge.ty) { if (lastedge == null) active = edge.nextactive; else lastedge.nextactive = edge.nextactive; } else { edge.fx += edge.increment; lastedge = edge; } } } // if outlined pattern, draw the outline if (pattern != null) { EGraphics.Outline o = desc.getOutlined(); if (o != EGraphics.Outline.NOPAT) { for(int i=0; i<points.length; i++) { int last = i-1; if (last < 0) last = points.length - 1; int fX = points[last].x; int fY = points[last].y; int tX = points[i].x; int tY = points[i].y; drawOutline(fX, fY, tX, tY, layerBitMap, col, o.getPattern(), o.getLen()); if (o.getThickness() != 1) { int ang = GenMath.figureAngle(new Point2D.Double(fX, fY), new Point2D.Double(tX, tY)); double sin = DBMath.sin(ang+900); double cos = DBMath.cos(ang+900); for(int t=1; t<o.getThickness(); t++) { int dX = (int)(cos*t + 0.5); int dY = (int)(sin*t + 0.5); drawOutline(fX+dX, fY+dY, tX+dX, tY+dY, layerBitMap, col, o.getPattern(), o.getLen()); } } } } } } // ************************************* TEXT DRAWING ************************************* /** * Method to draw a text on the off-screen buffer */ public void drawText(Rectangle rect, Poly.Type style, TextDescriptor descript, String s, byte [][] layerBitMap, EGraphics desc, boolean dimmed) { // quit if string is null if (s == null) return; int len = s.length(); if (len == 0) return; // get parameters int col = gp.getColor(User.ColorPrefType.TEXT).getRGB() & GraphicsPreferences.RGB_MASK; if (desc != null) col = getTheColor(desc, dimmed); // get text description int size = EditWindow.getDefaultFontSize(); String fontName = gp.defaultFont; boolean italic = false; boolean bold = false; boolean underline = false; int rotation = 0; int greekScale = 0; int shiftUp = 0; if (descript != null) { rotation = descript.getRotation().getIndex(); int colorIndex = descript.getColorIndex(); if (colorIndex != 0) { Color full = EGraphics.getColorFromIndex(colorIndex); if (full != null) col = full.getRGB() & 0xFFFFFF; } double dSize = descript.getTrueSize(scale, wnd); size = (int)dSize; if (size < MINIMUMTEXTSIZE) { // text too small: scale it to get proper size greekScale = 2; for(;;) { size = (int)(dSize * greekScale); if (size >= MINIMUMTEXTSIZE) break; greekScale *= 2; } } // prevent exceedingly large text while (size > MAXIMUMTEXTSIZE) { size /= 2; shiftUp++; } italic = descript.isItalic(); bold = descript.isBold(); underline = descript.isUnderline(); int fontIndex = descript.getFace(); if (fontIndex != 0) { TextDescriptor.ActiveFont af = TextDescriptor.ActiveFont.findActiveFont(fontIndex); if (af != null) fontName = af.getName(); } } // get box information for limiting text size if (style == Poly.Type.TEXTBOX) { if (rect.x >= sz.width || rect.x + rect.width < 0 || rect.y >= sz.height || rect.y + rect.height < 0) return; } // create RenderInfo long startTime = 0; if (DEBUGRENDERTIMING) System.currentTimeMillis(); RenderTextInfo renderInfo = new RenderTextInfo(); if (!renderInfo.buildInfo(s, fontName, size, italic, bold, underline, rect, style, rotation, shiftUp)) return; // if text was made "greek", just draw a line if (greekScale != 0) { // text too small: make it "greek" int width = (int)renderInfo.bounds.getWidth() / greekScale; int sizeIndent = (size/greekScale+1) / 4; Point pt = getTextCorner(width, size/greekScale, style, rect, rotation); // do clipping int lX = pt.x; int hX = lX + width; int lY = pt.y + sizeIndent; int hY = lY; if (lX < 0) lX = 0; if (hX >= sz.width) hX = sz.width-1; if (lY < 0) lY = 0; if (hY >= sz.height) hY = sz.height-1; drawBox(lX, hX, lY, hY, layerBitMap, desc, dimmed); return; } // check if text is on-screen if (renderInfo.bounds.getMinX() >= sz.width || renderInfo.bounds.getMaxX() < 0 || renderInfo.bounds.getMinY() >= sz.height || renderInfo.bounds.getMaxY() < 0) return; // render the text Raster ras = renderText(renderInfo); if (DEBUGRENDERTIMING) renderTextTime += (System.currentTimeMillis() - startTime); if (ras == null) return; int rasWidth = (int)renderInfo.rasBounds.getWidth() << shiftUp; int rasHeight = (int)renderInfo.rasBounds.getHeight() << shiftUp; Point pt = getTextCorner(rasWidth, rasHeight, style, rect, rotation); int atX = pt.x; int atY = pt.y; DataBufferByte dbb = (DataBufferByte)ras.getDataBuffer(); byte [] samples = dbb.getData(); int sx, ex; switch (rotation) { case 0: // no rotation if (atX < 0) sx = -atX; else sx = 0; if (atX+rasWidth >= sz.width) ex = sz.width-1 - atX; else ex = rasWidth; for(int y=0; y<rasHeight; y++) { int trueY = atY + y; if (trueY < 0 || trueY >= sz.height) continue; // setup pointers for filling this row byte [] row = null; int baseIndex = 0; if (layerBitMap == null) baseIndex = trueY * sz.width; else row = layerBitMap[trueY]; int samp = (y>>shiftUp) * textImageWidth; for(int x=sx; x<ex; x++) { int trueX = atX + x; int alpha = samples[samp + (x>>shiftUp)] & 0xFF; if (alpha == 0) continue; if (layerBitMap == null) { // drawing opaque int fullIndex = baseIndex + trueX; int pixelValue = opaqueData[fullIndex]; int oldAlpha = (pixelValue >> 24) & 0xFF; int color = col; if (oldAlpha == 0) { // blend with opaque if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha); } else if (oldAlpha == 0xFF) { // blend with background if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24); } opaqueData[fullIndex] = color; } else { // draw in a transparent layer if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7)); } } } break; case 1: // 90 degrees counterclockwise if (atX < 0) sx = -atX; else sx = 0; if (atX >= sz.width) ex = sz.width - atX; else ex = rasHeight; for(int y=0; y<rasWidth; y++) { int trueY = atY - y; if (trueY < 0 || trueY >= sz.height) continue; // setup pointers for filling this row byte [] row = null; int baseIndex = 0; if (layerBitMap == null) baseIndex = trueY * sz.width; else row = layerBitMap[trueY]; for(int x=sx; x<ex; x++) { int trueX = atX + x; int alpha = samples[(x>>shiftUp) * textImageWidth + (y>>shiftUp)] & 0xFF; if (alpha == 0) continue; if (layerBitMap == null) { // drawing opaque int fullIndex = baseIndex + trueX; int pixelValue = opaqueData[fullIndex]; int oldAlpha = (pixelValue >> 24) & 0xFF; int color = col; if (oldAlpha == 0) { // blend with opaque if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha); } else if (oldAlpha == 0xFF) { // blend with background if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24); } opaqueData[fullIndex] = color; } else { if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7)); } } } break; case 2: // 180 degrees atX -= rasWidth; atY -= rasHeight; if (atX < 0) sx = -atX; else sx = 0; if (atX+rasWidth >= sz.width) ex = sz.width-1 - atX; else ex = rasWidth; for(int y=0; y<rasHeight; y++) { int trueY = atY + y; if (trueY < 0 || trueY >= sz.height) continue; // setup pointers for filling this row byte [] row = null; int baseIndex = 0; if (layerBitMap == null) baseIndex = trueY * sz.width; else row = layerBitMap[trueY]; for(int x=sx; x<ex; x++) { int trueX = atX + x; int index = ((rasHeight-y-1)>>shiftUp) * textImageWidth + ((rasWidth-x-1)>>shiftUp); int alpha = samples[index] & 0xFF; if (alpha == 0) continue; if (layerBitMap == null) { // drawing opaque int fullIndex = baseIndex + trueX; int pixelValue = opaqueData[fullIndex]; int oldAlpha = (pixelValue >> 24) & 0xFF; int color = col; if (oldAlpha == 0) { // blend with opaque if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha); } else if (oldAlpha == 0xFF) { // blend with background if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24); } opaqueData[fullIndex] = color; } else { if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7)); } } } break; case 3: // 90 degrees clockwise if (atX < 0) sx = -atX; else sx = 0; if (atX >= sz.width) ex = sz.width - atX; else ex = rasHeight; for(int y=0; y<rasWidth; y++) { int trueY = atY + y; if (trueY < 0 || trueY >= sz.height) continue; // setup pointers for filling this row byte [] row = null; int baseIndex = 0; if (layerBitMap == null) baseIndex = trueY * sz.width; else row = layerBitMap[trueY]; for(int x=sx; x<ex; x++) { int trueX = atX - x; int alpha = samples[(x>>shiftUp) * textImageWidth + (y>>shiftUp)] & 0xFF; if (alpha == 0) continue; if (layerBitMap == null) { // drawing opaque int fullIndex = baseIndex + trueX; int pixelValue = opaqueData[fullIndex]; int oldAlpha = (pixelValue >> 24) & 0xFF; int color = col; if (oldAlpha == 0) { // blend with opaque if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha); } else if (oldAlpha == 0xFF) { // blend with background if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24); } opaqueData[fullIndex] = color; } else { if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7)); } } } break; } } private int alphaBlend(int color, int backgroundColor, int alpha) { int red = (color >> 16) & 0xFF; int green = (color >> 8) & 0xFF; int blue = color & 0xFF; int inverseAlpha = 254 - alpha; int redBack = (backgroundColor >> 16) & 0xFF; int greenBack = (backgroundColor >> 8) & 0xFF; int blueBack = backgroundColor & 0xFF; red = ((red * alpha) + (redBack * inverseAlpha)) / 255; green = ((green * alpha) + (greenBack * inverseAlpha)) / 255; blue = ((blue * alpha) + (blueBack * inverseAlpha)) / 255; color = (red << 16) | (green << 8) + blue; return color; } private static class RenderTextInfo { private Font font; private GlyphVector gv; private LineMetrics lm; private Point2D anchorPoint; private Rectangle2D rasBounds; // the raster bounds of the unrotated text, in pixels (screen units) private Rectangle2D bounds; // the real bounds of the rotated, anchored text (in screen units) private boolean underline; private boolean buildInfo(String msg, String fontName, int tSize, boolean italic, boolean bold, boolean underline, Rectangle probableBoxedBounds, Poly.Type style, int rotation, int shiftUp) { font = getFont(msg, fontName, tSize, italic, bold, underline); this.underline = underline; // convert the text to a GlyphVector FontRenderContext frc = new FontRenderContext(null, true, true); gv = font.createGlyphVector(frc, msg); lm = font.getLineMetrics(msg, frc); // figure bounding box of text Rectangle2D rasRect = gv.getLogicalBounds(); int width = (int)rasRect.getWidth(); int height = (int)(lm.getHeight()+0.5); if (width <= 0 || height <= 0) return false; int fontStyle = font.getStyle(); int boxedWidth = (int)probableBoxedBounds.getWidth() >> shiftUp; int boxedHeight = (int)probableBoxedBounds.getHeight() >> shiftUp; // if text is to be "boxed", make sure it fits if (boxedWidth > 1 && boxedHeight > 1) { if (width > boxedWidth || height > boxedHeight) { double scale = Math.min((double)boxedWidth / width, (double)boxedHeight / height); font = new Font(fontName, fontStyle, (int)(tSize*scale)); if (font != null) { // convert the text to a GlyphVector gv = font.createGlyphVector(frc, msg); lm = font.getLineMetrics(msg, frc); rasRect = gv.getLogicalBounds(); height = (int)(lm.getHeight()+0.5); if (height <= 0) return false; width = (int)rasRect.getWidth(); } } } if (underline) height++; rasBounds = new Rectangle2D.Double(0, lm.getAscent()-lm.getLeading(), width, height); anchorPoint = getTextCorner(width, height, style, probableBoxedBounds, rotation); if (rotation == 1 || rotation == 3) { bounds = new Rectangle2D.Double(anchorPoint.getX(), anchorPoint.getY(), height, width); } else { bounds = new Rectangle2D.Double(anchorPoint.getX(), anchorPoint.getY(), width, height); } return true; } } /** * Method to return the coordinates of the lower-left corner of text in this window. * @param rasterWidth the width of the text. * @param rasterHeight the height of the text. * @param style the anchor information for the text. * @param rect the bounds of the polygon containing the text. * @param rotation the rotation of the text (0=normal, 1=90 counterclockwise, 2=180, 3=90 clockwise). * @return the coordinates of the lower-left corner of the text. */ private static Point getTextCorner(int rasterWidth, int rasterHeight, Poly.Type style, Rectangle rect, int rotation) { // adjust to place text in the center int textWidth = rasterWidth; int textHeight = rasterHeight; int offX = 0, offY = 0; if (style == Poly.Type.TEXTCENT) { offX = -textWidth/2; offY = -textHeight/2; } else if (style == Poly.Type.TEXTTOP) { offX = -textWidth/2; } else if (style == Poly.Type.TEXTBOT) { offX = -textWidth/2; offY = -textHeight; } else if (style == Poly.Type.TEXTLEFT) { offY = -textHeight/2; } else if (style == Poly.Type.TEXTRIGHT) { offX = -textWidth; offY = -textHeight/2; } else if (style == Poly.Type.TEXTTOPLEFT) { } else if (style == Poly.Type.TEXTBOTLEFT) { offY = -textHeight; } else if (style == Poly.Type.TEXTTOPRIGHT) { offX = -textWidth; } else if (style == Poly.Type.TEXTBOTRIGHT) { offX = -textWidth; offY = -textHeight; } if (style == Poly.Type.TEXTBOX) { offX = -textWidth/2; offY = -textHeight/2; } if (rotation != 0) { int saveOffX = offX; switch (rotation) { case 1: offX = offY; offY = -saveOffX; break; case 2: offX = -offX; offY = -offY; break; case 3: offX = -offY; offY = saveOffX; break; } } int cX = (int)rect.getCenterX() + offX; int cY = (int)rect.getCenterY() + offY; return new Point(cX, cY); } private int textImageWidth = 0, textImageHeight = 0; private BufferedImage textImage = null; private Graphics2D textImageGraphics; private Raster renderText(RenderTextInfo renderInfo) { Font theFont = renderInfo.font; if (theFont == null) return null; int width = (int)renderInfo.rasBounds.getWidth(); int height = (int)renderInfo.rasBounds.getHeight(); GlyphVector gv = renderInfo.gv; LineMetrics lm = renderInfo.lm; // Too small to appear in the screen if (width <= 0 || height <= 0) return null; // if the new image is larger than what is saved, must rebuild if (width > textImageWidth || height > textImageHeight) textImage = null; if (textImage == null) { // create a new text buffer textImageWidth = width; textImageHeight = height; textImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); textImageGraphics = textImage.createGraphics(); } else { // clear and reuse the existing text buffer textImageGraphics.setColor(Color.BLACK); textImageGraphics.fillRect(0, 0, width, height); } // now render it Graphics2D g2 = (Graphics2D)textImage.getGraphics(); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setColor(new Color(255,255,255)); g2.drawGlyphVector(gv, (float)-renderInfo.rasBounds.getX(), lm.getAscent()-lm.getLeading()); if (renderInfo.underline) { g2.drawLine(0, height-1, width-1, height-1); } // return the bits return textImage.getData(); } public static Font getFont(String msg, String font, int tSize, boolean italic, boolean bold, boolean underline) { // get the font int fontStyle = Font.PLAIN; if (italic) fontStyle |= Font.ITALIC; if (bold) fontStyle |= Font.BOLD; Font theFont = new Font(font, fontStyle, tSize); if (theFont == null) { System.out.println("Could not find font "+font+" to render text: "+msg); return null; } return theFont; } // ************************************* CIRCLE DRAWING ************************************* /** * Method to draw a circle on the off-screen buffer */ void drawCircle(Point center, Point edge, byte [][] layerBitMap, EGraphics desc, boolean dimmed) { // get parameters int radius = (int)center.distance(edge); int col = 0; if (desc != null) col = getTheColor(desc, dimmed); // set redraw area int left = center.x - radius; int right = center.x + radius + 1; int top = center.y - radius; int bottom = center.y + radius + 1; int x = 0; int y = radius; int d = 3 - 2 * radius; if (left >= 0 && right < sz.width && top >= 0 && bottom < sz.height) { // no clip version is faster while (x <= y) { if (layerBitMap == null) { int baseIndex = (center.y + y) * sz.width; opaqueData[baseIndex + (center.x+x)] = col; opaqueData[baseIndex + (center.x-x)] = col; baseIndex = (center.y - y) * sz.width; opaqueData[baseIndex + (center.x+x)] = col; opaqueData[baseIndex + (center.x-x)] = col; baseIndex = (center.y + x) * sz.width; opaqueData[baseIndex + (center.x+y)] = col; opaqueData[baseIndex + (center.x-y)] = col; baseIndex = (center.y - x) * sz.width; opaqueData[baseIndex + (center.x+y)] = col; opaqueData[baseIndex + (center.x-y)] = col; } else { byte [] row = layerBitMap[center.y + y]; row[(center.x+x)>>3] |= (1 << ((center.x+x)&7)); row[(center.x-x)>>3] |= (1 << ((center.x-x)&7)); row = layerBitMap[center.y - y]; row[(center.x+x)>>3] |= (1 << ((center.x+x)&7)); row[(center.x-x)>>3] |= (1 << ((center.x-x)&7)); row = layerBitMap[center.y + x]; row[(center.x+y)>>3] |= (1 << ((center.x+y)&7)); row[(center.x-y)>>3] |= (1 << ((center.x-y)&7)); row = layerBitMap[center.y - x]; row[(center.x+y)>>3] |= (1 << ((center.x+y)&7)); row[(center.x-y)>>3] |= (1 << ((center.x-y)&7)); } if (d < 0) d += 4*x + 6; else { d += 4 * (x-y) + 10; y--; } x++; } } else { // clip version while (x <= y) { int thisy = center.y + y; if (thisy >= 0 && thisy < sz.height) { int thisx = center.x + x; if (thisx >= 0 && thisx < sz.width) drawPoint(thisx, thisy, layerBitMap, col); thisx = center.x - x; if (thisx >= 0 && thisx < sz.width) drawPoint(thisx, thisy, layerBitMap, col); } thisy = center.y - y; if (thisy >= 0 && thisy < sz.height) { int thisx = center.x + x; if (thisx >= 0 && thisx < sz.width) drawPoint(thisx, thisy, layerBitMap, col); thisx = center.x - x; if (thisx >= 0 && thisx < sz.width) drawPoint(thisx, thisy, layerBitMap, col); } thisy = center.y + x; if (thisy >= 0 && thisy < sz.height) { int thisx = center.x + y; if (thisx >= 0 && thisx < sz.width) drawPoint(thisx, thisy, layerBitMap, col); thisx = center.x - y; if (thisx >= 0 && thisx < sz.width) drawPoint(thisx, thisy, layerBitMap, col); } thisy = center.y - x; if (thisy >= 0 && thisy < sz.height) { int thisx = center.x + y; if (thisx >= 0 && thisx < sz.width) drawPoint(thisx, thisy, layerBitMap, col); thisx = center.x - y; if (thisx >= 0 && thisx < sz.width) drawPoint(thisx, thisy, layerBitMap, col); } if (d < 0) d += 4*x + 6; else { d += 4 * (x-y) + 10; y--; } x++; } } } /** * Method to draw a thick circle on the off-screen buffer */ void drawThickCircle(Point center, Point edge, byte [][] layerBitMap, EGraphics desc, boolean dimmed) { // get parameters int radius = (int)center.distance(edge); int col = 0; if (desc != null) col = getTheColor(desc, dimmed); int x = 0; int y = radius; int d = 3 - 2 * radius; while (x <= y) { int thisy = center.y + y; if (thisy >= 0 && thisy < sz.height) { int thisx = center.x + x; if (thisx >= 0 && thisx < sz.width) drawThickPoint(thisx, thisy, layerBitMap, col); thisx = center.x - x; if (thisx >= 0 && thisx < sz.width) drawThickPoint(thisx, thisy, layerBitMap, col); } thisy = center.y - y; if (thisy >= 0 && thisy < sz.height) { int thisx = center.x + x; if (thisx >= 0 && thisx < sz.width) drawThickPoint(thisx, thisy, layerBitMap, col); thisx = center.x - x; if (thisx >= 0 && thisx < sz.width) drawThickPoint(thisx, thisy, layerBitMap, col); } thisy = center.y + x; if (thisy >= 0 && thisy < sz.height) { int thisx = center.x + y; if (thisx >= 0 && thisx < sz.width) drawThickPoint(thisx, thisy, layerBitMap, col); thisx = center.x - y; if (thisx >= 0 && thisx < sz.width) drawThickPoint(thisx, thisy, layerBitMap, col); } thisy = center.y - x; if (thisy >= 0 && thisy < sz.height) { int thisx = center.x + y; if (thisx >= 0 && thisx < sz.width) drawThickPoint(thisx, thisy, layerBitMap, col); thisx = center.x - y; if (thisx >= 0 && thisx < sz.width) drawThickPoint(thisx, thisy, layerBitMap, col); } if (d < 0) d += 4*x + 6; else { d += 4 * (x-y) + 10; y--; } x++; } } // ************************************* DISC DRAWING ************************************* /** * Method to draw a scan line of the filled-in circle of radius "radius" */ private void drawDiscRow(int thisy, int startx, int endx, byte [][] layerBitMap, int col, int [] pattern) { if (thisy < 0 || thisy >= sz.height) return; if (startx < 0) startx = 0; if (endx >= sz.width) endx = sz.width - 1; if (pattern != null) { int pat = pattern[thisy & 15]; if (pat != 0) { if (layerBitMap == null) { int baseIndex = thisy * sz.width; for(int x=startx; x<=endx; x++) { if ((pat & (1 << (15-(x&15)))) != 0) opaqueData[baseIndex + x] = col; } } else { byte [] row = layerBitMap[thisy]; for(int x=startx; x<=endx; x++) { if ((pat & (1 << (15-(x&15)))) != 0) row[x>>3] |= (1 << (x&7)); } } } } else { if (layerBitMap == null) { int baseIndex = thisy * sz.width; for(int x=startx; x<=endx; x++) { int index = baseIndex + x; int alpha = (opaqueData[index] >> 24) & 0xFF; if (alpha == 0xFF) opaqueData[index] = col; } } else { byte [] row = layerBitMap[thisy]; for(int x=startx; x<=endx; x++) { row[x>>3] |= (1 << (x&7)); } } } } /** * Method to draw a filled-in circle of radius "radius" on the off-screen buffer */ void drawDisc(Point center, Point edge, byte [][] layerBitMap, EGraphics desc, boolean dimmed) { // get parameters int radius = (int)center.distance(edge); int col = 0; int [] pattern = null; if (desc != null) { col = getTheColor(desc, dimmed); if (nowPrinting != 0 ? desc.isPatternedOnPrinter() : desc.isPatternedOnDisplay()) { pattern = desc.getPattern(); if (desc.getOutlined() != EGraphics.Outline.NOPAT) { drawCircle(center, edge, layerBitMap, desc, dimmed); } } } // set redraw area int left = center.x - radius; int right = center.x + radius + 1; int top = center.y - radius; int bottom = center.y + radius + 1; if (radius == 1) { // just fill the area for discs this small if (left < 0) left = 0; if (right >= sz.width) right = sz.width - 1; for(int y=top; y<bottom; y++) { if (y < 0 || y >= sz.height) continue; for(int x=left; x<right; x++) drawPoint(x, y, layerBitMap, col); } return; } int x = 0; int y = radius; int d = 3 - 2 * radius; while (x <= y) { drawDiscRow(center.y+y, center.x-x, center.x+x, layerBitMap, col, pattern); drawDiscRow(center.y-y, center.x-x, center.x+x, layerBitMap, col, pattern); drawDiscRow(center.y+x, center.x-y, center.x+y, layerBitMap, col, pattern); drawDiscRow(center.y-x, center.x-y, center.x+y, layerBitMap, col, pattern); if (d < 0) d += 4*x + 6; else { d += 4 * (x-y) + 10; y--; } x++; } } // ************************************* ARC DRAWING ************************************* private boolean [] arcOctTable = new boolean[9]; private Point arcCenter; private int arcRadius; private int arcCol; private byte [][] arcLayerBitMap; private boolean arcThick; private int arcFindOctant(int x, int y) { if (x > 0) { if (y >= 0) { if (y >= x) return 7; return 8; } if (x >= -y) return 1; return 2; } if (y > 0) { if (y > -x) return 6; return 5; } if (y > x) return 4; return 3; } private Point arcXformOctant(int x, int y, int oct) { switch (oct) { case 1 : return new Point(-y, x); case 2 : return new Point( x, -y); case 3 : return new Point(-x, -y); case 4 : return new Point(-y, -x); case 5 : return new Point( y, -x); case 6 : return new Point(-x, y); case 7 : return new Point( x, y); case 8 : return new Point( y, x); } return null; } private void arcDoPixel(int x, int y) { if (x < 0 || x >= sz.width || y < 0 || y >= sz.height) return; if (arcThick) { drawThickPoint(x, y, arcLayerBitMap, arcCol); } else { drawPoint(x, y, arcLayerBitMap, arcCol); } } private void arcOutXform(int x, int y) { if (arcOctTable[1]) arcDoPixel( y + arcCenter.x, -x + arcCenter.y); if (arcOctTable[2]) arcDoPixel( x + arcCenter.x, -y + arcCenter.y); if (arcOctTable[3]) arcDoPixel(-x + arcCenter.x, -y + arcCenter.y); if (arcOctTable[4]) arcDoPixel(-y + arcCenter.x, -x + arcCenter.y); if (arcOctTable[5]) arcDoPixel(-y + arcCenter.x, x + arcCenter.y); if (arcOctTable[6]) arcDoPixel(-x + arcCenter.x, y + arcCenter.y); if (arcOctTable[7]) arcDoPixel( x + arcCenter.x, y + arcCenter.y); if (arcOctTable[8]) arcDoPixel( y + arcCenter.x, x + arcCenter.y); } private void arcBresCW(Point pt, Point pt1) { int d = 3 - 2 * pt.y + 4 * pt.x; while (pt.x < pt1.x && pt.y > pt1.y) { arcOutXform(pt.x, pt.y); if (d < 0) d += 4 * pt.x + 6; else { d += 4 * (pt.x-pt.y) + 10; pt.y--; } pt.x++; } // get to the end for ( ; pt.x < pt1.x; pt.x++) arcOutXform(pt.x, pt.y); for ( ; pt.y > pt1.y; pt.y--) arcOutXform(pt.x, pt.y); arcOutXform(pt1.x, pt1.y); } private void arcBresMidCW(Point pt) { int d = 3 - 2 * pt.y + 4 * pt.x; while (pt.x < pt.y) { arcOutXform(pt.x, pt.y); if (d < 0) d += 4 * pt.x + 6; else { d += 4 * (pt.x-pt.y) + 10; pt.y--; } pt.x++; } if (pt.x == pt.y) arcOutXform(pt.x, pt.y); } private void arcBresMidCCW(Point pt) { int d = 3 + 2 * pt.y - 4 * pt.x; while (pt.x > 0) { arcOutXform(pt.x, pt.y); if (d > 0) d += 6-4 * pt.x; else { d += 4 * (pt.y-pt.x) + 10; pt.y++; } pt.x--; } arcOutXform(0, arcRadius); } private void arcBresCCW(Point pt, Point pt1) { int d = 3 + 2 * pt.y + 4 * pt.x; while(pt.x > pt1.x && pt.y < pt1.y) { // not always correct arcOutXform(pt.x, pt.y); if (d > 0) d += 6 - 4 * pt.x; else { d += 4 * (pt.y-pt.x) + 10; pt.y++; } pt.x--; } // get to the end for ( ; pt.x > pt1.x; pt.x--) arcOutXform(pt.x, pt.y); for ( ; pt.y < pt1.y; pt.y++) arcOutXform(pt.x, pt.y); arcOutXform(pt1.x, pt1.y); } /** * draws an arc centered at (centerx, centery), clockwise, * passing by (x1,y1) and (x2,y2) */ void drawCircleArc(Point center, Point p1, Point p2, boolean thick, byte [][] layerBitMap, EGraphics desc, boolean dimmed) { // ignore tiny arcs if (p1.x == p2.x && p1.y == p2.y) return; // get parameters arcLayerBitMap = layerBitMap; arcCol = 0; if (desc != null) arcCol = getTheColor(desc, dimmed); arcCenter = center; int pa_x = p2.x - arcCenter.x; int pa_y = p2.y - arcCenter.y; int pb_x = p1.x - arcCenter.x; int pb_y = p1.y - arcCenter.y; arcRadius = (int)arcCenter.distance(p2); int alternate = (int)arcCenter.distance(p1); int start_oct = arcFindOctant(pa_x, pa_y); int end_oct = arcFindOctant(pb_x, pb_y); arcThick = thick; // move the point if (arcRadius != alternate) { int diff = arcRadius-alternate; switch (end_oct) { case 6: case 7: /* y > x */ pb_y += diff; break; case 8: /* x > y */ case 1: /* x > -y */ pb_x += diff; break; case 2: /* -y > x */ case 3: /* -y > -x */ pb_y -= diff; break; case 4: /* -y < -x */ case 5: /* y < -x */ pb_x -= diff; break; } } for(int i=1; i<9; i++) arcOctTable[i] = false; if (start_oct == end_oct) { arcOctTable[start_oct] = true; Point pa = arcXformOctant(pa_x, pa_y, start_oct); Point pb = arcXformOctant(pb_x, pb_y, start_oct); if ((start_oct&1) != 0) arcBresCW(pa, pb); else arcBresCCW(pa, pb); arcOctTable[start_oct] = false; } else { arcOctTable[start_oct] = true; Point pt = arcXformOctant(pa_x, pa_y, start_oct); if ((start_oct&1) != 0) arcBresMidCW(pt); else arcBresMidCCW(pt); arcOctTable[start_oct] = false; arcOctTable[end_oct] = true; pt = arcXformOctant(pb_x, pb_y, end_oct); if ((end_oct&1) != 0) arcBresMidCCW(pt); else arcBresMidCW(pt); arcOctTable[end_oct] = false; if (MODP(start_oct+1) != end_oct) { if (MODP(start_oct+1) == MODM(end_oct-1)) { arcOctTable[MODP(start_oct+1)] = true; } else { for(int i = MODP(start_oct+1); i != end_oct; i = MODP(i+1)) arcOctTable[i] = true; } arcBresMidCW(new Point(0, arcRadius)); } } } private int MODM(int x) { return (x<1) ? x+8 : x; } private int MODP(int x) { return (x>8) ? x-8 : x; } // ************************************* RENDERING SUPPORT ************************************* void drawPoint(int x, int y, byte [][] layerBitMap, int col) { if (layerBitMap == null) { opaqueData[y * sz.width + x] = col; } else { layerBitMap[y][x>>3] |= (1 << (x&7)); } } private void drawThickPoint(int x, int y, byte [][] layerBitMap, int col) { if (layerBitMap == null) { int baseIndex = y * sz.width + x; opaqueData[baseIndex] = col; if (x > 0) opaqueData[baseIndex - 1] = col; if (x < sz.width-1) opaqueData[baseIndex + 1] = col; if (y > 0) opaqueData[baseIndex - sz.width] = col; if (y < sz.height-1) opaqueData[baseIndex + sz.width] = col; } else { layerBitMap[y][x>>3] |= (1 << (x&7)); if (x > 0) layerBitMap[y][(x-1)>>3] |= (1 << ((x-1)&7)); if (x < sz.width-1) layerBitMap[y][(x+1)>>3] |= (1 << ((x+1)&7)); if (y > 0) layerBitMap[y-1][x>>3] |= (1 << (x&7)); if (y < sz.height-1) layerBitMap[y+1][x>>3] |= (1 << (x&7)); } } /** * Method to convert a database coordinate to screen coordinates. * @param dbX the X coordinate (in database units). * @param dbY the Y coordinate (in database units). * @param result the Point in which to store the screen coordinates. */ private void databaseToScreen(double dbX, double dbY, Point result) { double scrX = originX + dbX*scale; double scrY = originY - dbY*scale; result.x = (int)(scrX >= 0 ? scrX + 0.5 : scrX - 0.5); result.y = (int)(scrY >= 0 ? scrY + 0.5 : scrY - 0.5); } private void screenToDatabase(int x, int y, Point2D result) { result.setLocation((x - originX)/scale, (originY - y)/scale); } /** * Method to convert a database rectangle to screen coordinates. * @param db the rectangle (in database units). * @return the rectangle on the screen. */ private Rectangle databaseToScreen(Rectangle2D db) { Point llPt = tempPt1; Point urPt = tempPt2; databaseToScreen(db.getMinX(), db.getMinY(), llPt); databaseToScreen(db.getMaxX(), db.getMaxY(), urPt); int screenLX = llPt.x; int screenHX = urPt.x; int screenLY = llPt.y; int screenHY = urPt.y; if (screenHX < screenLX) { int swap = screenHX; screenHX = screenLX; screenLX = swap; } if (screenHY < screenLY) { int swap = screenHY; screenHY = screenLY; screenLY = swap; } return new Rectangle(screenLX, screenLY, screenHX-screenLX+1, screenHY-screenLY+1); } }
f2a2008fd5487c3f0a888203f92dc1d164341e12
b9648eb0f0475e4a234e5d956925ff9aa8c34552
/google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/services/GetKeywordPlanAdGroupRequestOrBuilder.java
7a5cc831d6483ff85460385ac1c0abf96f1c5f84
[ "Apache-2.0" ]
permissive
wfansh/google-ads-java
ce977abd611d1ee6d6a38b7b3032646d5ffb0b12
7dda56bed67a9e47391e199940bb8e1568844875
refs/heads/main
2022-05-22T23:45:55.238928
2022-03-03T14:23:07
2022-03-03T14:23:07
460,746,933
0
0
Apache-2.0
2022-02-18T07:08:46
2022-02-18T07:08:45
null
UTF-8
Java
false
true
1,063
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/services/keyword_plan_ad_group_service.proto package com.google.ads.googleads.v9.services; public interface GetKeywordPlanAdGroupRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v9.services.GetKeywordPlanAdGroupRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. The resource name of the Keyword Plan ad group to fetch. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * Required. The resource name of the Keyword Plan ad group to fetch. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); }
e3d7d362c82a179cd72e348e2b4d12da7039f035
b0bb3b91738834c612ad1772005e3bc8e3940e1a
/src/cn/tl/domain/Point.java
8935a26d55eafc435c7d8eda690cf5e185f046bc
[]
no_license
Namikun/javase
1c13459fb88ced1771167b9ff854221d4a94f992
5fb06ad0fa5909d675604a72e8552b158bad30cb
refs/heads/master
2022-09-23T09:28:47.946286
2022-09-21T10:06:25
2022-09-21T10:06:25
280,384,278
1
0
null
null
null
null
UTF-8
Java
false
false
175
java
package cn.tl.domain; public class Point { public final int x; public final int y; public Point(int x, int y) { this.x = x; this.y = y; } }
74b92c666ee51fc1a6defc048cfac96ca936255f
71ce953002ad3db67333f56b0cc4deffa3bed32e
/acmdb-lab3/src/java/simpledb/StringAggregator.java
a79ac985cd2bd8d2f42f365b70c8f9d4ba0da895
[]
no_license
sun-enze/acmdb20-517030910416
66b00f27132462e9bd9abf44b90581dbf6b52f9d
6dff20f99935f711952bad21cf448f99562012e4
refs/heads/master
2022-11-15T11:32:01.401680
2020-06-20T16:08:33
2020-06-20T16:08:33
254,542,192
0
0
null
null
null
null
UTF-8
Java
false
false
3,295
java
package simpledb; import java.util.ArrayList; import java.util.HashMap; /** * Knows how to compute some aggregate over a set of StringFields. */ public class StringAggregator implements Aggregator { private static final long serialVersionUID = 1L; private int gbfield; private Type gbfieldtype; private int afield; private Op what; private HashMap<Field, Integer> groupAns; /** * Aggregate constructor * @param gbfield the 0-based index of the group-by field in the tuple, or NO_GROUPING if there is no grouping * @param gbfieldtype the type of the group by field (e.g., Type.INT_TYPE), or null if there is no grouping * @param afield the 0-based index of the aggregate field in the tuple * @param what aggregation operator to use -- only supports COUNT * @throws IllegalArgumentException if what != COUNT */ public StringAggregator(int gbfield, Type gbfieldtype, int afield, Op what) { // some code goes here this.gbfield = gbfield; this.gbfieldtype = gbfieldtype; this.afield = afield; this.what = what; groupAns = new HashMap<>(); } /** * Merge a new tuple into the aggregate, grouping as indicated in the constructor * @param tup the Tuple containing an aggregate field and a group-by field */ public void mergeTupleIntoGroup(Tuple tup) { // some code goes here if(gbfield == Aggregator.NO_GROUPING) return; Field groupField = tup.getField(gbfield); if(!groupAns.containsKey(groupField)) { groupAns.put(groupField, 1); return; } int val = groupAns.get(groupField) + 1; groupAns.put(groupField, val); } /** * Create a DbIterator over group aggregate results. * * @return a DbIterator whose tuples are the pair (groupVal, * aggregateVal) if using group, or a single (aggregateVal) if no * grouping. The aggregateVal is determined by the type of * aggregate specified in the constructor. */ public DbIterator iterator() { // some code goes here String groupName[] = null; Type groupType[] ; if(gbfield == Aggregator.NO_GROUPING) { groupName = new String[1]; groupType = new Type[1]; groupName[0] = "aggregateVal"; groupType[0] = Type.INT_TYPE; } else { groupName = new String[2]; groupType = new Type[2]; groupName[0] = "groupVal"; groupType[0] = gbfieldtype; groupName[1] = "aggregateVal"; groupType[1] = Type.INT_TYPE; } TupleDesc td = new TupleDesc(groupType, groupName); ArrayList<Tuple> tuples = new ArrayList<>(); for(Field key : groupAns.keySet()) { int val = groupAns.get(key); Tuple curTuple = new Tuple(td); if(gbfield == Aggregator.NO_GROUPING) { curTuple.setField(0, new IntField(val)); } else { curTuple.setField(0, key); curTuple.setField(1, new IntField(val)); } tuples.add(curTuple); } return new TupleIterator(td, tuples); } }
d9152a91cf74befa23ded8a5440c976e280e731e
c7fb39cb84a98aeea48349d06c582395cee2c789
/src/org/minima/utils/tests/nio/SocketServerExample.java
cbef7948fd14be02c30e3c615033081f5d6de137
[ "Apache-2.0" ]
permissive
fundamentallycrypto/Minima
c5d78fa8ff1d38458c03218578d337555247f84a
b2ccea2928e483b50364405b862712aea0933557
refs/heads/master
2020-12-06T22:01:05.853806
2020-01-07T13:43:33
2020-01-07T13:43:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,453
java
package org.minima.utils.tests.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.*; public class SocketServerExample { private Selector selector; private Map<SocketChannel,List> dataMapper; private InetSocketAddress listenAddress; public static void main(String[] args) throws Exception { Runnable server = new Runnable() { @Override public void run() { try { new SocketServerExample("127.0.0.1", 8090).startServer(); } catch (IOException e) { e.printStackTrace(); } } }; Runnable client = new Runnable() { @Override public void run() { try { new SocketClientExample().startClient(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }; new Thread(server).start(); Thread.sleep(1000); new Thread(client, "client-A").start(); new Thread(client, "client-B").start(); } public SocketServerExample(String address, int port) throws IOException { listenAddress = new InetSocketAddress(address, port); dataMapper = new HashMap<SocketChannel,List>(); } // create server channel private void startServer() throws IOException { this.selector = Selector.open(); ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); // retrieve server socket and bind to port serverChannel.socket().bind(listenAddress); serverChannel.register(this.selector, SelectionKey.OP_ACCEPT); System.out.println("Server started..."); while (true) { // wait for events this.selector.select(); //work on selected keys Iterator keys = this.selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = (SelectionKey) keys.next(); // this is necessary to prevent the same key from coming up // again the next time around. keys.remove(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { this.accept(key); } else if (key.isReadable()) { this.read(key); } } } } //accept a connection made to this channel's socket private void accept(SelectionKey key) throws IOException { ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel channel = serverChannel.accept(); channel.configureBlocking(false); Socket socket = channel.socket(); SocketAddress remoteAddr = socket.getRemoteSocketAddress(); System.out.println("Connected to: " + remoteAddr); // register channel with selector for further IO dataMapper.put(channel, new ArrayList()); channel.register(this.selector, SelectionKey.OP_READ); } //read from the socket channel private void read(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int numRead = -1; numRead = channel.read(buffer); if (numRead == -1) { this.dataMapper.remove(channel); Socket socket = channel.socket(); SocketAddress remoteAddr = socket.getRemoteSocketAddress(); System.out.println("Connection closed by client: " + remoteAddr); channel.close(); key.cancel(); return; } byte[] data = new byte[numRead]; System.arraycopy(buffer.array(), 0, data, 0, numRead); System.out.println("Got: " + new String(data)); } }
5fc469378307a568c6d7723c37ac9d4b8670df2b
7af6bdce2f4ebceadd39d502c7823da7390ec463
/zipkin-ui-server/src/main/java/com/barath/app/ZipkinUiServerApplication.java
0fad1e917a4f40f514127d42262f55b73c6be4bc
[]
no_license
BarathArivazhagan/spring-cloud-zipkin-tracing
19fe15ae604cbcefaae8c9ecd5a6e72425319ddd
184469161681179a3da090a7673adb848df86e1a
refs/heads/master
2020-12-03T00:43:12.741905
2019-04-16T11:32:38
2019-04-16T11:32:38
96,069,688
1
3
null
2019-04-16T04:08:16
2017-07-03T04:17:51
Shell
UTF-8
Java
false
false
1,065
java
package com.barath.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import zipkin.server.EnableZipkinServer; @SpringBootApplication @EnableZipkinServer public class ZipkinUiServerApplication { public static void main(String[] args) { SpringApplication.run(ZipkinUiServerApplication.class, args); } @Configuration @EnableSwagger2 public class SwaggerConfiguration{ @Bean public Docket docker(){ return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } }
10964f1d543db23635b593330b59f8938b2c642a
f02c5fc7dadcda9e3c97addbfffa379dc1c1b77b
/src/main/java/com/karalundi/koala_finger_desktop/config/UIConfig.java
3c70789da5c23fcf96e88a105c21387b63a063c7
[]
no_license
jorgelopezrivas/testkfd
9824d3b12f598084d0e3a8a8b33a9d6cdb29ec9e
7555cadde095dbc0428eff635dea4f82e8c95020
refs/heads/master
2021-05-09T14:55:35.040331
2018-01-19T18:27:12
2018-01-19T18:27:12
119,079,272
0
0
null
null
null
null
UTF-8
Java
false
false
318
java
/* * Propiedad Intelectual de Karalundi. Todos los Derechos Reservados */ package com.karalundi.koala_finger_desktop.config; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; /** * * @author jorgelr */ public class UIConfig { }
1bfcac79b5693474fa857485943dd2169aff7c86
76b738b2b55a4155b43026457b33ad3bf43f98e9
/app/src/main/java/ng/sterling/footballfixtures/ui/competitionDetail/CompetitionDetailView.java
6d1bbf91f0b2cfafa3e5a0182d791f0afab17e1b
[]
no_license
uncle-tee/Football-Data-App
bb0dfc7d7885346932c6a9bb88f8feab6070a5a1
61f9da1d1f7beef69febcd6cb2a5c0a3a6f4e98d
refs/heads/master
2020-07-05T23:44:14.503687
2019-09-11T08:46:32
2019-09-11T08:46:32
202,820,214
2
0
null
null
null
null
UTF-8
Java
false
false
391
java
package ng.sterling.footballfixtures.ui.competitionDetail; import ng.sterling.footballfixtures.dto.response.CompetitionDetailResponse; /** * Author: Oluwatobi Adenekan * date: 15/08/2019 **/ public interface CompetitionDetailView { void data(CompetitionDetailResponse data); void showViewDistroyMessage(String message); void showNetworkErrorMessage(String message); }
07e5bb16e04702ad9206241d22f28fba025dbfe2
46b9417e90f6478ee10361f883953a1531afc40e
/pc/src/main/java/com/mycompany/myapp/service/UserService.java
b12afa9c539b6c5def4afac2e219dd75db2efd6a
[]
no_license
JuanGimenez/Pc
57105f088877ab76281216dae17873d3db61197e
1c806e25f793e67af0775774b2cf9c4aae2943e8
refs/heads/master
2021-06-02T16:09:18.754910
2017-05-07T23:17:58
2017-05-07T23:17:58
90,553,911
0
1
null
2020-09-18T15:58:13
2017-05-07T18:43:54
Java
UTF-8
Java
false
false
9,151
java
package com.mycompany.myapp.service; import com.mycompany.myapp.domain.Authority; import com.mycompany.myapp.domain.User; import com.mycompany.myapp.repository.AuthorityRepository; import com.mycompany.myapp.config.Constants; import com.mycompany.myapp.repository.UserRepository; import com.mycompany.myapp.security.AuthoritiesConstants; import com.mycompany.myapp.security.SecurityUtils; import com.mycompany.myapp.service.util.RandomUtil; import com.mycompany.myapp.service.dto.UserDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.ZonedDateTime; import java.util.*; /** * Service class for managing users. */ @Service @Transactional public class UserService { private final Logger log = LoggerFactory.getLogger(UserService.class); private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final AuthorityRepository authorityRepository; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.authorityRepository = authorityRepository; } public Optional<User> activateRegistration(String key) { log.debug("Activating user for activation key {}", key); return userRepository.findOneByActivationKey(key) .map(user -> { // activate given user for the registration key. user.setActivated(true); user.setActivationKey(null); log.debug("Activated user: {}", user); return user; }); } public Optional<User> completePasswordReset(String newPassword, String key) { log.debug("Reset user password for reset key {}", key); return userRepository.findOneByResetKey(key) .filter(user -> { ZonedDateTime oneDayAgo = ZonedDateTime.now().minusHours(24); return user.getResetDate().isAfter(oneDayAgo); }) .map(user -> { user.setPassword(passwordEncoder.encode(newPassword)); user.setResetKey(null); user.setResetDate(null); return user; }); } public Optional<User> requestPasswordReset(String mail) { return userRepository.findOneByEmail(mail) .filter(User::getActivated) .map(user -> { user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(ZonedDateTime.now()); return user; }); } public User createUser(String login, String password, String firstName, String lastName, String email, String imageUrl, String langKey) { User newUser = new User(); Authority authority = authorityRepository.findOne(AuthoritiesConstants.USER); Set<Authority> authorities = new HashSet<>(); String encryptedPassword = passwordEncoder.encode(password); newUser.setLogin(login); // new user gets initially a generated password newUser.setPassword(encryptedPassword); newUser.setFirstName(firstName); newUser.setLastName(lastName); newUser.setEmail(email); newUser.setImageUrl(imageUrl); newUser.setLangKey(langKey); // new user is not active newUser.setActivated(false); // new user gets registration key newUser.setActivationKey(RandomUtil.generateActivationKey()); authorities.add(authority); newUser.setAuthorities(authorities); userRepository.save(newUser); log.debug("Created Information for User: {}", newUser); return newUser; } public User createUser(UserDTO userDTO) { User user = new User(); user.setLogin(userDTO.getLogin()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); user.setEmail(userDTO.getEmail()); user.setImageUrl(userDTO.getImageUrl()); if (userDTO.getLangKey() == null) { user.setLangKey("es"); // default language } else { user.setLangKey(userDTO.getLangKey()); } if (userDTO.getAuthorities() != null) { Set<Authority> authorities = new HashSet<>(); userDTO.getAuthorities().forEach( authority -> authorities.add(authorityRepository.findOne(authority)) ); user.setAuthorities(authorities); } String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); user.setPassword(encryptedPassword); user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(ZonedDateTime.now()); user.setActivated(true); userRepository.save(user); log.debug("Created Information for User: {}", user); return user; } /** * Update basic information (first name, last name, email, language) for the current user. * * @param firstName first name of user * @param lastName last name of user * @param email email id of user * @param langKey language key * @param imageUrl image URL of user */ public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) { userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> { user.setFirstName(firstName); user.setLastName(lastName); user.setEmail(email); user.setLangKey(langKey); user.setImageUrl(imageUrl); log.debug("Changed Information for User: {}", user); }); } /** * Update all information for a specific user, and return the modified user. * * @param userDTO user to update * @return updated user */ public Optional<UserDTO> updateUser(UserDTO userDTO) { return Optional.of(userRepository .findOne(userDTO.getId())) .map(user -> { user.setLogin(userDTO.getLogin()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); user.setEmail(userDTO.getEmail()); user.setImageUrl(userDTO.getImageUrl()); user.setActivated(userDTO.isActivated()); user.setLangKey(userDTO.getLangKey()); Set<Authority> managedAuthorities = user.getAuthorities(); managedAuthorities.clear(); userDTO.getAuthorities().stream() .map(authorityRepository::findOne) .forEach(managedAuthorities::add); log.debug("Changed Information for User: {}", user); return user; }) .map(UserDTO::new); } public void deleteUser(String login) { userRepository.findOneByLogin(login).ifPresent(user -> { userRepository.delete(user); log.debug("Deleted User: {}", user); }); } public void changePassword(String password) { userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> { String encryptedPassword = passwordEncoder.encode(password); user.setPassword(encryptedPassword); log.debug("Changed password for User: {}", user); }); } @Transactional(readOnly = true) public Page<UserDTO> getAllManagedUsers(Pageable pageable) { return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new); } @Transactional(readOnly = true) public Optional<User> getUserWithAuthoritiesByLogin(String login) { return userRepository.findOneWithAuthoritiesByLogin(login); } @Transactional(readOnly = true) public User getUserWithAuthorities(Long id) { return userRepository.findOneWithAuthoritiesById(id); } @Transactional(readOnly = true) public User getUserWithAuthorities() { return userRepository.findOneWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin()).orElse(null); } /** * Not activated users should be automatically deleted after 3 days. * <p> * This is scheduled to get fired everyday, at 01:00 (am). * </p> */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { ZonedDateTime now = ZonedDateTime.now(); List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3)); for (User user : users) { log.debug("Deleting not activated user {}", user.getLogin()); userRepository.delete(user); } } }
9c823919ae2438af933a83d35784ed113a6b1fac
c29c645081013905b80bb7db9c188f6eb7342781
/src/main/java/afinal/proyecto/cuatro/grupo/dao/DaoUser.java
51bb12491f37179b7d3a344bad36b434472575b8
[]
no_license
PF-G4/airports-indoor-location-backend
818be91eec48a0897af64d1f22bb4836563d9b59
fd1971376f6eb2e7660a98e0294215f7aae3f509
refs/heads/master
2020-03-12T08:01:40.871998
2018-12-02T21:47:43
2018-12-02T21:47:43
130,518,957
0
0
null
2018-11-30T20:29:47
2018-04-21T23:16:00
Java
UTF-8
Java
false
false
255
java
package afinal.proyecto.cuatro.grupo.dao; import org.springframework.data.repository.CrudRepository; import afinal.proyecto.cuatro.grupo.entities.User; public interface DaoUser extends CrudRepository<User, Long> { User findByEmail(String email); }
8eca78c6ea9c0043f9c16c04a7a32d8b5df5e841
eeb83e80f006d44d74620b0a7ea8ec20e877578c
/godsoft.mdatagokr/src/main/java/egovframework/com/cop/ems/service/EgovSndngMailDtlsService.java
9b016b6208db5b8458c5217a449ee1d5d1149c5a
[]
no_license
LeeBaekHaeng/GodTest2016
52bd1c867647acd40a00b5ce4035f718201544fb
a080fc963eaaf372ec5fab132b954849090a3225
refs/heads/master
2022-12-24T21:19:46.464098
2020-06-21T12:39:28
2020-06-21T12:39:28
67,454,036
3
2
null
2022-12-16T04:27:05
2016-09-05T22:14:42
PLSQL
UTF-8
Java
false
false
1,128
java
package egovframework.com.cop.ems.service; import java.util.List; import egovframework.com.cmm.ComDefaultVO; /** * 발송메일 내역을 조회하는 비즈니스 인터페이스 클래스 * @author 공통서비스 개발팀 박지욱 * @since 2009.03.12 * @version 1.0 * @see * * <pre> * << 개정이력(Modification Information) >> * * 수정일 수정자 수정내용 * ------- -------- --------------------------- * 2009.03.12 박지욱 최초 생성 * * </pre> */ public interface EgovSndngMailDtlsService { /** * 발송메일 목록을 조회한다. * @param vo ComDefaultVO * @return List * @exception Exception */ List<?> selectSndngMailList(ComDefaultVO vo) throws Exception; /** * 발송메일 총건수를 조회한다. * @param vo ComDefaultVO * @return int * @exception */ int selectSndngMailListTotCnt(ComDefaultVO vo) throws Exception; /** * 발송메일을 삭제한다. * @param vo SndngMailVO * @exception */ void deleteSndngMailList(SndngMailVO vo) throws Exception; }
dd3716027c61eab3458ace45e1ff81044ead1b5c
7a9a0e2fab22f9b9251ed9b56a7682f39a30c599
/src/com/huangjq/wbssq/commons/CTool.java
a7bdb569871757e9f3f0be26417745c73cb36901
[ "Apache-2.0" ]
permissive
huangjiaqian/wbczq
4484828aec68d23e6f4e6eaeed386a1340c720ea
0ded964fad7e4c77bf1ea8eb9754dbd09160d27d
refs/heads/master
2021-01-01T19:05:10.222979
2017-07-27T07:10:26
2017-07-27T07:10:26
98,504,504
2
0
null
null
null
null
UTF-8
Java
false
false
16,002
java
package com.huangjq.wbssq.commons; /** * 此类中收集Java编程中WEB开发常用到的一些工具。 * 为避免生成此类的实例,构造方法被申明为private类型的。 * @author */ import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.util.Date; public class CTool { /** * 私有构造方法,防止类的实例化,因为工具类不需要实例化。 */ private CTool() { } /** * <pre> * 例: String strVal="This is a dog"; String * strResult=CTools.replace(strVal,"dog","cat"); 结果: strResult equals "This * is cat" * * @param strSrc * 要进行替换操作的字符串 * @param strOld * 要查找的字符串 * @param strNew * 要替换的字符串 * @return 替换后的字符串 * * <pre> */ public static final String replace(String strSrc, String strOld, String strNew) { if (strSrc == null || strOld == null || strNew == null) return ""; int i = 0; if (strOld.equals(strNew)) // 避免新旧字符一样产生死循环 return strSrc; if ((i = strSrc.indexOf(strOld, i)) >= 0) { char[] arr_cSrc = strSrc.toCharArray(); char[] arr_cNew = strNew.toCharArray(); int intOldLen = strOld.length(); StringBuffer buf = new StringBuffer(arr_cSrc.length); buf.append(arr_cSrc, 0, i).append(arr_cNew); i += intOldLen; int j = i; while ((i = strSrc.indexOf(strOld, i)) > 0) { buf.append(arr_cSrc, j, i - j).append(arr_cNew); i += intOldLen; j = i; } buf.append(arr_cSrc, j, arr_cSrc.length - j); return buf.toString(); } return strSrc; } /** * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串 * 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&' * * @param strSrc * 要进行替换操作的字符串 * @return 替换特殊字符后的字符串 * @since 1.0 */ public static String htmlEncode(String strSrc) { if (strSrc == null) return ""; char[] arr_cSrc = strSrc.toCharArray(); StringBuffer buf = new StringBuffer(arr_cSrc.length); char ch; for (int i = 0; i < arr_cSrc.length; i++) { ch = arr_cSrc[i]; if (ch == '<') buf.append("&lt;"); else if (ch == '>') buf.append("&gt;"); else if (ch == '"') buf.append("&quot;"); else if (ch == '\'') buf.append("&#039;"); else if (ch == '&') buf.append("&amp;"); else buf.append(ch); } return buf.toString(); } /** * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串 * 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&' * * @param strSrc * 要进行替换操作的字符串 * @param quotes * 为0时单引号和双引号都替换,为1时不替换单引号,为2时不替换双引号,为3时单引号和双引号都不替换 * @return 替换特殊字符后的字符串 * @since 1.0 */ public static String htmlEncode(String strSrc, int quotes) { if (strSrc == null) return ""; if (quotes == 0) { return htmlEncode(strSrc); } char[] arr_cSrc = strSrc.toCharArray(); StringBuffer buf = new StringBuffer(arr_cSrc.length); char ch; for (int i = 0; i < arr_cSrc.length; i++) { ch = arr_cSrc[i]; if (ch == '<') buf.append("&lt;"); else if (ch == '>') buf.append("&gt;"); else if (ch == '"' && quotes == 1) buf.append("&quot;"); else if (ch == '\'' && quotes == 2) buf.append("&#039;"); else if (ch == '&') buf.append("&amp;"); else buf.append(ch); } return buf.toString(); } /** * 和htmlEncode正好相反 * * @param strSrc * 要进行转换的字符串 * @return 转换后的字符串 * @since 1.0 */ public static String htmlDecode(String strSrc) { if (strSrc == null) return ""; strSrc = strSrc.replaceAll("&lt;", "<"); strSrc = strSrc.replaceAll("&gt;", ">"); strSrc = strSrc.replaceAll("&quot;", "\""); strSrc = strSrc.replaceAll("&#039;", "'"); strSrc = strSrc.replaceAll("&amp;", "&"); return strSrc; } /** * HTML标签转义方法 * * 空格 &nbsp; < 小于号 &lt; > 大于号 &gt; & 和号 &amp; " 引号 &quot; ' 撇号 &apos; ¢ 分 &cent; £ 镑 &pound; ¥ 日圆 &yen; € 欧元 &euro; § 小节 &sect; © 版权 &copy; ® 注册商标 &reg; ™ 商标 &trade; × 乘号 &times; ÷ 除号 &divide; */ public static String unhtml(String content) { if (StringUtils.isBlank(content)) { return ""; } String html = content; html = html.replaceAll("'", "&apos;"); html = html.replaceAll("\"", "&quot;"); html = html.replaceAll("\t", "&nbsp;&nbsp;");// 替换跳格 html = html.replaceAll("<", "&lt;"); html = html.replaceAll(">", "&gt;"); return html; } public static String html(String content) { if (StringUtils.isBlank(content)) { return ""; } String html = content; html = html.replaceAll("&apos;", "'"); html = html.replaceAll("&quot;", "\""); html = html.replaceAll("&nbsp;", " ");// 替换跳格 html = html.replaceAll("&lt;", "<"); html = html.replaceAll("&gt;", ">"); return html; } /** * 在将数据存入数据库前转换 * * @param strVal * 要转换的字符串 * @return 从“ISO8859_1”到“GBK”得到的字符串 * @since 1.0 */ public static String toChinese(String strVal) { try { if (strVal == null) { return ""; } else { strVal = strVal.trim(); strVal = new String(strVal.getBytes("ISO8859_1"), "GBK"); return strVal; } } catch (Exception exp) { return ""; } } /** * 编码转换 从UTF-8到GBK * * @param strVal * @return */ public static String toGBK(String strVal) { try { if (strVal == null) { return ""; } else { strVal = strVal.trim(); strVal = new String(strVal.getBytes("UTF-8"), "GBK"); return strVal; } } catch (Exception exp) { return ""; } } /** * 将数据从数据库中取出后转换 * * * @param strVal * 要转换的字符串 * @return 从“GBK”到“ISO8859_1”得到的字符串 * @since 1.0 */ public static String toISO(String strVal) { try { if (strVal == null) { return ""; } else { strVal = new String(strVal.getBytes("GBK"), "ISO8859_1"); return strVal; } } catch (Exception exp) { return ""; } } public static String gbk2UTF8(String strVal) { try { if (strVal == null) { return ""; } else { strVal = new String(strVal.getBytes("GBK"), "UTF-8"); return strVal; } } catch (Exception exp) { return ""; } } public static String ISO2UTF8(String strVal) { try { if (strVal == null) { return ""; } else { strVal = new String(strVal.getBytes("ISO-8859-1"), "UTF-8"); return strVal; } } catch (Exception exp) { return ""; } } public static String UTF82ISO(String strVal) { try { if (strVal == null) { return ""; } else { strVal = new String(strVal.getBytes("UTF-8"), "ISO-8859-1"); return strVal; } } catch (Exception exp) { return ""; } } /** * 显示大文本块处理(将字符集转成ISO) * * @deprecated * @param str * 要进行转换的字符串 * @return 转换成html可以正常显示的字符串 */ public static String toISOHtml(String str) { return toISO(htmlDecode(null2Blank((str)))); } /** * 实际处理 return toChineseNoReplace(null2Blank(str)); 主要应用于老牛的信息发布 * * @param str * 要进行处理的字符串 * @return 转换后的字符串 * @see fs_com.utils.CTools#toChinese * @see fs_com.utils.CTools#null2Blank */ public static String toChineseAndHtmlEncode(String str, int quotes) { return htmlEncode(toChinese(str), quotes); } /** * 把null值和""值转换成&nbsp; 主要应用于页面表格格的显示 * * @param str * 要进行处理的字符串 * @return 转换后的字符串 */ public static String str4Table(String str) { if (str == null) return "&nbsp;"; else if (str.equals("")) return "&nbsp;"; else return str; } /** * String型变量转换成int型变量 * * @param str * 要进行转换的字符串 * @return intVal 如果str不可以转换成int型数据,返回-1表示异常,否则返回转换后的值 * @since 1.0 */ public static int str2Int(String str) { int intVal; try { intVal = Integer.parseInt(str); } catch (Exception e) { intVal = 0; } return intVal; } public static double str2Double(String str) { double dVal = 0; try { dVal = Double.parseDouble(str); } catch (Exception e) { dVal = 0; } return dVal; } public static long str2Long(String str) { long longVal = 0; try { longVal = Long.parseLong(str); } catch (Exception e) { longVal = 0; } return longVal; } public static float stringToFloat(String floatstr) { Float floatee; floatee = Float.valueOf(floatstr); return floatee.floatValue(); } // change the float type to the string type public static String floatToString(float value) { Float floatee = new Float(value); return floatee.toString(); } /** * int型变量转换成String型变量 * * @param intVal * 要进行转换的整数 * @return str 如果intVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值 */ /** * int型变量转换成String型变量 * * @param intVal * 要进行转换的整数 * @return str 如果intVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值 */ public static String int2Str(int intVal) { String str; try { str = String.valueOf(intVal); } catch (Exception e) { str = ""; } return str; } /** * long型变量转换成String型变量 * * @param longVal * 要进行转换的整数 * @return str 如果longVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值 */ public static String long2Str(long longVal) { String str; try { str = String.valueOf(longVal); } catch (Exception e) { str = ""; } return str; } /** * null 处理 * * @param str * 要进行转换的字符串 * @return 如果str为null值,返回空串"",否则返回str */ public static String null2Blank(String str) { if (str == null) return ""; else return str; } /** * null 处理 * * @param d * 要进行转换的日期对像 * @return 如果d为null值,返回空串"",否则返回d.toString() */ public static String null2Blank(Date d) { if (d == null) return ""; else return d.toString(); } /** * null 处理 * * @param str * 要进行转换的字符串 * @return 如果str为null值,返回空串整数0,否则返回相应的整数 */ public static int null2Zero(String str) { int intTmp; intTmp = str2Int(str); if (intTmp == -1) return 0; else return intTmp; } /** * 把null转换为字符串"0" * * @param str * @return */ public static String null2SZero(String str) { str = CTool.null2Blank(str); if (str.equals("")) return "0"; else return str; } /** * sql语句 处理 * * @param sql * 要进行处理的sql语句 * @param dbtype * 数据库类型 * @return 处理后的sql语句 */ public static String sql4DB(String sql, String dbtype) { if (!dbtype.equalsIgnoreCase("oracle")) { sql = CTool.toISO(sql); } return sql; } /** * 对字符串进行md5加密 * * @param s * 要加密的字符串 * @return md5加密后的字符串 */ public final static String MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { byte[] strTemp = s.getBytes(); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } /** * 字符串从GBK编码转换为Unicode编码 * * @param text * @return */ public static String StringToUnicode(String text) { String result = ""; int input; StringReader isr; try { isr = new StringReader(new String(text.getBytes(), "GBK")); } catch (UnsupportedEncodingException e) { return "-1"; } try { while ((input = isr.read()) != -1) { result = result + "&#x" + Integer.toHexString(input) + ";"; } } catch (IOException e) { return "-2"; } isr.close(); return result; } /** * * @param inStr * @return */ public static String gb2utf(String inStr) { char temChr; int ascInt; int i; String result = new String(""); if (inStr == null) { inStr = ""; } for (i = 0; i < inStr.length(); i++) { temChr = inStr.charAt(i); ascInt = temChr + 0; // System.out.println("1=="+ascInt); // System.out.println("1=="+Integer.toBinaryString(ascInt)); if (Integer.toHexString(ascInt).length() > 2) { result = result + "&#x" + Integer.toHexString(ascInt) + ";"; } else { result = result + temChr; } } return result; } /** * This method will encode the String to unicode. * * @param gbString * @return */ // 代码:-------------------------------------------------------------------------------- public static String gbEncoding(final String gbString) { char[] utfBytes = gbString.toCharArray(); String unicodeBytes = ""; for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) { String hexB = Integer.toHexString(utfBytes[byteIndex]); if (hexB.length() <= 2) { hexB = "00" + hexB; } unicodeBytes = unicodeBytes + "\\u" + hexB; } System.out.println("unicodeBytes is: " + unicodeBytes); return unicodeBytes; } /** * This method will decode the String to a recognized String in ui. * * @param dataStr * @return */ public static StringBuffer decodeUnicode(final String dataStr) { int start = 0; int end = 0; final StringBuffer buffer = new StringBuffer(); while (start > -1) { end = dataStr.indexOf("\\u", start + 2); String charStr = ""; if (end == -1) { charStr = dataStr.substring(start + 2, dataStr.length()); } else { charStr = dataStr.substring(start + 2, end); } char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。 buffer.append(new Character(letter).toString()); start = end; } return buffer; } }
35d9509172f1c34a4a9e0658b7e2cf1fa03993c1
d40409faf4bb6ecb600eb9fe9e43772e1c364495
/src/main/java/com/iu/util/FileDownload.java
35dab9486302b41e924c123dd8f153f1ac5ea2f4
[]
no_license
seryu96/spring_2
dd5e2514f67b68202bbb07f371a6c3ffb03c976b
2cbbacfc25a5075914fc370d1d970b9ab00e9903
refs/heads/master
2021-08-24T00:06:40.025747
2017-12-07T06:20:15
2017-12-07T06:20:15
112,291,578
0
0
null
null
null
null
UTF-8
Java
false
false
1,154
java
package com.iu.util; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.net.URLEncoder; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.FileCopyUtils; import org.springframework.web.servlet.view.AbstractView; public class FileDownload extends AbstractView { @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { File file = (File)model.get("download"); // 클라이언트 측으로 전달 response.setCharacterEncoding("UTF-8"); response.setContentLength((int)file.length()); String fileName = (String)model.get("oriname"); fileName = URLEncoder.encode(fileName, "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=\""+fileName+"\""); response.setHeader("Content-Transfer-Encoding", "binary"); FileInputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); FileCopyUtils.copy(in, out); in.close(); out.close(); } }
f7e6a4e11f3b74ebf76458416049ed24281da6ba
37dcdc0bb41563e44ea2c523724ac98523ed1717
/Crucigrama_1/src/view/Start.java
cf33624178c739b34d712abb6c5adf3855a7aa0b
[]
no_license
StevenSanchez/TareaProgramada2
527addeacf3f047a9a4575cba64538bd898ca7f1
11b9c994a132ca598484c93920fd10d4b7459928
refs/heads/master
2020-04-09T09:49:37.087324
2018-12-06T21:11:23
2018-12-06T21:11:23
160,247,999
0
0
null
null
null
null
UTF-8
Java
false
false
5,984
java
/* * 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 view; import static Main.Crucigrama.listaRegistrados; import model.Person; /** * * @author Steven */ public class Start extends javax.swing.JDialog { private Person person; /** * Creates new form Start */ public Start() { initComponents(); setLocationRelativeTo(null); person = listaRegistrados.getPerson(0); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lbWelcome = new javax.swing.JLabel(); lbAutor1 = new javax.swing.JLabel(); lbAutor2 = new javax.swing.JLabel(); lbAutors = new javax.swing.JLabel(); btregister = new javax.swing.JButton(); btEnter = new javax.swing.JButton(); lbAutor3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); lbWelcome.setFont(new java.awt.Font("Microsoft New Tai Lue", 1, 14)); // NOI18N lbWelcome.setText("Bienvenido al juego de Crucigrama"); lbAutor1.setFont(new java.awt.Font("Microsoft New Tai Lue", 1, 13)); // NOI18N lbAutor1.setText("Steven Sanchez"); lbAutor2.setFont(new java.awt.Font("Microsoft New Tai Lue", 1, 13)); // NOI18N lbAutor2.setText("Leonardo Gomes"); lbAutors.setFont(new java.awt.Font("Microsoft New Tai Lue", 1, 12)); // NOI18N lbAutors.setText("Autores"); btregister.setText("Registrarse"); btregister.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btregisterActionPerformed(evt); } }); btEnter.setText("Ingresar"); btEnter.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btEnterActionPerformed(evt); } }); lbAutor3.setFont(new java.awt.Font("Microsoft New Tai Lue", 1, 13)); // NOI18N lbAutor3.setText("Marcell Granados"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(67, 67, 67) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lbWelcome) .addComponent(lbAutor1) .addComponent(lbAutor2) .addComponent(lbAutors) .addGroup(layout.createSequentialGroup() .addComponent(btregister) .addGap(208, 208, 208) .addComponent(btEnter)) .addComponent(lbAutor3)) .addContainerGap(46, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(lbWelcome) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lbAutors) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lbAutor1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lbAutor2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lbAutor3) .addGap(53, 53, 53) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btregister) .addComponent(btEnter)) .addGap(93, 93, 93)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btregisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btregisterActionPerformed // TODO add your handling code here: Register register = new Register(null, true); setVisible(false); register.setVisible(true); Person person = register.getPerson(); if (person != null) { listaRegistrados.addPerson(person); } listaRegistrados.printVector(); setVisible(true); }//GEN-LAST:event_btregisterActionPerformed private void btEnterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEnterActionPerformed // TODO add your handling code here: Enter enter = new Enter(null, true); setVisible(false); enter.setVisible(true); setVisible(true); }//GEN-LAST:event_btEnterActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btEnter; private javax.swing.JButton btregister; private javax.swing.JLabel lbAutor1; private javax.swing.JLabel lbAutor2; private javax.swing.JLabel lbAutor3; private javax.swing.JLabel lbAutors; private javax.swing.JLabel lbWelcome; // End of variables declaration//GEN-END:variables }
[ "Steven@Toshiba" ]
Steven@Toshiba
87c92b29002fe65cc4a6fd534e60ec1cab7f0250
655df4becb0731c9fd5f58c930007682bf2b8846
/app/src/main/java/com/langbai/tdhd/parse/ParseManager.java
842c99ad71b387141245a338b275ec1a010030af
[]
no_license
moushao/Langxun
b4927e82c6f653bf64c9d802aac287cb39b6399e
4fa101bf959c5dde9ffa5ee0279fad52045ea74a
refs/heads/master
2021-05-12T03:47:56.780330
2018-01-16T03:34:55
2018-01-16T03:34:55
115,302,109
0
0
null
null
null
null
UTF-8
Java
false
false
8,853
java
package com.langbai.tdhd.parse; import android.content.Context; import com.hyphenate.EMValueCallBack; import com.hyphenate.chat.EMClient; import com.hyphenate.easeui.domain.EaseUser; import com.hyphenate.easeui.utils.EaseCommonUtils; import com.hyphenate.util.EMLog; import com.langbai.tdhd.DemoHelper; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.SaveCallback; import java.util.ArrayList; import java.util.List; public class ParseManager { private static final String TAG = ParseManager.class.getSimpleName(); private static final String ParseAppID = "UUL8TxlHwKj7ZXEUr2brF3ydOxirCXdIj9LscvJs"; private static final String ParseClientKey = "B1jH9bmxuYyTcpoFfpeVslhmLYsytWTxqYqKQhBJ"; // private static final String ParseAppID = "task"; // private static final String ParseClientKey = "123456789"; private static final String CONFIG_TABLE_NAME = "hxuser"; private static final String CONFIG_USERNAME = "username"; private static final String CONFIG_NICK = "nickname"; private static final String CONFIG_AVATAR = "avatar"; private static final String parseServer = "http://parse.easemob.com/parse/"; private static ParseManager instance = new ParseManager(); private ParseManager() { } public static ParseManager getInstance() { return instance; } public void onInit(Context context) { //parse包 compile 'com.parse:parse-android:1.15.7' Context appContext = context.getApplicationContext(); Parse.enableLocalDatastore(appContext); // Parse.initialize(context, ParseAppID, ParseClientKey); Parse.initialize(new Parse.Configuration.Builder(appContext).applicationId(ParseAppID).server(parseServer) .build()); } public boolean updateParseNickName(final String nickname) { String username = EMClient.getInstance().getCurrentUser(); ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME); pQuery.whereEqualTo(CONFIG_USERNAME, username); ParseObject pUser = null; try { pUser = pQuery.getFirst(); if (pUser == null) { return false; } pUser.put(CONFIG_NICK, nickname); pUser.save(); return true; } catch (ParseException e) { if (e.getCode() == ParseException.OBJECT_NOT_FOUND) { pUser = new ParseObject(CONFIG_TABLE_NAME); pUser.put(CONFIG_USERNAME, username); pUser.put(CONFIG_NICK, nickname); try { pUser.save(); return true; } catch (ParseException e1) { e1.printStackTrace(); EMLog.e(TAG, "parse error " + e1.getMessage()); } } e.printStackTrace(); EMLog.e(TAG, "parse error " + e.getMessage()); } catch (Exception e) { EMLog.e(TAG, "updateParseNickName error"); e.printStackTrace(); } return false; } public void getContactInfos(List<String> usernames, final EMValueCallBack<List<EaseUser>> callback) { ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME); pQuery.whereContainedIn(CONFIG_USERNAME, usernames); pQuery.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> arg0, ParseException arg1) { if (arg0 != null) { List<EaseUser> mList = new ArrayList<EaseUser>(); for (ParseObject pObject : arg0) { EaseUser user = new EaseUser(pObject.getString(CONFIG_USERNAME)); ParseFile parseFile = pObject.getParseFile(CONFIG_AVATAR); if (parseFile != null) { user.setAvatar(parseFile.getUrl()); } user.setNick(pObject.getString(CONFIG_NICK)); EaseCommonUtils.setUserInitialLetter(user); mList.add(user); } callback.onSuccess(mList); } else { callback.onError(arg1.getCode(), arg1.getMessage()); } } }); } public void asyncGetCurrentUserInfo(final EMValueCallBack<EaseUser> callback) { final String username = EMClient.getInstance().getCurrentUser(); asyncGetUserInfo(username, new EMValueCallBack<EaseUser>() { @Override public void onSuccess(EaseUser value) { callback.onSuccess(value); } @Override public void onError(int error, String errorMsg) { if (error == ParseException.OBJECT_NOT_FOUND) { ParseObject pUser = new ParseObject(CONFIG_TABLE_NAME); pUser.put(CONFIG_USERNAME, username); pUser.saveInBackground(new SaveCallback() { @Override public void done(ParseException arg0) { if (arg0 == null) { callback.onSuccess(new EaseUser(username)); } } }); } else { callback.onError(error, errorMsg); } } }); } public void asyncGetUserInfo(final String username, final EMValueCallBack<EaseUser> callback) { ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME); pQuery.whereEqualTo(CONFIG_USERNAME, username); pQuery.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject pUser, ParseException e) { if (pUser != null) { String nick = pUser.getString(CONFIG_NICK); ParseFile pFile = pUser.getParseFile(CONFIG_AVATAR); if (callback != null) { EaseUser user = DemoHelper.getInstance().getContactList().get(username); if (user != null) { user.setNick(nick); if (pFile != null && pFile.getUrl() != null) { user.setAvatar(pFile.getUrl()); } } else { user = new EaseUser(username); user.setNick(nick); if (pFile != null && pFile.getUrl() != null) { user.setAvatar(pFile.getUrl()); } } callback.onSuccess(user); } } else { if (callback != null) { callback.onError(e.getCode(), e.getMessage()); } } } }); } public String uploadParseAvatar(byte[] data) { String username = EMClient.getInstance().getCurrentUser(); ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME); pQuery.whereEqualTo(CONFIG_USERNAME, username); ParseObject pUser = null; try { pUser = pQuery.getFirst(); if (pUser == null) { pUser = new ParseObject(CONFIG_TABLE_NAME); pUser.put(CONFIG_USERNAME, username); } ParseFile pFile = new ParseFile(data); pUser.put(CONFIG_AVATAR, pFile); pUser.save(); return pFile.getUrl(); } catch (ParseException e) { if (e.getCode() == ParseException.OBJECT_NOT_FOUND) { try { pUser = new ParseObject(CONFIG_TABLE_NAME); pUser.put(CONFIG_USERNAME, username); ParseFile pFile = new ParseFile(data); pUser.put(CONFIG_AVATAR, pFile); pUser.save(); return pFile.getUrl(); } catch (ParseException e1) { e1.printStackTrace(); EMLog.e(TAG, "parse error " + e1.getMessage()); } } else { e.printStackTrace(); EMLog.e(TAG, "parse error " + e.getMessage()); } } catch (Exception e) { EMLog.e(TAG, "uploadParseAvatar error"); e.printStackTrace(); } return null; } }
6804552d427dcd528f482ce18e96ce47a1ad7381
01e25b532e9468fd35330266de10183a99a3dc15
/commons-dict-wordnet-frames/src/main/java/org/swtk/commons/dict/wordnet/frames/instance/p1/p3/WordnetNounFrame1345.java
86b5475056736244534318baa946b5f21241a7fd
[ "Apache-2.0" ]
permissive
torrances/swtk-commons
a3f95206204becf138718e297f2bb939c65cafa5
78ee97835e4437d91fd4ba0cf6ccab40be5c8889
refs/heads/master
2021-01-17T11:31:27.004328
2016-01-07T17:26:09
2016-01-07T17:26:09
43,841,418
0
0
null
null
null
null
UTF-8
Java
false
false
22,584
java
package org.swtk.commons.dict.wordnet.frames.instance.p1.p3; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.DataNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounFrame1345 { private static Map<String, DataNoun> map = new TreeMap<String, DataNoun>(); static { add("{\"id\":\"13450179\", \"upperType\":\"NOUN\", \"term\":\"aging\", \"synonyms\":[\"ageing\", \"senescence\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13547313\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"01649151\", \"semPointer\":\"0303\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"SYNONYM\", \"id\":\"13464882\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13450367\", \"upperType\":\"NOUN\", \"term\":\"aldol_reaction\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13468534\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13450473\", \"upperType\":\"NOUN\", \"term\":\"alluvion\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13508041\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13450605\", \"upperType\":\"NOUN\", \"term\":\"alpha_decay\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13478072\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13450758\", \"upperType\":\"NOUN\", \"term\":\"alternative_birth\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13469507\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13450953\", \"upperType\":\"NOUN\", \"term\":\"amelogenesis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13510240\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13451061\", \"upperType\":\"NOUN\", \"term\":\"Americanization\", \"synonyms\":[\"Americanisation\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13456051\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"00411331\", \"semPointer\":\"0202\", \"upperType\":\"VERB\"},{\"frameType\":\"ACTION\", \"id\":\"00410568\", \"semPointer\":\"0202\", \"upperType\":\"VERB\"},{\"frameType\":\"ACTION\", \"id\":\"00411331\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"},{\"frameType\":\"ACTION\", \"id\":\"00410568\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"}]}}"); add("{\"id\":\"13451247\", \"upperType\":\"NOUN\", \"term\":\"amitosis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13465876\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02627774\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13451435\", \"upperType\":\"NOUN\", \"term\":\"ammonification\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13556157\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"00498300\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"}]}}"); add("{\"id\":\"13451564\", \"upperType\":\"NOUN\", \"term\":\"amylolysis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13467563\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02629591\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13451668\", \"upperType\":\"NOUN\", \"term\":\"anabolism\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13455861\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_14\", \"id\":\"13535517\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02629821\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"00108459\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"UNKNOWN_16\", \"id\":\"13464960\", \"semPointer\":\"0101\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13451959\", \"upperType\":\"NOUN\", \"term\":\"anaglyphy\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13557997\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02630256\", \"semPointer\":\"0103\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02630256\", \"semPointer\":\"0102\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13452216\", \"upperType\":\"NOUN\", \"term\":\"anamorphism\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13535851\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_16\", \"id\":\"13526272\", \"semPointer\":\"0101\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13452394\", \"upperType\":\"NOUN\", \"term\":\"anamorphosis\", \"synonyms\":[\"anamorphism\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13498226\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13452553\", \"upperType\":\"NOUN\", \"term\":\"anaphase\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13557502\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_14\", \"id\":\"13533928\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02631534\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13452742\", \"upperType\":\"NOUN\", \"term\":\"anastalsis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13461236\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_16\", \"id\":\"13555976\", \"semPointer\":\"0101\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13452895\", \"upperType\":\"NOUN\", \"term\":\"androgenesis\", \"synonyms\":[\"androgeny\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13553704\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02632510\", \"semPointer\":\"0201\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02632318\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02632318\", \"semPointer\":\"0102\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13453165\", \"upperType\":\"NOUN\", \"term\":\"angiogenesis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13510240\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13453258\", \"upperType\":\"NOUN\", \"term\":\"Anglicization\", \"synonyms\":[\"Anglicisation\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13456051\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"00301098\", \"semPointer\":\"0201\", \"upperType\":\"VERB\"},{\"frameType\":\"ACTION\", \"id\":\"00301098\", \"semPointer\":\"0102\", \"upperType\":\"VERB\"}]}}"); add("{\"id\":\"13453422\", \"upperType\":\"NOUN\", \"term\":\"anisogamy\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13576443\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_09\", \"id\":\"06047178\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02635032\", \"semPointer\":\"0102\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13453616\", \"upperType\":\"NOUN\", \"term\":\"anovulation\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13547313\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_16\", \"id\":\"13551440\", \"semPointer\":\"0101\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13453820\", \"upperType\":\"NOUN\", \"term\":\"anthropogenesis\", \"synonyms\":[\"anthropogeny\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13498226\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02639228\", \"semPointer\":\"0201\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02639228\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13453975\", \"upperType\":\"NOUN\", \"term\":\"antiredeposition\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13540166\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13454076\", \"upperType\":\"NOUN\", \"term\":\"antisepsis\", \"synonyms\":[\"asepsis\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13547313\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02123039\", \"semPointer\":\"0201\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13454234\", \"upperType\":\"NOUN\", \"term\":\"aphaeresis\", \"synonyms\":[\"apheresis\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13545602\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_09\", \"id\":\"06182505\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02642606\", \"semPointer\":\"0202\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02642606\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13454456\", \"upperType\":\"NOUN\", \"term\":\"aphesis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13545602\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02643155\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13454635\", \"upperType\":\"NOUN\", \"term\":\"apogamy\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13454900\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_09\", \"id\":\"06076105\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02644098\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02644098\", \"semPointer\":\"0103\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13454900\", \"upperType\":\"NOUN\", \"term\":\"apomixis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13455293\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02143570\", \"semPointer\":\"0104\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02644528\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02644528\", \"semPointer\":\"0102\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"SYNONYM\", \"id\":\"13454635\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13553559\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13553704\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13455121\", \"upperType\":\"NOUN\", \"term\":\"apposition\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13510240\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_09\", \"id\":\"06047178\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13455293\", \"upperType\":\"NOUN\", \"term\":\"asexual_reproduction\", \"synonyms\":[\"agamogenesis\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13571521\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02143570\", \"semPointer\":\"0203\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"SYNONYM\", \"id\":\"13454900\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13460152\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13463132\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13502611\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13502783\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13538402\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13553950\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13565276\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13455579\", \"upperType\":\"NOUN\", \"term\":\"assibilation\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13486023\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"00548102\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"}]}}"); add("{\"id\":\"13455710\", \"upperType\":\"NOUN\", \"term\":\"assimilation\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13529536\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"00160255\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"}]}}"); add("{\"id\":\"13455861\", \"upperType\":\"NOUN\", \"term\":\"assimilation\", \"synonyms\":[\"absorption\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13547313\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"01542830\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"},{\"frameType\":\"SYNONYM\", \"id\":\"13451668\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13532032\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13456051\", \"upperType\":\"NOUN\", \"term\":\"assimilation\", \"synonyms\":[\"absorption\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13578654\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"00603650\", \"semPointer\":\"0201\", \"upperType\":\"VERB\"},{\"frameType\":\"ACTION\", \"id\":\"00160069\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"},{\"frameType\":\"ACTION\", \"id\":\"00159450\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"},{\"frameType\":\"SYNONYM\", \"id\":\"13451061\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13453258\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13497643\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13595785\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13456325\", \"upperType\":\"NOUN\", \"term\":\"association\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13467563\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_09\", \"id\":\"06094057\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13515528\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13579328\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13456550\", \"upperType\":\"NOUN\", \"term\":\"asynchronous_operation\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13546128\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_16\", \"id\":\"13585704\", \"semPointer\":\"0101\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13456721\", \"upperType\":\"NOUN\", \"term\":\"attack\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13481502\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"00019785\", \"semPointer\":\"0101\", \"upperType\":\"VERB\"}]}}"); add("{\"id\":\"13456943\", \"upperType\":\"NOUN\", \"term\":\"autocatalysis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13465304\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02662401\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13457091\", \"upperType\":\"NOUN\", \"term\":\"autolysis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13530731\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02662723\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13457236\", \"upperType\":\"NOUN\", \"term\":\"automatic_data_processing\", \"synonyms\":[\"ADP\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13476660\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13493544\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"SYNONYM\", \"id\":\"13522063\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13457379\", \"upperType\":\"NOUN\", \"term\":\"autoradiography\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13566585\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13457534\", \"upperType\":\"NOUN\", \"term\":\"autotype\", \"synonyms\":[\"autotypy\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13557997\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02663761\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13457676\", \"upperType\":\"NOUN\", \"term\":\"autoregulation\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13547313\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"UNKNOWN_09\", \"id\":\"06090110\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13457855\", \"upperType\":\"NOUN\", \"term\":\"auxesis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13510240\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02663879\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13457982\", \"upperType\":\"NOUN\", \"term\":\"auxiliary_operation\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13546128\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13458165\", \"upperType\":\"NOUN\", \"term\":\"background_processing\", \"synonyms\":[\"backgrounding\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13562178\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13458354\", \"upperType\":\"NOUN\", \"term\":\"backup\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13446038\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"01481233\", \"semPointer\":\"0104\", \"upperType\":\"VERB\"}]}}"); add("{\"id\":\"13458552\", \"upperType\":\"NOUN\", \"term\":\"bacteriolysis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13530731\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02668039\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13458668\", \"upperType\":\"NOUN\", \"term\":\"bacteriostasis\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13547313\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02668324\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); add("{\"id\":\"13458783\", \"upperType\":\"NOUN\", \"term\":\"basal_metabolic_rate\", \"synonyms\":[\"BMR\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"15305419\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13458926\", \"upperType\":\"NOUN\", \"term\":\"basal_metabolism\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13535517\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13459075\", \"upperType\":\"NOUN\", \"term\":\"batch_processing\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13498665\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13459179\", \"upperType\":\"NOUN\", \"term\":\"beach_erosion\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13496741\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13459261\", \"upperType\":\"NOUN\", \"term\":\"bed-wetting\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13496061\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13459396\", \"upperType\":\"NOUN\", \"term\":\"Bessemer_process\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13519131\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"HYPERNYM\", \"id\":\"13582599\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13459694\", \"upperType\":\"NOUN\", \"term\":\"beta_decay\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13478072\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13459844\", \"upperType\":\"NOUN\", \"term\":\"biochemical_mechanism\", \"synonyms\":[], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13533709\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"}]}}"); add("{\"id\":\"13459990\", \"upperType\":\"NOUN\", \"term\":\"biosynthesis\", \"synonyms\":[\"biogenesis\"], \"dataNounFrames\":{\"list\":[{\"frameType\":\"HYPERNYM\", \"id\":\"13586582\", \"semPointer\":\"0000\", \"upperType\":\"NOUN\"},{\"frameType\":\"ACTION\", \"id\":\"02676072\", \"semPointer\":\"0201\", \"upperType\":\"ADJECTIVE\"},{\"frameType\":\"ACTION\", \"id\":\"02677235\", \"semPointer\":\"0101\", \"upperType\":\"ADJECTIVE\"}]}}"); } private static void add(final String JSON) { DataNoun bean = GsonUtils.toObject(JSON, DataNoun.class); map.put(bean.getId(), bean); } public static DataNoun get(final String ID) { return map.get(ID); } public static boolean has(final String ID) { return map.containsKey(ID); } }
667a2b7aa3aa39c0578f088ccbf47a767b09e7d5
b2cd0236e341660131522587099fadec261ecc30
/app/src/main/java/com/example/studenthelper/FoldersActivity.java
e4499ab581e06994d77530502877210c61ea9d72
[]
no_license
ozzael-codes/StudentHelper
3c4bfccbfb8a6224831f1057ae502b06a5d179d9
0a8899afbdb04bfbd7ad199a3191ac402504f402
refs/heads/master
2021-09-10T19:25:33.189642
2018-03-31T18:13:56
2018-03-31T18:13:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,916
java
package com.example.studenthelper; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; /** * Created by DELL on 3/28/2018. */ public class FoldersActivity extends AppCompatActivity { private EditText mFolderTextField; private Button mAddFolderBtn; private FoldersAdapter mFoldersAdapter; private ArrayList<String> mFoldersList; private GridView mFoldersGrid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_folders_list); SharedPreferences prefs = getSharedPreferences("PREFERENCES", MODE_PRIVATE); final String user_id = prefs.getString("user_id", "null"); // Get GridView reference mFoldersGrid = findViewById(R.id.folder_grid); // Get reference to the database final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("folders/" + user_id); mFoldersList = new ArrayList<>(); // Set values to the GridView ref.orderByKey().addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot folder: dataSnapshot.getChildren()){ mFoldersList.add(folder.child("folder_name").getValue(String.class)); FoldersActivity.this.mFoldersAdapter = new FoldersAdapter(FoldersActivity.this, mFoldersList); FoldersActivity.this.mFoldersGrid.setAdapter(mFoldersAdapter); } } @Override public void onCancelled(DatabaseError databaseError) { } }); // Folder name mFolderTextField = findViewById(R.id.folder_name_field); // Add Folder Button mAddFolderBtn = findViewById(R.id.add_folder_btn); mAddFolderBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String folderName = mFolderTextField.getText().toString().trim(); try { validateFolderName(folderName); } catch (ExceptionHandler e){ Toast.makeText(FoldersActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); return; } // Check if the folder name is already taken ref.orderByKey().addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { boolean found = false; for(DataSnapshot folder: dataSnapshot.getChildren()){ String foundName = folder.child("folder_name").getValue(String.class); if(foundName.equals(folderName)){ found = true; Toast.makeText(FoldersActivity.this, "Folder already exists", Toast.LENGTH_LONG).show(); break; } } if(!found){ // No folder with name exists; Proceed with adding folder addFolder(folderName, ref); if(mFoldersList.isEmpty()){ FoldersActivity.this.mFoldersAdapter = new FoldersAdapter(FoldersActivity.this, mFoldersList); FoldersActivity.this.mFoldersGrid.setAdapter(mFoldersAdapter); } mFoldersList.add(folderName); mFoldersAdapter.notifyDataSetChanged(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); // End of addListenerForSingleValueEvent() } }); // End of Add Folder Button Click Listener mFoldersGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { final String folderClicked = mFoldersGrid.getItemAtPosition(i).toString(); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot folder: dataSnapshot.getChildren()){ DataSnapshot folder_names = folder.child("folder_name"); if(folder_names.getValue(String.class).equals(folderClicked)){ String id = folder.getKey(); Intent ViewFolderPage = new Intent(FoldersActivity.this, ViewFolderContentActivity.class); ViewFolderPage.putExtra("folder_id", id); startActivity(ViewFolderPage); break; } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } }); } private void validateFolderName(String name) throws ExceptionHandler { if(!name.matches("[a-zA-Z0-9 _]*")){ throw new ExceptionHandler("Folder name cannot contain any special characters other than space/underscore"); } else if(name.length() > 15){ throw new ExceptionHandler("Folder name cannot contain more than 15 characters"); } else if(name.length() < 1){ throw new ExceptionHandler("Folder needs a better name"); } } private void addFolder(String name, DatabaseReference dRef){ HashMap<String, String> dataMap = new HashMap<>(); dataMap.put("folder_name", name); dRef.push().setValue(dataMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { // Folder Added if(task.isSuccessful()){ Toast.makeText(FoldersActivity.this, "Folder added", Toast.LENGTH_LONG).show(); } else { Toast.makeText(FoldersActivity.this, "Error adding folder", Toast.LENGTH_LONG).show(); } } }); } private void logout(){ SharedPreferences PREFS = getSharedPreferences("PREFERENCES", MODE_PRIVATE); SharedPreferences.Editor editor = PREFS.edit(); editor.clear(); editor.apply(); } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { //respond to menu item selection switch (item.getItemId()) { case R.id.logout_option: logout(); Intent loginPage = new Intent(this, MainActivity.class); loginPage.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(loginPage); break; } return super.onOptionsItemSelected(item); } } class FoldersAdapter extends BaseAdapter { private ArrayList<String> mList; private Context context; class ViewHolder { TextView folderName; ViewHolder(View v){ folderName = v.findViewById(R.id.single_folder_name); } } FoldersAdapter(Context context, ArrayList<String> foldersList){ this.context = context; this.mList = foldersList; } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int i) { return mList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { View row = view; ViewHolder holder; if(row == null){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.grid_single_folder_item, viewGroup, false); holder = new ViewHolder(row); row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } holder.folderName.setText(mList.get(i)); return row; } }
5516b6953c4fe4eab51722876dbc31b9756340aa
296a47e592b09f488f82d02853de4f4e68a2e868
/common-client/src/main/java/cn/vonfly/common/dto/common/CommonSettleApiConfig.java
ed7b4c443639c9f8cabd3cbdce7147643fb2282f
[]
no_license
f18850017170/common-base-parent
e6b39ffd4e20c0fd591fcdea6cea9a1204ed89d6
ff8a70f655d084bd699ae39586bccb8a36bb649d
refs/heads/master
2020-03-22T08:46:24.955693
2018-07-13T09:22:45
2018-07-13T09:22:45
139,789,979
0
0
null
null
null
null
UTF-8
Java
false
false
1,481
java
package cn.vonfly.common.dto.common; /** * 通用配置参数 */ public class CommonSettleApiConfig { private String serverUrl;// 请求的服务地址 private String appKey;// 请求key private String appSecret;// 请求serect private String appToken;// 请求token private String callbackNotifyUrl;// 回调通知地址 private String publicKeyPath;// 公钥文件路径 private String privateKeyPath;// 私钥文件路径 public String getServerUrl() { return serverUrl; } public void setServerUrl(String serverUrl) { this.serverUrl = serverUrl; } public String getAppKey() { return appKey; } public void setAppKey(String appKey) { this.appKey = appKey; } public String getAppSecret() { return appSecret; } public void setAppSecret(String appSecret) { this.appSecret = appSecret; } public String getAppToken() { return appToken; } public void setAppToken(String appToken) { this.appToken = appToken; } public String getCallbackNotifyUrl() { return callbackNotifyUrl; } public void setCallbackNotifyUrl(String callbackNotifyUrl) { this.callbackNotifyUrl = callbackNotifyUrl; } public String getPublicKeyPath() { return publicKeyPath; } public void setPublicKeyPath(String publicKeyPath) { this.publicKeyPath = publicKeyPath; } public String getPrivateKeyPath() { return privateKeyPath; } public void setPrivateKeyPath(String privateKeyPath) { this.privateKeyPath = privateKeyPath; } }
d752f2b0155568402fd321028e9d9dbd4d20d977
187bfc174997dee5cff5d1fba7242b18a79cf68d
/ArrayList/fnameDsc.java
c3964c1ba6a813928151b34ee46bc3223586461f
[]
no_license
ervikasti/JavaMix
6fe7816ae144787376b4a25e7732213235a43d44
6c3c8ce37f753220e9bc9e113d4e3196e7cf128a
refs/heads/main
2023-03-19T09:12:29.850231
2021-02-24T17:21:22
2021-02-24T17:21:22
341,975,013
0
0
null
null
null
null
UTF-8
Java
false
false
219
java
package ArrayList; import java.util.Comparator; public class fnameDsc implements Comparator<menuCard>{ @Override public int compare(menuCard o1,menuCard o2) { return -1*o1.food.compareTo(o2.food); } }
f662c370f12775917e4b73976343db833b9e3e6a
439d99e4b9e570da768eccdf0c4c37d6dfbd21e3
/Generics/src/LinkedList.java
50330f4c059c27a571bdb15f08a7a75253af83a0
[]
no_license
Ikuni17/CSCI-132
1035ac5d0cd3d91592d19fe69bcf03b429bcde33
1d9f9a8965514458da7255c7ec8f613375d4c65a
refs/heads/master
2021-01-19T07:01:52.534874
2016-09-20T05:40:11
2016-09-20T05:40:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,109
java
/** * * @author Bradley White */ public class LinkedList<E> { // nested Node class private static class Node<E> { private E element; private Node<E> next; public Node(E newElement, Node<E> newLink) { element = newElement; next = newLink; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> newLink) { next = newLink; } } // instance variables private Node<E> head = null; private Node<E> tail = null; private int size = 0; // constructor for empty list public LinkedList() { } // methods // returns size of the list public int size() { return size; } // tests whether the list is empty public boolean isEmpty() { return size == 0; } // returns the first element in the list public E first() { if (isEmpty()) { return null; } return head.getElement(); } // returns the last element in the list public E last() { if (isEmpty()) { return null; } return tail.getElement(); } // adds an element to the front of the list public void addFirst(E newElement) { head = new Node<>(newElement, head); if (size == 0) { tail = head; } size++; } // adds an element to the end of the list public void addLast(E newElement) { Node<E> tempNode = new Node<>(newElement, null); if (isEmpty()) { head = tempNode; } else { tail.setNext(tempNode); } tail = tempNode; size++; } // removes and returns the first element public E removeFirst() { if (isEmpty()) { return null; } E firstNode = head.getElement(); head = head.getNext(); size--; if (size == 0) { tail = null; } return firstNode; } }
b607ea5ed0e1c3fdfe32e34cd22c014805af88b7
62c51bf75a9f46fc8b304e0d33a27836d59efad4
/app/src/main/java/com/cardiomood/hoanglong/tools/SavedTranslatedText.java
33912f8f312604a9a917cd2e8e3ada4bca8c0a55
[]
no_license
longhoang1612/TranslateApp
c7ef9592a1d267637bb36b7521a96843f62fc382
6793d90474d60b073e93a88f86aa2a6766c94b66
refs/heads/master
2022-05-08T09:43:40.772936
2017-10-04T02:50:35
2017-10-04T02:50:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
763
java
package com.cardiomood.hoanglong.tools; import com.cardiomood.hoanglong.db.entity.TranslationHistoryEntity; import java.util.Arrays; import translate.provider.TranslatedText; public class SavedTranslatedText extends TranslatedText { private TranslationHistoryEntity historyItem; public SavedTranslatedText(TranslationHistoryEntity historyItem) { super(historyItem.getSourceLang(), historyItem.getTargetLang(), Arrays.asList(historyItem.getTranslation().split("\\n"))); this.historyItem = historyItem; } public TranslationHistoryEntity getHistoryItem() { return historyItem; } public void setHistoryItem(TranslationHistoryEntity historyItem) { this.historyItem = historyItem; } }
ce97d8fadfce42ccaad782a1ad7c80cfade4f3ad
0e2ae3cc3372b80c92366404e672021cc9e119f6
/semester-2/java/Example.java
49d555cf88421b541369f903b122bd12b33f1c6b
[ "MIT" ]
permissive
saranshbht/bsc-codes
63c933d2f74754aa6136bb80eec6531ce14a5b02
7386c09cc986de9c84947f7dea7db3dc42219a35
refs/heads/master
2022-12-15T01:01:18.379679
2020-08-27T01:24:51
2020-08-27T01:24:51
290,544,479
4
1
MIT
2020-08-27T01:24:52
2020-08-26T16:11:26
Jupyter Notebook
UTF-8
Java
false
false
118
java
class Example { public static void main(String args[]) { System.out.println("This is a simple java program."); } }
90256e3d00bfb48cbff0efd19da446900656316d
9117c0da4cd7ce47fef60200370fb8a8c6c6eab6
/SeaBattle3/src/ua/kpi/tef/controller/Controller.java
6b9dd88a6a3c6ca5f83ab436b30e4049740b26f3
[]
no_license
diana5712/SeaBattle3_4
894af365a91893531ea02971043cd665c51f9cc3
eb791058439fef61dca6fed7c3197cb74fbb9ae4
refs/heads/master
2021-01-11T14:55:42.895607
2017-01-27T22:43:58
2017-01-27T22:43:58
80,252,289
0
0
null
null
null
null
UTF-8
Java
false
false
29,755
java
package ua.kpi.tef.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.stage.Modality; import javafx.stage.Stage; import ua.kpi.tef.model.Algorithm; import ua.kpi.tef.model.Coordinate; import ua.kpi.tef.model.Field; import ua.kpi.tef.model.Ship; import ua.kpi.tef.view.View; import java.io.IOException; import java.util.Random; public class Controller { @FXML Canvas canvas1; @FXML Canvas canvas2; @FXML Label lettersLabel1; @FXML Label lettersLabel2; @FXML Label numbersLabel1; @FXML Label numbersLabel2; @FXML Button hintCanvas1; @FXML Button hintCanvas2; @FXML TextArea messageArea; public void setCheckShipSize1(boolean checkShipSize) { this.checkShipSize1.setSelected(checkShipSize); } public void setCheckShipSize2(boolean checkShipSize) { this.checkShipSize2.setSelected(checkShipSize); } public void setCheckShipSize3(boolean checkShipSize) { this.checkShipSize3.setSelected(checkShipSize); } public void setCheckShipSize4(boolean checkShipSize) { this.checkShipSize4.setSelected(checkShipSize); } @FXML RadioButton checkShipSize1; @FXML RadioButton checkShipSize2; @FXML RadioButton checkShipSize3; @FXML RadioButton checkShipSize4; @FXML Label shipSize1Amount; @FXML Label shipSize2Amount; @FXML Label shipSize3Amount; @FXML Label shipSize4Amount; @FXML Button applyButton; public int getShipSize1Amount() { return Integer.parseInt(shipSize1Amount.getText()); } public void setShipSize1Amount(int shipSize1Amount) { this.shipSize1Amount.setText(shipSize1Amount+""); } public int getShipSize2Amount() { return Integer.parseInt(shipSize2Amount.getText()); } public void setShipSize2Amount(int shipSize2Amount) { this.shipSize2Amount.setText(shipSize2Amount+""); } public int getShipSize3Amount() { return Integer.parseInt(shipSize3Amount.getText()); } public void setShipSize3Amount(int shipSize3Amount) { this.shipSize3Amount.setText(shipSize3Amount+""); } public int getShipSize4Amount() { return Integer.parseInt(shipSize4Amount.getText()); } public void setShipSize4Amount(int shipSize4Amount) { this.shipSize4Amount.setText(shipSize4Amount+""); } public Button getHintCanvas2() { return hintCanvas2; } public Button getHintCanvas1() { return hintCanvas1; } private Stage mainStage; //player mode form private Parent fxmlPlayerMode; private Parent fxmlWinnerMode; private Stage PlayerModeStage; private Stage winnerStage; int c = 0; ToggleGroup buttonGroup = new ToggleGroup(); Algorithm algorithm = new Algorithm(canvas1,canvas2,this); WinnerController win_contr; int counterViewBut1 = 2; int counterViewBut2 = 2; public void setMainStage(Stage mainStage) { this.mainStage = mainStage; } private void initLoader() { try { FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource("../fxml/PlayerMode.fxml")); Parent fxmlPlayerMode = (Parent) fxmlLoader.load(); PlayerModeController contr = fxmlLoader.getController(); contr.setLabels(lettersLabel1,lettersLabel2,hintCanvas1,hintCanvas2); PlayerModeStage = new Stage(); PlayerModeStage.setTitle("Choose mode"); PlayerModeStage.setResizable(false); PlayerModeStage.initOwner(mainStage); PlayerModeStage.initModality(Modality.APPLICATION_MODAL); PlayerModeStage.setScene(new Scene(fxmlPlayerMode, PlayerModeStage.getWidth(), PlayerModeStage.getHeight())); PlayerModeStage.hide(); FXMLLoader fxmlLoader2 = new FXMLLoader( getClass().getResource("../fxml/Winner.fxml")); Parent fxmlWinnerMode = (Parent) fxmlLoader2.load(); win_contr= fxmlLoader2.getController(); winnerStage = new Stage(); winnerStage.setTitle("Congratulations!"); winnerStage.setResizable(false); winnerStage.initOwner(mainStage); winnerStage.initModality(Modality.APPLICATION_MODAL); winnerStage.setScene(new Scene(fxmlWinnerMode, winnerStage.getWidth(), winnerStage.getHeight())); winnerStage.hide(); } catch (IOException e) { e.printStackTrace(); } } @FXML public void initialize(){ initLoader(); Algorithm.selectFieldMode(PlayerModeController.fieldMode,lettersLabel1,lettersLabel2); View.drawField(canvas1.getGraphicsContext2D()); View.drawField(canvas2.getGraphicsContext2D()); checkShipSize1.setToggleGroup(buttonGroup); checkShipSize2.setToggleGroup(buttonGroup); checkShipSize3.setToggleGroup(buttonGroup); checkShipSize4.setToggleGroup(buttonGroup); hintCanvas1.setVisible(false); hintCanvas2.setVisible(false); applyButton.setVisible(false); } @FXML public void startGame(){ checkShipSize4.setSelected(true); hintCanvas1.setVisible(true); hintCanvas2.setVisible(false); applyButton.setVisible(true); hideShips(canvas1); hideShips(canvas2); setShipsAmount(); if(c != 0){ canvas1.removeEventFilter(MouseEvent.MOUSE_CLICKED, Algorithm.filter); canvas2.removeEventFilter(MouseEvent.MOUSE_CLICKED, Algorithm.filter); algorithm.flag = false; } c++; algorithm = new Algorithm(canvas1, canvas2, this); PlayerModeStage.show(); messageArea.setText(messageArea.getText() + "\nPlayer 1: set your ships, please!"); algorithm.mouseClick(canvas1,algorithm.getField1(), applyButton, messageArea); } private void setShipsAmount(){ shipSize1Amount.setText("4"); shipSize2Amount.setText("3"); shipSize3Amount.setText("2"); shipSize4Amount.setText("1"); } public void hideShips(Canvas canvas){ GraphicsContext gc = canvas.getGraphicsContext2D(); gc.clearRect(0, 0, 300, 300); View.drawField(canvas.getGraphicsContext2D()); } @FXML public void viewShips1(){ if(counterViewBut1 % 2 == 0) { hideShips(canvas1); algorithm.recoverCanvas(canvas1, algorithm.getField1(), applyButton); if(!applyButton.isVisible()) { canvas2.setDisable(true); } //System.out.println(counterViewBut1); counterViewBut1++; } else{ hideShips(canvas1); if(!applyButton.isVisible()){ canvas2.setDisable(false); algorithm.returnToGame(canvas1, algorithm.getField1()); } //System.out.println(counterViewBut1); counterViewBut1++; } } @FXML public void viewShips2(){ if(counterViewBut2 % 2 == 0) { hideShips(canvas2); algorithm.recoverCanvas(canvas2, algorithm.getField2(), applyButton); if(!applyButton.isVisible()) { canvas1.setDisable(true); } //System.out.println(counterViewBut2); counterViewBut2++; } else{ hideShips(canvas2); if(!applyButton.isVisible()) { canvas1.setDisable(false); algorithm.returnToGame(canvas2, algorithm.getField2()); } //System.out.println(counterViewBut2); counterViewBut2++; } } @FXML public void applyShipLocation(){ if(algorithm.getField1().getShipsList().size() <= 10 && algorithm.getField2().getShipsList().size()==0) { if(locateShips(algorithm.getField1())){ hideShips(canvas1); getHintCanvas1().setVisible(false); getHintCanvas2().setVisible(true); if(PlayerModeController.playerMode.equals(View.COMPUTER_MODE)) { applyButton.setVisible(false); getHintCanvas2().setVisible(false); setRandomShips(); setCheckShipSize4(false); } else{ setShipsAmount(); messageArea.setText(messageArea.getText()+"\nPlayer 2: set your ships, please!"); algorithm.mouseClick(algorithm.getField2().getCanvas(), algorithm.getField2(), applyButton, messageArea); } } } else if (algorithm.getField2().getShipsList().size() != 0) { if(locateShips(algorithm.getField2())) { hideShips(canvas2); setCheckShipSize4(false); applyButton.setVisible(false); } } if(!applyButton.isVisible()){ algorithm.getField1().getDisableSquaresList().removeAll(algorithm.getField1().getDisableSquaresList()); algorithm.getField2().getDisableSquaresList().removeAll(algorithm.getField2().getDisableSquaresList()); startShootGame(); } } public boolean locateShips(Field field){ if(shipSize1Amount.getText().equals("0") && shipSize2Amount.getText().equals("0") && shipSize3Amount.getText().equals("0") && shipSize4Amount.getText().equals("0")) { messageArea.setText(messageArea.getText() + "\nShips located!"); return true; } else messageArea.setText(messageArea.getText()+"\nLess than 10 ships!"); return false; } public void startShootGame(){ algorithm.mouseClick(algorithm.getField2().getCanvas(), algorithm.getField2(), applyButton, messageArea); getHintCanvas1().setVisible(true); getHintCanvas2().setVisible(false); } public void setRandomShips(){ GraphicsContext context = algorithm.getField2().getCanvas().getGraphicsContext2D(); Random random = new Random(); Field field = algorithm.getField2(); Ship ship; switch (random.nextInt(2)){ case 1: //4 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(0,0)); ship.getCoordinateList().add(new Coordinate(0,30)); ship.getCoordinateList().add(new Coordinate(0,60)); ship.getCoordinateList().add(new Coordinate(0,90)); setAutoShip(field,ship); //3.1 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(60,0)); ship.getCoordinateList().add(new Coordinate(60,30)); ship.getCoordinateList().add(new Coordinate(60,60)); setAutoShip(field,ship); //3.2 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(60,120)); ship.getCoordinateList().add(new Coordinate(60,150)); ship.getCoordinateList().add(new Coordinate(60,180)); setAutoShip(field,ship); //2.1 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(0,150)); ship.getCoordinateList().add(new Coordinate(0,180)); setAutoShip(field,ship); //2.2 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(0,240)); ship.getCoordinateList().add(new Coordinate(0,270)); setAutoShip(field,ship); //2.3 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(60,240)); ship.getCoordinateList().add(new Coordinate(60,270)); setAutoShip(field,ship); for(int i = 0; i <4;i++){ Coordinate coord = new Coordinate((random.nextInt(6)+4)*30,random.nextInt(10)*30); if(field.belongDisableSquaresList(coord)) i--; else { ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(coord); setAutoShip(field, ship); } } break; case 2: //4 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(270,0)); ship.getCoordinateList().add(new Coordinate(240,0)); ship.getCoordinateList().add(new Coordinate(210,0)); ship.getCoordinateList().add(new Coordinate(180,0)); setAutoShip(field,ship); //3.1 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(210,270)); ship.getCoordinateList().add(new Coordinate(240,270)); ship.getCoordinateList().add(new Coordinate(270,270)); setAutoShip(field,ship); //3.2 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(0,270)); ship.getCoordinateList().add(new Coordinate(30,270)); ship.getCoordinateList().add(new Coordinate(60,270)); setAutoShip(field,ship); //2.1 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(0,0)); ship.getCoordinateList().add(new Coordinate(30,0)); setAutoShip(field,ship); //2.2 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(90,0)); ship.getCoordinateList().add(new Coordinate(120,0)); setAutoShip(field,ship); //2.3 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(120,270)); ship.getCoordinateList().add(new Coordinate(150,270)); setAutoShip(field,ship); for(int i = 0; i <4;i++){ Coordinate coord = new Coordinate(random.nextInt(10)*30,(random.nextInt(7)+2)*30); if(field.belongDisableSquaresList(coord)) i--; else { ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(coord); setAutoShip(field, ship); algorithm.checkRestrict(ship,field,context, false); } } break; default: //4 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(0,0)); ship.getCoordinateList().add(new Coordinate(0,30)); ship.getCoordinateList().add(new Coordinate(0,60)); ship.getCoordinateList().add(new Coordinate(0,90)); setAutoShip(field,ship); //3.1 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(0,150)); ship.getCoordinateList().add(new Coordinate(0,180)); ship.getCoordinateList().add(new Coordinate(0,210)); setAutoShip(field,ship); //3.2 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(60,0)); ship.getCoordinateList().add(new Coordinate(90,0)); ship.getCoordinateList().add(new Coordinate(120,0)); setAutoShip(field,ship); //2.1 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(0,270)); ship.getCoordinateList().add(new Coordinate(30,270)); setAutoShip(field,ship); //2.2 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(180,0)); ship.getCoordinateList().add(new Coordinate(210,0)); setAutoShip(field,ship); //2.3 ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(new Coordinate(270,0)); ship.getCoordinateList().add(new Coordinate(270,30)); setAutoShip(field,ship); for(int i = 0; i <4;i++){ Coordinate coord = new Coordinate((random.nextInt(7)+3)*30,(random.nextInt(7)+3)*30); if(field.belongDisableSquaresList(coord)) i--; else { ship = new Ship(1, Color.AQUA); ship.getCoordinateList().add(coord); setAutoShip(field, ship); algorithm.checkRestrict(ship,field,context, false); } } break; } } public void computerShot(){ boolean flag = true; Random rand = new Random(); Coordinate coor = new Coordinate(rand.nextInt(10) * 30, rand.nextInt(10) * 30); while (algorithm.getField1().belongDisableSquaresList(coor)) coor = new Coordinate(rand.nextInt(10) * 30, rand.nextInt(10) * 30); po: while(flag) { System.out.println("inside flag = true"); po1: if (algorithm.getField1().belongShipList(coor)) { System.out.println("Попали "+coor.getX()+" "+coor.getY()); po3: for (int i = 0; i < algorithm.getField1().getShipsList().size(); i++) { System.out.println("проходимся по всіх кораблях "+i); Ship _ship = algorithm.getField1().getShipsList().get(i); po2: for (int j = 0; j < _ship.getCoordinateList().size(); j++) { System.out.println("проходимось по всых координатах корабля "+ j); Coordinate _coord = _ship.getCoordinateList().get(j); po5: if (_coord.getX() == coor.getX() && _coord.getY() == coor.getY()) {//якщо на місці координати є корабель System.out.println("найшли координату"); canvas1.getGraphicsContext2D().setFill(Color.RED); //synchronized (canvas1){ //try { // Thread.sleep(2000); //} catch (InterruptedException e) { //} // } canvas1.getGraphicsContext2D().fillRect(coor.getX(), coor.getY(), 30, 30); po4: System.out.println("Перевірка вбили чи ранили"); for (int k = 0; k < algorithm.getField1().getKilledShipsList().size(); k++) { System.out.println(i+"вбитий корабель"); Ship killedShip = algorithm.getField1().getKilledShipsList().get(k); if (algorithm.isNearShip(killedShip, coor)) { System.out.println("Поруч є вбитий корабель, значить ранили, тому адд до нього коорд"); killedShip.getCoordinateList().add(coor); algorithm.getField1().getDisableSquaresList().add(coor); //якзо поруч нема кораблыв, значить вбитий ы рестррікт поставати, інакше int p=0; for(p =0;p<4;p++){ coor = getNearCoordinate(coor); if(algorithm.getField1().belongDisableSquaresList(coor) || ((coor.getX()<0 || coor.getX()>=300)&& (coor.getY()<0 || coor.getY()>=300))) p++; else { System.out.println("Координата поруч: "+coor.getX()+" "+coor.getY()); break; } } if(p==4){//значить не знайшли поруч координату coor = new Coordinate(rand.nextInt(10)*30,rand.nextInt(10)*30); while (algorithm.getField1().belongDisableSquaresList(coor)) coor = new Coordinate(rand.nextInt(10)*30,rand.nextInt(10)*30); System.out.println("Координата поруч: "+coor.getX()+" "+coor.getY()); algorithm.checkRestrict(killedShip,algorithm.getField1(),canvas1.getGraphicsContext2D(),true); } // coor = getNearCoordinate(coor); // while (algorithm.getField1().belongDisableSquaresList(coor)) // coor = getNearCoordinate(coor); // System.out.println("Координата поруч: "+coor.getX()+" "+coor.getY()); break po5; } // System.out.println("wondered or deaded"); // if (algorithm.isNearShipNotBelongKilledArray(killedShip, coor, algorithm.getField1())) { // System.out.println("wonded"); // flag = true; // getNearCoordinate(coor); // while (algorithm.getField1().belongDisableSquaresList(coor)) // getNearCoordinate(coor); // //coor set new value как- то перейти на po1 // break; // } // algorithm.checkRestrict(killedShip, algorithm.getField1(), canvas1.getGraphicsContext2D(), true); // System.out.println("deaded"); // algorithm.getField1().setKilled(algorithm.getField1().getKilled() + 1); // flag = true; // coor = new Coordinate(rand.nextInt(10),rand.nextInt(10)); // while (algorithm.getField1().belongDisableSquaresList(coor)) // coor = new Coordinate(rand.nextInt(10),rand.nextInt(10)); // break; // } // } // if(flag==false) { // Ship ship = new Ship(new Random().nextInt(), Color.AQUA); // ship.getCoordinateList().add(coor); // algorithm.getField1().getKilledShipsList().add(ship); // System.out.println("created"); // if (algorithm.isNearShipNotBelongKilledArray(ship, coor, algorithm.getField1())) { // System.out.println("wonded"); // flag = true; // //coor set new value как- то перейти на po1 // getNearCoordinate(coor); // while (algorithm.getField1().belongDisableSquaresList(coor)) // getNearCoordinate(coor); // break; // }else { // algorithm.checkRestrict(ship, algorithm.getField1(), canvas1.getGraphicsContext2D(), true); // System.out.println("deaded"); // algorithm.getField1().setKilled(algorithm.getField1().getKilled() + 1); // flag = true; // coor = new Coordinate(rand.nextInt(10),rand.nextInt(10)); // while (algorithm.getField1().belongDisableSquaresList(coor)) // coor = new Coordinate(rand.nextInt(10),rand.nextInt(10));//coor set new value как- то перейти на po // break; // } } System.out.println("якщо ми тут, значить поруч вбитих нема"); Ship ship = new Ship(new Random().nextInt(), Color.AQUA); ship.getCoordinateList().add(coor); algorithm.getField1().getKilledShipsList().add(ship); algorithm.getField1().getDisableSquaresList().add(coor); System.out.println("перша палуба вбитого"); //якзо поруч нема кораблыв, значить вбитий ы рестррікт поставати, інакше int p=0; for(p =0;p<4;p++){ coor = getNearCoordinate(coor); if(algorithm.getField1().belongDisableSquaresList(coor) || ((coor.getX()<0 || coor.getX()>300)&& (coor.getY()<0 || coor.getY()>300))) p++; else { System.out.println("Координата поруч: "+coor.getX()+" "+coor.getY()); break; } } if(p==4){//значить не знайшли поруч координату coor = new Coordinate(rand.nextInt(10)*30,rand.nextInt(10)*30); while (algorithm.getField1().belongDisableSquaresList(coor)) coor = new Coordinate(rand.nextInt(10)*30,rand.nextInt(10)*30); System.out.println("Координата поруч: "+coor.getX()+" "+coor.getY()); algorithm.checkRestrict(ship,algorithm.getField1(),canvas1.getGraphicsContext2D(),true); } flag = true; break po3; } System.out.println(" не найшли координату"); } } } else { System.out.println("промазали "+coor.getX()+" "+coor.getY()); flag = false; algorithm.getField1().getDisableSquaresList().add(coor); canvas1.getGraphicsContext2D().setFill(Color.GREY); canvas1.getGraphicsContext2D().fillOval(coor.getX() + 15 - 4, coor.getY() + 15 - 4, 8, 8); } } algorithm.mouseClick(algorithm.getField2().getCanvas(), algorithm.getField2(), applyButton, messageArea); System.out.println("ставим 2"); } public void setAutoShip(Field field,Ship ship){ field.getShipsList().add(ship); for (Coordinate coor:ship.getCoordinateList()) { field.getDisableSquaresList().add(coor); } } public void setWinner(String winner){ hintCanvas1.setVisible(false); hintCanvas2.setVisible(false); win_contr.setWinnerLabel(winner); winnerStage.show(); } public Coordinate getNearCoordinate(Coordinate coordinate){ Random random = new Random(); switch (random.nextInt(4)){ case 1: return new Coordinate(coordinate.getX(),coordinate.getY()+30); case 2: return new Coordinate(coordinate.getX(),coordinate.getY()-30); case 3: return new Coordinate(coordinate.getX()+30,coordinate.getY()); default: return new Coordinate(coordinate.getX()-30,coordinate.getY()); } } }
b07933d170108f50f6d5a42c59086029575bae8e
7b02ce34bb331e80c235bb351f40bb6f9d46c2e0
/sla/clientes/forms/FormAlterarCliente.java
16f937951a4b1e482df6958cd1587ec852b0d08b
[]
no_license
CarlosFFBS/Tsw
5351e6d3e173ad5befd62afde20e4a3fe1b6d9b0
75e617ac877992d780f67019d77ff4ad8ca447b3
refs/heads/master
2020-04-22T19:07:12.515654
2019-05-10T20:35:08
2019-05-10T20:35:08
170,598,454
0
0
null
null
null
null
UTF-8
Java
false
false
44,852
java
package sla.clientes.forms; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.text.MaskFormatter; import sla.clientes.ClientePessoaFisica; import sla.clientes.ClientePessoaJuridica; import sla.clientes.NegocioCliente; import sla.operacoes.Operacao; /** * * @author Consultor SCA 02 */ public class FormAlterarCliente extends javax.swing.JFrame { ClientePessoaFisica pf; ClientePessoaJuridica pj; MaskFormatter mascaraCPF; MaskFormatter mascaraCNPJ; String textoCpf; String textoNome; String textoCNPJ; String razaoSocial; String textoTelefone; String textoCEP; String logradouro; String numeroLogradouro; String complemento; String bairro; String cidade; String estado; String email; /** * Creates new form FormAlterarCliente */ public FormAlterarCliente() { initComponents(); try { jTextFieldCodCliente.setEnabled(false); jTextFieldCpfCnpj.setEnabled(false); jTextFieldNomeRazaoSocial.setEnabled(false); jTextFieldTelefone.setEnabled(false); jTextFieldCep.setEnabled(false); jTextFieldEndereco.setEnabled(false); jTextFieldNumeroEndereco.setEnabled(false); jTextFieldComplemento.setEnabled(false); jTextFieldBairro.setEnabled(false); jTextFieldCidade.setEnabled(false); jTextFieldUF.setEnabled(false); jTextFieldEmail.setEnabled(false); jTextFieldSexo.setEnabled(false); mascaraCPF = new MaskFormatter("###.###.###-##"); mascaraCNPJ = new MaskFormatter("##.###.###/####-##"); //RecebeJtablePJ(69); //mascaracep = new MaskFormatter("##.###-###"); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabelcomplemento = new javax.swing.JLabel(); jLabelbairro = new javax.swing.JLabel(); jLabelemail = new javax.swing.JLabel(); jLabelOperacaoCpfCNPJ = new javax.swing.JLabel(); jLabelOperacaoNomeRazaoSocial = new javax.swing.JLabel(); jLabeltelefoneCliente = new javax.swing.JLabel(); jLabelenderecoCliente = new javax.swing.JLabel(); jLabelSexoCliente = new javax.swing.JLabel(); jLabelcepCliente = new javax.swing.JLabel(); jLabelcidade = new javax.swing.JLabel(); jLabelnumeroEndereco = new javax.swing.JLabel(); jLabel1UF = new javax.swing.JLabel(); jTextFieldNumeroEndereco = new javax.swing.JTextField(); jTextFieldComplemento = new javax.swing.JTextField(); jTextFieldBairro = new javax.swing.JTextField(); jTextFieldCidade = new javax.swing.JTextField(); jTextFieldEmail = new javax.swing.JTextField(); jTextFieldUF = new javax.swing.JTextField(); jTextFieldCep = new javax.swing.JTextField(); jTextFieldEndereco = new javax.swing.JTextField(); jTextFieldSexo = new javax.swing.JTextField(); jTextFieldNomeRazaoSocial = new javax.swing.JTextField(); jTextFieldCpfCnpj = new javax.swing.JTextField(); jTextFieldTelefone = new javax.swing.JTextField(); jLabelMensagemInicial = new javax.swing.JLabel(); jFormattedTextFieldOperacaoNovoCpfCnpj = new javax.swing.JFormattedTextField(); jTextFieldNovouf = new javax.swing.JTextField(); jLabelEXUF = new javax.swing.JLabel(); jTextFieldNovobairro = new javax.swing.JTextField(); jTextFieldNovoemail = new javax.swing.JTextField(); jTextFieldNovocidade = new javax.swing.JTextField(); jTextFieldOperacaoNovoNomeRazaoSocial = new javax.swing.JTextField(); jFormattedTextFieldNovotelefoneCliente = new javax.swing.JFormattedTextField(); jTextFieldNovoEnderecoCliente = new javax.swing.JTextField(); jTextFieldNovonumeroEndereco = new javax.swing.JTextField(); jTextFieldNovocomplemento = new javax.swing.JTextField(); jButtonAtualizar = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jTextFieldCodCliente = new javax.swing.JTextField(); jFormattedTextFieldNovocepCliente = new javax.swing.JFormattedTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabelcomplemento.setText("COMPLEMENTO"); jLabelbairro.setText("BAIRRO"); jLabelemail.setText("EMAIL"); jLabelOperacaoCpfCNPJ.setText("CPF"); jLabelOperacaoNomeRazaoSocial.setText("NOME"); jLabeltelefoneCliente.setText("TELEFONE"); jLabelenderecoCliente.setText("ENDEREÇO"); jLabelSexoCliente.setText("SEXO"); jLabelcepCliente.setText("CEP"); jLabelcidade.setText("CIDADE"); jLabelnumeroEndereco.setText("NUMERO"); jLabel1UF.setText("UF"); jLabelMensagemInicial.setText("PREENCHA APENAS OS CAMPOS QUE DEVEM SER ATUALIZADOS"); jTextFieldNovouf.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextFieldNovoufKeyTyped(evt); } }); jLabelEXUF.setText("Ex: SP"); try { jFormattedTextFieldNovotelefoneCliente.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)#.####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jFormattedTextFieldNovotelefoneCliente.setText("( )9. - "); jButtonAtualizar.setText("ATUALIZAR"); jButtonAtualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAtualizarActionPerformed(evt); } }); jLabel2.setText("COD"); jFormattedTextFieldNovocepCliente.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jFormattedTextFieldNovocepClienteKeyTyped(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabelcepCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelenderecoCliente) .addComponent(jLabeltelefoneCliente) .addComponent(jLabelbairro) .addComponent(jLabelemail) .addComponent(jLabelnumeroEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelSexoCliente) .addComponent(jLabel1UF) .addComponent(jLabelcomplemento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelcidade) .addComponent(jLabelOperacaoNomeRazaoSocial, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel2)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(368, 368, 368) .addComponent(jButtonAtualizar) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(46, 46, 46) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldUF, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextFieldBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldNomeRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldNumeroEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldComplemento, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextFieldCep, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE) .addComponent(jTextFieldTelefone, javax.swing.GroupLayout.Alignment.LEADING)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextFieldCodCliente, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE) .addComponent(jTextFieldCpfCnpj, javax.swing.GroupLayout.Alignment.LEADING))) .addComponent(jTextFieldCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldSexo, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldNovoemail) .addComponent(jTextFieldNovoEnderecoCliente) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextFieldNovocomplemento, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) .addComponent(jTextFieldNovonumeroEndereco) .addComponent(jTextFieldNovobairro, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jFormattedTextFieldNovotelefoneCliente, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jTextFieldNovouf, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabelEXUF)) .addComponent(jTextFieldOperacaoNovoNomeRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldNovocidade, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFormattedTextFieldOperacaoNovoCpfCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFormattedTextFieldNovocepCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 53, Short.MAX_VALUE)))))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabelOperacaoCpfCNPJ)) .addGroup(layout.createSequentialGroup() .addGap(242, 242, 242) .addComponent(jLabelMensagemInicial))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabelMensagemInicial) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldCodCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelOperacaoCpfCNPJ) .addComponent(jTextFieldCpfCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFormattedTextFieldOperacaoNovoCpfCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldNomeRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldOperacaoNovoNomeRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelOperacaoNomeRazaoSocial)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabeltelefoneCliente) .addComponent(jFormattedTextFieldNovotelefoneCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldCep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelcepCliente) .addComponent(jFormattedTextFieldNovocepCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(14, 14, 14) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelenderecoCliente) .addComponent(jTextFieldEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldNovoEnderecoCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelnumeroEndereco) .addComponent(jTextFieldNumeroEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldNovonumeroEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelcomplemento) .addComponent(jTextFieldComplemento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldNovocomplemento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldBairro, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelbairro) .addComponent(jTextFieldNovobairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelcidade) .addComponent(jTextFieldNovocidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1UF) .addComponent(jTextFieldUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldNovouf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelEXUF)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelemail) .addComponent(jTextFieldNovoemail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelSexoCliente) .addComponent(jTextFieldSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButtonAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextFieldNovoufKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldNovoufKeyTyped // Teste de uso de eventos para limitar o campo estado somente com caracteres e com limite de 2 caracteres para o estado. char c = evt.getKeyChar(); if (!(Character.isAlphabetic(c)) || c == ' ') { evt.consume(); } int numerocaracter = 2; if (jTextFieldNovouf.getText().length() >= numerocaracter) { evt.consume(); } }//GEN-LAST:event_jTextFieldNovoufKeyTyped private void jButtonAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAtualizarActionPerformed NegocioCliente cliente = new NegocioCliente(); Operacao op = new Operacao(); if (jLabelOperacaoCpfCNPJ.getText().equals("CPF")) { try { pf = new ClientePessoaFisica(); pf.setCli_Codigo(Integer.parseInt(jTextFieldCodCliente.getText())); pf.setCli_Cpf(jTextFieldCpfCnpj.getText()); pf.setNome(jTextFieldNomeRazaoSocial.getText()); pf.setTelefone(jTextFieldTelefone.getText()); pf.setCep(jTextFieldCep.getText()); pf.setLogradouro(jTextFieldEndereco.getText()); pf.setNumeroLogradouro(jTextFieldNumeroEndereco.getText()); pf.setComplemento(jTextFieldComplemento.getText()); pf.setBairro(jTextFieldBairro.getText()); pf.setCidade(jTextFieldCidade.getText()); pf.setEstado(jTextFieldUF.getText()); pf.setEmail(jTextFieldEmail.getText()); pf.setSexo(jTextFieldSexo.getText()); textoCpf = jFormattedTextFieldOperacaoNovoCpfCnpj.getText().trim(); if (textoCpf.charAt(0) != '.') { pf.setCli_Cpf(jFormattedTextFieldOperacaoNovoCpfCnpj.getText()); } textoNome = jTextFieldOperacaoNovoNomeRazaoSocial.getText().trim(); if (textoNome.isEmpty() == false) { pf.setNome(jTextFieldOperacaoNovoNomeRazaoSocial.getText()); } textoTelefone = jFormattedTextFieldNovotelefoneCliente.getText(); if (textoTelefone.charAt(1) != ' ') { pf.setTelefone(jFormattedTextFieldNovotelefoneCliente.getText()); } try { textoCEP = jFormattedTextFieldNovocepCliente.getText(); if (textoCEP != null && textoCEP.length() == 8) { textoCEP = op.formataCEP(jFormattedTextFieldNovocepCliente.getText()); pf.setCep(textoCEP); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); } logradouro = jTextFieldNovoEnderecoCliente.getText(); if (logradouro != null && logradouro.isEmpty() == false) { pf.setLogradouro(jTextFieldNovoEnderecoCliente.getText().trim()); } numeroLogradouro = jTextFieldNovonumeroEndereco.getText(); if (numeroLogradouro != null && numeroLogradouro.isEmpty() == false) { pf.setNumeroLogradouro(numeroLogradouro.trim()); } complemento = jTextFieldNovocomplemento.getText(); if (complemento != null && complemento.isEmpty() == false) { pf.setComplemento(complemento.trim()); } bairro = jTextFieldNovobairro.getText(); if (bairro != null && bairro.isEmpty() == false) { pf.setBairro(bairro.trim()); } cidade = jTextFieldNovocidade.getText(); if (cidade != null && cidade.isEmpty() == false) { pf.setCidade(cidade.trim()); } estado = jTextFieldNovouf.getText(); if (estado != null && estado.isEmpty() == false) { pf.setEstado(estado.trim()); } email = jTextFieldNovoemail.getText(); if (email != null && email.isEmpty() == false) { pf.setEmail(email.trim()); } try { cliente.alterarClientePF(pf); jTextFieldCodCliente.setText(String.valueOf(pf.getCli_Codigo())); jTextFieldCpfCnpj.setText(pf.getCli_Cpf()); jTextFieldNomeRazaoSocial.setText(pf.getNome()); jTextFieldTelefone.setText(pf.getTelefone()); jTextFieldCep.setText(pf.getCep()); jTextFieldEndereco.setText(pf.getLogradouro()); jTextFieldNumeroEndereco.setText(pf.getNumeroLogradouro()); jTextFieldComplemento.setText(pf.getComplemento()); jTextFieldBairro.setText(pf.getBairro()); jTextFieldCidade.setText(pf.getCidade()); jTextFieldUF.setText(pf.getEstado()); jTextFieldEmail.setText(pf.getEmail()); jTextFieldSexo.setText(pf.getSexo()); JOptionPane.showMessageDialog(null, "Cliente atualizado com sucesso."); jFormattedTextFieldOperacaoNovoCpfCnpj.setText(""); jTextFieldOperacaoNovoNomeRazaoSocial.setText(""); jFormattedTextFieldNovotelefoneCliente.setText(""); jFormattedTextFieldNovocepCliente.setText(""); jTextFieldNovoEnderecoCliente.setText(""); jTextFieldNovonumeroEndereco.setText(""); jTextFieldNovocomplemento.setText(""); jTextFieldNovobairro.setText(""); jTextFieldNovocidade.setText(""); jTextFieldNovouf.setText(""); jTextFieldNovoemail.setText(""); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); jFormattedTextFieldOperacaoNovoCpfCnpj.setText(""); jTextFieldOperacaoNovoNomeRazaoSocial.setText(""); jFormattedTextFieldNovotelefoneCliente.setText(""); jFormattedTextFieldNovocepCliente.setText(""); jTextFieldNovoEnderecoCliente.setText(""); jTextFieldNovonumeroEndereco.setText(""); jTextFieldNovocomplemento.setText(""); jTextFieldNovobairro.setText(""); jTextFieldNovocidade.setText(""); jTextFieldNovouf.setText(""); jTextFieldNovoemail.setText(""); } } catch (NullPointerException ez) { //Possibilidade de tratamento de fluxo de exceções para cada campo nulo específico, pois os campos //foram declarados como variáveis globais. if (textoCpf == null) { JOptionPane.showMessageDialog(null, " Valor nulo para o cpf informado. Preencha o campo e tente novamente"); } } } if (jLabelOperacaoCpfCNPJ.getText().equals("CNPJ")) { try { pj = new ClientePessoaJuridica(); pj.setCli_Codigo(Integer.parseInt(jTextFieldCodCliente.getText())); pj.setCli_Cnpj(jTextFieldCpfCnpj.getText()); pj.setRazaoSocial(jTextFieldNomeRazaoSocial.getText()); pj.setTelefone(jTextFieldTelefone.getText()); pj.setCep(jTextFieldCep.getText()); pj.setLogradouro(jTextFieldEndereco.getText()); pj.setNumeroLogradouro(jTextFieldNumeroEndereco.getText()); pj.setComplemento(jTextFieldComplemento.getText()); pj.setBairro(jTextFieldBairro.getText()); pj.setCidade(jTextFieldCidade.getText()); pj.setEstado(jTextFieldUF.getText()); pj.setEmail(jTextFieldEmail.getText()); textoCNPJ = jFormattedTextFieldOperacaoNovoCpfCnpj.getText(); if (textoCNPJ.charAt(0) != ' ') { pj.setCli_Cnpj(textoCNPJ); } razaoSocial = jTextFieldOperacaoNovoNomeRazaoSocial.getText(); if (razaoSocial != null && razaoSocial.isEmpty() == false) { pj.setRazaoSocial(razaoSocial.trim()); } textoTelefone = jFormattedTextFieldNovotelefoneCliente.getText(); if (textoTelefone.charAt(1) != ' ') { pj.setTelefone(jFormattedTextFieldNovotelefoneCliente.getText()); } try { textoCEP = jFormattedTextFieldNovocepCliente.getText(); if (textoCEP != null && textoCEP.length() == 8) { textoCEP = op.formataCEP(textoCEP); pj.setCep(textoCEP); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); } logradouro = jTextFieldNovoEnderecoCliente.getText(); if (logradouro != null && logradouro.isEmpty() == false) { pj.setLogradouro(jTextFieldNovoEnderecoCliente.getText().trim()); } numeroLogradouro = jTextFieldNovonumeroEndereco.getText(); if (numeroLogradouro != null && numeroLogradouro.isEmpty() == false) { pj.setNumeroLogradouro(numeroLogradouro.trim()); } complemento = jTextFieldNovocomplemento.getText(); if (complemento != null && complemento.isEmpty() == false) { pj.setComplemento(complemento.trim()); } bairro = jTextFieldNovobairro.getText(); if (bairro != null && bairro.isEmpty() == false) { pj.setBairro(bairro.trim()); } cidade = jTextFieldNovocidade.getText(); if (cidade != null && cidade.isEmpty() == false) { pj.setCidade(cidade.trim()); } estado = jTextFieldNovouf.getText(); if (estado != null && estado.isEmpty() == false) { pj.setEstado(estado.trim()); } email = jTextFieldNovoemail.getText(); if (email != null && email.isEmpty() == false) { pj.setEmail(email.trim()); } try { cliente.alterarClientePJ(pj); jTextFieldCodCliente.setText(String.valueOf(pj.getCli_Codigo())); jTextFieldCpfCnpj.setText(pj.getCli_Cnpj()); jTextFieldNomeRazaoSocial.setText(pj.getRazaoSocial()); jTextFieldTelefone.setText(pj.getTelefone()); jTextFieldCep.setText(pj.getCep()); jTextFieldEndereco.setText(pj.getLogradouro()); jTextFieldNumeroEndereco.setText(pj.getNumeroLogradouro()); jTextFieldComplemento.setText(pj.getComplemento()); jTextFieldBairro.setText(pj.getBairro()); jTextFieldCidade.setText(pj.getCidade()); jTextFieldUF.setText(pj.getEstado()); jTextFieldEmail.setText(pj.getEmail()); JOptionPane.showMessageDialog(null, "Cliente atualizado com sucesso."); jFormattedTextFieldOperacaoNovoCpfCnpj.setText(""); jTextFieldOperacaoNovoNomeRazaoSocial.setText(""); jFormattedTextFieldNovotelefoneCliente.setText(""); jFormattedTextFieldNovocepCliente.setText(""); jTextFieldNovoEnderecoCliente.setText(""); jTextFieldNovonumeroEndereco.setText(""); jTextFieldNovocomplemento.setText(""); jTextFieldNovobairro.setText(""); jTextFieldNovocidade.setText(""); jTextFieldNovouf.setText(""); jTextFieldNovoemail.setText(""); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); jFormattedTextFieldOperacaoNovoCpfCnpj.setText(""); jTextFieldOperacaoNovoNomeRazaoSocial.setText(""); jFormattedTextFieldNovotelefoneCliente.setText(""); jFormattedTextFieldNovocepCliente.setText(""); jTextFieldNovoEnderecoCliente.setText(""); jTextFieldNovonumeroEndereco.setText(""); jTextFieldNovocomplemento.setText(""); jTextFieldNovobairro.setText(""); jTextFieldNovocidade.setText(""); jTextFieldNovouf.setText(""); jTextFieldNovoemail.setText(""); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); jFormattedTextFieldOperacaoNovoCpfCnpj.setText(""); jTextFieldOperacaoNovoNomeRazaoSocial.setText(""); jFormattedTextFieldNovotelefoneCliente.setText(""); jFormattedTextFieldNovocepCliente.setText(""); jTextFieldNovoEnderecoCliente.setText(""); jTextFieldNovonumeroEndereco.setText(""); jTextFieldNovocomplemento.setText(""); jTextFieldNovobairro.setText(""); jTextFieldNovocidade.setText(""); jTextFieldNovouf.setText(""); jTextFieldNovoemail.setText(""); } } }//GEN-LAST:event_jButtonAtualizarActionPerformed private void jFormattedTextFieldNovocepClienteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jFormattedTextFieldNovocepClienteKeyTyped // Teste de uso de eventos para limitar o campo estado somente com caracteres e com limite de 2 caracteres para o estado. char c = evt.getKeyChar(); if (!(Character.isDigit(c))) { evt.consume(); } int numerocaracter = 8; if (jFormattedTextFieldNovocepCliente.getText().length() >= numerocaracter) { evt.consume(); } }//GEN-LAST:event_jFormattedTextFieldNovocepClienteKeyTyped /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FormAlterarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormAlterarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormAlterarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormAlterarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FormAlterarCliente().setVisible(true); } }); } public void RecebeJtablePF(Integer pfSelecionado) throws Exception { //Alimentando o objeto passado pelo form setTitle("ATUALIZAÇÃO DE CLIENTES- PESSOA FISICA"); pf = new ClientePessoaFisica(); NegocioCliente a = new NegocioCliente(); pf.setCli_Codigo(pfSelecionado); ArrayList<ClientePessoaFisica> pfConsultado = a.consultarClientePF(pf); pf = pfConsultado.get(0); //Preenchendo os campos de texto com o objeto alimentado jTextFieldCodCliente.setText(String.valueOf(pf.getCli_Codigo())); jTextFieldCpfCnpj.setText(pf.getCli_Cpf()); jTextFieldNomeRazaoSocial.setText(pf.getNome()); jTextFieldTelefone.setText(pf.getTelefone()); jTextFieldCep.setText(pf.getCep()); jTextFieldEndereco.setText(pf.getLogradouro()); jTextFieldNumeroEndereco.setText(pf.getNumeroLogradouro()); jTextFieldComplemento.setText(pf.getComplemento()); jTextFieldBairro.setText(pf.getBairro()); jTextFieldCidade.setText(pf.getCidade()); jTextFieldUF.setText(pf.getEstado()); jTextFieldEmail.setText(pf.getEmail()); jTextFieldSexo.setText(pf.getSexo()); // mascaracep.install(jFormattedTextFieldNovocepCliente); mascaraCNPJ.uninstall(); mascaraCPF.install(jFormattedTextFieldOperacaoNovoCpfCnpj); } public void RecebeJtablePJ(Integer pjSelecionado) throws Exception { setTitle("ATUALIZAÇÃO DE CLIENTES- PESSOA JURIDICA"); //Alimentando o objeto passado pelo form pj = new ClientePessoaJuridica(); NegocioCliente a = new NegocioCliente(); pj.setCli_Codigo(pjSelecionado); ArrayList<ClientePessoaJuridica> pjConsultado = a.consultarClientePJ(pj); pj = pjConsultado.get(0); //Preenchendo os campos de texto com o objeto alimentado jLabelOperacaoCpfCNPJ.setText("CNPJ"); jLabelOperacaoNomeRazaoSocial.setText("Razão Social"); jLabelSexoCliente.setVisible(false); jTextFieldSexo.setVisible(false); jTextFieldCodCliente.setText(String.valueOf(pj.getCli_Codigo())); jTextFieldCpfCnpj.setText(pj.getCli_Cnpj()); jTextFieldNomeRazaoSocial.setText(pj.getRazaoSocial()); jTextFieldTelefone.setText(pj.getTelefone()); jTextFieldCep.setText(pj.getCep()); jTextFieldEndereco.setText(pj.getLogradouro()); jTextFieldNumeroEndereco.setText(pj.getNumeroLogradouro()); jTextFieldComplemento.setText(pj.getComplemento()); jTextFieldBairro.setText(pj.getBairro()); jTextFieldCidade.setText(pj.getCidade()); jTextFieldUF.setText(pj.getEstado()); jTextFieldEmail.setText(pj.getEmail()); // mascaracep.install(jFormattedTextFieldNovocepCliente); mascaraCPF.uninstall(); mascaraCNPJ.install(jFormattedTextFieldOperacaoNovoCpfCnpj); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAtualizar; private javax.swing.JFormattedTextField jFormattedTextFieldNovocepCliente; private javax.swing.JFormattedTextField jFormattedTextFieldNovotelefoneCliente; private javax.swing.JFormattedTextField jFormattedTextFieldOperacaoNovoCpfCnpj; private javax.swing.JLabel jLabel1UF; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabelEXUF; private javax.swing.JLabel jLabelMensagemInicial; private javax.swing.JLabel jLabelOperacaoCpfCNPJ; private javax.swing.JLabel jLabelOperacaoNomeRazaoSocial; private javax.swing.JLabel jLabelSexoCliente; private javax.swing.JLabel jLabelbairro; private javax.swing.JLabel jLabelcepCliente; private javax.swing.JLabel jLabelcidade; private javax.swing.JLabel jLabelcomplemento; private javax.swing.JLabel jLabelemail; private javax.swing.JLabel jLabelenderecoCliente; private javax.swing.JLabel jLabelnumeroEndereco; private javax.swing.JLabel jLabeltelefoneCliente; private javax.swing.JTextField jTextFieldBairro; private javax.swing.JTextField jTextFieldCep; private javax.swing.JTextField jTextFieldCidade; private javax.swing.JTextField jTextFieldCodCliente; private javax.swing.JTextField jTextFieldComplemento; private javax.swing.JTextField jTextFieldCpfCnpj; private javax.swing.JTextField jTextFieldEmail; private javax.swing.JTextField jTextFieldEndereco; private javax.swing.JTextField jTextFieldNomeRazaoSocial; private javax.swing.JTextField jTextFieldNovoEnderecoCliente; private javax.swing.JTextField jTextFieldNovobairro; private javax.swing.JTextField jTextFieldNovocidade; private javax.swing.JTextField jTextFieldNovocomplemento; private javax.swing.JTextField jTextFieldNovoemail; private javax.swing.JTextField jTextFieldNovonumeroEndereco; private javax.swing.JTextField jTextFieldNovouf; private javax.swing.JTextField jTextFieldNumeroEndereco; private javax.swing.JTextField jTextFieldOperacaoNovoNomeRazaoSocial; private javax.swing.JTextField jTextFieldSexo; private javax.swing.JTextField jTextFieldTelefone; private javax.swing.JTextField jTextFieldUF; // End of variables declaration//GEN-END:variables }
1d3c3d4d9a44f064c834e297e443f793cf46ff8f
dbd5ad64aa42ddcf0ef6f2328801acededeb5281
/src/builder/example/Builder.java
1ccf54a5391e0e6d8be8e121e92b5a5f85e32e50
[]
no_license
MoAmr/Java-Creational-Design-Patterns
c2e8ca5caeadff64d0e27a857f8838232ed98fe0
e6d0e95dd37d5157128048488bd8b2686d72282b
refs/heads/master
2020-12-02T00:01:03.303473
2019-12-31T01:44:58
2019-12-31T01:44:58
230,822,167
0
0
null
null
null
null
UTF-8
Java
false
false
370
java
package builder.example; import java.awt.*; public interface Builder { Builder setDimensions(Dimension dimensions); Builder setCeilingHeight(int ceilingHeight); Builder setFloorNumber(int floorNumber); Builder setWallColor(Color wallColor); Builder setNumberOfWindows(int numberOfWindows); Builder setNumberOfDoors(int numberOfDoors); }
0db644ada06fcf36859b97e1d4844ba9a1a46b20
e84cb5f649bb3d246a7e583c9396a6d439222c7a
/test/integration-test/src/test/java/com/hexaware/FTP109/integration/test/Menu.java
40b74c5ded595ba826d640842882687e5384420f
[]
no_license
tejassalvi1/project
8455a9e3d29017653572ec36143bd404d524bf90
7c8af18151eff227a057d4eaa08e998f1ca9e7c6
refs/heads/master
2020-04-20T11:38:04.282032
2019-03-13T13:12:01
2019-03-13T13:12:01
168,822,308
0
1
null
null
null
null
UTF-8
Java
false
false
2,290
java
package com.hexaware.FTP109.integration.test; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.Objects; import com.hexaware.FTP109.integration.test.CommonUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; /** * MenuFactory class used to fetch menu data from database. * @author hexware. */ @JsonIgnoreProperties(ignoreUnknown = true) public class Menu { /** * foodId to store foodId. * foodName to store foodName. * foodPrice to store foodPrice. * venId to store venId * venName to store * rating to store */ private int foodId; private String foodName; private double foodPrice; private int venId; private String venName; private int ratings; /** * @param argFoodId to initialize food id. * @param argFoodName to initialize food name. * @param argFoodPrice to initialize food price. * @param argVenId to initialize vendor id. * @param argVenName to initialize Vendor Name. * @param argRatings to initialize rating. */ public Menu(final int argFoodId, final String argFoodName, final double argFoodPrice, final int argVenId, final String argVenName, final int argRatings) { this.foodId = argFoodId; this.foodName = argFoodName; this.foodPrice = argFoodPrice; this.venId = argVenId; this.venName = argVenName; this.ratings = argRatings; } /** * @param argFoodName to initialize vendor name. * */ public final void setFoodName(final String argFoodName) { this.foodName = argFoodName; } /** * * @return foodName */ public final String getFoodName() { return this.foodName; } /** * * @return this food id */ public final int getFoodId() { return this.foodId; } /** * * @return this food price */ public final double getFoodPrice() { return this.foodPrice; } /** * * @return this vendor id */ public final int getVendorId() { return this.venId; } /** * * @return this vendor name */ public final String getVendorName() { return this.venName; } /** * * @return this rating */ public final int getRatings() { return this.ratings; } }
a728c6e47b35e215460d7bc82763a036574f8820
ba64e2a41cf86e435b2759199d34b87e12a08d84
/ihmc-robot-data-logger/src/main/java-generated/us/ihmc/robotDataLogger/CameraAnnouncementPubSubType.java
b5b37492db1ffc7cdb28273357283f33e99cff48
[ "Apache-2.0" ]
permissive
ath12/ihmc-open-robotics-software
01040cbbf92d07f8cd3c17b9ce6fb3f9f8c1f2d1
7ce92dd0c3261fa2e49253a267c31ce87a49ba0d
refs/heads/master
2021-07-16T13:56:14.306799
2017-10-06T16:28:04
2017-10-06T16:31:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,168
java
package us.ihmc.robotDataLogger; import java.io.IOException; import us.ihmc.pubsub.TopicDataType; import us.ihmc.pubsub.common.SerializedPayload; import us.ihmc.idl.InterchangeSerializer; import us.ihmc.idl.CDR; import us.ihmc.idl.IDLSequence; /** * * Topic data type of the struct "CameraAnnouncement" defined in "Announcement.idl". Use this class to provide the TopicDataType to a Participant. * * This file was automatically generated from Announcement.idl by us.ihmc.idl.generator.IDLGenerator. * Do not update this file directly, edit Announcement.idl instead. * */ public class CameraAnnouncementPubSubType implements TopicDataType<us.ihmc.robotDataLogger.CameraAnnouncement> { public static final String name = "us::ihmc::robotDataLogger::CameraAnnouncement"; public CameraAnnouncementPubSubType() { } private final CDR serializeCDR = new CDR(); private final CDR deserializeCDR = new CDR(); @Override public void serialize(us.ihmc.robotDataLogger.CameraAnnouncement data, SerializedPayload serializedPayload) throws IOException { serializeCDR.serialize(serializedPayload); write(data, serializeCDR); serializeCDR.finishSerialize(); } @Override public void deserialize(SerializedPayload serializedPayload, us.ihmc.robotDataLogger.CameraAnnouncement data) throws IOException { deserializeCDR.deserialize(serializedPayload); read(data, deserializeCDR); deserializeCDR.finishDeserialize(); } public static int getMaxCdrSerializedSize() { return getMaxCdrSerializedSize(0); } public static int getMaxCdrSerializedSize(int current_alignment) { int initial_alignment = current_alignment; current_alignment += 4 + CDR.alignment(current_alignment, 4); current_alignment += 4 + CDR.alignment(current_alignment, 4) + 255 + 1; current_alignment += 4 + CDR.alignment(current_alignment, 4) + 255 + 1; return current_alignment - initial_alignment; } public final static int getCdrSerializedSize(us.ihmc.robotDataLogger.CameraAnnouncement data) { return getCdrSerializedSize(data, 0); } public final static int getCdrSerializedSize(us.ihmc.robotDataLogger.CameraAnnouncement data, int current_alignment) { int initial_alignment = current_alignment; current_alignment += 4 + CDR.alignment(current_alignment, 4); current_alignment += 4 + CDR.alignment(current_alignment, 4) + data.getName().length() + 1; current_alignment += 4 + CDR.alignment(current_alignment, 4) + data.getIdentifier().length() + 1; return current_alignment - initial_alignment; } public static void write(us.ihmc.robotDataLogger.CameraAnnouncement data, CDR cdr) { cdr.write_type_c(data.getType().ordinal()); if(data.getName().length() <= 255) cdr.write_type_d(data.getName());else throw new RuntimeException("name field exceeds the maximum length"); if(data.getIdentifier().length() <= 255) cdr.write_type_d(data.getIdentifier());else throw new RuntimeException("identifier field exceeds the maximum length"); } public static void read(us.ihmc.robotDataLogger.CameraAnnouncement data, CDR cdr) { data.setType(us.ihmc.robotDataLogger.CameraType.values[cdr.read_type_c()]); cdr.read_type_d(data.getName()); cdr.read_type_d(data.getIdentifier()); } @Override public final void serialize(us.ihmc.robotDataLogger.CameraAnnouncement data, InterchangeSerializer ser) { ser.write_type_c("type", data.getType()); ser.write_type_d("name", data.getName()); ser.write_type_d("identifier", data.getIdentifier()); } @Override public final void deserialize(InterchangeSerializer ser, us.ihmc.robotDataLogger.CameraAnnouncement data) { data.setType((us.ihmc.robotDataLogger.CameraType)ser.read_type_c("type", us.ihmc.robotDataLogger.CameraType.class)); ser.read_type_d("name", data.getName()); ser.read_type_d("identifier", data.getIdentifier()); } public static void staticCopy(us.ihmc.robotDataLogger.CameraAnnouncement src, us.ihmc.robotDataLogger.CameraAnnouncement dest) { dest.set(src); } @Override public us.ihmc.robotDataLogger.CameraAnnouncement createData() { return new us.ihmc.robotDataLogger.CameraAnnouncement(); } @Override public int getTypeSize() { return CDR.getTypeSize(getMaxCdrSerializedSize()); } @Override public String getName() { return name; } public void serialize(us.ihmc.robotDataLogger.CameraAnnouncement data, CDR cdr) { write(data, cdr); } public void deserialize(us.ihmc.robotDataLogger.CameraAnnouncement data, CDR cdr) { read(data, cdr); } public void copy(us.ihmc.robotDataLogger.CameraAnnouncement src, us.ihmc.robotDataLogger.CameraAnnouncement dest) { staticCopy(src, dest); } @Override public CameraAnnouncementPubSubType newInstance() { return new CameraAnnouncementPubSubType(); } }
9c89cb80ae19aea62b14c073a4112994922ccb6a
4157e8893925e27804d3f7a27791894d21861cc7
/aeda/20162-aeda-lab5-compressao/src/br/pit/aeda/lab5/compressao/de/ProgramaPrincipal.java
9c8322a4e81d1a2d037d6974c43f22d8aae7f6fb
[]
no_license
waldirpires/pitagoras
229874d406d2d6ed3804600c0b71846effe97382
e9d937449fdfc787f0e5f49520122163dc2ed749
refs/heads/master
2020-12-24T07:20:47.128614
2017-12-22T16:01:27
2017-12-22T16:01:27
58,762,822
0
0
null
null
null
null
ISO-8859-1
Java
false
false
854
java
package br.pit.aeda.lab5.compressao.de; import java.util.Arrays; import javax.swing.JOptionPane; public class ProgramaPrincipal { public static void main(String[] args) { String m = JOptionPane.showInputDialog("Digite uma frase:", null); System.out.println(m); int a[] = new int[m.length()]; for (int i = 0; i < m.length(); i++){ a[i] = m.charAt(i); } int[] encode = CodificadorDelta.encode(a); JOptionPane.showMessageDialog(null, "Resultado: \n" + Arrays.toString(encode)); // realizando a decompressão dos dados int[] decode = CodificadorDelta.decode(encode); char b[] = new char[decode.length]; for (int i = 0; i < decode.length; i++){ b[i] = (char)decode[i]; } String frase = new String(b); JOptionPane.showMessageDialog(null, "Resultado decompressão: \n" + frase); } }
69e93f0ca0d02e0483b29028b57d502bdd3c08df
00bb541e12c92806b298dd1a1bf822222015f0bb
/app/src/main/java/edu/galileo/android/androidchat/chat/ChatRepository.java
7a5651326064ee8e0abdeb34c2a9b3b17b3170f6
[]
no_license
fjbatresv/EduAndroidChat
dbc4f1c3d30d1a2cb81e2876d51fa9708ddc6a57
6e337af831a2526b19ac16c6a17603b61c56c8a5
refs/heads/master
2020-04-02T12:58:52.993499
2016-12-13T17:16:19
2016-12-13T17:16:19
60,863,590
0
0
null
null
null
null
UTF-8
Java
false
false
326
java
package edu.galileo.android.androidchat.chat; /** * Created by javie on 10/06/2016. */ public interface ChatRepository { void changeConnectionStatus(boolean status); void setRecipient(String recipient); void sendMessage(String msg); void subscribe(); void unSubscribe(); void destroyListener(); }
50fee864d4ff0a31eb5561fc25ff96da01f142fa
890d09f1dead045a925e8d03f40af83dd533c354
/app/src/main/java/com/example/whatsappclone/model/Grupo.java
2f52536e817d64d6a06c1db183e303e4ddfb7e01
[ "MIT" ]
permissive
AlsGomes/WhatsAppClone
3d19ec0f652e153b48cd829e88f27e6690c7141f
b1fc438704ead28314f37f1ee38f09daf596522c
refs/heads/main
2022-12-31T13:16:49.439669
2020-10-23T02:45:14
2020-10-23T02:45:14
306,510,004
0
0
null
null
null
null
UTF-8
Java
false
false
976
java
package com.example.whatsappclone.model; import com.google.firebase.database.Exclude; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Grupo implements Serializable { private String id; private String nome; private String foto; private List<String> membrosId = new ArrayList<>(); public Grupo() { } public Grupo(String id, String nome, String foto) { this.id = id; this.nome = nome; this.foto = foto; } @Exclude public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getFoto() { return foto; } public void setFoto(String foto) { this.foto = foto; } public List<String> getMembrosId() { return membrosId; } }
a995003ef360bc4b65acf2431db6bdfa0632d83e
016cc602d20ed1e73387cb58886915a2015f1be1
/app/src/main/java/com/edu/educatie/SyllabusActivity.java
856d7c74908668dafa3595726d000296c6135aad
[ "MIT" ]
permissive
achuthan02/Educatie
57ac4c212f90b2481385a86553dfe294f060fb04
7e504c5b7c6f64bcb7ed15fbcdccc45adaee61d7
refs/heads/master
2023-02-12T20:37:08.067330
2021-01-15T13:17:14
2021-01-15T13:17:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,252
java
package com.edu.educatie; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class SyllabusActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_syllabus); TextView SubName, Book, Author; TextView U1, U2, U3, U4, U5; TextView c1, c2, c3, c4, c5; SubName = findViewById(R.id.subName); Book = findViewById(R.id.BookName); Author = findViewById(R.id.AuthorName); U1 = findViewById(R.id.Unit1); U2 = findViewById(R.id.Unit2); U3 = findViewById(R.id.Unit3); U4 = findViewById(R.id.Unit4); U5 = findViewById(R.id.Unit5); c1 = findViewById(R.id.content1); c2 = findViewById(R.id.content2); c3 = findViewById(R.id.content3); c4 = findViewById(R.id.content4); c5 = findViewById(R.id.content5); String subName = getIntent().getStringExtra("SubName"); String authorName = getIntent().getStringExtra("AuthorName"); String bookName = getIntent().getStringExtra("BookName"); String unit1 = getIntent().getStringExtra("Unit1"); String unit2 = getIntent().getStringExtra("Unit2"); String unit3 = getIntent().getStringExtra("Unit3"); String unit4 = getIntent().getStringExtra("Unit4"); String unit5 = getIntent().getStringExtra("Unit5"); String content1 = getIntent().getStringExtra("Content1"); String content2 = getIntent().getStringExtra("Content2"); String content3 = getIntent().getStringExtra("Content3"); String content4 = getIntent().getStringExtra("Content4"); String content5 = getIntent().getStringExtra("Content5"); SubName.setText(subName); Book.setText(bookName); Author.setText(authorName); U1.setText(unit1); U2.setText(unit2); U3.setText(unit3); U4.setText(unit4); U5.setText(unit5); c1.setText(content1); c2.setText(content2); c3.setText(content3); c4.setText(content4); c5.setText(content5); } }
3a6a69e3a26908b984a975dfe94a0ce8e4043a9e
0e5c2366d53b47ddab388e703a8c60cdc8b549bc
/src/main/java/com/cev/aircev/domain/Aeropuerto.java
a4e87c64e790cee7abe47f5112cdb5085197a530
[ "Apache-2.0" ]
permissive
elencha3/acceso-a-datos-simulacro1
ab3fc2c4ecd0f16135691966966d8f46e9e81dc5
f0d763f51a4f91b5902550a5f685b4a8c7cb4fc8
refs/heads/main
2023-08-11T22:41:05.950666
2021-10-13T12:37:09
2021-10-13T12:37:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,264
java
package com.cev.aircev.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.*; import javax.validation.constraints.*; /** * A Aeropuerto. */ @Entity @Table(name = "aeropuerto") public class Aeropuerto implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Size(min = 10, max = 255) @Column(name = "nombre", length = 255) private String nombre; @NotNull @Size(min = 10, max = 255) @Column(name = "ciudad", length = 255, nullable = false) private String ciudad; @OneToMany(mappedBy = "origen") @JsonIgnoreProperties(value = { "avion", "origen", "destino", "piloto", "tripulacions" }, allowSetters = true) private Set<Vuelo> salidas = new HashSet<>(); @OneToMany(mappedBy = "destino") @JsonIgnoreProperties(value = { "avion", "origen", "destino", "piloto", "tripulacions" }, allowSetters = true) private Set<Vuelo> destinos = new HashSet<>(); // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return this.id; } public Aeropuerto id(Long id) { this.setId(id); return this; } public void setId(Long id) { this.id = id; } public String getNombre() { return this.nombre; } public Aeropuerto nombre(String nombre) { this.setNombre(nombre); return this; } public void setNombre(String nombre) { this.nombre = nombre; } public String getCiudad() { return this.ciudad; } public Aeropuerto ciudad(String ciudad) { this.setCiudad(ciudad); return this; } public void setCiudad(String ciudad) { this.ciudad = ciudad; } public Set<Vuelo> getSalidas() { return this.salidas; } public void setSalidas(Set<Vuelo> vuelos) { if (this.salidas != null) { this.salidas.forEach(i -> i.setOrigen(null)); } if (vuelos != null) { vuelos.forEach(i -> i.setOrigen(this)); } this.salidas = vuelos; } public Aeropuerto salidas(Set<Vuelo> vuelos) { this.setSalidas(vuelos); return this; } public Aeropuerto addSalidas(Vuelo vuelo) { this.salidas.add(vuelo); vuelo.setOrigen(this); return this; } public Aeropuerto removeSalidas(Vuelo vuelo) { this.salidas.remove(vuelo); vuelo.setOrigen(null); return this; } public Set<Vuelo> getDestinos() { return this.destinos; } public void setDestinos(Set<Vuelo> vuelos) { if (this.destinos != null) { this.destinos.forEach(i -> i.setDestino(null)); } if (vuelos != null) { vuelos.forEach(i -> i.setDestino(this)); } this.destinos = vuelos; } public Aeropuerto destinos(Set<Vuelo> vuelos) { this.setDestinos(vuelos); return this; } public Aeropuerto addDestinos(Vuelo vuelo) { this.destinos.add(vuelo); vuelo.setDestino(this); return this; } public Aeropuerto removeDestinos(Vuelo vuelo) { this.destinos.remove(vuelo); vuelo.setDestino(null); return this; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Aeropuerto)) { return false; } return id != null && id.equals(((Aeropuerto) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "Aeropuerto{" + "id=" + getId() + ", nombre='" + getNombre() + "'" + ", ciudad='" + getCiudad() + "'" + "}"; } }
11bd62ffa1cb13fe7d70230f5df5e72172e26f37
b2942a9dbaf71d52476f124c80447cec9e222ba4
/lab3/library-server-complete/src/main/java/com/example/libraryserver/config/WebSecurityConfiguration.java
e975aaf4efd2c5282bb4ce379f49b3551c1c45a6
[ "Apache-2.0" ]
permissive
andifalk/cloud-native-microservices-security
406ab3316e881f96c170a5854d00596fcc0715a3
ab65097519118e1a624e8e594b96c4a8734c57ce
refs/heads/master
2023-05-15T04:57:15.699302
2021-06-11T14:25:06
2021-06-11T14:25:06
229,095,535
19
3
null
null
null
null
UTF-8
Java
false
false
3,286
java
package com.example.libraryserver.config; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.boot.actuate.health.HealthEndpoint; import org.springframework.boot.actuate.info.InfoEndpoint; import org.springframework.boot.autoconfigure.security.servlet.PathRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.DelegatingPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.HashMap; import java.util.Map; import static org.springframework.security.config.Customizer.withDefaults; @Configuration @EnableWebSecurity public class WebSecurityConfiguration { @Primary @Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Qualifier("LegacyEncoder") @Bean public PasswordEncoder legacyPasswordEncoder() { String encodingId = "MD5"; Map<String, PasswordEncoder> encoders = new HashMap<>(); encoders.put( encodingId, new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5")); return new DelegatingPasswordEncoder(encodingId, encoders); } @Configuration public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { private final UserDetailsService userDetailsService; public ApiWebSecurityConfigurationAdapter( @Qualifier("library-user-details-service") UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } @Override protected void configure(HttpSecurity http) throws Exception { // http.csrf().disable(); http.authorizeRequests( authorizeRequests -> authorizeRequests .requestMatchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)) .permitAll() .requestMatchers(EndpointRequest.toAnyEndpoint()) .authenticated() .requestMatchers(PathRequest.toStaticResources().atCommonLocations()) .permitAll() .mvcMatchers("/") .permitAll() .anyRequest() .authenticated()) .httpBasic(withDefaults()) .formLogin(withDefaults()) .headers(h -> h.httpStrictTransportSecurity().disable()) .x509( x -> { x.subjectPrincipalRegex("CN=(.*?),"); x.userDetailsService(userDetailsService); }); } } }
7cad25aa8c61a0fe1b8526d2c2f042b6d5d45fed
0bd32ae0138494d6d7e516377970f85003e9af8e
/src/chatserver/Session.java
bcc141b04d2d631a55982b0aef8b60d71f7e5ae3
[]
no_license
strongjet/Plagiarism
fe72c4a93e6149df87ea8a72b0a9aa3a9f14c0da
32d7601efb9bf08dd2382c204523fed9de37152d
refs/heads/master
2021-05-01T16:04:25.253840
2018-02-10T19:03:10
2018-02-10T19:03:10
121,044,884
0
0
null
null
null
null
UTF-8
Java
false
false
2,165
java
package chatserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.SocketException; public class Session { private String username; private Socket socket; private PrintWriter outputWriter; private BufferedReader inputBuffer; /** Constructor establishes a Connection for a given connected socket. * * @param socket A connected socket for communication. */ Session(Socket socket) { this.socket = socket; try { inputBuffer = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); outputWriter = new PrintWriter(this.socket.getOutputStream(), true); } catch(IOException e) { System.err.println(e); e.printStackTrace(); } } /** Write to the connection socket */ public void write(String msg) { outputWriter.println(msg); outputWriter.flush(); } /** Attempt to read from the connection socket. */ public String read() { String line = null; try { line = inputBuffer.readLine(); } catch(SocketException e) { System.out.println("Log: Client disconnected, session ended"); } catch(IOException e) { System.err.println(e); e.printStackTrace(); } return line; } /** Attempt to close the connection, including input/output streams. */ public boolean disconnect() { try { socket.close(); inputBuffer.close(); } catch(IOException e) { System.err.println(e); e.printStackTrace(); return false; } outputWriter.close(); return true; } /** Set the username associated with the given connection */ public void setUsername(String username) { this.username = username; } public Socket getSocket() { return socket; } public String getUsername() { return username; } }
11ef59502be3982be27eb7da1a7dfb4cc9b42cf4
fe06f97c2cf33a8b4acb7cb324b79a6cb6bb9dac
/java/po/impl/CLMS_AP/WarehsePo.java
af4fb696b40c0365d9e256650a16ac4ce7b35ff9
[]
no_license
HeimlichLin/TableSchema
3f67dae0b5b169ee3a1b34837ea9a2d34265f175
64b66a2968c3a169b75d70d9e5cf75fa3bb65354
refs/heads/master
2023-02-11T09:42:47.210289
2023-02-01T02:58:44
2023-02-01T02:58:44
196,526,843
0
0
null
2022-06-29T18:53:55
2019-07-12T07:03:58
Java
UTF-8
Java
false
false
5,418
java
package com.doc.common.po.impl; public class WarehsePo implements IWarehsePo { public enum COLUMNS { POSTCODE("地區碼"), // BONDNO("監管編號"), // BONDBAN("倉儲業統一編碼"), // BONDNAME("保稅倉儲業"), // SPECIALST("專責人員"), // BONDADD("保稅倉儲業地址"), // BONDID("倉儲業代碼"), // BONDPW("倉儲業密碼"), // AUTHORITY("使用權限"), // RCVID("收件人代碼"), // SEPID("Sepower代碼"), // CUSTOMSOFFICE("關別"), // RECV_FLAG("准單接收註記"), // BONDTYPE("倉庫別"), // STATUS("狀態"), // ACTIVEDATE("啟用日期"), // ENDDATE("截止日期"), // CHARGEDATE("收費日期"), // TEL("電話"), // FAX("傳真"), // COFFICER("null"), // CUSTOM_FLAG("null"), // AUTOCONFIRM("null") // ; private final String comment; private COLUMNS(final String comment) { this.comment = comment; } public String getComment() { return this.comment; } } private String postcode; private String bondno; private String bondban; private String bondname; private String specialst; private String bondadd; private String bondid; private String bondpw; private String authority; private String rcvid; private String sepid; private String customsoffice; private String recvFlag; private String bondtype; private String status; private java.sql.Timestamp activedate; private java.sql.Timestamp enddate; private java.sql.Timestamp chargedate; private String tel; private String fax; private String cofficer; private String customFlag; private String autoconfirm; @Override public String getPostcode() { return this.postcode; } @Override public void setPostcode(final String postcode) { this.postcode = postcode; } @Override public String getBondno() { return this.bondno; } @Override public void setBondno(final String bondno) { this.bondno = bondno; } @Override public String getBondban() { return this.bondban; } @Override public void setBondban(final String bondban) { this.bondban = bondban; } @Override public String getBondname() { return this.bondname; } @Override public void setBondname(final String bondname) { this.bondname = bondname; } @Override public String getSpecialst() { return this.specialst; } @Override public void setSpecialst(final String specialst) { this.specialst = specialst; } @Override public String getBondadd() { return this.bondadd; } @Override public void setBondadd(final String bondadd) { this.bondadd = bondadd; } @Override public String getBondid() { return this.bondid; } @Override public void setBondid(final String bondid) { this.bondid = bondid; } @Override public String getBondpw() { return this.bondpw; } @Override public void setBondpw(final String bondpw) { this.bondpw = bondpw; } @Override public String getAuthority() { return this.authority; } @Override public void setAuthority(final String authority) { this.authority = authority; } @Override public String getRcvid() { return this.rcvid; } @Override public void setRcvid(final String rcvid) { this.rcvid = rcvid; } @Override public String getSepid() { return this.sepid; } @Override public void setSepid(final String sepid) { this.sepid = sepid; } @Override public String getCustomsoffice() { return this.customsoffice; } @Override public void setCustomsoffice(final String customsoffice) { this.customsoffice = customsoffice; } @Override public String getRecvFlag() { return this.recvFlag; } @Override public void setRecvFlag(final String recvFlag) { this.recvFlag = recvFlag; } @Override public String getBondtype() { return this.bondtype; } @Override public void setBondtype(final String bondtype) { this.bondtype = bondtype; } @Override public String getStatus() { return this.status; } @Override public void setStatus(final String status) { this.status = status; } @Override public java.sql.Timestamp getActivedate() { return this.activedate; } @Override public void setActivedate(final java.sql.Timestamp activedate) { this.activedate = activedate; } @Override public java.sql.Timestamp getEnddate() { return this.enddate; } @Override public void setEnddate(final java.sql.Timestamp enddate) { this.enddate = enddate; } @Override public java.sql.Timestamp getChargedate() { return this.chargedate; } @Override public void setChargedate(final java.sql.Timestamp chargedate) { this.chargedate = chargedate; } @Override public String getTel() { return this.tel; } @Override public void setTel(final String tel) { this.tel = tel; } @Override public String getFax() { return this.fax; } @Override public void setFax(final String fax) { this.fax = fax; } @Override public String getCofficer() { return this.cofficer; } @Override public void setCofficer(final String cofficer) { this.cofficer = cofficer; } @Override public String getCustomFlag() { return this.customFlag; } @Override public void setCustomFlag(final String customFlag) { this.customFlag = customFlag; } @Override public String getAutoconfirm() { return this.autoconfirm; } @Override public void setAutoconfirm(final String autoconfirm) { this.autoconfirm = autoconfirm; } }
194f1c410829cab051af0c0545e2da10149aa680
e2c5f97074476733a4372c662d8430029e381a8c
/src/day13/StringPractice.java
9157b74639d7aecbc3cc1790596c2759d3f5c095
[]
no_license
Halis-Can/JavaProgrammingB15Online
571e8bf07697d6c274c55d270ef4f0a7ca97e890
6df977bddc9531a932893965cdcf9ced2ee76c69
refs/heads/master
2021-08-20T04:04:40.840907
2021-02-11T05:00:33
2021-02-11T05:00:33
244,282,494
1
0
null
null
null
null
UTF-8
Java
false
false
292
java
package day13; import java.util.Scanner; public class StringPractice { public static void main(String[] args) { int x = 10; int y = 12; Scanner scan = new Scanner(System.in); String s1 = new String("abc"); String s2 = "hello"; } }
99db88989248df892ebcac5098096479d5e42f0c
bde7f05a8e2186ba8fb6e7c79e6f3ae9af71b161
/Kalendim/src/modelo/Materia.java
c8ceecb90edb98865fbdcdf4b0a260961d7eb2ef
[]
no_license
Kalendim/gerador
7b475bac7cb1069793e077e95cc44d8a7364e429
63c787f2b62a330e1be006571e68846751c8cbb5
refs/heads/master
2022-04-18T19:23:34.072571
2020-04-10T03:58:33
2020-04-10T03:58:33
254,510,115
1
0
null
null
null
null
UTF-8
Java
false
false
920
java
package modelo; import java.time.LocalDate; import java.util.Date; public class Materia { public String nome; private Professor professor; private int idmateria; public Materia() { } public Materia(String nome, Professor professor, int idmateria) { this.nome = nome; this.professor = professor; this.idmateria = idmateria; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Professor getProfessor() { return professor; } public void setProfessor(Professor professor) { this.professor = professor; } public int getIdmateria() { return idmateria; } public void setIdmateria(int idmateria) { this.idmateria = idmateria; } @Override public String toString() { return nome; } }
8d3315162f3882277e76036c5c5a77353beb8a9d
ccd8ae66ca68b216fcafbef713d9edf9aa3786a9
/src/SnakeG/GamePanel.java
b2b8b81afb64b1dcd81cbef6a7308e8a9695227c
[]
no_license
Clara-Sousa-Neves/Snake_Game
1362f5ef822a4f7ed8a8b0f501f2acd2d411d597
090bbd749b831b13b1ffd4f4105274760c4f67ae
refs/heads/master
2023-02-21T03:05:18.016704
2021-01-16T18:01:13
2021-01-16T18:01:13
312,882,668
0
0
null
null
null
null
UTF-8
Java
false
false
4,274
java
package SnakeG; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; import javax.swing.JPanel; public class GamePanel extends JPanel implements ActionListener{ static final int SCREEN_WIDTH = 600; static final int SCREEN_HEIGHT = 600; static final int UNIT_SIZE = 25; static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE; static final int DELAY = 75; final int x[] = new int[GAME_UNITS]; final int y[] = new int[GAME_UNITS]; int bodyParts = 6; int applesEaten; int appleX; int appleY; char direction = 'R'; boolean running = false; Timer timer; Random random; GamePanel() { random = new Random (); this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT)); this.setBackground(Color.pink); this.setFocusable(true); this.addKeyListener(new MyKeyAdapter()); startGame(); } public void startGame() { newApple(); running = true; timer = new Timer(DELAY, this); timer.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); draw(g); } public void draw(Graphics g) { if(running ) { /* Remove the grid lines. for (int i=0; i<SCREEN_HEIGHT/UNIT_SIZE; i++) { g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT); g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE); } */ g.setColor(Color.green); g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE); for(int i = 0; i< bodyParts; i++) { if(i == 0) { g.setColor(Color.gray); g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE); } else { g.setColor(new Color(117, 163, 163)); g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE); } } g.setColor(Color.red); g.setFont( new Font("INK FREE", Font.BOLD, 40)); FontMetrics metrics = getFontMetrics(g.getFont()); g.drawString("Score: " +applesEaten, (SCREEN_WIDTH - metrics.stringWidth("Score: " +applesEaten))/2, g.getFont().getSize()); } else { gameOver(g); } } public void newApple() { appleX= random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE; appleY= random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE; } public void move() { for(int i = bodyParts; i>0; i--) { x[i] = x[i-1]; y[i] = y[i-1]; } switch(direction) { case 'U': y[0] = y[0] - UNIT_SIZE; break; case 'D': y[0] = y[0] + UNIT_SIZE; break; case 'L': x[0] = x[0] - UNIT_SIZE; break; case 'R': y[0] = y[0] + UNIT_SIZE; break; } } public void checkApple() { if((x[0] == appleX) && (y[0] == appleY)) { bodyParts++; applesEaten++; newApple(); } } public void checkCollisions() { for(int i = bodyParts; i>0; i--) { if((x[0] == x[i])&& (y[0] == y[i])) { running = false; } } if(x[0]< 0) { running = false; } if(x[0] > SCREEN_WIDTH) { running = false; } if(y[0] < 0) { running = false; } if(y[0] > SCREEN_HEIGHT) { running = false; } if(!running) { timer.stop(); } } public void gameOver(Graphics g) { g.setColor(Color.red); g.setFont( new Font("INK FREE", Font.BOLD, 40)); FontMetrics metrics1 = getFontMetrics(g.getFont()); g.drawString("Score: " +applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("Score: " +applesEaten))/2, g.getFont().getSize()); g.setColor(Color.red); g.setFont( new Font("INK FREE", Font.BOLD, 75)); FontMetrics metrics2 = getFontMetrics(g.getFont()); g.drawString("Game Over" , (SCREEN_WIDTH - metrics2.stringWidth("Game Over"))/2, SCREEN_HEIGHT/2); } @Override public void actionPerformed(ActionEvent e) { if(running) { move(); checkApple(); checkCollisions(); } repaint(); } public class MyKeyAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()) { case KeyEvent.VK_LEFT: if(direction != 'R') { direction = 'L'; } break; case KeyEvent.VK_RIGHT: if(direction != 'L') { direction = 'R'; } break; case KeyEvent.VK_UP: if(direction != 'D') { direction = 'U'; } break; case KeyEvent.VK_DOWN: if(direction != 'U') { direction = 'D'; } break; } } } }
9e2ebc70c8283b0587674d37ee28018ed5fd9043
3651634521600111276b9516a60a79ca22665df0
/src/com/backendless/transaction/OperationUpdateBulkFactory.java
6401f31eb5822f3cd81df97dd48a3a26a1a9bb81
[ "MIT" ]
permissive
Backendless/Android-SDK
e5685e8e0889b9b583c301875a493cad4471ca38
2512fa8cced66c880ed86581ce8c1f4f91ced73d
refs/heads/master
2023-03-10T22:00:42.626791
2023-03-03T11:56:23
2023-03-03T11:56:23
15,827,300
70
66
MIT
2023-01-26T13:00:52
2014-01-11T17:47:15
Java
UTF-8
Java
false
false
549
java
package com.backendless.transaction; import com.backendless.transaction.payload.UpdateBulkPayload; public class OperationUpdateBulkFactory extends OperationFactory<OperationUpdateBulk> { @Override protected Class<OperationUpdateBulk> getClazz() { return OperationUpdateBulk.class; } @Override protected OperationUpdateBulk createOperation( OperationType operationType, String table, String opResultId, Object payload ) { return new OperationUpdateBulk( operationType, table, opResultId, (UpdateBulkPayload) payload ); } }
759d1517392fba08546069fe45f06eae963ed650
4df7e7daa8cba9489424cd09a247099ebb8767b5
/app/src/main/java/com/example/money/heart/MainActivity.java
8d16a9ef95e917d8ca29aafc7ea59de48acafa94
[]
no_license
moneywhang/heart_beat
75df76c79986c216244f7888618b1437f5e546fa
61a0edac1560728e118f79785c9a46903de06f65
refs/heads/master
2020-03-27T23:26:05.554057
2018-09-06T09:56:02
2018-09-06T09:56:02
147,316,376
0
0
null
null
null
null
UTF-8
Java
false
false
9,761
java
package com.example.money.heart; import android.app.Activity; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.LimitLine; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; public class MainActivity extends Activity { bluetooth_40 Bl_0; bluetooth_41 Bl_1; TextView bpm_txt; Thread thread1,thread2; Message ss1,ss2; LineChart mChart,mChart2 ; ILineDataSet set,set2; int usedata =0,usedata1 =0,savecount=0; float datause; FirebaseDatabase database; ArrayList setdatable ; float [] setdata2 =new float[100]; //------------------------------------------------- ListView listView_use; RelativeLayout relayout1,relayout2; TextView bpmtxt,spo2txt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mChart = (LineChart) findViewById(R.id.chart1); bpm_txt=(TextView)findViewById(R.id.text); //------------------------------------ listView_use=(ListView)findViewById(R.id.listView); relayout1=(RelativeLayout)findViewById(R.id.r1); relayout2=(RelativeLayout)findViewById(R.id.r2); bpmtxt=(TextView)findViewById(R.id.bpm_txt); spo2txt=(TextView)findViewById(R.id.spo2_txt); // Bl_0 =new bluetooth_40(this); //Bl_0.mBleName =new ArrayList<>(); // Bl_0.btArrayAdapter= new ArrayAdapter<String>(this, // android.R.layout.simple_list_item_1,Bl_0.mBleName ); /* listView_use.setAdapter(Bl_0.btArrayAdapter); listView_use.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i("'jim"," onItemClick :"+Bl_0.mBleName.get(position)); Bl_0.DEVICE_adress =Bl_0.mBleName.get(position); Bl_0.Connectoutside(); changepage(); } }); setdatable =new ArrayList();*/ Set_chart(); thread1 =new Thread(new Runnable() { @Override public void run() { while (true){ try { if(Bl_0.drawstus==true){ addEntry(); } /* if(Bl_0.readdata_ble!=null){ datause =Float.valueOf(Bl_0.readdata_ble); usedata=(int)(datause); // usedata=(int)(datause); }*/ /* ss1 =new Message(); ss1.what =1; mHandler.sendMessage(ss1); if(Bl_0.readdata_ble!=null){ usedata =Integer.parseInt(Bl_0.readdata_ble); } if(Bl_0.readdata_ble1!=null){ datause =Float.valueOf(Bl_0.readdata_ble1); usedata1=(int)(datause); // usedata=(int)(datause); } addEntry();*/ //savearydata(); Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); // thread1.start(); } private Handler mHandler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case 1: bpm_txt.setText(""+usedata1); break; } } }; private void addEntry(){ LineData data = mChart.getData(); // 每一个LineDataSet代表一条线,每张统计图表可以同时存在若干个统计折线,这些折线像数组一样从0开始下标。 // 本例只有一个,那么就是第0条折线 ILineDataSet set = data.getDataSetByIndex(0); // 如果该统计折线图还没有数据集,则创建一条出来,如果有则跳过此处代码。 if (set == null) { set = createSet(); data.addDataSet(set); } // 先添加一个x坐标轴的值 // 因为是从0开始,data.getXValCount()每次返回的总是全部x坐标轴上总数量,所以不必多此一举的加1 for(int i=0;i<bluetooth_40.blesetAry.length;i++){ data.addEntry(new Entry(set.getEntryCount(), (float) (bluetooth_40.blesetAry[i])), 0); data.notifyDataChanged(); mChart.notifyDataSetChanged(); } /*for(int i=0;i<setdata2.length;i++){ data.addEntry(new Entry(set.getEntryCount(), (float) (setdata2[i])), 0); //Log.i("JIM","ARRAYBUFFER: "+setdata2.length); // Log.i("JIM","ARRAYBUFFER: "+setdata2[i]); data.notifyDataChanged(); mChart.notifyDataSetChanged(); }*/ // 像ListView那样的通知数据更新 mChart.notifyDataSetChanged(); // 当前统计图表中最多在x轴坐标线上显示的总量 mChart.setVisibleXRangeMaximum(200); // 将坐标移动到最新 // 此代码将刷新图表的绘图 mChart.moveViewToX(data.getEntryCount() ); // if(data != null &&data.getEntryCount()>200) Log.i("jim","Coun"+data.getEntryCount()); if(data != null &&data.getEntryCount()>30) { data.removeDataSet(data.getDataSetCount() - 20); data.notifyDataChanged(); mChart.notifyDataSetChanged(); //mChart.invalidate(); } } // 初始化数据集,添加一条统计折线,可以简单的理解是初始化y坐标轴线上点的表征 private LineDataSet createSet() { LineDataSet set = new LineDataSet(null, " "); set.setAxisDependency(YAxis.AxisDependency.LEFT); set.setLineWidth(3f); set.setColor(ColorTemplate.getHoloBlue()); set.setHighlightEnabled(false); set.setDrawValues(false); set.setDrawCircles(false); set.setMode(LineDataSet.Mode.CUBIC_BEZIER); set.setCubicIntensity(0.2f); return set; } private void Set_chart(){ // mChart.setDescription("Zhang Phil @ http://blog.csdn.net/zhangphil"); // mChart.setNoDataTextDescription("暂时尚无数据"); mChart.setTouchEnabled(true); // 可拖曳 mChart.setDragEnabled(true); // 可缩放 mChart.setScaleEnabled(true); mChart.setDrawGridBackground(false); mChart.setPinchZoom(true); mChart.setDescription(null); // 设置图表的背景颜色 mChart.setBackgroundColor(Color.WHITE); LineData data = new LineData(); // 数据显示的颜色 data.setValueTextColor(Color.BLACK); // 先增加一个空的数据,随后往里面动态添加 mChart.setData(data); // 图表的注解(只有当数据集存在时候才生效) Legend l = mChart.getLegend(); // 可以修改图表注解部分的位置 // l.setPosition(LegendPosition.LEFT_OF_CHART); // 线性,也可是圆 l.setForm(Legend.LegendForm.LINE); // 颜色 l.setTextColor(Color.BLACK); // x坐标轴 XAxis xl = mChart.getXAxis(); xl.setTextColor(Color.BLACK); xl.setDrawGridLines(false); xl.setAvoidFirstLastClipping(true); // 几个x坐标轴之间才绘制? // xl.setSpaceBetweenLabels(5); // 如果false,那么x坐标轴将不可见 xl.setEnabled(true); // 将X坐标轴放置在底部,默认是在顶部。 xl.setPosition(XAxis.XAxisPosition.BOTTOM); // 图表左边的y坐标轴线 YAxis leftAxis = mChart.getAxisLeft(); leftAxis.setTextColor(Color.BLACK); // 最大值 leftAxis.setAxisMaximum(500f); // 最小值 leftAxis.setAxisMinimum(-300f); // 不一定要从0开始 leftAxis.setStartAtZero(false); leftAxis.setDrawGridLines(false); YAxis rightAxis = mChart.getAxisRight(); // 不显示图表的右边y坐标轴线 rightAxis.setEnabled(false); } private void changepage(){ if(Bl_0.BLe_stus==true){ Log.i("'jim"," connecttrue"); relayout2.setVisibility(View.GONE); relayout1.setVisibility(View.VISIBLE); } } public void onClick(View view){ switch (view.getId()){ } } }
f5b84613e80699fb36397be553aa9fc797cf915f
56943b4b3ab56ffcc7a4cb0e09c7d0c79329832e
/app/src/main/java/com/codepath/gridimagesearch/Activities/SearchActivity.java
983d20a1d70bca8cb0974fa486d9535fa833f12e
[]
no_license
eyecx/ImageSearchClient
baa58f01d3e964aa1cb4ab360eb3a4bee1c741b7
82f6a69b0784f3b1239ac73c765dfb55597db129
refs/heads/master
2021-01-22T04:36:36.502224
2015-02-10T04:49:09
2015-02-10T04:49:09
30,513,800
0
0
null
null
null
null
UTF-8
Java
false
false
5,839
java
package com.codepath.gridimagesearch.Activities; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.Image; import android.net.Uri; import android.preference.PreferenceManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.Toast; import com.codepath.gridimagesearch.Adapters.ImageResultsAdapter; import com.codepath.gridimagesearch.Models.ImageResult; import com.codepath.gridimagesearch.R; import com.codepath.gridimagesearch.Utils.EndlessScrollListener; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class SearchActivity extends ActionBarActivity { private GridView gvResults; private ArrayList<ImageResult> imageResults; private ImageResultsAdapter aImageResults; private String searchQuery; private SearchView searchView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); setupViews(); imageResults = new ArrayList<ImageResult>(); aImageResults = new ImageResultsAdapter(this, imageResults); gvResults.setAdapter(aImageResults); gvResults.setOnScrollListener(new EndlessScrollListener() { @Override public void onLoadMore(int page, int totalItemsCount) { onSearchAPICall(page, false); } }); } private void setupViews() { gvResults = (GridView) findViewById(R.id.gvResults); gvResults.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(SearchActivity.this, ImageDisplayActivity.class); ImageResult result = imageResults.get(position); i.putExtra("result", result); startActivity(i); } }); } public boolean onClickedSettings (MenuItem item) { Intent i = new Intent(this, SettingsActivity.class); startActivity(i); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_search, menu); MenuItem searchItem = menu.findItem(R.id.action_search); searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchQuery = query; onSearchAPICall(0, true); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return super.onCreateOptionsMenu(menu); } public void onSearchAPICall(int page, final boolean shouldClearAdapter) { SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String imageSizePref = sharedPref.getString("image_size", ""); String imageColorPref = sharedPref.getString("image_color", ""); String imageTypePref = sharedPref.getString("image_type", ""); String searchSitePref = sharedPref.getString("search_site", ""); AsyncHttpClient client = new AsyncHttpClient(); String searchUrl = "https://ajax.googleapis.com/ajax/services/search/images"; Uri.Builder builder = Uri.parse(searchUrl).buildUpon(); builder.appendQueryParameter("v", "1.0"); builder.appendQueryParameter("rsz", "8"); builder.appendQueryParameter("q", searchQuery); builder.appendQueryParameter("start", Integer.toString(page)); builder.appendQueryParameter("imgsz", imageSizePref); builder.appendQueryParameter("imgcolor", imageColorPref); builder.appendQueryParameter("imgtype", imageTypePref); builder.appendQueryParameter("as_sitesearch", searchSitePref); String finalUrl = builder.build().toString(); client.get(finalUrl, new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { JSONArray imageResultsJSON = response.getJSONObject("responseData").getJSONArray("results"); if (shouldClearAdapter) { aImageResults.clear(); } aImageResults.addAll(ImageResult.fromJSONArray(imageResultsJSON)); } catch (JSONException e) { e.printStackTrace(); } } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
cab8d16f82fd8300b99df5d8d9b5aefeef86f16e
fcd30a1f519cd737058f8616996c62b2b43415e8
/MapboxAndroidSDK/src/main/java/com/mapbox/mapboxsdk/tileprovider/tilesource/TileMillLayer.java
ec31f66efd982cef538af02deca80d97cd573d74
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
onaio/OpenMapKit
4117c4d41541730ef33880f8c50bb9e1bff810b9
403d80d5d9412e82a2149d53522a097a6e9da41d
refs/heads/onadev
2021-01-17T04:59:23.815983
2017-08-31T08:07:45
2017-08-31T08:07:45
38,626,768
0
1
BSD-3-Clause
2017-12-01T06:29:06
2015-07-06T15:10:01
Java
UTF-8
Java
false
false
1,354
java
package com.mapbox.mapboxsdk.tileprovider.tilesource; import com.mapbox.mapboxsdk.constants.MapboxConstants; import com.mapbox.mapboxsdk.tileprovider.MapTile; import com.mapbox.mapboxsdk.tileprovider.constants.TileLayerConstants; public class TileMillLayer extends WebSourceTileLayer implements MapboxConstants { private static final String BASE_URL = "http://%s:20008/tile/%s"; public TileMillLayer(final String pHost, final String pMap, final float pMinZoom, final float pMaxZoom) { super(pHost, String.format(MAPBOX_LOCALE, BASE_URL, pHost, pMap)); mName = "TileMill"; mMinimumZoomLevel = pMinZoom; mMaximumZoomLevel = pMaxZoom; } public TileMillLayer(final String pHost, final String pMap) { this(pHost, pMap, TileLayerConstants.MINIMUM_ZOOMLEVEL, TileLayerConstants.MAXIMUM_ZOOMLEVEL); } public TileMillLayer(final String pMap) { this("localhost", pMap); } @Override public TileLayer setURL(final String aUrl) { super.setURL(aUrl + "/%d/%d/%d.png?updated=%d"); return this; } @Override public String getTileURL(final MapTile aTile, boolean hdpi) { return String.format(MAPBOX_LOCALE, mUrl, aTile.getZ(), aTile.getX(), aTile.getY(), System.currentTimeMillis() / 1000L); } }
29ee28259045cbfae3579d3f5b3747f3bf0ad2a1
fa869aa4e32e1fbcf585d675fe14e9e31910c431
/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java
2711f4a9a0455cc1a3029f143ee9cb9e0ac24a97
[ "Apache-2.0" ]
permissive
yu-yamada/presto-custom
4a90973e320eb3c1e37043d8879c0f215d52c5b2
0c9f35a34675b5155d3567688c19dee9593866ae
refs/heads/master
2021-01-13T07:52:46.017153
2016-09-26T14:07:22
2016-09-26T14:07:22
69,256,205
0
0
null
null
null
null
UTF-8
Java
false
false
102,187
java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.analyzer; import com.facebook.presto.Session; import com.facebook.presto.metadata.FunctionKind; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.metadata.QualifiedObjectName; import com.facebook.presto.metadata.SessionPropertyManager.SessionPropertyValue; import com.facebook.presto.metadata.SqlFunction; import com.facebook.presto.metadata.TableHandle; import com.facebook.presto.metadata.TableLayout; import com.facebook.presto.metadata.TableLayoutResult; import com.facebook.presto.metadata.TableMetadata; import com.facebook.presto.metadata.ViewDefinition; import com.facebook.presto.security.AccessControl; import com.facebook.presto.security.AllowAllAccessControl; import com.facebook.presto.security.ViewAccessControl; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.Constraint; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.security.Identity; import com.facebook.presto.spi.session.PropertyMetadata; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeSignature; import com.facebook.presto.sql.ExpressionUtils; import com.facebook.presto.sql.parser.ParsingException; import com.facebook.presto.sql.parser.SqlParser; import com.facebook.presto.sql.planner.DependencyExtractor; import com.facebook.presto.sql.planner.ExpressionInterpreter; import com.facebook.presto.sql.planner.NoOpSymbolResolver; import com.facebook.presto.sql.planner.Symbol; import com.facebook.presto.sql.planner.optimizations.CanonicalizeExpressions; import com.facebook.presto.sql.tree.AliasedRelation; import com.facebook.presto.sql.tree.AllColumns; import com.facebook.presto.sql.tree.ArrayConstructor; import com.facebook.presto.sql.tree.BooleanLiteral; import com.facebook.presto.sql.tree.Cast; import com.facebook.presto.sql.tree.ComparisonExpression; import com.facebook.presto.sql.tree.CreateTable; import com.facebook.presto.sql.tree.CreateTableAsSelect; import com.facebook.presto.sql.tree.CreateView; import com.facebook.presto.sql.tree.DefaultTraversalVisitor; import com.facebook.presto.sql.tree.Delete; import com.facebook.presto.sql.tree.DereferenceExpression; import com.facebook.presto.sql.tree.DoubleLiteral; import com.facebook.presto.sql.tree.Except; import com.facebook.presto.sql.tree.Explain; import com.facebook.presto.sql.tree.ExplainFormat; import com.facebook.presto.sql.tree.ExplainOption; import com.facebook.presto.sql.tree.ExplainType; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FieldReference; import com.facebook.presto.sql.tree.FrameBound; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.GroupBy; import com.facebook.presto.sql.tree.GroupingElement; import com.facebook.presto.sql.tree.InPredicate; import com.facebook.presto.sql.tree.Insert; import com.facebook.presto.sql.tree.Intersect; import com.facebook.presto.sql.tree.Join; import com.facebook.presto.sql.tree.JoinCriteria; import com.facebook.presto.sql.tree.JoinOn; import com.facebook.presto.sql.tree.JoinUsing; import com.facebook.presto.sql.tree.LikePredicate; import com.facebook.presto.sql.tree.LongLiteral; import com.facebook.presto.sql.tree.NaturalJoin; import com.facebook.presto.sql.tree.Node; import com.facebook.presto.sql.tree.QualifiedName; import com.facebook.presto.sql.tree.QualifiedNameReference; import com.facebook.presto.sql.tree.Query; import com.facebook.presto.sql.tree.QuerySpecification; import com.facebook.presto.sql.tree.Relation; import com.facebook.presto.sql.tree.Row; import com.facebook.presto.sql.tree.SampledRelation; import com.facebook.presto.sql.tree.SelectItem; import com.facebook.presto.sql.tree.SetOperation; import com.facebook.presto.sql.tree.ShowCatalogs; import com.facebook.presto.sql.tree.ShowColumns; import com.facebook.presto.sql.tree.ShowCreate; import com.facebook.presto.sql.tree.ShowFunctions; import com.facebook.presto.sql.tree.ShowPartitions; import com.facebook.presto.sql.tree.ShowSchemas; import com.facebook.presto.sql.tree.ShowSession; import com.facebook.presto.sql.tree.ShowTables; import com.facebook.presto.sql.tree.SimpleGroupBy; import com.facebook.presto.sql.tree.SingleColumn; import com.facebook.presto.sql.tree.SortItem; import com.facebook.presto.sql.tree.Statement; import com.facebook.presto.sql.tree.StringLiteral; import com.facebook.presto.sql.tree.Table; import com.facebook.presto.sql.tree.TableElement; import com.facebook.presto.sql.tree.TableSubquery; import com.facebook.presto.sql.tree.Unnest; import com.facebook.presto.sql.tree.Use; import com.facebook.presto.sql.tree.Values; import com.facebook.presto.sql.tree.Window; import com.facebook.presto.sql.tree.WindowFrame; import com.facebook.presto.sql.tree.With; import com.facebook.presto.sql.tree.WithQuery; import com.facebook.presto.type.ArrayType; import com.facebook.presto.type.MapType; import com.facebook.presto.type.RowType; import com.facebook.presto.type.TypeRegistry; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.primitives.Ints; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_COLUMNS; import static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_INTERNAL_PARTITIONS; import static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_SCHEMATA; import static com.facebook.presto.connector.informationSchema.InformationSchemaMetadata.TABLE_TABLES; import static com.facebook.presto.metadata.FunctionKind.AGGREGATE; import static com.facebook.presto.metadata.FunctionKind.APPROXIMATE_AGGREGATE; import static com.facebook.presto.metadata.FunctionKind.WINDOW; import static com.facebook.presto.metadata.MetadataUtil.createQualifiedName; import static com.facebook.presto.metadata.MetadataUtil.createQualifiedObjectName; import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static com.facebook.presto.spi.StandardErrorCode.INVALID_TABLE_PROPERTY; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.sql.QueryUtil.aliased; import static com.facebook.presto.sql.QueryUtil.aliasedName; import static com.facebook.presto.sql.QueryUtil.aliasedNullToEmpty; import static com.facebook.presto.sql.QueryUtil.ascending; import static com.facebook.presto.sql.QueryUtil.caseWhen; import static com.facebook.presto.sql.QueryUtil.equal; import static com.facebook.presto.sql.QueryUtil.functionCall; import static com.facebook.presto.sql.QueryUtil.logicalAnd; import static com.facebook.presto.sql.QueryUtil.nameReference; import static com.facebook.presto.sql.QueryUtil.ordering; import static com.facebook.presto.sql.QueryUtil.row; import static com.facebook.presto.sql.QueryUtil.selectAll; import static com.facebook.presto.sql.QueryUtil.selectList; import static com.facebook.presto.sql.QueryUtil.simpleQuery; import static com.facebook.presto.sql.QueryUtil.singleValueQuery; import static com.facebook.presto.sql.QueryUtil.subquery; import static com.facebook.presto.sql.QueryUtil.table; import static com.facebook.presto.sql.QueryUtil.unaliasedName; import static com.facebook.presto.sql.SqlFormatter.formatSql; import static com.facebook.presto.sql.analyzer.ExpressionAnalyzer.createConstantAnalyzer; import static com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypes; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.AMBIGUOUS_ATTRIBUTE; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.CATALOG_NOT_SPECIFIED; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.COLUMN_NAME_NOT_SPECIFIED; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.COLUMN_TYPE_UNKNOWN; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.DUPLICATE_COLUMN_NAME; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.DUPLICATE_RELATION; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_ORDINAL; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_SCHEMA_NAME; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_WINDOW_FRAME; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISMATCHED_COLUMN_ALIASES; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISMATCHED_SET_COLUMN_TYPES; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISSING_CATALOG; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISSING_COLUMN; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISSING_SCHEMA; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.MISSING_TABLE; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.MUST_BE_WINDOW_FUNCTION; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.NESTED_WINDOW; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.NON_NUMERIC_SAMPLE_PERCENTAGE; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.NOT_SUPPORTED; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.ORDER_BY_MUST_BE_IN_SELECT; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.SCHEMA_NOT_SPECIFIED; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.TABLE_ALREADY_EXISTS; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.TYPE_MISMATCH; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.VIEW_ANALYSIS_ERROR; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.VIEW_IS_STALE; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.VIEW_PARSE_ERROR; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.WILDCARD_WITHOUT_FROM; import static com.facebook.presto.sql.planner.ExpressionInterpreter.expressionOptimizer; import static com.facebook.presto.sql.tree.BooleanLiteral.FALSE_LITERAL; import static com.facebook.presto.sql.tree.BooleanLiteral.TRUE_LITERAL; import static com.facebook.presto.sql.tree.ComparisonExpression.Type.EQUAL; import static com.facebook.presto.sql.tree.ExplainFormat.Type.TEXT; import static com.facebook.presto.sql.tree.ExplainType.Type.DISTRIBUTED; import static com.facebook.presto.sql.tree.ExplainType.Type.LOGICAL; import static com.facebook.presto.sql.tree.FrameBound.Type.CURRENT_ROW; import static com.facebook.presto.sql.tree.FrameBound.Type.FOLLOWING; import static com.facebook.presto.sql.tree.FrameBound.Type.PRECEDING; import static com.facebook.presto.sql.tree.FrameBound.Type.UNBOUNDED_FOLLOWING; import static com.facebook.presto.sql.tree.FrameBound.Type.UNBOUNDED_PRECEDING; import static com.facebook.presto.sql.tree.ShowCreate.Type.TABLE; import static com.facebook.presto.sql.tree.ShowCreate.Type.VIEW; import static com.facebook.presto.sql.tree.WindowFrame.Type.RANGE; import static com.facebook.presto.type.TypeRegistry.canCoerce; import static com.facebook.presto.type.UnknownType.UNKNOWN; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.facebook.presto.util.ImmutableCollectors.toImmutableSet; import static com.facebook.presto.util.Types.checkType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Iterables.transform; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; class StatementAnalyzer extends DefaultTraversalVisitor<RelationType, AnalysisContext> { private final Analysis analysis; private final Metadata metadata; private final Session session; private final Optional<QueryExplainer> queryExplainer; private final boolean experimentalSyntaxEnabled; private final SqlParser sqlParser; private final AccessControl accessControl; public StatementAnalyzer( Analysis analysis, Metadata metadata, SqlParser sqlParser, AccessControl accessControl, Session session, boolean experimentalSyntaxEnabled, Optional<QueryExplainer> queryExplainer) { this.analysis = requireNonNull(analysis, "analysis is null"); this.metadata = requireNonNull(metadata, "metadata is null"); this.sqlParser = requireNonNull(sqlParser, "sqlParser is null"); this.accessControl = requireNonNull(accessControl, "accessControl is null"); this.session = requireNonNull(session, "session is null"); this.experimentalSyntaxEnabled = experimentalSyntaxEnabled; this.queryExplainer = requireNonNull(queryExplainer, "queryExplainer is null"); } @Override protected RelationType visitShowTables(ShowTables showTables, AnalysisContext context) { String catalogName = session.getCatalog().orElse(null); String schemaName = session.getSchema().orElse(null); Optional<QualifiedName> schema = showTables.getSchema(); if (schema.isPresent()) { List<String> parts = schema.get().getParts(); if (parts.size() > 2) { throw new SemanticException(INVALID_SCHEMA_NAME, showTables, "Too many parts in schema name: %s", schema.get()); } if (parts.size() == 2) { catalogName = parts.get(0); } schemaName = schema.get().getSuffix(); } if (catalogName == null) { throw new SemanticException(CATALOG_NOT_SPECIFIED, showTables, "Catalog must be specified when session catalog is not set"); } if (schemaName == null) { throw new SemanticException(SCHEMA_NOT_SPECIFIED, showTables, "Schema must be specified when session schema is not set"); } if (!metadata.listSchemaNames(session, catalogName).contains(schemaName)) { throw new SemanticException(MISSING_SCHEMA, showTables, "Schema '%s' does not exist", schemaName); } Expression predicate = equal(nameReference("table_schema"), new StringLiteral(schemaName)); Optional<String> likePattern = showTables.getLikePattern(); if (likePattern.isPresent()) { Expression likePredicate = new LikePredicate(nameReference("table_name"), new StringLiteral(likePattern.get()), null); predicate = logicalAnd(predicate, likePredicate); } Query query = simpleQuery( selectList(aliasedName("table_name", "Table")), from(catalogName, TABLE_TABLES), predicate, ordering(ascending("table_name"))); return process(query, context); } @Override protected RelationType visitShowSchemas(ShowSchemas node, AnalysisContext context) { if (!node.getCatalog().isPresent() && !session.getCatalog().isPresent()) { throw new SemanticException(CATALOG_NOT_SPECIFIED, node, "Catalog must be specified when session catalog is not set"); } Optional<Expression> predicate = Optional.empty(); Optional<String> likePattern = node.getLikePattern(); if (likePattern.isPresent()) { predicate = Optional.of(new LikePredicate(nameReference("schema_name"), new StringLiteral(likePattern.get()), null)); } Query query = simpleQuery( selectList(aliasedName("schema_name", "Schema")), from(node.getCatalog().orElseGet(() -> session.getCatalog().get()), TABLE_SCHEMATA), predicate, ordering(ascending("schema_name"))); return process(query, context); } @Override protected RelationType visitShowCatalogs(ShowCatalogs node, AnalysisContext context) { List<Expression> rows = metadata.getCatalogNames().keySet().stream() .map(name -> row(new StringLiteral(name))) .collect(toList()); Optional<Expression> predicate = Optional.empty(); Optional<String> likePattern = node.getLikePattern(); if (likePattern.isPresent()) { predicate = Optional.of(new LikePredicate(nameReference("Catalog"), new StringLiteral(likePattern.get()), null)); } Query query = simpleQuery( selectList(new AllColumns()), aliased(new Values(rows), "catalogs", ImmutableList.of("Catalog")), predicate, ordering(ascending("Catalog"))); return process(query, context); } @Override protected RelationType visitShowColumns(ShowColumns showColumns, AnalysisContext context) { QualifiedObjectName tableName = createQualifiedObjectName(session, showColumns, showColumns.getTable()); if (!metadata.getView(session, tableName).isPresent() && !metadata.getTableHandle(session, tableName).isPresent()) { throw new SemanticException(MISSING_TABLE, showColumns, "Table '%s' does not exist", tableName); } Query query = simpleQuery( selectList( aliasedName("column_name", "Column"), aliasedName("data_type", "Type"), aliasedNullToEmpty("comment", "Comment")), from(tableName.getCatalogName(), TABLE_COLUMNS), logicalAnd( equal(nameReference("table_schema"), new StringLiteral(tableName.getSchemaName())), equal(nameReference("table_name"), new StringLiteral(tableName.getObjectName()))), ordering(ascending("ordinal_position"))); return process(query, context); } private static <T> Expression getExpression(PropertyMetadata<T> property, Object value) throws PrestoException { return toExpression(property.encode(property.getJavaType().cast(value))); } private static Expression toExpression(Object value) throws PrestoException { if (value instanceof String) { return new StringLiteral(value.toString()); } if (value instanceof Boolean) { return new BooleanLiteral(value.toString()); } if (value instanceof Long || value instanceof Integer) { return new LongLiteral(value.toString()); } if (value instanceof Double) { return new DoubleLiteral(value.toString()); } if (value instanceof List) { List<?> list = (List<?>) value; return new ArrayConstructor(list.stream() .map(StatementAnalyzer::toExpression) .collect(toList())); } throw new PrestoException(INVALID_TABLE_PROPERTY, format("Failed to convert object of type %s to expression: %s", value.getClass().getName(), value)); } @Override protected RelationType visitUse(Use node, AnalysisContext context) { analysis.setUpdateType("USE"); throw new SemanticException(NOT_SUPPORTED, node, "USE statement is not supported"); } @Override protected RelationType visitShowPartitions(ShowPartitions showPartitions, AnalysisContext context) { QualifiedObjectName table = createQualifiedObjectName(session, showPartitions, showPartitions.getTable()); Optional<TableHandle> tableHandle = metadata.getTableHandle(session, table); if (!tableHandle.isPresent()) { throw new SemanticException(MISSING_TABLE, showPartitions, "Table '%s' does not exist", table); } List<TableLayoutResult> layouts = metadata.getLayouts(session, tableHandle.get(), Constraint.alwaysTrue(), Optional.empty()); if (layouts.size() != 1) { throw new SemanticException(NOT_SUPPORTED, showPartitions, "Table does not have exactly one layout: %s", table); } TableLayout layout = getOnlyElement(layouts).getLayout(); if (!layout.getDiscretePredicates().isPresent()) { throw new SemanticException(NOT_SUPPORTED, showPartitions, "Table does not have partition columns: %s", table); } List<ColumnHandle> partitionColumns = layout.getDiscretePredicates().get().getColumns(); /* Generate a dynamic pivot to output one column per partition key. For example, a table with two partition keys (ds, cluster_name) would generate the following query: SELECT partition_number , max(CASE WHEN partition_key = 'ds' THEN partition_value END) ds , max(CASE WHEN partition_key = 'cluster_name' THEN partition_value END) cluster_name FROM ... GROUP BY partition_number The values are also cast to the type of the partition column. The query is then wrapped to allow custom filtering and ordering. */ ImmutableList.Builder<SelectItem> selectList = ImmutableList.builder(); ImmutableList.Builder<SelectItem> wrappedList = ImmutableList.builder(); selectList.add(unaliasedName("partition_number")); for (ColumnHandle columnHandle : partitionColumns) { ColumnMetadata column = metadata.getColumnMetadata(session, tableHandle.get(), columnHandle); Expression key = equal(nameReference("partition_key"), new StringLiteral(column.getName())); Expression value = caseWhen(key, nameReference("partition_value")); value = new Cast(value, column.getType().getTypeSignature().toString()); Expression function = functionCall("max", value); selectList.add(new SingleColumn(function, column.getName())); wrappedList.add(unaliasedName(column.getName())); } Query query = simpleQuery( selectAll(selectList.build()), from(table.getCatalogName(), TABLE_INTERNAL_PARTITIONS), Optional.of(logicalAnd( equal(nameReference("table_schema"), new StringLiteral(table.getSchemaName())), equal(nameReference("table_name"), new StringLiteral(table.getObjectName())))), Optional.of(new GroupBy(false, ImmutableList.of(new SimpleGroupBy(ImmutableList.of(nameReference("partition_number")))))), Optional.empty(), ImmutableList.of(), Optional.empty()); query = simpleQuery( selectAll(wrappedList.build()), subquery(query), showPartitions.getWhere(), Optional.empty(), Optional.empty(), ImmutableList.<SortItem>builder() .addAll(showPartitions.getOrderBy()) .add(ascending("partition_number")) .build(), showPartitions.getLimit()); return process(query, context); } @Override protected RelationType visitShowCreate(ShowCreate node, AnalysisContext context) { QualifiedObjectName objectName = createQualifiedObjectName(session, node, node.getName()); Optional<ViewDefinition> viewDefinition = metadata.getView(session, objectName); if (node.getType() == VIEW) { if (!viewDefinition.isPresent()) { if (metadata.getTableHandle(session, objectName).isPresent()) { throw new SemanticException(NOT_SUPPORTED, node, "Relation '%s' is a table, not a view", objectName); } throw new SemanticException(MISSING_TABLE, node, "View '%s' does not exist", objectName); } Query query = parseView(viewDefinition.get().getOriginalSql(), objectName, node); String sql = formatSql(new CreateView(createQualifiedName(objectName), query, false)).trim(); return process(singleValueQuery("Create View", sql), context); } if (node.getType() == TABLE) { if (viewDefinition.isPresent()) { throw new SemanticException(NOT_SUPPORTED, node, "Relation '%s' is a view, not a table", objectName); } Optional<TableHandle> tableHandle = metadata.getTableHandle(session, objectName); if (!tableHandle.isPresent()) { throw new SemanticException(MISSING_TABLE, node, "Table '%s' does not exist", objectName); } ConnectorTableMetadata connectorTableMetadata = metadata.getTableMetadata(session, tableHandle.get()).getMetadata(); List<TableElement> columns = connectorTableMetadata.getColumns().stream() .filter(column -> !column.isHidden()) .map(column -> new TableElement(column.getName(), column.getType().getDisplayName())) .collect(toImmutableList()); Map<String, Object> properties = connectorTableMetadata.getProperties(); Map<String, PropertyMetadata<?>> allTableProperties = metadata.getTablePropertyManager().getAllTableProperties().get(objectName.getCatalogName()); Map<String, Expression> sqlProperties = new HashMap<>(); for (Map.Entry<String, Object> propertyEntry : properties.entrySet()) { String propertyName = propertyEntry.getKey(); Object value = propertyEntry.getValue(); if (value == null) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("Property %s for table %s cannot have a null value", propertyName, objectName)); } PropertyMetadata<?> property = allTableProperties.get(propertyName); if (!property.getJavaType().isInstance(value)) { throw new PrestoException(INVALID_TABLE_PROPERTY, format( "Property %s for table %s should have value of type %s, not %s", propertyName, objectName, property.getJavaType().getName(), value.getClass().getName())); } Expression sqlExpression = getExpression(property, value); sqlProperties.put(propertyName, sqlExpression); } CreateTable createTable = new CreateTable(QualifiedName.of(objectName.getCatalogName(), objectName.getSchemaName(), objectName.getObjectName()), columns, false, sqlProperties); Query query = singleValueQuery("Create Table", formatSql(createTable).trim()); return process(query, context); } throw new UnsupportedOperationException("SHOW CREATE only supported for tables and views"); } @Override protected RelationType visitShowFunctions(ShowFunctions node, AnalysisContext context) { ImmutableList.Builder<Expression> rows = ImmutableList.builder(); for (SqlFunction function : metadata.listFunctions()) { if (function.getSignature().getKind() == APPROXIMATE_AGGREGATE) { continue; } rows.add(row( new StringLiteral(function.getSignature().getName()), new StringLiteral(function.getSignature().getReturnType().toString()), new StringLiteral(Joiner.on(", ").join(function.getSignature().getArgumentTypes())), new StringLiteral(getFunctionType(function)), function.isDeterministic() ? TRUE_LITERAL : FALSE_LITERAL, new StringLiteral(nullToEmpty(function.getDescription())))); } Map<String, String> columns = ImmutableMap.<String, String>builder() .put("function_name", "Function") .put("return_type", "Return Type") .put("argument_types", "Argument Types") .put("function_type", "Function Type") .put("deterministic", "Deterministic") .put("description", "Description") .build(); Query query = simpleQuery( selectAll(columns.entrySet().stream() .map(entry -> aliasedName(entry.getKey(), entry.getValue())) .collect(toImmutableList())), aliased(new Values(rows.build()), "functions", ImmutableList.copyOf(columns.keySet())), ordering( ascending("function_name"), ascending("return_type"), ascending("argument_types"), ascending("function_type"))); return process(query, context); } private static String getFunctionType(SqlFunction function) { FunctionKind kind = function.getSignature().getKind(); switch (kind) { case AGGREGATE: case APPROXIMATE_AGGREGATE: return "aggregate"; case WINDOW: return "window"; case SCALAR: return "scalar"; } throw new IllegalArgumentException("Unsupported function kind: " + kind); } @Override protected RelationType visitShowSession(ShowSession node, AnalysisContext context) { ImmutableList.Builder<Expression> rows = ImmutableList.builder(); List<SessionPropertyValue> sessionProperties = metadata.getSessionPropertyManager().getAllSessionProperties(session); for (SessionPropertyValue sessionProperty : sessionProperties) { if (sessionProperty.isHidden()) { continue; } String value = sessionProperty.getValue(); String defaultValue = sessionProperty.getDefaultValue(); rows.add(row( new StringLiteral(sessionProperty.getFullyQualifiedName()), new StringLiteral(nullToEmpty(value)), new StringLiteral(nullToEmpty(defaultValue)), new StringLiteral(sessionProperty.getType()), new StringLiteral(sessionProperty.getDescription()), TRUE_LITERAL)); } // add bogus row so we can support empty sessions StringLiteral empty = new StringLiteral(""); rows.add(row(empty, empty, empty, empty, empty, FALSE_LITERAL)); Query query = simpleQuery( selectList( aliasedName("name", "Name"), aliasedName("value", "Value"), aliasedName("default", "Default"), aliasedName("type", "Type"), aliasedName("description", "Description")), aliased( new Values(rows.build()), "session", ImmutableList.of("name", "value", "default", "type", "description", "include")), nameReference("include")); return process(query, context); } @Override protected RelationType visitInsert(Insert insert, AnalysisContext context) { QualifiedObjectName targetTable = createQualifiedObjectName(session, insert, insert.getTarget()); if (metadata.getView(session, targetTable).isPresent()) { throw new SemanticException(NOT_SUPPORTED, insert, "Inserting into views is not supported"); } // analyze the query that creates the data RelationType queryDescriptor = process(insert.getQuery(), context); analysis.setUpdateType("INSERT"); analysis.setStatement(insert); // verify the insert destination columns match the query Optional<TableHandle> targetTableHandle = metadata.getTableHandle(session, targetTable); if (!targetTableHandle.isPresent()) { throw new SemanticException(MISSING_TABLE, insert, "Table '%s' does not exist", targetTable); } accessControl.checkCanInsertIntoTable(session.getRequiredTransactionId(), session.getIdentity(), targetTable); TableMetadata tableMetadata = metadata.getTableMetadata(session, targetTableHandle.get()); List<String> tableColumns = tableMetadata.getVisibleColumnNames(); List<String> insertColumns; if (insert.getColumns().isPresent()) { insertColumns = insert.getColumns().get().stream() .map(String::toLowerCase) .collect(toImmutableList()); Set<String> columnNames = new HashSet<>(); for (String insertColumn : insertColumns) { if (!tableColumns.contains(insertColumn)) { throw new SemanticException(MISSING_COLUMN, insert, "Insert column name does not exist in target table: %s", insertColumn); } if (!columnNames.add(insertColumn)) { throw new SemanticException(DUPLICATE_COLUMN_NAME, insert, "Insert column name is specified more than once: %s", insertColumn); } } } else { insertColumns = tableColumns; } Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, targetTableHandle.get()); analysis.setInsert(new Analysis.Insert( targetTableHandle.get(), insertColumns.stream().map(columnHandles::get).collect(toImmutableList()))); Iterable<Type> tableTypes = insertColumns.stream() .map(insertColumn -> tableMetadata.getColumn(insertColumn).getType()) .collect(toImmutableList()); Iterable<Type> queryTypes = transform(queryDescriptor.getVisibleFields(), Field::getType); if (!typesMatchForInsert(tableTypes, queryTypes)) { throw new SemanticException(MISMATCHED_SET_COLUMN_TYPES, insert, "Insert query has mismatched column types: " + "Table: [" + Joiner.on(", ").join(tableTypes) + "], " + "Query: [" + Joiner.on(", ").join(queryTypes) + "]"); } return new RelationType(Field.newUnqualified("rows", BIGINT)); } private static boolean typesMatchForInsert(Iterable<Type> tableTypes, Iterable<Type> queryTypes) { if (Iterables.size(tableTypes) != Iterables.size(queryTypes)) { return false; } Iterator<Type> tableTypesIterator = tableTypes.iterator(); Iterator<Type> queryTypesIterator = queryTypes.iterator(); while (tableTypesIterator.hasNext()) { Type tableType = tableTypesIterator.next(); Type queryType = queryTypesIterator.next(); if (!canCoerce(queryType.getTypeSignature(), tableType.getTypeSignature())) { return false; } } return true; } @Override protected RelationType visitDelete(Delete node, AnalysisContext context) { Table table = node.getTable(); QualifiedObjectName tableName = createQualifiedObjectName(session, table, table.getName()); if (metadata.getView(session, tableName).isPresent()) { throw new SemanticException(NOT_SUPPORTED, node, "Deleting from views is not supported"); } // Analyzer checks for select permissions but DELETE has a separate permission, so disable access checks // TODO: we shouldn't need to create a new analyzer. The access control should be carried in the context object StatementAnalyzer analyzer = new StatementAnalyzer( analysis, metadata, sqlParser, new AllowAllAccessControl(), session, experimentalSyntaxEnabled, queryExplainer); RelationType descriptor = analyzer.process(table, context); node.getWhere().ifPresent(where -> analyzer.analyzeWhere(node, descriptor, context, where)); analysis.setUpdateType("DELETE"); analysis.setStatement(node); accessControl.checkCanDeleteFromTable(session.getRequiredTransactionId(), session.getIdentity(), tableName); return new RelationType(Field.newUnqualified("rows", BIGINT)); } @Override protected RelationType visitCreateTableAsSelect(CreateTableAsSelect node, AnalysisContext context) { analysis.setUpdateType("CREATE TABLE"); // turn this into a query that has a new table writer node on top. QualifiedObjectName targetTable = createQualifiedObjectName(session, node, node.getName()); analysis.setCreateTableDestination(targetTable); Optional<TableHandle> targetTableHandle = metadata.getTableHandle(session, targetTable); if (targetTableHandle.isPresent()) { if (node.isNotExists()) { analysis.setCreateTableAsSelectNoOp(true); analysis.setStatement(node); return new RelationType(Field.newUnqualified("rows", BIGINT)); } throw new SemanticException(TABLE_ALREADY_EXISTS, node, "Destination table '%s' already exists", targetTable); } for (Expression expression : node.getProperties().values()) { // analyze table property value expressions which must be constant createConstantAnalyzer(metadata, session) .analyze(expression, new RelationType(), context); } analysis.setCreateTableProperties(node.getProperties()); accessControl.checkCanCreateTable(session.getRequiredTransactionId(), session.getIdentity(), targetTable); analysis.setCreateTableAsSelectWithData(node.isWithData()); // analyze the query that creates the table RelationType descriptor = process(node.getQuery(), context); analysis.setStatement(node); validateColumns(node, descriptor); return new RelationType(Field.newUnqualified("rows", BIGINT)); } @Override protected RelationType visitCreateView(CreateView node, AnalysisContext context) { analysis.setUpdateType("CREATE VIEW"); // analyze the query that creates the view StatementAnalyzer analyzer = new StatementAnalyzer( analysis, metadata, sqlParser, new ViewAccessControl(accessControl), session, experimentalSyntaxEnabled, queryExplainer); RelationType descriptor = analyzer.process(node.getQuery(), new AnalysisContext()); QualifiedObjectName viewName = createQualifiedObjectName(session, node, node.getName()); accessControl.checkCanCreateView(session.getRequiredTransactionId(), session.getIdentity(), viewName); validateColumns(node, descriptor); return descriptor; } private static void validateColumns(Statement node, RelationType descriptor) { // verify that all column names are specified and unique // TODO: collect errors and return them all at once Set<String> names = new HashSet<>(); for (Field field : descriptor.getVisibleFields()) { Optional<String> fieldName = field.getName(); if (!fieldName.isPresent()) { throw new SemanticException(COLUMN_NAME_NOT_SPECIFIED, node, "Column name not specified at position %s", descriptor.indexOf(field) + 1); } if (!names.add(fieldName.get())) { throw new SemanticException(DUPLICATE_COLUMN_NAME, node, "Column name '%s' specified more than once", fieldName.get()); } if (field.getType().equals(UNKNOWN)) { throw new SemanticException(COLUMN_TYPE_UNKNOWN, node, "Column type is unknown: %s", fieldName.get()); } } } @Override protected RelationType visitExplain(Explain node, AnalysisContext context) throws SemanticException { if (node.isAnalyze()) { if (node.getOptions().stream().anyMatch(option -> !option.equals(new ExplainType(DISTRIBUTED)))) { throw new SemanticException(NOT_SUPPORTED, node, "EXPLAIN ANALYZE only supports TYPE DISTRIBUTED option"); } process(node.getStatement(), context); Statement statement = analysis.getStatement(); // Some statements, like SHOW COLUMNS, are rewritten into a SELECT if (statement != node.getStatement()) { if (node.getLocation().isPresent()) { node = new Explain(node.getLocation().get(), node.isAnalyze(), statement, node.getOptions()); } else { node = new Explain(statement, node.isAnalyze(), node.getOptions()); } } analysis.setStatement(node); analysis.setUpdateType(null); RelationType type = new RelationType(Field.newUnqualified("Query Plan", VARCHAR)); analysis.setOutputDescriptor(node, type); return type; } checkState(queryExplainer.isPresent(), "query explainer not available"); ExplainType.Type planType = LOGICAL; ExplainFormat.Type planFormat = TEXT; List<ExplainOption> options = node.getOptions(); for (ExplainOption option : options) { if (option instanceof ExplainType) { planType = ((ExplainType) option).getType(); break; } } for (ExplainOption option : options) { if (option instanceof ExplainFormat) { planFormat = ((ExplainFormat) option).getType(); break; } } String plan = getQueryPlan(node, planType, planFormat); return process(singleValueQuery("Query Plan", plan), context); } private String getQueryPlan(Explain node, ExplainType.Type planType, ExplainFormat.Type planFormat) throws IllegalArgumentException { switch (planFormat) { case GRAPHVIZ: return queryExplainer.get().getGraphvizPlan(session, node.getStatement(), planType); case TEXT: return queryExplainer.get().getPlan(session, node.getStatement(), planType); } throw new IllegalArgumentException("Invalid Explain Format: " + planFormat.toString()); } @Override protected RelationType visitQuery(Query node, AnalysisContext parentContext) { AnalysisContext context = new AnalysisContext(parentContext, new RelationType()); if (node.getApproximate().isPresent()) { if (!experimentalSyntaxEnabled) { throw new SemanticException(NOT_SUPPORTED, node, "approximate queries are not enabled"); } context.setApproximate(true); } analyzeWith(node, context); RelationType descriptor = process(node.getQueryBody(), context); analyzeOrderBy(node, descriptor, context); // Input fields == Output fields analysis.setOutputDescriptor(node, descriptor); analysis.setOutputExpressions(node, descriptorToFields(descriptor, context)); analysis.setStatement(node); return descriptor; } @Override protected RelationType visitUnnest(Unnest node, AnalysisContext context) { ImmutableList.Builder<Field> outputFields = ImmutableList.builder(); for (Expression expression : node.getExpressions()) { ExpressionAnalysis expressionAnalysis = analyzeExpression(expression, context.getLateralTupleDescriptor(), context); Type expressionType = expressionAnalysis.getType(expression); if (expressionType instanceof ArrayType) { outputFields.add(Field.newUnqualified(Optional.empty(), ((ArrayType) expressionType).getElementType())); } else if (expressionType instanceof MapType) { outputFields.add(Field.newUnqualified(Optional.empty(), ((MapType) expressionType).getKeyType())); outputFields.add(Field.newUnqualified(Optional.empty(), ((MapType) expressionType).getValueType())); } else { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Cannot unnest type: " + expressionType); } } if (node.isWithOrdinality()) { outputFields.add(Field.newUnqualified(Optional.empty(), BIGINT)); } RelationType descriptor = new RelationType(outputFields.build()); analysis.setOutputDescriptor(node, descriptor); return descriptor; } @Override protected RelationType visitTable(Table table, AnalysisContext context) { if (!table.getName().getPrefix().isPresent()) { // is this a reference to a WITH query? String name = table.getName().getSuffix(); WithQuery withQuery = context.getNamedQuery(name); if (withQuery != null) { Query query = withQuery.getQuery(); analysis.registerNamedQuery(table, query); // re-alias the fields with the name assigned to the query in the WITH declaration RelationType queryDescriptor = analysis.getOutputDescriptor(query); List<Field> fields; if (withQuery.getColumnNames().isPresent()) { // if columns are explicitly aliased -> WITH cte(alias1, alias2 ...) ImmutableList.Builder<Field> fieldBuilder = ImmutableList.builder(); int field = 0; for (String columnName : withQuery.getColumnNames().get()) { Field inputField = queryDescriptor.getFieldByIndex(field); fieldBuilder.add(Field.newQualified( QualifiedName.of(name), Optional.of(columnName), inputField.getType(), false)); field++; } fields = fieldBuilder.build(); } else { fields = queryDescriptor.getAllFields().stream() .map(field -> Field.newQualified( QualifiedName.of(name), field.getName(), field.getType(), field.isHidden())) .collect(toImmutableList()); } RelationType descriptor = new RelationType(fields); analysis.setOutputDescriptor(table, descriptor); return descriptor; } } QualifiedObjectName name = createQualifiedObjectName(session, table, table.getName()); Optional<ViewDefinition> optionalView = metadata.getView(session, name); if (optionalView.isPresent()) { ViewDefinition view = optionalView.get(); Query query = parseView(view.getOriginalSql(), name, table); analysis.registerNamedQuery(table, query); accessControl.checkCanSelectFromView(session.getRequiredTransactionId(), session.getIdentity(), name); RelationType descriptor = analyzeView(query, name, view.getCatalog(), view.getSchema(), view.getOwner(), table); if (isViewStale(view.getColumns(), descriptor.getVisibleFields())) { throw new SemanticException(VIEW_IS_STALE, table, "View '%s' is stale; it must be re-created", name); } // Derive the type of the view from the stored definition, not from the analysis of the underlying query. // This is needed in case the underlying table(s) changed and the query in the view now produces types that // are implicitly coercible to the declared view types. List<Field> outputFields = view.getColumns().stream() .map(column -> Field.newQualified( QualifiedName.of(name.getObjectName()), Optional.of(column.getName()), column.getType(), false)) .collect(toImmutableList()); analysis.addRelationCoercion(table, outputFields.stream().map(Field::getType).toArray(Type[]::new)); RelationType outputType = new RelationType(outputFields); analysis.setOutputDescriptor(table, outputType); return outputType; } Optional<TableHandle> tableHandle = metadata.getTableHandle(session, name); if (!tableHandle.isPresent()) { if (!metadata.getCatalogNames().containsKey(name.getCatalogName())) { throw new SemanticException(MISSING_CATALOG, table, "Catalog %s does not exist", name.getCatalogName()); } if (!metadata.listSchemaNames(session, name.getCatalogName()).contains(name.getSchemaName())) { throw new SemanticException(MISSING_SCHEMA, table, "Schema %s does not exist", name.getSchemaName()); } throw new SemanticException(MISSING_TABLE, table, "Table %s does not exist", name); } accessControl.checkCanSelectFromTable(session.getRequiredTransactionId(), session.getIdentity(), name); TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle.get()); Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle.get()); // TODO: discover columns lazily based on where they are needed (to support datasources that can't enumerate all tables) ImmutableList.Builder<Field> fields = ImmutableList.builder(); for (ColumnMetadata column : tableMetadata.getColumns()) { Field field = Field.newQualified(table.getName(), Optional.of(column.getName()), column.getType(), column.isHidden()); fields.add(field); ColumnHandle columnHandle = columnHandles.get(column.getName()); checkArgument(columnHandle != null, "Unknown field %s", field); analysis.setColumn(field, columnHandle); } analysis.registerTable(table, tableHandle.get()); RelationType descriptor = new RelationType(fields.build()); analysis.setOutputDescriptor(table, descriptor); return descriptor; } @Override protected RelationType visitAliasedRelation(AliasedRelation relation, AnalysisContext context) { RelationType child = process(relation.getRelation(), context); // todo this check should be inside of TupleDescriptor.withAlias, but the exception needs the node object if (relation.getColumnNames() != null) { int totalColumns = child.getVisibleFieldCount(); if (totalColumns != relation.getColumnNames().size()) { throw new SemanticException(MISMATCHED_COLUMN_ALIASES, relation, "Column alias list has %s entries but '%s' has %s columns available", relation.getColumnNames().size(), relation.getAlias(), totalColumns); } } RelationType descriptor = child.withAlias(relation.getAlias(), relation.getColumnNames()); analysis.setOutputDescriptor(relation, descriptor); return descriptor; } @Override protected RelationType visitSampledRelation(SampledRelation relation, AnalysisContext context) { if (relation.getColumnsToStratifyOn().isPresent()) { throw new SemanticException(NOT_SUPPORTED, relation, "STRATIFY ON is not yet implemented"); } if (!DependencyExtractor.extractNames(relation.getSamplePercentage(), analysis.getColumnReferences()).isEmpty()) { throw new SemanticException(NON_NUMERIC_SAMPLE_PERCENTAGE, relation.getSamplePercentage(), "Sample percentage cannot contain column references"); } IdentityHashMap<Expression, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, ImmutableMap.<Symbol, Type>of(), relation.getSamplePercentage()); ExpressionInterpreter samplePercentageEval = expressionOptimizer(relation.getSamplePercentage(), metadata, session, expressionTypes); Object samplePercentageObject = samplePercentageEval.optimize(symbol -> { throw new SemanticException(NON_NUMERIC_SAMPLE_PERCENTAGE, relation.getSamplePercentage(), "Sample percentage cannot contain column references"); }); if (!(samplePercentageObject instanceof Number)) { throw new SemanticException(NON_NUMERIC_SAMPLE_PERCENTAGE, relation.getSamplePercentage(), "Sample percentage should evaluate to a numeric expression"); } double samplePercentageValue = ((Number) samplePercentageObject).doubleValue(); if (samplePercentageValue < 0.0) { throw new SemanticException(SemanticErrorCode.SAMPLE_PERCENTAGE_OUT_OF_RANGE, relation.getSamplePercentage(), "Sample percentage must be greater than or equal to 0"); } if ((samplePercentageValue > 100.0) && ((relation.getType() != SampledRelation.Type.POISSONIZED) || relation.isRescaled())) { throw new SemanticException(SemanticErrorCode.SAMPLE_PERCENTAGE_OUT_OF_RANGE, relation.getSamplePercentage(), "Sample percentage must be less than or equal to 100"); } if (relation.isRescaled() && !experimentalSyntaxEnabled) { throw new SemanticException(NOT_SUPPORTED, relation, "Rescaling is not enabled"); } RelationType descriptor = process(relation.getRelation(), context); analysis.setOutputDescriptor(relation, descriptor); analysis.setSampleRatio(relation, samplePercentageValue / 100); return descriptor; } @Override protected RelationType visitTableSubquery(TableSubquery node, AnalysisContext context) { StatementAnalyzer analyzer = new StatementAnalyzer(analysis, metadata, sqlParser, accessControl, session, experimentalSyntaxEnabled, Optional.empty()); RelationType descriptor = analyzer.process(node.getQuery(), context); analysis.setOutputDescriptor(node, descriptor); return descriptor; } @Override protected RelationType visitQuerySpecification(QuerySpecification node, AnalysisContext parentContext) { // TODO: extract candidate names from SELECT, WHERE, HAVING, GROUP BY and ORDER BY expressions // to pass down to analyzeFrom AnalysisContext context = new AnalysisContext(parentContext, new RelationType()); RelationType sourceType = analyzeFrom(node, context); node.getWhere().ifPresent(where -> analyzeWhere(node, sourceType, context, where)); List<Expression> outputExpressions = analyzeSelect(node, sourceType, context); List<List<Expression>> groupByExpressions = analyzeGroupBy(node, sourceType, context, outputExpressions); RelationType outputType = computeOutputDescriptor(node, sourceType); List<Expression> orderByExpressions = analyzeOrderBy(node, sourceType, outputType, context, outputExpressions); analyzeHaving(node, sourceType, context); analyzeAggregations(node, sourceType, groupByExpressions, outputExpressions, orderByExpressions, context, analysis.getColumnReferences()); analyzeWindowFunctions(node, outputExpressions, orderByExpressions); analysis.setOutputDescriptor(node, outputType); return outputType; } @Override protected RelationType visitSetOperation(SetOperation node, AnalysisContext context) { checkState(node.getRelations().size() >= 2); RelationType[] descriptors = node.getRelations().stream() .map(relation -> process(relation, context).withOnlyVisibleFields()) .toArray(RelationType[]::new); Type[] outputFieldTypes = descriptors[0].getVisibleFields().stream() .map(Field::getType) .toArray(Type[]::new); for (RelationType descriptor : descriptors) { int outputFieldSize = outputFieldTypes.length; int descFieldSize = descriptor.getVisibleFields().size(); String setOperationName = node.getClass().getSimpleName(); if (outputFieldSize != descFieldSize) { throw new SemanticException(MISMATCHED_SET_COLUMN_TYPES, node, "%s query has different number of fields: %d, %d", setOperationName, outputFieldSize, descFieldSize); } for (int i = 0; i < descriptor.getVisibleFields().size(); i++) { Type descFieldType = descriptor.getFieldByIndex(i).getType(); Optional<Type> commonSuperType = metadata.getTypeManager().getCommonSuperType(outputFieldTypes[i], descFieldType); if (!commonSuperType.isPresent()) { throw new SemanticException(TYPE_MISMATCH, node, "column %d in %s query has incompatible types: %s, %s", i, outputFieldTypes[i].getDisplayName(), setOperationName, descFieldType.getDisplayName()); } outputFieldTypes[i] = commonSuperType.get(); } } Field[] outputDescriptorFields = new Field[outputFieldTypes.length]; RelationType firstDescriptor = descriptors[0].withOnlyVisibleFields(); for (int i = 0; i < outputFieldTypes.length; i++) { Field oldField = firstDescriptor.getFieldByIndex(i); outputDescriptorFields[i] = new Field(oldField.getRelationAlias(), oldField.getName(), outputFieldTypes[i], oldField.isHidden()); } RelationType outputDescriptor = new RelationType(outputDescriptorFields); analysis.setOutputDescriptor(node, outputDescriptor); for (int i = 0; i < node.getRelations().size(); i++) { Relation relation = node.getRelations().get(i); RelationType descriptor = descriptors[i]; for (int j = 0; j < descriptor.getVisibleFields().size(); j++) { Type outputFieldType = outputFieldTypes[j]; Type descFieldType = descriptor.getFieldByIndex(j).getType(); if (!outputFieldType.equals(descFieldType)) { analysis.addRelationCoercion(relation, outputFieldTypes); break; } } } return outputDescriptor; } @Override protected RelationType visitIntersect(Intersect node, AnalysisContext context) { if (!node.isDistinct()) { throw new SemanticException(NOT_SUPPORTED, node, "INTERSECT ALL not yet implemented"); } return visitSetOperation(node, context); } @Override protected RelationType visitExcept(Except node, AnalysisContext context) { throw new SemanticException(NOT_SUPPORTED, node, "EXCEPT not yet implemented"); } @Override protected RelationType visitJoin(Join node, AnalysisContext context) { JoinCriteria criteria = node.getCriteria().orElse(null); if (criteria instanceof NaturalJoin) { throw new SemanticException(NOT_SUPPORTED, node, "Natural join not supported"); } AnalysisContext leftContext = new AnalysisContext(context, new RelationType()); RelationType left = process(node.getLeft(), context); leftContext.setLateralTupleDescriptor(left); RelationType right = process(node.getRight(), leftContext); RelationType output = left.joinWith(right); if (node.getType() == Join.Type.CROSS || node.getType() == Join.Type.IMPLICIT) { analysis.setOutputDescriptor(node, output); return output; } if (criteria instanceof JoinUsing) { // TODO: implement proper "using" semantics with respect to output columns List<String> columns = ((JoinUsing) criteria).getColumns(); List<Expression> expressions = new ArrayList<>(); for (String column : columns) { Expression leftExpression = new QualifiedNameReference(QualifiedName.of(column)); Expression rightExpression = new QualifiedNameReference(QualifiedName.of(column)); ExpressionAnalysis leftExpressionAnalysis = analyzeExpression(leftExpression, left, context); ExpressionAnalysis rightExpressionAnalysis = analyzeExpression(rightExpression, right, context); checkState(leftExpressionAnalysis.getSubqueryInPredicates().isEmpty(), "INVARIANT"); checkState(rightExpressionAnalysis.getSubqueryInPredicates().isEmpty(), "INVARIANT"); addCoercionForJoinCriteria(node, leftExpression, rightExpression); expressions.add(new ComparisonExpression(EQUAL, leftExpression, rightExpression)); } analysis.setJoinCriteria(node, ExpressionUtils.and(expressions)); } else if (criteria instanceof JoinOn) { Expression expression = ((JoinOn) criteria).getExpression(); // ensure all names can be resolved, types match, etc (we don't need to record resolved names, subexpression types, etc. because // we do it further down when after we determine which subexpressions apply to left vs right tuple) ExpressionAnalyzer analyzer = ExpressionAnalyzer.create(analysis, session, metadata, sqlParser, accessControl, experimentalSyntaxEnabled); analyzer.analyze(expression, output, context); Analyzer.verifyNoAggregatesOrWindowFunctions(metadata, expression, "JOIN"); // expressionInterpreter/optimizer only understands a subset of expression types // TODO: remove this when the new expression tree is implemented Expression canonicalized = CanonicalizeExpressions.canonicalizeExpression(expression); analyzer.analyze(canonicalized, output, context); Object optimizedExpression = expressionOptimizer(canonicalized, metadata, session, analyzer.getExpressionTypes()).optimize(NoOpSymbolResolver.INSTANCE); if (!(optimizedExpression instanceof Expression) && optimizedExpression instanceof Boolean) { // If the JoinOn clause evaluates to a boolean expression, simulate a cross join by adding the relevant redundant expression if (optimizedExpression.equals(Boolean.TRUE)) { optimizedExpression = new ComparisonExpression(EQUAL, new LongLiteral("0"), new LongLiteral("0")); } else { optimizedExpression = new ComparisonExpression(EQUAL, new LongLiteral("0"), new LongLiteral("1")); } } if (!(optimizedExpression instanceof Expression)) { throw new SemanticException(TYPE_MISMATCH, node, "Join clause must be a boolean expression"); } // The optimization above may have rewritten the expression tree which breaks all the identity maps, so redo the analysis // to re-analyze coercions that might be necessary analyzer = ExpressionAnalyzer.create(analysis, session, metadata, sqlParser, accessControl, experimentalSyntaxEnabled); analyzer.analyze((Expression) optimizedExpression, output, context); analysis.addCoercions(analyzer.getExpressionCoercions()); Set<Expression> postJoinConjuncts = new HashSet<>(); final Set<InPredicate> leftJoinInPredicates = new HashSet<>(); final Set<InPredicate> rightJoinInPredicates = new HashSet<>(); for (Expression conjunct : ExpressionUtils.extractConjuncts((Expression) optimizedExpression)) { conjunct = ExpressionUtils.normalize(conjunct); if (conjunct instanceof ComparisonExpression) { Expression conjunctFirst = ((ComparisonExpression) conjunct).getLeft(); Expression conjunctSecond = ((ComparisonExpression) conjunct).getRight(); Set<QualifiedName> firstDependencies = DependencyExtractor.extractNames(conjunctFirst, analyzer.getColumnReferences()); Set<QualifiedName> secondDependencies = DependencyExtractor.extractNames(conjunctSecond, analyzer.getColumnReferences()); Expression leftExpression = null; Expression rightExpression = null; if (firstDependencies.stream().allMatch(left.canResolvePredicate()) && secondDependencies.stream().allMatch(right.canResolvePredicate())) { leftExpression = conjunctFirst; rightExpression = conjunctSecond; } else if (firstDependencies.stream().allMatch(right.canResolvePredicate()) && secondDependencies.stream().allMatch(left.canResolvePredicate())) { leftExpression = conjunctSecond; rightExpression = conjunctFirst; } // expression on each side of comparison operator references only symbols from one side of join. // analyze the clauses to record the types of all subexpressions and resolve names against the left/right underlying tuples if (rightExpression != null) { ExpressionAnalysis leftExpressionAnalysis = analyzeExpression(leftExpression, left, context); ExpressionAnalysis rightExpressionAnalysis = analyzeExpression(rightExpression, right, context); leftJoinInPredicates.addAll(leftExpressionAnalysis.getSubqueryInPredicates()); rightJoinInPredicates.addAll(rightExpressionAnalysis.getSubqueryInPredicates()); addCoercionForJoinCriteria(node, leftExpression, rightExpression); } else { // mixed references to both left and right join relation on one side of comparison operator. // expression will be put in post-join condition; analyze in context of output table. postJoinConjuncts.add(conjunct); } } else { // non-comparison expression. // expression will be put in post-join condition; analyze in context of output table. postJoinConjuncts.add(conjunct); } } ExpressionAnalysis postJoinPredicatesConjunctsAnalysis = analyzeExpression(ExpressionUtils.combineConjuncts(postJoinConjuncts), output, context); analysis.recordSubqueries(node, postJoinPredicatesConjunctsAnalysis); analysis.addJoinInPredicates(node, new Analysis.JoinInPredicates(leftJoinInPredicates, rightJoinInPredicates)); analysis.setJoinCriteria(node, (Expression) optimizedExpression); } else { throw new UnsupportedOperationException("unsupported join criteria: " + criteria.getClass().getName()); } analysis.setOutputDescriptor(node, output); return output; } private void addCoercionForJoinCriteria(Join node, Expression leftExpression, Expression rightExpression) { Type leftType = analysis.getType(leftExpression); Type rightType = analysis.getType(rightExpression); Optional<Type> superType = metadata.getTypeManager().getCommonSuperType(leftType, rightType); if (!superType.isPresent()) { throw new SemanticException(TYPE_MISMATCH, node, "Join criteria has incompatible types: %s, %s", leftType.getDisplayName(), rightType.getDisplayName()); } if (!leftType.equals(superType.get())) { analysis.addCoercion(leftExpression, superType.get()); } if (!rightType.equals(superType.get())) { analysis.addCoercion(rightExpression, superType.get()); } } @Override protected RelationType visitValues(Values node, AnalysisContext context) { checkState(node.getRows().size() >= 1); // get unique row types Set<List<Type>> rowTypes = node.getRows().stream() .map(row -> analyzeExpression(row, new RelationType(), context).getType(row)) .map(type -> { if (type instanceof RowType) { return type.getTypeParameters(); } return ImmutableList.of(type); }) .collect(toImmutableSet()); // determine common super type of the rows List<Type> fieldTypes = new ArrayList<>(rowTypes.iterator().next()); for (List<Type> rowType : rowTypes) { for (int i = 0; i < rowType.size(); i++) { Type fieldType = rowType.get(i); Type superType = fieldTypes.get(i); Optional<Type> commonSuperType = metadata.getTypeManager().getCommonSuperType(fieldType, superType); if (!commonSuperType.isPresent()) { throw new SemanticException(MISMATCHED_SET_COLUMN_TYPES, node, "Values rows have mismatched types: %s vs %s", Iterables.get(rowTypes, 0), Iterables.get(rowTypes, 1)); } fieldTypes.set(i, commonSuperType.get()); } } // add coercions for the rows for (Expression row : node.getRows()) { if (row instanceof Row) { List<Expression> items = ((Row) row).getItems(); for (int i = 0; i < items.size(); i++) { Type expectedType = fieldTypes.get(i); Expression item = items.get(i); if (!analysis.getType(item).equals(expectedType)) { analysis.addCoercion(item, expectedType); } } } else { Type expectedType = fieldTypes.get(0); if (!analysis.getType(row).equals(expectedType)) { analysis.addCoercion(row, expectedType); } } } RelationType descriptor = new RelationType(fieldTypes.stream() .map(valueType -> Field.newUnqualified(Optional.empty(), valueType)) .collect(toImmutableList())); analysis.setOutputDescriptor(node, descriptor); return descriptor; } private void analyzeWindowFunctions(QuerySpecification node, List<Expression> outputExpressions, List<Expression> orderByExpressions) { WindowFunctionExtractor extractor = new WindowFunctionExtractor(); for (Expression expression : Iterables.concat(outputExpressions, orderByExpressions)) { extractor.process(expression, null); new WindowFunctionValidator().process(expression, analysis); } List<FunctionCall> windowFunctions = extractor.getWindowFunctions(); for (FunctionCall windowFunction : windowFunctions) { Window window = windowFunction.getWindow().get(); WindowFunctionExtractor nestedExtractor = new WindowFunctionExtractor(); for (Expression argument : windowFunction.getArguments()) { nestedExtractor.process(argument, null); } for (Expression expression : window.getPartitionBy()) { nestedExtractor.process(expression, null); } for (SortItem sortItem : window.getOrderBy()) { nestedExtractor.process(sortItem.getSortKey(), null); } if (window.getFrame().isPresent()) { nestedExtractor.process(window.getFrame().get(), null); } if (!nestedExtractor.getWindowFunctions().isEmpty()) { throw new SemanticException(NESTED_WINDOW, node, "Cannot nest window functions inside window function '%s': %s", windowFunction, extractor.getWindowFunctions()); } if (windowFunction.isDistinct()) { throw new SemanticException(NOT_SUPPORTED, node, "DISTINCT in window function parameters not yet supported: %s", windowFunction); } if (window.getFrame().isPresent()) { analyzeWindowFrame(window.getFrame().get()); } List<TypeSignature> argumentTypes = Lists.transform(windowFunction.getArguments(), expression -> analysis.getType(expression).getTypeSignature()); FunctionKind kind = metadata.getFunctionRegistry().resolveFunction(windowFunction.getName(), argumentTypes, false).getKind(); if (kind != AGGREGATE && kind != APPROXIMATE_AGGREGATE && kind != WINDOW) { throw new SemanticException(MUST_BE_WINDOW_FUNCTION, node, "Not a window function: %s", windowFunction.getName()); } } analysis.setWindowFunctions(node, windowFunctions); } private static void analyzeWindowFrame(WindowFrame frame) { FrameBound.Type startType = frame.getStart().getType(); FrameBound.Type endType = frame.getEnd().orElse(new FrameBound(CURRENT_ROW)).getType(); if (startType == UNBOUNDED_FOLLOWING) { throw new SemanticException(INVALID_WINDOW_FRAME, frame, "Window frame start cannot be UNBOUNDED FOLLOWING"); } if (endType == UNBOUNDED_PRECEDING) { throw new SemanticException(INVALID_WINDOW_FRAME, frame, "Window frame end cannot be UNBOUNDED PRECEDING"); } if ((startType == CURRENT_ROW) && (endType == PRECEDING)) { throw new SemanticException(INVALID_WINDOW_FRAME, frame, "Window frame starting from CURRENT ROW cannot end with PRECEDING"); } if ((startType == FOLLOWING) && (endType == PRECEDING)) { throw new SemanticException(INVALID_WINDOW_FRAME, frame, "Window frame starting from FOLLOWING cannot end with PRECEDING"); } if ((startType == FOLLOWING) && (endType == CURRENT_ROW)) { throw new SemanticException(INVALID_WINDOW_FRAME, frame, "Window frame starting from FOLLOWING cannot end with CURRENT ROW"); } if ((frame.getType() == RANGE) && ((startType == PRECEDING) || (endType == PRECEDING))) { throw new SemanticException(INVALID_WINDOW_FRAME, frame, "Window frame RANGE PRECEDING is only supported with UNBOUNDED"); } if ((frame.getType() == RANGE) && ((startType == FOLLOWING) || (endType == FOLLOWING))) { throw new SemanticException(INVALID_WINDOW_FRAME, frame, "Window frame RANGE FOLLOWING is only supported with UNBOUNDED"); } } private void analyzeHaving(QuerySpecification node, RelationType tupleDescriptor, AnalysisContext context) { if (node.getHaving().isPresent()) { Expression predicate = node.getHaving().get(); ExpressionAnalysis expressionAnalysis = analyzeExpression(predicate, tupleDescriptor, context); analysis.recordSubqueries(node, expressionAnalysis); Type predicateType = expressionAnalysis.getType(predicate); if (!predicateType.equals(BOOLEAN) && !predicateType.equals(UNKNOWN)) { throw new SemanticException(TYPE_MISMATCH, predicate, "HAVING clause must evaluate to a boolean: actual type %s", predicateType); } analysis.setHaving(node, predicate); } } private List<Expression> analyzeOrderBy(QuerySpecification node, RelationType sourceType, RelationType outputType, AnalysisContext context, List<Expression> outputExpressions) { List<SortItem> items = node.getOrderBy(); ImmutableList.Builder<Expression> orderByExpressionsBuilder = ImmutableList.builder(); if (!items.isEmpty()) { // Compute aliased output terms so we can resolve order by expressions against them first ImmutableMultimap.Builder<QualifiedName, Expression> byAliasBuilder = ImmutableMultimap.builder(); for (SelectItem item : node.getSelect().getSelectItems()) { if (item instanceof SingleColumn) { Optional<String> alias = ((SingleColumn) item).getAlias(); if (alias.isPresent()) { byAliasBuilder.put(QualifiedName.of(alias.get()), ((SingleColumn) item).getExpression()); // TODO: need to know if alias was quoted } } } Multimap<QualifiedName, Expression> byAlias = byAliasBuilder.build(); for (SortItem item : items) { Expression expression = item.getSortKey(); Expression orderByExpression = null; if (expression instanceof QualifiedNameReference && !((QualifiedNameReference) expression).getName().getPrefix().isPresent()) { // if this is a simple name reference, try to resolve against output columns QualifiedName name = ((QualifiedNameReference) expression).getName(); Collection<Expression> expressions = byAlias.get(name); if (expressions.size() > 1) { throw new SemanticException(AMBIGUOUS_ATTRIBUTE, expression, "'%s' in ORDER BY is ambiguous", name.getSuffix()); } if (expressions.size() == 1) { orderByExpression = Iterables.getOnlyElement(expressions); } // otherwise, couldn't resolve name against output aliases, so fall through... } else if (expression instanceof LongLiteral) { // this is an ordinal in the output tuple long ordinal = ((LongLiteral) expression).getValue(); if (ordinal < 1 || ordinal > outputExpressions.size()) { throw new SemanticException(INVALID_ORDINAL, expression, "ORDER BY position %s is not in select list", ordinal); } int field = Ints.checkedCast(ordinal - 1); Type type = outputType.getFieldByIndex(field).getType(); if (!type.isOrderable()) { throw new SemanticException(TYPE_MISMATCH, node, "The type of expression in position %s is not orderable (actual: %s), and therefore cannot be used in ORDER BY", ordinal, type); } orderByExpression = outputExpressions.get(field); } // otherwise, just use the expression as is if (orderByExpression == null) { orderByExpression = expression; } ExpressionAnalysis expressionAnalysis = analyzeExpression(orderByExpression, sourceType, context); analysis.recordSubqueries(node, expressionAnalysis); Type type = expressionAnalysis.getType(orderByExpression); if (!type.isOrderable()) { throw new SemanticException(TYPE_MISMATCH, node, "Type %s is not orderable, and therefore cannot be used in ORDER BY: %s", type, expression); } orderByExpressionsBuilder.add(orderByExpression); } } List<Expression> orderByExpressions = orderByExpressionsBuilder.build(); analysis.setOrderByExpressions(node, orderByExpressions); if (node.getSelect().isDistinct() && !outputExpressions.containsAll(orderByExpressions)) { throw new SemanticException(ORDER_BY_MUST_BE_IN_SELECT, node.getSelect(), "For SELECT DISTINCT, ORDER BY expressions must appear in select list"); } return orderByExpressions; } private List<List<Expression>> analyzeGroupBy(QuerySpecification node, RelationType tupleDescriptor, AnalysisContext context, List<Expression> outputExpressions) { List<Set<Expression>> computedGroupingSets = ImmutableList.of(); // empty list = no aggregations if (node.getGroupBy().isPresent()) { List<List<Set<Expression>>> enumeratedGroupingSets = node.getGroupBy().get().getGroupingElements().stream() .map(GroupingElement::enumerateGroupingSets) .collect(toImmutableList()); // compute cross product of enumerated grouping sets, if there are any computedGroupingSets = computeGroupingSetsCrossProduct(enumeratedGroupingSets, node.getGroupBy().get().isDistinct()); checkState(!computedGroupingSets.isEmpty(), "computed grouping sets cannot be empty"); } else if (!extractAggregates(node).isEmpty()) { // if there are aggregates, but no group by, create a grand total grouping set (global aggregation) computedGroupingSets = ImmutableList.of(ImmutableSet.of()); } List<List<Expression>> analyzedGroupingSets = computedGroupingSets.stream() .map(groupingSet -> analyzeGroupingColumns(groupingSet, node, tupleDescriptor, context, outputExpressions)) .collect(toImmutableList()); analysis.setGroupingSets(node, analyzedGroupingSets); return analyzedGroupingSets; } private List<Set<Expression>> computeGroupingSetsCrossProduct(List<List<Set<Expression>>> enumeratedGroupingSets, boolean isDistinct) { checkState(!enumeratedGroupingSets.isEmpty(), "enumeratedGroupingSets cannot be empty"); List<Set<Expression>> groupingSetsCrossProduct = new ArrayList<>(); enumeratedGroupingSets.get(0) .stream() .map(ImmutableSet::copyOf) .forEach(groupingSetsCrossProduct::add); for (int i = 1; i < enumeratedGroupingSets.size(); i++) { List<Set<Expression>> groupingSets = enumeratedGroupingSets.get(i); List<Set<Expression>> oldGroupingSetsCrossProduct = ImmutableList.copyOf(groupingSetsCrossProduct); groupingSetsCrossProduct.clear(); for (Set<Expression> existingSet : oldGroupingSetsCrossProduct) { for (Set<Expression> groupingSet : groupingSets) { Set<Expression> concatenatedSet = ImmutableSet.<Expression>builder() .addAll(existingSet) .addAll(groupingSet) .build(); groupingSetsCrossProduct.add(concatenatedSet); } } } if (isDistinct) { return ImmutableList.copyOf(ImmutableSet.copyOf(groupingSetsCrossProduct)); } return groupingSetsCrossProduct; } private List<Expression> analyzeGroupingColumns(Set<Expression> groupingColumns, QuerySpecification node, RelationType tupleDescriptor, AnalysisContext context, List<Expression> outputExpressions) { ImmutableList.Builder<Expression> groupingColumnsBuilder = ImmutableList.builder(); for (Expression groupingColumn : groupingColumns) { // first, see if this is an ordinal Expression groupByExpression; if (groupingColumn instanceof LongLiteral) { long ordinal = ((LongLiteral) groupingColumn).getValue(); if (ordinal < 1 || ordinal > outputExpressions.size()) { throw new SemanticException(INVALID_ORDINAL, groupingColumn, "GROUP BY position %s is not in select list", ordinal); } groupByExpression = outputExpressions.get(Ints.checkedCast(ordinal - 1)); } else { ExpressionAnalysis expressionAnalysis = analyzeExpression(groupingColumn, tupleDescriptor, context); analysis.recordSubqueries(node, expressionAnalysis); groupByExpression = groupingColumn; } Analyzer.verifyNoAggregatesOrWindowFunctions(metadata, groupByExpression, "GROUP BY"); Type type = analysis.getType(groupByExpression); if (!type.isComparable()) { throw new SemanticException(TYPE_MISMATCH, node, "%s is not comparable, and therefore cannot be used in GROUP BY", type); } groupingColumnsBuilder.add(groupByExpression); } return groupingColumnsBuilder.build(); } private RelationType computeOutputDescriptor(QuerySpecification node, RelationType inputTupleDescriptor) { ImmutableList.Builder<Field> outputFields = ImmutableList.builder(); for (SelectItem item : node.getSelect().getSelectItems()) { if (item instanceof AllColumns) { // expand * and T.* Optional<QualifiedName> starPrefix = ((AllColumns) item).getPrefix(); for (Field field : inputTupleDescriptor.resolveFieldsWithPrefix(starPrefix)) { outputFields.add(Field.newUnqualified(field.getName(), field.getType())); } } else if (item instanceof SingleColumn) { SingleColumn column = (SingleColumn) item; Expression expression = column.getExpression(); Optional<String> alias = column.getAlias(); if (!alias.isPresent()) { QualifiedName name = null; if (expression instanceof QualifiedNameReference) { name = ((QualifiedNameReference) expression).getName(); } else if (expression instanceof DereferenceExpression) { name = DereferenceExpression.getQualifiedName((DereferenceExpression) expression); } if (name != null) { alias = Optional.of(getLast(name.getOriginalParts())); } } outputFields.add(Field.newUnqualified(alias, analysis.getType(expression))); // TODO don't use analysis as a side-channel. Use outputExpressions to look up the type } else { throw new IllegalArgumentException("Unsupported SelectItem type: " + item.getClass().getName()); } } return new RelationType(outputFields.build()); } private List<Expression> analyzeSelect(QuerySpecification node, RelationType tupleDescriptor, AnalysisContext context) { ImmutableList.Builder<Expression> outputExpressionBuilder = ImmutableList.builder(); for (SelectItem item : node.getSelect().getSelectItems()) { if (item instanceof AllColumns) { // expand * and T.* Optional<QualifiedName> starPrefix = ((AllColumns) item).getPrefix(); List<Field> fields = tupleDescriptor.resolveFieldsWithPrefix(starPrefix); if (fields.isEmpty()) { if (starPrefix.isPresent()) { throw new SemanticException(MISSING_TABLE, item, "Table '%s' not found", starPrefix.get()); } throw new SemanticException(WILDCARD_WITHOUT_FROM, item, "SELECT * not allowed in queries without FROM clause"); } for (Field field : fields) { int fieldIndex = tupleDescriptor.indexOf(field); FieldReference expression = new FieldReference(fieldIndex); outputExpressionBuilder.add(expression); ExpressionAnalysis expressionAnalysis = analyzeExpression(expression, tupleDescriptor, context); Type type = expressionAnalysis.getType(expression); if (node.getSelect().isDistinct() && !type.isComparable()) { throw new SemanticException(TYPE_MISMATCH, node.getSelect(), "DISTINCT can only be applied to comparable types (actual: %s)", type); } } } else if (item instanceof SingleColumn) { SingleColumn column = (SingleColumn) item; ExpressionAnalysis expressionAnalysis = analyzeExpression(column.getExpression(), tupleDescriptor, context); analysis.recordSubqueries(node, expressionAnalysis); outputExpressionBuilder.add(column.getExpression()); Type type = expressionAnalysis.getType(column.getExpression()); if (node.getSelect().isDistinct() && !type.isComparable()) { throw new SemanticException(TYPE_MISMATCH, node.getSelect(), "DISTINCT can only be applied to comparable types (actual: %s): %s", type, column.getExpression()); } } else { throw new IllegalArgumentException("Unsupported SelectItem type: " + item.getClass().getName()); } } ImmutableList<Expression> result = outputExpressionBuilder.build(); analysis.setOutputExpressions(node, result); return result; } public void analyzeWhere(Node node, RelationType tupleDescriptor, AnalysisContext context, Expression predicate) { Analyzer.verifyNoAggregatesOrWindowFunctions(metadata, predicate, "WHERE"); ExpressionAnalysis expressionAnalysis = analyzeExpression(predicate, tupleDescriptor, context); analysis.recordSubqueries(node, expressionAnalysis); Type predicateType = expressionAnalysis.getType(predicate); if (!predicateType.equals(BOOLEAN)) { if (!predicateType.equals(UNKNOWN)) { throw new SemanticException(TYPE_MISMATCH, predicate, "WHERE clause must evaluate to a boolean: actual type %s", predicateType); } // coerce null to boolean analysis.addCoercion(predicate, BOOLEAN); } analysis.setWhere(node, predicate); } private RelationType analyzeFrom(QuerySpecification node, AnalysisContext context) { RelationType fromDescriptor = new RelationType(); if (node.getFrom().isPresent()) { fromDescriptor = process(node.getFrom().get(), context); } return fromDescriptor; } private void analyzeAggregations(QuerySpecification node, RelationType tupleDescriptor, List<List<Expression>> groupingSets, List<Expression> outputExpressions, List<Expression> orderByExpressions, AnalysisContext context, Set<Expression> columnReferences) { List<FunctionCall> aggregates = extractAggregates(node); if (context.isApproximate()) { if (aggregates.stream().anyMatch(FunctionCall::isDistinct)) { throw new SemanticException(NOT_SUPPORTED, node, "DISTINCT aggregations not supported for approximate queries"); } } // is this an aggregation query? if (!groupingSets.isEmpty()) { // ensure SELECT, ORDER BY and HAVING are constant with respect to group // e.g, these are all valid expressions: // SELECT f(a) GROUP BY a // SELECT f(a + 1) GROUP BY a + 1 // SELECT a + sum(b) GROUP BY a ImmutableList<Expression> distinctGroupingColumns = groupingSets.stream() .flatMap(Collection::stream) .distinct() .collect(toImmutableList()); for (Expression expression : Iterables.concat(outputExpressions, orderByExpressions)) { verifyAggregations(node, distinctGroupingColumns, tupleDescriptor, expression, columnReferences); } if (node.getHaving().isPresent()) { verifyAggregations(node, distinctGroupingColumns, tupleDescriptor, node.getHaving().get(), columnReferences); } } } private List<FunctionCall> extractAggregates(QuerySpecification node) { AggregateExtractor extractor = new AggregateExtractor(metadata); for (SelectItem item : node.getSelect().getSelectItems()) { if (item instanceof SingleColumn) { extractor.process(((SingleColumn) item).getExpression(), null); } } for (SortItem item : node.getOrderBy()) { extractor.process(item.getSortKey(), null); } if (node.getHaving().isPresent()) { extractor.process(node.getHaving().get(), null); } List<FunctionCall> aggregates = extractor.getAggregates(); analysis.setAggregates(node, aggregates); return aggregates; } private void verifyAggregations( QuerySpecification node, List<Expression> groupByExpressions, RelationType tupleDescriptor, Expression expression, Set<Expression> columnReferences) { AggregationAnalyzer analyzer = new AggregationAnalyzer(groupByExpressions, metadata, tupleDescriptor, columnReferences); analyzer.analyze(expression); } private RelationType analyzeView(Query query, QualifiedObjectName name, Optional<String> catalog, Optional<String> schema, Optional<String> owner, Table node) { try { // run view as view owner if set; otherwise, run as session user Identity identity; AccessControl viewAccessControl; if (owner.isPresent()) { identity = new Identity(owner.get(), Optional.empty()); viewAccessControl = new ViewAccessControl(accessControl); } else { identity = session.getIdentity(); viewAccessControl = accessControl; } Session viewSession = Session.builder(metadata.getSessionPropertyManager()) .setQueryId(session.getQueryId()) .setTransactionId(session.getTransactionId().orElse(null)) .setIdentity(identity) .setSource(session.getSource().orElse(null)) .setCatalog(catalog.orElse(null)) .setSchema(schema.orElse(null)) .setTimeZoneKey(session.getTimeZoneKey()) .setLocale(session.getLocale()) .setRemoteUserAddress(session.getRemoteUserAddress().orElse(null)) .setUserAgent(session.getUserAgent().orElse(null)) .setStartTime(session.getStartTime()) .build(); StatementAnalyzer analyzer = new StatementAnalyzer(analysis, metadata, sqlParser, viewAccessControl, viewSession, experimentalSyntaxEnabled, Optional.empty()); RelationType descriptor = analyzer.process(query, new AnalysisContext()); return descriptor.withAlias(name.getObjectName(), null); } catch (RuntimeException e) { throw new SemanticException(VIEW_ANALYSIS_ERROR, node, "Failed analyzing stored view '%s': %s", name, e.getMessage()); } } private Query parseView(String view, QualifiedObjectName name, Node node) { try { Statement statement = sqlParser.createStatement(view); return checkType(statement, Query.class, "parsed view"); } catch (ParsingException e) { throw new SemanticException(VIEW_PARSE_ERROR, node, "Failed parsing stored view '%s': %s", name, e.getMessage()); } } private static boolean isViewStale(List<ViewDefinition.ViewColumn> columns, Collection<Field> fields) { if (columns.size() != fields.size()) { return true; } List<Field> fieldList = ImmutableList.copyOf(fields); for (int i = 0; i < columns.size(); i++) { ViewDefinition.ViewColumn column = columns.get(i); Field field = fieldList.get(i); if (!column.getName().equals(field.getName().orElse(null)) || !TypeRegistry.canCoerce(field.getType(), column.getType())) { return true; } } return false; } private ExpressionAnalysis analyzeExpression(Expression expression, RelationType tupleDescriptor, AnalysisContext context) { return ExpressionAnalyzer.analyzeExpression( session, metadata, accessControl, sqlParser, tupleDescriptor, analysis, experimentalSyntaxEnabled, context, expression); } private List<Expression> descriptorToFields(RelationType tupleDescriptor, AnalysisContext context) { ImmutableList.Builder<Expression> builder = ImmutableList.builder(); for (int fieldIndex = 0; fieldIndex < tupleDescriptor.getAllFieldCount(); fieldIndex++) { FieldReference expression = new FieldReference(fieldIndex); builder.add(expression); analyzeExpression(expression, tupleDescriptor, context); } return builder.build(); } private void analyzeWith(Query node, AnalysisContext context) { // analyze WITH clause if (!node.getWith().isPresent()) { return; } With with = node.getWith().get(); if (with.isRecursive()) { throw new SemanticException(NOT_SUPPORTED, with, "Recursive WITH queries are not supported"); } for (WithQuery withQuery : with.getQueries()) { Query query = withQuery.getQuery(); process(query, context); String name = withQuery.getName(); if (context.isNamedQueryDeclared(name)) { throw new SemanticException(DUPLICATE_RELATION, withQuery, "WITH query name '%s' specified more than once", name); } // check if all or none of the columns are explicitly alias if (withQuery.getColumnNames().isPresent()) { List<String> columnNames = withQuery.getColumnNames().get(); RelationType queryDescriptor = analysis.getOutputDescriptor(query); if (columnNames.size() != queryDescriptor.getVisibleFieldCount()) { throw new SemanticException(MISMATCHED_COLUMN_ALIASES, withQuery, "WITH column alias list has %s entries but WITH query(%s) has %s columns", columnNames.size(), name, queryDescriptor.getVisibleFieldCount()); } } context.addNamedQuery(name, withQuery); } } private void analyzeOrderBy(Query node, RelationType tupleDescriptor, AnalysisContext context) { List<SortItem> items = node.getOrderBy(); ImmutableList.Builder<Expression> orderByFieldsBuilder = ImmutableList.builder(); for (SortItem item : items) { Expression expression = item.getSortKey(); if (expression instanceof LongLiteral) { // this is an ordinal in the output tuple long ordinal = ((LongLiteral) expression).getValue(); if (ordinal < 1 || ordinal > tupleDescriptor.getVisibleFieldCount()) { throw new SemanticException(INVALID_ORDINAL, expression, "ORDER BY position %s is not in select list", ordinal); } expression = new FieldReference(Ints.checkedCast(ordinal - 1)); } ExpressionAnalysis expressionAnalysis = ExpressionAnalyzer.analyzeExpression(session, metadata, accessControl, sqlParser, tupleDescriptor, analysis, experimentalSyntaxEnabled, context, expression); analysis.recordSubqueries(node, expressionAnalysis); orderByFieldsBuilder.add(expression); } analysis.setOrderByExpressions(node, orderByFieldsBuilder.build()); } private static Relation from(String catalog, SchemaTableName table) { return table(QualifiedName.of(catalog, table.getSchemaName(), table.getTableName())); } }
3fb7258e73c7c4435c9ba3d35eef231f1487566f
1617995774ec9349f39f8991f6cd5438048cffff
/Step14_Swing/src/test/frame02/MainFrame3.java
0b4c65e41bd59593ccc473ad04e6fa98ad9794fc
[]
no_license
kinhoz9321/java_work_study
c434ba7ec657538c17278f391c88e8ebca1fd28b
c8b3045b4fba7e92f725ab1e15e5b546e2ea8005
refs/heads/master
2023-01-30T10:12:31.084262
2020-12-16T08:54:52
2020-12-16T08:54:52
314,846,756
0
0
null
null
null
null
UTF-8
Java
false
false
1,345
java
package test.frame02; /* * JFrame 상속받아서 * 생성자 안에 모든 설정을 마친 후 * ActionListener 생성자 안에서 생성 후 버튼 만들기3 * * 버튼에 ActionListener 추가해서 람다식 사용하기 */ import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; public class MainFrame3 extends JFrame{ public MainFrame3(String title) { super(title); setLayout(new FlowLayout()); JButton sendBtn=new JButton("전송"); JButton updateBtn=new JButton("수정"); JButton deleteBtn=new JButton("삭제"); add(sendBtn); add(updateBtn); add(deleteBtn); //버튼에 ActionListener 추가해서 람다식 사용하기 sendBtn.addActionListener((e)->{ JOptionPane.showMessageDialog(MainFrame3.this, "전송 버튼을 눌렀습니다."); }); updateBtn.addActionListener((e)->{ JOptionPane.showMessageDialog(MainFrame3.this, "수정 버튼을 눌렀습니다."); }); deleteBtn.addActionListener((e)->{ JOptionPane.showMessageDialog(MainFrame3.this, "삭제 버튼을 눌렀습니다."); }); } public static void main(String[] args) { MainFrame3 f=new MainFrame3("메인 프레임3"); f.setBounds(100, 100, 500, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }
fa14519e1e1fbefe878091a772f46d8dd59c4038
9135e8868994c806c5a9f2387b4042399d4ebfa0
/javaProject/src/io/InputStreamReaderExample.java
6d8356ee4fe25234f40f270d098ad85846f80b8f
[]
no_license
egg100/javaProject
fb59ba402172f94d9b3cbf1cdcd8d975ac1eaac5
7f79909d149acaa91c11bf9faf4fb7ab2382a39c
refs/heads/master
2023-04-03T03:13:31.125320
2021-04-07T14:03:21
2021-04-07T14:03:21
339,925,341
1
0
null
null
null
null
UTF-8
Java
false
false
597
java
package io; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class InputStreamReaderExample { public static void main(String[] args) throws IOException { InputStream is = System.in; InputStreamReader isr = new InputStreamReader(is); BufferedInputStream bis = new BufferedInputStream(is); int data = 0; char[] charBuf = new char[100]; while((isr.read(charBuf)) != -1) { String str = new String(charBuf); System.out.println(str); } isr.close(); is.close(); } }
c321d5d33e69e17951a350be4951fa12f5f580c2
a3747cd2268d18069bfd1e8efcf71d60039522fe
/src/main/java/org/apdplat/superword/freemarker/TemplateUtils.java
16131b6f3a8d6ac73e964b3616dba5645885c774
[ "Apache-2.0" ]
permissive
ikaroso/superword
fa1ca28174d9594d11706a05e3f4febece11202b
fad61fad5ea688ff5bf8838ee2a9b5ba2ae81349
refs/heads/master
2020-09-07T20:45:34.245180
2018-09-06T20:00:55
2018-09-06T20:00:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,047
java
package org.apdplat.superword.freemarker; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import org.apdplat.superword.model.QuizItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * 模板工具, 用于生成html代码 * Created by ysc on 4/2/16. */ public class TemplateUtils { private TemplateUtils(){} private static final Logger LOGGER = LoggerFactory.getLogger(TemplateUtils.class); private static final Configuration CFG = new Configuration(Configuration.VERSION_2_3_23); static{ LOGGER.info("开始初始化模板配置"); CFG.setClassLoaderForTemplateLoading(TemplateUtils.class.getClassLoader(), "/template/freemarker/"); CFG.setDefaultEncoding("UTF-8"); if(LOGGER.isDebugEnabled()) { CFG.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); }else{ CFG.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); } CFG.setLogTemplateExceptions(false); LOGGER.info("模板配置初始化完毕"); } /** * 在识别用户是否是机器人的测试中, 如果用户测试失败, 则向用户显示这里生成的HTML代码 * @param data 需要两个数据项, 一是测试数据集quizItem, 二是用户的回答answer * @return 测试结果HTML代码 */ public static String getIdentifyQuizFailure(Map<String, Object> data){ return merge(data, "identify_quiz_failure.ftlh"); } /** * 在识别用户是否是机器人的测试中, 给用户展示这里生成的HTML代码 * @param data 需要三个数据项, 一是servletContext, 二是token, 三是quizItem * @return 测试HTML代码 */ public static String getIdentifyQuizForm(Map<String, Object> data){ return merge(data, "identify_quiz_form.ftlh"); } /** * 在词汇量测试中, 给用户展示这里生成的HTML代码 * @param data 需要二个数据项, 一是step, 二是quizItem * @return 词汇量测试HTML代码 */ public static String getVocabularyTestForm(Map<String, Object> data){ return merge(data, "vocabulary_test_form.ftlh"); } /** * 在词汇量测试结束后, 给用户展示这里生成的HTML代码 * @param data 需要一个数据项: quiz * @return 词汇量测试结果HTML代码 */ public static String getVocabularyTestResult(Map<String, Object> data){ return merge(data, "vocabulary_test_result.ftlh"); } /** * 生成单词定义页面的HTML * @param data * word * servletContext * hasOxfordAudio * oxfordAudios * hasWebsterAudio * websterAudios * icibaDefinitionHtml * youdaoDefinitionHtml * icibaPronunciation * icibaDefinition * youdaoPronunciation * youdaoDefinition * oxfordDefinitionHtml * websterDefinitionHtml * oxfordPronunciation * oxfordDefinition * websterPronunciation * websterDefinition * otherDictionary * isMyNewWord * wordLevels * @return */ public static String getWordDefinition(Map<String, Object> data){ return merge(data, "word_definition.ftlh"); } /** * 单词定义相似性计算结果展示HTML * @param data * results * word * dictionary * count * words_type * @return */ public static String getDefinitionSimilarResult(Map<String, Object> data) { return merge(data, "definition_similar_rule.ftlh"); } public static String merge(Map<String, Object> data, String templateName){ try { Template template = CFG.getTemplate(templateName); Writer out = new StringWriter(); template.process(data, out); return out.toString(); }catch (Exception e){ LOGGER.error("generate template "+templateName+" failed", e); } return ""; } public static void main(String[] args) { Map<String, Object> data = new HashMap<>(); QuizItem quizItem = QuizItem.buildIdentifyHumanQuiz(12); data.put("quizItem", quizItem); data.put("answer", "random answer"); System.out.println(TemplateUtils.getIdentifyQuizFailure(data)); quizItem = QuizItem.buildIdentifyHumanQuiz(12); data.put("quizItem", quizItem); data.put("servletContext", ""); data.put("token", UUID.randomUUID().toString()); System.out.println(TemplateUtils.getIdentifyQuizForm(data)); quizItem = QuizItem.buildIdentifyHumanQuiz(12); data.put("quizItem", quizItem); data.put("servletContext", "/superword"); data.put("token", UUID.randomUUID().toString()); System.out.println(TemplateUtils.getIdentifyQuizForm(data)); } }
fbe50f155bef4387f808383b6fdc7e51366f2505
aede85516075ed24429079969ff889db611ee2ab
/app/src/main/java/com/dogvip/giannis/dogviprefactored/lifecycle/Lifecycle.java
411cbe5198d85fad2c9bb0e1d2d6af6632e97ce7
[]
no_license
tsironis13/DogVIPRefactored
df67b77b077c2dfec214cc616abd015522fe6002
30873a402c6f982bec0334ca81df382a6ce562d7
refs/heads/master
2021-08-30T10:03:48.233731
2017-12-17T11:43:39
2017-12-17T11:43:39
112,445,261
0
0
null
null
null
null
UTF-8
Java
false
false
469
java
package com.dogvip.giannis.dogviprefactored.lifecycle; /** * Created by giannis on 4/11/2017. */ public interface Lifecycle { interface View {} interface ViewModel { void onViewAttached(View viewCallback); void onViewResumed(); void onViewDetached(); } interface MyDateDialogCallbackContract { void onDisplayDateSet(String displayDate); void onDateSet(long date); void onInvalidDateSet(); } }
b9a643795849fc0a5308a2d1a46ce311c7de60cb
0a31f4361bad9d1c96351d1ddf08f18109969af0
/src/test/java/com/leetcode/algorithm/easy/ReverseListTest.java
2036e30c28b4665b0b44c4a1b48a3e70564b5488
[]
no_license
luiz158/tutorials-interview-questions
43ce780c2b6cfc55fddce2e5beb2b43716730f07
221db57e406d5c930971a93470923c155a3316f1
refs/heads/master
2022-09-21T23:15:55.638796
2020-03-11T12:54:39
2020-03-11T12:54:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
812
java
package com.leetcode.algorithm.easy; import com.leetcode.algorithm.common.struct.LinkedList; import com.leetcode.algorithm.common.struct.ListNode; import com.leetcode.algorithm.common.util.LinkedListUtil; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; @Slf4j public class ReverseListTest { @Test public void reverseList() { LinkedList linkedList = LinkedListUtil.generateLinkedListSample(Arrays.asList(1, 2, 3, 4, 5)); linkedList.printList(); ListNode tempNode = new ReverseList().reverseList(linkedList.head); int count = 5; while (tempNode != null) { assertThat(tempNode.val).isEqualTo(count--); tempNode = tempNode.next; } } }
04dd9f63ec4953a2cd8db358f2524ff9a7a66b70
329605a11d8ea7000c02e2ec2ffe8243d1eb5b8a
/src/com/lmh/function/email/EmailContent.java
1dbd427c9a17322dc18a043b0f44e727afe9f527
[]
no_license
liminghui2011/testgit
b15f04b17ffd0d2830e06c46517790162dd51c21
fb394eb078bd66030253acca3241ea9d5ec26437
refs/heads/master
2020-12-29T02:22:42.475013
2017-05-11T06:48:44
2017-05-11T06:48:44
42,304,534
0
0
null
null
null
null
UTF-8
Java
false
false
1,226
java
package com.lmh.function.email; import java.util.ArrayList; import java.util.List; /** * Email 内容对象 * @author tianjp * */ public class EmailContent { public static enum Type { TEXT(null), HTML("text/html;charset=utf-8"); private String header; private Type(String header) { this.header = header; } public String getHeader() { return header; } } private String content; private Type type; private List<EmailFile> files; public EmailContent(String content) { this.content = content; this.type = Type.TEXT; files = new ArrayList<EmailFile>(); } public EmailContent(String content, Type type) { this(content); this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public List<EmailFile> getFiles() { return files; } public void setFiles(List<EmailFile> files) { this.files = files; } public void add(EmailFile emailFile){ files.add(emailFile); } @Override public String toString() { return "EmailContent [content=" + content + ", type=" + type + "]"; } }
0d6888adec3470f77a166603d8d1b56019a6e427
34e66ecf8aa07d1c0dcb96c6186cd316440ec384
/ginvoicing/src/cbmarc/ginvoicing/client/view/customers/CustomersEditView.java
89ebca70ac262e4cb0f57d97208f4ba7a642fce4
[]
no_license
cbmarc-labs/ginvoicing
22e7682657e03d7b840fb4b152707e2793178954
dbd242f3376627cf98fec50f282cc665286801fd
refs/heads/master
2021-01-15T21:09:59.115304
2013-04-24T19:27:44
2013-04-24T19:27:44
33,946,024
0
0
null
null
null
null
UTF-8
Java
false
false
911
java
/** * */ package cbmarc.ginvoicing.client.view.customers; import cbmarc.ginvoicing.client.ui.LoadingPanel; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.Widget; /** * @author MCOSTA * */ public interface CustomersEditView { public interface Presenter { void onListButtonClicked(); void onSubmitButtonClicked(); void onCancelButtonClicked(); } LoadingPanel getLoadingPanel(); Panel getFormPanel(); HasValue<String> getName(); HasValue<String> getContact(); HasValue<String> getAddress(); HasValue<String> getCity(); HasValue<String> getCountry(); HasValue<String> getPhone(); HasValue<String> getFax(); HasValue<String> getEmail(); HasValue<String> getNotes(); void focus(); void reset(); void setPresenter(Presenter presenter); Widget asWidget(); }
[ "cbmarc@d00d3892-1c5f-11df-85fa-65efc338fd8f" ]
cbmarc@d00d3892-1c5f-11df-85fa-65efc338fd8f
d39190f71affa1e4fc4dffb8a4cf3f67dc582962
f6cbf156dd13ef9f649194b70c5bf39c070c1458
/simulation/src/main/java/ufersa/tcc/plot/Plot2d.java
c961ca8eca90d20bf80f50c1f2cf67bff794d7fd
[]
no_license
juanxjk/ufersa-orbital-simulation
8091fa9ebe487be58c3ca4e43ad8d2ed2858f9e3
316697ceb816261bdf50c86a82d30ae13155e8e5
refs/heads/master
2021-03-19T18:48:14.170061
2018-12-26T19:28:22
2018-12-26T19:28:22
105,772,497
0
0
null
null
null
null
UTF-8
Java
false
false
2,661
java
package ufersa.tcc.plot; import java.io.IOException; import java.util.List; import javax.swing.WindowConstants; import org.knowm.xchart.BitmapEncoder; import org.knowm.xchart.BitmapEncoder.BitmapFormat; import org.knowm.xchart.SwingWrapper; import org.knowm.xchart.XYChart; import org.knowm.xchart.XYChartBuilder; import org.knowm.xchart.style.Styler.ChartTheme; import org.knowm.xchart.style.markers.Marker; import org.knowm.xchart.style.markers.SeriesMarkers; public class Plot2d { /** Nome do plot */ private String name; private XYChart chart; /** * Mostra vários gráficos em layout de matriz. */ public static void displayChartMatrix(List<XYChart> charts) { new SwingWrapper<XYChart>(charts).displayChartMatrix() .setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } public static double[] doubleArray(List<Double[]> array, int col) { double[] data = new double[array.size()]; for (int z = 0; z < array.size(); z++) { data[z] = array.get(z)[col]; } return data; } /** * Construtor principal. */ public Plot2d(String name, int width, int height, String xDataLabel, String yDataLabel) { this.name = name; // Criação do Gráfico this.chart = new XYChartBuilder().width(width).height(height).theme(ChartTheme.Matlab).title(name) .xAxisTitle(xDataLabel).yAxisTitle(yDataLabel).build(); // Estilização do Gráfico chart.getStyler().setPlotGridLinesVisible(true); chart.getStyler().setXAxisTickMarkSpacingHint(100); } /** * @see Plot2d#Plot2d(String, int, int, String, double[], String, double[]) */ public Plot2d(String name, String xDataLabel, String yDataLabel) { this(name, 800, 600, xDataLabel, yDataLabel); } /** * Mostrar plot na tela. */ public void display() { // Mostrar em tela SwingWrapper display = new SwingWrapper(chart); display.displayChart().setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } /** * Salva o plot em arquivo. Formato: PNG, 300 DPI. */ public void saveFile(String src) throws IOException { BitmapEncoder.saveBitmapWithDPI(chart, src + this.name + ".png", BitmapFormat.PNG, 300); } /** * @see Plot2d#saveFile(String) */ public void saveFile() throws IOException { this.saveFile("./"); } public void addSeries(String title, double[] xData, double[] yData, Marker marker) { // Adicionando série para plot - Sem marcador chart.addSeries(title, xData, yData).setMarker(marker); } public void addSeries(String title, double[] xData, double[] yData) { this.addSeries(title, xData, yData, SeriesMarkers.NONE); } // GETTERS AND SETTERS public XYChart getChart() { return this.chart; } }
cdbfe2aee686c30d384b99d39029ceb1281e1ca7
8b7a6e172288691c91e757ab051a73376fc6709c
/src/org/musicmod/android/util/LyricsSplitter.java
8eff413be3c5ca5d0fdecebe53809ff3961eb3b0
[ "Apache-2.0" ]
permissive
lmxiaohuoer/musicmod
06206f8ad801d872c4fb82467300e8bfe523386e
48466b288f7f1082cb3fda34684d7354cdfe60c1
refs/heads/master
2021-01-24T04:20:15.487106
2012-03-11T07:49:56
2012-03-11T07:49:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,714
java
/* * Copyright (C) 2011 The MusicMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.musicmod.android.util; import android.graphics.Paint; public class LyricsSplitter { public static String split(String line, float pixels) { if (measureString(line, pixels) <= 294) return line; else { int half = line.length() / 2; for (int i = 0; i < half / 2; i++) { int pos = half - i; char c = line.charAt(pos); if (c == ' ' || c == '\u3000') { return line.substring(0, pos).trim() + "\n" + line.substring(pos + 1, line.length()).trim(); } else if (c == '(' || c == '<' || c == '[' || c == '{' || c == '\uFF08' || c == '\u3010' || c == '\u3016' || c == '\u300C' || c == '/') { return line.substring(0, pos).trim() + "\n" + line.substring(pos, line.length()).trim(); } else if (c == ')' || c == '>' || c == ']' || c == '}' || c == '\uFF09' || c == '\u3011' || c == '\u3017' || c == '\u300D' || c == ',' || c == '\uFF0C' || c == '\u3002') { return line.substring(0, pos + 1).trim() + "\n" + line.substring(pos + 1, line.length()).trim(); } pos = half + i + 1; c = line.charAt(pos); if (c == ' ' || c == '\u3000') { return line.substring(0, pos).trim() + "\n" + line.substring(pos + 1, line.length()).trim(); } else if (c == '(' || c == '<' || c == '[' || c == '{' || c == '\uFF08' || c == '\u3010' || c == '\u3016' || c == '\u300C' || c == '/') { return line.substring(0, pos).trim() + "\n" + line.substring(pos, line.length()).trim(); } else if (c == ')' || c == '>' || c == ']' || c == '}' || c == '\uFF09' || c == '\u3011' || c == '\u3017' || c == '\u300D' || c == ',' || c == '\uFF0C' || c == '\u3002') { return line.substring(0, pos + 1).trim() + "\n" + line.substring(pos + 1, line.length()).trim(); } } return line.substring(0, half) + "\n" + line.substring(half, line.length()); } } private static float measureString(String line, float pixels) { Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setTextSize(pixels); return mTextPaint.measureText(line); } }
0fb7283e2ecd34a2a2b65ed805a04e3743a35e64
ad3b0a36589f3b33c3e726f1b283bcd99ecfae97
/L8_HW5/src/Task9.java
0647c9a672d87f01978e87673a69e39715987936
[]
no_license
gsbozukov/itTalents_Assignments
0eb1055eab336d0817e9d78acc17aaebe32275aa
8f641818a0adc3125a1ef7f8eb33913de7b5dc96
refs/heads/master
2020-09-22T03:48:46.532833
2019-11-30T16:33:41
2019-11-30T16:33:41
225,038,168
0
0
null
null
null
null
UTF-8
Java
false
false
2,017
java
import java.util.Scanner; public class Task9 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter a line of text, minuses and numbers without spaces and press Enter:"); String text = sc.next(); int sum = 0; //loop the whole string for (int i = 0; i < text.length(); i++) { char symbol = text.charAt(i); //if we have -ve or a number enter another loop if (symbol >= '0' && symbol <= '9' || symbol == '-'){ int number; //for negatives, we multiply the end result by -1 if (symbol == '-'){ number = 0; for (int j = i+1; j < text.length(); j++) { if (text.charAt(j) >= '0' && text.charAt(j) <= '9'){ number = number*10; number = number + text.charAt(j) - '0'; i++; } else { break; } } System.out.println(number*-1); sum = sum + (number*-1); } //for positives we simply 'save' the number created else { number = symbol - '0'; for (int j = i+1; j < text.length(); j++) { if (text.charAt(j) >= '0' && text.charAt(j) <= '9'){ number = number*10; number = number + text.charAt(j) - '0'; i++; } else { break; } } System.out.println(number); sum = sum+number; } } } System.out.println("The total sum is: " + sum); } }
107fb100d0f797d04235ad3eac59c1f759e2a360
7d35366911b13b65b437ca08ba2cb8dd0dd940ea
/lab6/lab6part3/Carnivore.java
8f104097228568707e0ed9f1b76015103c066104
[]
no_license
BrodyW11/Programming-I-Labs
8484d897555c09816ec87556acf11e2bf368cea9
644c1623cea1f80ff691e7a7a2948c3e5a569b1d
refs/heads/master
2020-09-09T20:04:32.094022
2020-01-02T17:13:26
2020-01-02T17:13:26
221,553,313
0
0
null
null
null
null
UTF-8
Java
false
false
525
java
package lab6.lab6part3; public class Carnivore extends Animal { public Carnivore(String name, int age) { super(name, age); } void makeNoise(String Noise) { } void eat(Food f) { System.out.println("Carnivore Animal " + this.getName() + " " + this.getAge() + " years old eating " + f.getName()); try{ if(f instanceof Plant) throw new Exception(); }catch(Exception e){ System.out.println("This animal should not eat plants"); } } }
73c244965dc692f9abdedbeec0800270316392e2
bf596eea6659034a481a801fa4bd472eeb480c78
/Assignments_Indu/src/day20/CalenderDemo.java
f2716aad4420094b76ca668fd1535cc95f62b2d9
[]
no_license
Yindira/Assignments_Indu
82f20ce60af447e44a35e91a47631e3a1dfd7aa1
31f5ec708853a56a9713791503e3b8d761b22b21
refs/heads/master
2020-04-05T06:08:57.449915
2018-11-30T11:00:47
2018-11-30T11:00:47
156,627,220
0
0
null
null
null
null
UTF-8
Java
false
false
2,028
java
package day20; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class CalenderDemo { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get("https://www.makemytrip.com/"); driver.findElement(By.id("hp-widget__sfrom")).clear(); driver.findElement(By.id("hp-widget__sfrom")).sendKeys("New Delhi, India)"); driver.findElement(By.id("hp-widget__sTo")).clear(); driver.findElement(By.id("hp-widget__sTo")).sendKeys("Mumbai, India"); driver.findElement(By.id("hp-widget__depart")).click(); WebElement comingMonth = driver.findElement(By.xpath("(//div[contains(@class,'last')])[1]")); List<WebElement> columns = comingMonth.findElements(By.tagName("td")); for (WebElement x : columns) { if (x.getText().equals("10")) { x.click(); break; } } driver.findElement(By.id("searchBtn")).click(); String airline = driver.findElement(By.cssSelector( "#content > div > div.container.ng-scope > div.row > div.main.col-lg-9.col-md-9.col-sm-12.col-xs-12 > div:nth-child(5) > div > div.top_first_part.clearfix > div.col-lg-2.col-md-2.col-sm-2.col-xs-2.logo_section.padR0 > span.block.append_bottom3.clearfix > span.pull-left.airline_info_detls > span.logo_name.append_bottomSpace6.hidden-xs.visible-stb.ng-binding.ng-scope")) .getText(); String price = driver.findElement(By.cssSelector( "#content > div > div.container.ng-scope > div.row > div.main.col-lg-9.col-md-9.col-sm-12.col-xs-12 > div:nth-child(5) > div > div.top_first_part.clearfix > div.col-lg-2.col-md-2.col-sm-2.col-xs-4.text-right.price_sectn.make_relative.pad0 > p.price_info.RobotoRegular > span.num.ng-binding")) .getText(); System.out.println(airline); System.out.println(price); } }
94400057ffc7021fac9e28ac6657eecbf6d5ef71
088dac289b730e51d8796a69f6fde035cd98bd56
/src/main/java/org/systemsbiology/sax/ISaxHandler.java
d67793cc132462a73252091d4b389ae1a6e7607d
[]
no_license
gurvindersingh/sparkhydra
bf011609ebfcb14a9a8f9cf54dd12ad38276d945
e7b1a53d53cdafb373a62abd8fb73ce6c633d2f2
refs/heads/master
2021-01-21T13:48:26.941892
2017-11-24T23:24:20
2017-11-24T23:24:20
28,445,434
3
2
null
null
null
null
UTF-8
Java
false
false
5,081
java
package org.systemsbiology.sax; import org.xml.sax.*; /** * org.systemsbiology.xtandem.sax.ISaxHandler * User: steven * Date: Jan 3, 2011 */ public interface ISaxHandler { public static final ISaxHandler[] EMPTY_ARRAY = {}; /** * Receive notification of the start of an element. * <p/> * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the start of * each element (such as allocating a new tree node or writing * output to a file).</p> * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @param attributes The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#startElement */ public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException; /** * Divides the handling of a start element into handling the element and handling * Attributes * <p/> * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the start of * each element (such as allocating a new tree node or writing * output to a file).</p> * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @param attributes The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#startElement */ public void handleAttributes(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException; /** * Receive notification of the end of an element. * <p/> * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the end of * each element (such as finalising a tree node or writing * output to a file).</p> * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#endElement */ public void endElement(final String uri, final String localName, final String qName) throws SAXException; /** * Receive notification of character data inside an element. * <p/> * <p>By default, do nothing. Application writers may override this * method to take specific actions for each chunk of character data * (such as adding the data to a node or buffer, or printing it to * a file).</p> * * @param ch The characters. * @param start The start position in the character array. * @param length The number of characters to use from the * character array. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#characters */ public void characters(final char[] ch, final int start, final int length) throws SAXException; }
fd7d0db391b7451c4a1a429d9c4a0e774969a12a
6a94901524582a464dee974e2fca83ca4f2580c8
/MediaPlayer/app/src/test/java/com/example/ricar/mediaplayer/ExampleUnitTest.java
259fd2d5616a87e05db6a4c90a19f16d6fad9ff9
[]
no_license
ricarrrdoaraujo/android-projects
0f11c561d5466f51b1f135cf653a30c9299474d3
33dbf90acf8a7899a342ec20e36c044b72dfed22
refs/heads/master
2021-10-22T13:03:40.734907
2019-03-10T22:45:03
2019-03-10T22:45:03
166,459,633
0
0
null
null
null
null
UTF-8
Java
false
false
390
java
package com.example.ricar.mediaplayer; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
a4d50c3f5c69236005d083a9b2640bf9bd38e5b1
0f1299c8edf7724a2cccf010648cbc19937efe4e
/tabalhoSemestral/src/View/Painel_Imoveis.java
c579aede2f14efb1cfebd78bf2f57c1455f43252
[]
no_license
ezequiel855/Sistema-de-venda-e-arrendamento-de-imoveis
7cad2673ba6ed3632a95d17649c73e4ef2a3f2f9
aa47b70a06d8bd28d2d15117acbe55935035ba74
refs/heads/master
2023-04-11T10:52:13.202180
2021-04-14T03:54:20
2021-04-14T03:54:20
357,571,129
0
0
null
null
null
null
UTF-8
Java
false
false
8,615
java
/* * 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 View; import Model.Dao.ModulodConexao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.swing.JOptionPane; import net.proteanit.sql.DbUtils; /** * * @author Lenovo */ public class Painel_Imoveis extends javax.swing.JInternalFrame { /** * Creates new form Painel_Imoveis */ Connection conexao = null; PreparedStatement pst = null; ResultSet rs = null; public Painel_Imoveis() { initComponents(); conexao = ModulodConexao.conector(); consultarAnuncio(); } private void consultarAnuncio() { String sql = "SELECT * FROM tbImovel"; try { pst = conexao.prepareStatement(sql); rs = pst.executeQuery(); do { tblePesquisarAnuncio.setModel(DbUtils.resultSetToTableModel(rs)); } while (rs.next()); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnelPrincipal = new javax.swing.JPanel(); txtPesquisar = new javax.swing.JTextField(); jSeparatorPesquisar = new javax.swing.JSeparator(); lblPesquisar = new javax.swing.JLabel(); cbxCriteriodPesquisar = new javax.swing.JComboBox(); jScrollPane1 = new javax.swing.JScrollPane(); tblePesquisarAnuncio = new javax.swing.JTable(); pnelPrincipal.setBackground(new java.awt.Color(255, 255, 255)); txtPesquisar.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N txtPesquisar.setText("Pesquisar"); txtPesquisar.setBorder(null); txtPesquisar.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtPesquisarFocusGained(evt); } }); jSeparatorPesquisar.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { cbxCriteriodPesquisarFocusGained(evt); } }); lblPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/search_50px_1.png"))); // NOI18N lblPesquisar.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { cbxCriteriodPesquisarFocusGained(evt); } }); cbxCriteriodPesquisar.setFont(new java.awt.Font("Arial", 3, 14)); // NOI18N cbxCriteriodPesquisar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Bairro", "Preço", "Venda", "Aluguer", "Casa", "Flat" })); tblePesquisarAnuncio.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "idImovel", "Bairro", "Tipo de imóvel", "Numero da casa", "Quarteirao", "Dimensao", "Andar", "Descricao", "Preco" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, true, true, true, true, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(tblePesquisarAnuncio); javax.swing.GroupLayout pnelPrincipalLayout = new javax.swing.GroupLayout(pnelPrincipal); pnelPrincipal.setLayout(pnelPrincipalLayout); pnelPrincipalLayout.setHorizontalGroup( pnelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnelPrincipalLayout.createSequentialGroup() .addContainerGap(105, Short.MAX_VALUE) .addComponent(cbxCriteriodPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtPesquisar) .addComponent(jSeparatorPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 387, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblPesquisar) .addGap(93, 93, 93)) .addGroup(pnelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnelPrincipalLayout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(jScrollPane1) .addGap(12, 12, 12))) ); pnelPrincipalLayout.setVerticalGroup( pnelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnelPrincipalLayout.createSequentialGroup() .addContainerGap() .addGroup(pnelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnelPrincipalLayout.createSequentialGroup() .addGroup(pnelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbxCriteriodPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparatorPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(lblPesquisar)) .addContainerGap(463, Short.MAX_VALUE)) .addGroup(pnelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnelPrincipalLayout.createSequentialGroup() .addGap(149, 149, 149) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(149, Short.MAX_VALUE))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cbxCriteriodPesquisarFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbxCriteriodPesquisarFocusGained // TODO add your handling code here: }//GEN-LAST:event_cbxCriteriodPesquisarFocusGained private void txtPesquisarFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPesquisarFocusGained // TODO add your handling code here: txtPesquisar.setText(""); }//GEN-LAST:event_txtPesquisarFocusGained // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox cbxCriteriodPesquisar; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparatorPesquisar; private javax.swing.JLabel lblPesquisar; private javax.swing.JPanel pnelPrincipal; private javax.swing.JTable tblePesquisarAnuncio; private javax.swing.JTextField txtPesquisar; // End of variables declaration//GEN-END:variables }
c8c7362b211dd21427332e9654a7eecbdc99357b
9bef7c1180258961ff0c1cb94db0d5f9af898c92
/projects/java_study/src/main/java/thread/MyThread.java
47907f0a43677c5560ff9eaf8ec0693963bd3c19
[]
no_license
zsgwsjj/java_experience
f3452e86b536bafb07edf683d8727642d970319d
ea9744cc6a9c3c5c4158f7348034537026ac0142
refs/heads/master
2020-03-11T03:35:28.642052
2018-06-11T15:04:18
2018-06-11T15:04:18
129,752,272
2
0
null
null
null
null
UTF-8
Java
false
false
525
java
package thread; /** * @author : jiang * @time : 2018/5/18 18:51 */ public class MyThread implements Runnable { private String name; public MyThread setName(String name) { this.name = name; return this; } @Override public void run() { System.out.println("hello " + name); } public static void main(String[] args) { MyThread thread = new MyThread(); thread.setName("xxx"); Thread thread1 = new Thread(thread); thread1.start(); } }
76ee17903c0171e981e272e1b528b7d74f93bea4
080ce194d0f4d93bb94b728b87fa871e27efdf41
/knxscada/webapp/src/main/java/pl/marek/knx/pages/CreateEditLayerFormPanel.java
789afed45aa4822ff684166bc36467e3df3d2e7b
[]
no_license
glocklueng/knxscada
a740b887efa2b8fc1b3a50b63ee38fe2b47ca767
1e395acbaf4440cc5cf6a317197d253e0ae64802
refs/heads/master
2021-01-20T12:38:28.410304
2014-01-03T13:10:09
2014-01-03T13:10:09
35,853,844
0
0
null
null
null
null
UTF-8
Java
false
false
7,238
java
package pl.marek.knx.pages; import java.io.File; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormValidatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.markup.html.form.SimpleFormComponentLabel; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.repeater.RepeatingView; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.util.time.Duration; import pl.marek.knx.annotations.HtmlFile; import pl.marek.knx.database.Layer; import pl.marek.knx.database.SubLayer; import pl.marek.knx.interfaces.DatabaseManager; import pl.marek.knx.utils.IconUtil; import pl.marek.knx.utils.StaticImage; @HtmlFile("create_edit_layer_form_panel.html") public class CreateEditLayerFormPanel extends BasePanel{ private static final long serialVersionUID = 1L; private Layer layer; private FeedbackPanel feedbackPanel; private LayerForm form; private String itemType; private StaticImage iconView; private RepeatingView chooserIcons; public CreateEditLayerFormPanel(String componentName, DatabaseManager dbManager, String itemType) { super(componentName, dbManager); this.itemType = itemType; loadComponents(); } public CreateEditLayerFormPanel(String componentName, DatabaseManager dbManager, String itemType, Layer layer) { super(componentName, dbManager); this.layer = layer; this.itemType = itemType; loadComponents(); } private void loadComponents(){ if(layer == null){ if(Layer.LAYER.equals(itemType)){ layer = new Layer(); }else if(SubLayer.SUBLAYER.equals(itemType)){ layer = new SubLayer(); } } form = new LayerForm("layer-form", layer); form.setOutputMarkupId(true); add(form); feedbackPanel = new FeedbackPanel("layer-feedback"); feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); String icon = getIconPath(); iconView = new StaticImage("layer-icon", new Model<String>(icon)); iconView.setOutputMarkupId(true); if(icon == null || icon.isEmpty()){ iconView.setVisible(false); iconView.setOutputMarkupPlaceholderTag(true); } add(iconView); chooserIcons = new RepeatingView("layer-icon-chooser-item"); loadChooserIcons(); add(chooserIcons); } private String getIconPath(){ String icon = ""; if(!layer.getIcon().isEmpty()){ if(Layer.LAYER.equals(itemType)){ icon = IconUtil.getLayerIconPath(layer.getIcon()); }else if(SubLayer.SUBLAYER.equals(itemType)){ icon = IconUtil.getSubLayerIconPath(layer.getIcon()); } } return icon; } private void loadChooserIcons(){ File imagesPath = new File(getServletContext().getRealPath("images")); String relativePath = ""; File imgDirectory = null; if(Layer.LAYER.equals(itemType)){ relativePath = "images/floors/"; imgDirectory = new File(imagesPath.getAbsolutePath(),"floors"); }else if(SubLayer.SUBLAYER.equals(itemType)){ relativePath = "images/rooms/"; imgDirectory = new File(imagesPath.getAbsolutePath(),"rooms"); } if(imgDirectory != null){ for(File file: imgDirectory.listFiles()){ String iconPath = relativePath + file.getName(); StaticImage img = new StaticImage(chooserIcons.newChildId(), new Model<String>(iconPath)); img.add(new LayerIconChooserClickBehavior(iconPath)); chooserIcons.add(img); } } } public Layer getLayer() { return layer; } public void setLayer(Layer layer) { this.layer = layer; loadComponents(); } private class LayerIconChooserClickBehavior extends AjaxEventBehavior{ private static final long serialVersionUID = 1L; private String iconPath; public LayerIconChooserClickBehavior(String iconPath) { super("click"); this.iconPath = iconPath; } @Override protected void onEvent(AjaxRequestTarget target) { layer.setIcon(getIconName()); iconView.setDefaultModelObject(iconPath); iconView.setVisible(true); target.add(iconView); } private String getIconName(){ int lastSlash = iconPath.lastIndexOf("/"); int lastDot = iconPath.lastIndexOf("."); String name = iconPath.substring(lastSlash + 1, lastDot); return name; } } private class LayerForm extends Form<Layer>{ private static final long serialVersionUID = 1L; private CompoundPropertyModel<Layer> model; public LayerForm(String id, Layer layer) { super(id); model = new CompoundPropertyModel<Layer>(layer); setModel(model); loadFields(); } private void loadFields(){ RequiredTextField<String> nameField = new RequiredTextField<String>("name"); TextArea<String> descriptionField = new TextArea<String>("description"); if(Layer.LAYER.equals(itemType)){ nameField.setLabel(new ResourceModel("layer-form.name.label")); descriptionField.setLabel(new ResourceModel("layer-form.description.label")); }else if(SubLayer.SUBLAYER.equals(itemType)){ nameField.setLabel(new ResourceModel("sublayer-form.name.label")); descriptionField.setLabel(new ResourceModel("sublayer-form.description.label")); } add(nameField); add(new SimpleFormComponentLabel("layer-name-label", nameField)); add(descriptionField); add(new SimpleFormComponentLabel("layer-description-label", descriptionField)); AjaxFormValidatingBehavior.addToAllFormComponents(this, "onkeyup", Duration.ONE_SECOND); AjaxButton submitButton = new AjaxButton("layer-form-submit-button", this) { private static final long serialVersionUID = 1L; @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { if(Layer.LAYER.equals(itemType)){ Layer l = (Layer)form.getModel().getObject(); String projectId = getParameter("project"); l.setProjectId(Integer.valueOf(projectId)); if(l.getId() == 0){ getDBManager().addLayer(l); }else{ getDBManager().updateLayer(l); } SideBarPanel panel = getSideBarPanel(); panel.refresh(); target.add(panel); }else if(SubLayer.SUBLAYER.equals(itemType)){ SubLayer l = (SubLayer)form.getModel().getObject(); SideBarPanel panel = getSideBarPanel(); String projectId = getParameter("project"); l.setProjectId(Integer.valueOf(projectId)); l.setLayerId(panel.getCurrentLayer().getId()); if(l.getId() == 0){ getDBManager().addSubLayer(l); }else{ getDBManager().updateSubLayer(l); } SubLayersPanel spanel = getSubLayersPanel(); spanel.refresh(); target.add(spanel); } target.add(feedbackPanel); target.appendJavaScript("loadAfterUpdateLayer();"); } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(feedbackPanel); } }; add(submitButton); } } }
[ "[email protected]@3a46568f-e696-a695-f9f6-4524ef62d10c" ]
[email protected]@3a46568f-e696-a695-f9f6-4524ef62d10c
b6ea9e416dde935a83202232de8d486535228023
10b6b795ec8e28fcad2132df41e38734b066cc77
/src/main/java/gp/nodes/internal/BloodPressure.java
b4a951279ed4c0bcd93531f4dc339a543d65767a
[ "AFL-3.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
the-mars-rover/cos_710_assignment_3
c29daa59d000cd0be58e14992c6c70b78165ce0d
a5f81cfd4f5b402098a4a0ce6fe752805bd627ff
refs/heads/master
2023-01-07T02:23:51.480135
2020-11-11T17:47:25
2020-11-11T17:47:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,311
java
package gp.nodes.internal; import ec.EvolutionState; import ec.Problem; import ec.gp.ADFStack; import ec.gp.GPData; import ec.gp.GPIndividual; import ec.gp.GPNode; import gp.problem.PostOperativeProblem; /** * This class models the blood pressure decision node. It accepts 3 children and acts as follows: * - if the patient's blood pressure is 'low' it evaluates the 1st child. * - if the patient's blood pressure is 'mid' it evaluates the 2nd child. * - if the patient's blood pressure is 'high' it evaluates the 3rd child. */ public class BloodPressure extends GPNode { @Override public String toString() { return "BP"; } @Override public int expectedChildren() { return 3; } @Override public void eval(EvolutionState evolutionState, int i, GPData gpData, ADFStack adfStack, GPIndividual gpIndividual, Problem problem) { PostOperativeProblem postOperativeProblem = ((PostOperativeProblem) (problem)); switch (postOperativeProblem.patient.bloodPressure) { case low: children[0].eval(evolutionState, i, gpData, adfStack, gpIndividual, problem); break; case mid: children[1].eval(evolutionState, i, gpData, adfStack, gpIndividual, problem); break; case high: children[2].eval(evolutionState, i, gpData, adfStack, gpIndividual, problem); break; } } }
23ab07f80389bf81336f10ba48c1fb2be19d8cd9
c07641caa3b8e92a04712e34d8df21c29096f166
/src/com/shops/StoreProduct.java
aa8b2fbfb93425fc780a1612b7e030d224cdd055
[]
no_license
DarraghLally/JSF_WebApp
56c6b135eeabfb94d5867080ca2b9deaff440a89
abd5f6d955c3ad71919ad233bf35ea50ad7e1615
refs/heads/master
2020-09-24T04:55:32.095896
2019-12-11T17:11:20
2019-12-11T17:11:20
225,667,796
0
0
null
null
null
null
UTF-8
Java
false
false
954
java
package com.shops; import javax.faces.bean.ManagedBean; @ManagedBean public class StoreProduct { //Variables private int sid; private String storeName; private int pid; private String product; private double price; private String founded; //Accessor methods public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public String getFounded() { return founded; } public void setFounded(String founded) { this.founded = founded; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
726594a837a473b4123a236873ebe03df9881e82
1925dc2945e1d6cc82525ceff3dbef278ba8d0d9
/src/main/java/com/jalaj/jhipstergateway/service/dto/package-info.java
30ff7754768d08ff82450eccea93e799ca73a9b6
[]
no_license
trustjalaj/jhipster-sample-application
54be7677e39e36abf0374be0b2dce11acd44b825
be357dfaa973bd8d98315d39ef6c6b544eb757c8
refs/heads/master
2020-03-27T01:41:02.390736
2018-08-22T16:10:26
2018-08-22T16:10:26
145,733,051
0
0
null
null
null
null
UTF-8
Java
false
false
81
java
/** * Data Transfer Objects. */ package com.jalaj.jhipstergateway.service.dto;
a7d9866d358faaee03d067dd89f24a2753f27313
024ad511aafc65adc1d3742e65aef45eb8d45c8a
/src/AbstractFactory/MAIB.java
5aebd9c57c024dc60faf2a0beda015924195ec17
[]
no_license
ion7Sate/TMPSLaborator
ab7d2c7efdb371ab9a215c8afa4362bca70530de
d6cce65c00004c4037f51ee951adc3a193bbaa24
refs/heads/main
2023-03-23T02:31:06.125672
2021-03-10T17:40:11
2021-03-10T17:40:11
346,455,144
0
0
null
null
null
null
UTF-8
Java
false
false
241
java
package AbstractFactory; public class MAIB implements Bank{ private final String BankName; public MAIB(){ BankName = "Moldova-Agroindbank"; } public String getBankCompletName(){ return BankName; } }
7f8d71f7307a63c13c5a8524d19e83a4369c9286
141a8418a9cf8442f9b7a39a003b2428cc4ef6da
/DesPatterns/src/strategy/Context.java
466ef1d7771e48a06775827e2b974113d622b296
[]
no_license
Roberto1987/DPattern
7b68b84454464274a0bde448cc619ee181fcfcea
584bb680d90780d2be6898ae42b7f3823113ab57
refs/heads/master
2021-01-11T23:05:54.716692
2017-05-15T16:51:49
2017-05-15T16:51:49
78,547,776
0
0
null
null
null
null
UTF-8
Java
false
false
243
java
package strategy; public class Context { private Choice choice; public void setChoice(Choice choice){ this.choice = choice; } public void showChoice(String s1, String s2){ this.choice.execute(s1, s2); } }
56a1b8154624a342390f172e99086235002393f1
b955e4d721ba50a1afe0865736ee57684669fce8
/app/src/main/java/com/sargent/mark/todolist/AddToDoFragment.java
0216ed613069b963ebac5acbc814d30dd4cee333
[]
no_license
ektakm18/Homework-3-Enhanced-to-do-list
90d623d5058ccd8ee7c5b9cfcf20d6aadc1862c1
12a7a87c7be6c7ec522d266b2a1ffde4aa90b232
refs/heads/master
2021-03-27T09:38:59.860876
2017-07-20T07:07:47
2017-07-20T07:07:47
97,793,864
0
0
null
null
null
null
UTF-8
Java
false
false
3,200
java
package com.sargent.mark.todolist; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import android.widget.TimePicker; import android.widget.Toast; import java.util.Calendar; /** * Created by mark on 7/4/17. */ public class AddToDoFragment extends DialogFragment{ private EditText toDo; private DatePicker dp; private Button add; private final String TAG = "addtodofragment"; private Spinner spin; private String spinner; public AddToDoFragment() { } //To have a way for the activity to get the data from the dialog public interface OnDialogCloseListener { void closeDialog(int year, int month, int day, String description, String category); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_to_do_adder, container, false); //Creating the spinner object and storing the spinner through it's id spin= (Spinner) view.findViewById(R.id.spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),R.array.to_do_array, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spin.setAdapter(adapter); //to handle the spinner events when it is getting clicked spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { spinner=spin.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); toDo = (EditText) view.findViewById(R.id.toDo); dp = (DatePicker) view.findViewById(R.id.datePicker); add = (Button) view.findViewById(R.id.add); final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); dp.updateDate(year, month, day); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OnDialogCloseListener activity = (OnDialogCloseListener) getActivity(); activity.closeDialog(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(), toDo.getText().toString(),spinner); AddToDoFragment.this.dismiss(); } }); return view; } }
fc79a31e10d39db55f6ca06a0f5857f1d3d31c44
55c99c3a9f99c9faf2c18b4bfddbf0561adfc525
/src/main/java/drocck/sp/beesandhoney/business/entities/validators/UserCreateFormValidator.java
8f85541ea67c7278366b623a2340705906862f37
[]
no_license
DROCCK/oh-behive
6b7e5f409b9015492c3bca77c89b48648504cf89
88465f4681287811d8ea12edca471cd9fc540fb0
refs/heads/master
2020-12-19T19:01:22.035399
2016-05-12T04:57:51
2016-05-12T04:57:51
43,217,459
5
1
null
2016-08-15T01:34:35
2015-09-26T18:24:59
HTML
UTF-8
Java
false
false
609
java
package drocck.sp.beesandhoney.business.entities.validators; import drocck.sp.beesandhoney.business.entities.DTOs.UserCreateForm; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; /** * @author Robert Wilk * Created on 10/3/2015. */ @Component public class UserCreateFormValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return clazz.equals(UserCreateForm.class); } @Override public void validate(Object target, Errors errors) { } }
afda935d8665788943318518ca161ed9bdbf609a
fe4014159617d8aef827f3ac70af3a9b7db7e199
/app/src/main/java/com/example/android/popularmovies/utilities/NetworkUtils.java
a1fb595d9f9ec9ca2d8d856dd99a67244166532a
[]
no_license
thib146/PopularMovies
96f742d51ec44aa3d818825b7b5a0a7ef401f0a9
6119ee7d32a3c965b1c060c8aca350d389d034e6
refs/heads/master
2021-01-11T18:32:36.507072
2017-04-12T22:45:27
2017-04-12T22:45:27
79,564,430
0
0
null
null
null
null
UTF-8
Java
false
false
7,617
java
package com.example.android.popularmovies.utilities; import android.net.Uri; import android.os.Handler; import android.util.Log; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Locale; import java.util.Scanner; /** * These utilities will be used to communicate with the movieDB servers. */ public final class NetworkUtils { private static final String TAG = NetworkUtils.class.getSimpleName(); private static final String THEMOVIEDB_BASE_URL = "http://api.themoviedb.org/3/movie"; private static final String TMDB_LANGUAGE = "language"; private static final String TMDB_PAGE_NUMBER = "page"; private static final String TMDB_VIDEOS = "videos"; private static final String TMDB_REVIEWS = "reviews"; // Get the device language here private static String deviceLanguage = Locale.getDefault().getLanguage(); /** * This is where the API KEY from the movieDB is required */ private static final String API_KEY = ""; /* The API Key parameter required in the url */ private static final String API_KEY_PARAM = "api_key"; /** * Builds the URL used to talk to the movieDB server using a sort query, a device language and a page number * * @param sortQuery The sort style (popular/top rated) that will be queried for. * @return The URL to use to query the movieDB server. */ public static URL buildUrl(String sortQuery, String currentPageNumber) { Uri builtUri = Uri.parse(THEMOVIEDB_BASE_URL).buildUpon() .appendPath(sortQuery) .appendQueryParameter(API_KEY_PARAM, API_KEY) .appendQueryParameter(TMDB_LANGUAGE, deviceLanguage) .appendQueryParameter(TMDB_PAGE_NUMBER, currentPageNumber) .build(); URL url = null; try { url = new URL(builtUri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } Log.v(TAG, "Built URI List " + url); return url; } // Check if the API Key is empty or not and returns true or false accordingly public static boolean isApiKeyOn() { return !API_KEY.equals(""); } /** * Builds the URL used to talk to the movieDB server int the detailed activity, once we have a movie ID * * @param id The id of a movie, once it's clicked * @return The URL to use to query the movieDB server. */ public static URL buildUrlDetail(String id) { Uri builtUri = Uri.parse(THEMOVIEDB_BASE_URL).buildUpon() .appendPath(id) .appendQueryParameter(API_KEY_PARAM, API_KEY) .appendQueryParameter(TMDB_LANGUAGE, deviceLanguage) .build(); URL url = null; try { url = new URL(builtUri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } Log.v(TAG, "Built URI Detail " + url); return url; } /** * Builds the URL used to talk to the movieDB server in the detailed activity, to get the videos once we have a movie ID * * @param id The id of a movie, once it's clicked * @return The URL to use to query the movieDB server. */ public static URL buildUrlVideos(String id) { Uri builtUri = Uri.parse(THEMOVIEDB_BASE_URL).buildUpon() .appendPath(id) .appendPath(TMDB_VIDEOS) .appendQueryParameter(API_KEY_PARAM, API_KEY) .appendQueryParameter(TMDB_LANGUAGE, deviceLanguage) .build(); URL url = null; try { url = new URL(builtUri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } Log.v(TAG, "Built URI Videos " + url); return url; } /** * Builds the URL used to talk to the movieDB server in the detailed activity, to get the reviews once we have a movie ID * * @param id The id of a movie, once it's clicked * @return The URL to use to query the movieDB server. */ public static URL buildUrlReviews(String id) { Uri builtUri = Uri.parse(THEMOVIEDB_BASE_URL).buildUpon() .appendPath(id) .appendPath(TMDB_REVIEWS) .appendQueryParameter(API_KEY_PARAM, API_KEY) .appendQueryParameter(TMDB_LANGUAGE, deviceLanguage) .build(); URL url = null; try { url = new URL(builtUri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } Log.v(TAG, "Built URI Reviews " + url); return url; } /** * This method returns the entire result from the HTTP response. * * @param url The URL to fetch the HTTP response from. * @return The contents of the HTTP response. * @throws IOException Related to network and stream reading */ public static String getResponseFromHttpUrl(URL url) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = urlConnection.getInputStream(); Scanner scanner = new Scanner(in); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); if (hasInput) { return scanner.next(); } else { return null; } } finally { urlConnection.disconnect(); } } /** * This method checks if the device is connected to the internet * * @param handler Changes the mConnected global variable according to connection status * @param timeout Time to wait for the server response before considering that the connexion is lost */ public static void isNetworkAvailable(final Handler handler, final int timeout) { // Asks for message '0' (not connected) or '1' (connected) on 'handler' // the answer must be sent within the 'timeout' (in milliseconds) new Thread() { private boolean responded = false; @Override public void run() { // set 'responded' to TRUE if is able to connect with google mobile (responds fast) new Thread() { @Override public void run() { HttpGet requestForTest = new HttpGet("http://m.google.com"); try { new DefaultHttpClient().execute(requestForTest); responded = true; } catch (Exception e) { } } }.start(); try { int waited = 0; while(!responded && (waited < timeout)) { sleep(100); if(!responded ) { waited += 100; } } } catch(InterruptedException e) {} // do nothing finally { if (!responded) { handler.sendEmptyMessage(0); } else { handler.sendEmptyMessage(1); } } } }.start(); } }
7d8dc8b0f495cc090a58d376bd4b289dc4de0d88
5120f6a7701a29f8e2eb61f384b436514087fd42
/org/apache/tomcat/util/http/fileupload/util/mime/QuotedPrintableDecoder.java
064470b93042dee269771c0e9c03d3b12508aa5e
[]
no_license
joellobo/tomcat-embed-core-10.0.6
4dbb1c4ed9b88921e7248ee2ee78542f9a80c7d3
7b95a7a0b0f719d7bb65b252b1153b43d6c3d198
refs/heads/main
2023-05-02T16:23:20.804573
2021-05-21T12:47:21
2021-05-21T12:47:21
369,532,705
1
1
null
null
null
null
UTF-8
Java
false
false
4,382
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.http.fileupload.util.mime; import java.io.IOException; import java.io.OutputStream; /** * @since 1.3 */ final class QuotedPrintableDecoder { /** * The shift value required to create the upper nibble * from the first of 2 byte values converted from ascii hex. */ private static final int UPPER_NIBBLE_SHIFT = Byte.SIZE / 2; /** * Hidden constructor, this class must not be instantiated. */ private QuotedPrintableDecoder() { // do nothing } /** * Decode the encoded byte data writing it to the given output stream. * * @param data The array of byte data to decode. * @param out The output stream used to return the decoded data. * * @return the number of bytes produced. * @throws IOException if a problem occurs during either decoding or * writing to the stream */ public static int decode(final byte[] data, final OutputStream out) throws IOException { int off = 0; final int length = data.length; final int endOffset = off + length; int bytesWritten = 0; while (off < endOffset) { final byte ch = data[off++]; // space characters were translated to '_' on encode, so we need to translate them back. if (ch == '_') { out.write(' '); } else if (ch == '=') { // we found an encoded character. Reduce the 3 char sequence to one. // but first, make sure we have two characters to work with. if (off + 1 >= endOffset) { throw new IOException("Invalid quoted printable encoding; truncated escape sequence"); } final byte b1 = data[off++]; final byte b2 = data[off++]; // we've found an encoded carriage return. The next char needs to be a newline if (b1 == '\r') { if (b2 != '\n') { throw new IOException("Invalid quoted printable encoding; CR must be followed by LF"); } // this was a soft linebreak inserted by the encoding. We just toss this away // on decode. } else { // this is a hex pair we need to convert back to a single byte. final int c1 = hexToBinary(b1); final int c2 = hexToBinary(b2); out.write((c1 << UPPER_NIBBLE_SHIFT) | c2); // 3 bytes in, one byte out bytesWritten++; } } else { // simple character, just write it out. out.write(ch); bytesWritten++; } } return bytesWritten; } /** * Convert a hex digit to the binary value it represents. * * @param b the ascii hex byte to convert (0-0, A-F, a-f) * @return the int value of the hex byte, 0-15 * @throws IOException if the byte is not a valid hex digit. */ private static int hexToBinary(final byte b) throws IOException { // CHECKSTYLE IGNORE MagicNumber FOR NEXT 1 LINE final int i = Character.digit((char) b, 16); if (i == -1) { throw new IOException("Invalid quoted printable encoding: not a valid hex digit: " + b); } return i; } }
fcf41f211b38692b20bae7268cdf6544c04fee72
a89db729bc25f558f678ccf997e7c18e8f3581b3
/EazyCore/core/src/main/java/vn/eazy/core/utils/ObjectUtils.java
c5589b85615d2e29ef0520b07e9cc3fda7637cfb
[ "Apache-2.0" ]
permissive
harrylefit/eazycore
561b208cab23abf586784fdf826b48db3aaf31fc
8c18bf8f2fb0d9a6a53b3396495b77a70e2e2c97
refs/heads/master
2021-01-13T05:01:30.753641
2018-08-07T01:44:25
2018-08-07T01:44:25
81,184,711
2
2
Apache-2.0
2018-08-07T01:44:26
2017-02-07T08:25:58
Java
UTF-8
Java
false
false
3,235
java
package vn.eazy.core.utils; /** * Object Utils * * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2011-10-24 */ public class ObjectUtils { private ObjectUtils() { throw new AssertionError(); } /** * compare two object * * @param actual * @param expected * @return <ul> * <li>if both are null, return true</li> * <li>return actual.{@link Object#equals(Object)}</li> * </ul> */ public static boolean isEquals(Object actual, Object expected) { return actual == expected || (actual == null ? expected == null : actual.equals(expected)); } /** * null Object to empty string * * <pre> * nullStrToEmpty(null) = &quot;&quot;; * nullStrToEmpty(&quot;&quot;) = &quot;&quot;; * nullStrToEmpty(&quot;aa&quot;) = &quot;aa&quot;; * </pre> * * @param str * @return */ public static String nullStrToEmpty(Object str) { return (str == null ? "" : (str instanceof String ? (String)str : str.toString())); } /** * convert long array to Long array * * @param source * @return */ public static Long[] transformLongArray(long[] source) { Long[] destin = new Long[source.length]; for (int i = 0; i < source.length; i++) { destin[i] = source[i]; } return destin; } /** * convert Long array to long array * * @param source * @return */ public static long[] transformLongArray(Long[] source) { long[] destin = new long[source.length]; for (int i = 0; i < source.length; i++) { destin[i] = source[i]; } return destin; } /** * convert int array to Integer array * * @param source * @return */ public static Integer[] transformIntArray(int[] source) { Integer[] destin = new Integer[source.length]; for (int i = 0; i < source.length; i++) { destin[i] = source[i]; } return destin; } /** * convert Integer array to int array * * @param source * @return */ public static int[] transformIntArray(Integer[] source) { int[] destin = new int[source.length]; for (int i = 0; i < source.length; i++) { destin[i] = source[i]; } return destin; } /** * compare two object * <ul> * <strong>About result</strong> * <li>if v1 > v2, return 1</li> * <li>if v1 = v2, return 0</li> * <li>if v1 < v2, return -1</li> * </ul> * <ul> * <strong>About rule</strong> * <li>if v1 is null, v2 is null, then return 0</li> * <li>if v1 is null, v2 is not null, then return -1</li> * <li>if v1 is not null, v2 is null, then return 1</li> * <li>return v1.{@link Comparable#compareTo(Object)}</li> * </ul> * * @param v1 * @param v2 * @return */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <V> int compare(V v1, V v2) { return v1 == null ? (v2 == null ? 0 : -1) : (v2 == null ? 1 : ((Comparable)v1).compareTo(v2)); } }
5f2b371edc8eb6ca97672d0bdfe5cbfd2fc5bf07
2b5a9fe32a5b70b5b1a03284ed28ac7cdaf0697e
/frontend/api/src/main/java/com/ml/prize/api/service/GameService.java
fd6d013a68a0b90ed4a80eff62b8833c2ce1854b
[]
no_license
Long-M/prize
1370a70abbdc9ed6a0648aacf11009b4dc202953
8e4544df97ae2090d843de4cad61caf410c54550
refs/heads/master
2023-03-20T00:30:07.348356
2021-03-27T14:30:56
2021-03-27T14:30:56
346,678,966
0
0
null
null
null
null
UTF-8
Java
false
false
322
java
package com.ml.prize.api.service; import com.ml.prize.commons.vo.ResultVO; public interface GameService { ResultVO list(Integer status, Integer curPage, Integer limit); ResultVO info(Integer gameId); ResultVO products(Integer gameId); ResultVO hit(Integer gameId, Integer curPage, Integer limit); }
f40ef2e09927ff251f32cd33e147ce32cc3c9eb3
0d8e0c6d327ae36a3eb600d4d61615a92c08a12d
/service-core/src/main/java/com/atguigu/srb/core/mapper/IntegralGradeMapper.java
89106da96396d70d533bdbc91d3ecc07d8ccf966
[]
no_license
liyi102683/srb-01
71cabb85433f33be10b37e793b2a88d64626d7ee
5ee84f226a3bf970d91d50173ae31b04bdef228b
refs/heads/master
2023-06-17T17:42:58.549667
2021-07-06T13:31:53
2021-07-06T13:31:53
383,483,612
0
0
null
null
null
null
UTF-8
Java
false
false
320
java
package com.atguigu.srb.core.mapper; import com.atguigu.srb.core.pojo.entity.IntegralGrade; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * 积分等级表 Mapper 接口 * </p> * * @author ly * @since 2021-06-09 */ public interface IntegralGradeMapper extends BaseMapper<IntegralGrade> { }
6297d99e91418eafaa5b17d7fcdeb263a0306e6f
0bc03f68066006522ce5854b2afc182e4ccf3579
/trunk/services/src/main/java/by/kanchanin/publications/services/OrderResultService.java
0bd6b8319b7466c1112ca06d351d571e37b48ca0
[]
no_license
NataliKan/my-publications
12f292ae54ddd94674b8ee00157916f3b0071981
7896d6efe6ba7261a7c5522f1eb550f6ec873526
refs/heads/master
2021-01-10T15:52:47.423852
2015-05-27T13:25:42
2015-05-27T13:25:42
36,940,729
0
0
null
null
null
null
UTF-8
Java
false
false
555
java
package by.kanchanin.publications.services; import java.util.List; import org.springframework.transaction.annotation.Transactional; import by.kanchanin.publications.datamodel.OrderResult; import by.kanchanin.publications.datamodel.enums.OrderStatus; public interface OrderResultService { @Transactional OrderResult get(Long id); @Transactional void updateOrderResult(OrderResult orderResult); @Transactional void removeOrderResult(Long id); List<OrderStatus> getStatus(Long orderId); }
1807a70a5952e4f9391c7088828254d807c37ac9
4aa02bbbeb769022c033470c905c817715c2c4ce
/weibo/src/main/java/net/zsy/weibo/ui/base/BaseView.java
2bfedbd5b36e76cd1af2fa9d7cd7671aa7a5ac21
[]
no_license
zhshy7713950/Weibo
6ba2f18901623b986618091d9065421592802b3d
b6061e9e1e9c0cfaa98aaa33b8f8509ec0ab16b7
refs/heads/master
2020-03-08T08:26:30.002822
2018-04-13T09:42:08
2018-04-13T09:42:08
128,021,964
0
0
null
null
null
null
UTF-8
Java
false
false
193
java
package net.zsy.weibo.ui.base; /** * Created by Android on 2018/4/9. */ public interface BaseView<T> { void setPresenter(T presenter); void setLoadingIndicator(boolean active); }
b3f90a6186c99e3820043b53a94336be981000ab
4ba132c18d7856f0842efba125dc4067731e65c2
/trade_hosting_apps/trade_hosting_asset/server/src/main/java/xueqiao/trade/hosting/asset/event/handler/AssetSyncEventHandler.java
1da089aa15fecf783fca6a7fb0d9ed01aae5060e
[]
no_license
feinoah/xueqiao-trade
a65496d7c529084964062dec00fc48903a4356a4
cf4283ab1ae8c7467ec51102dc08194e3e9ffc38
refs/heads/main
2023-04-19T11:42:31.813771
2021-04-25T12:03:56
2021-04-25T12:03:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,147
java
package xueqiao.trade.hosting.asset.event.handler; import org.soldier.base.beanfactory.Globals; import org.soldier.base.logger.AppLog; import org.soldier.framework.message_bus.api.IMessageConsumer; import org.soldier.framework.message_bus.api.consume; import org.soldier.platform.svr_platform.comm.ErrorInfo; import xueqiao.trade.hosting.*; import xueqiao.trade.hosting.asset.calculator.AssetCalculatorFactory; import xueqiao.trade.hosting.asset.calculator.account.sub.AssetCalculateConfigCalculator; import xueqiao.trade.hosting.asset.thriftapi.*; import xueqiao.trade.hosting.events.*; import xueqiao.trade.hosting.storage.apis.IHostingDealingApi; import java.util.*; public class AssetSyncEventHandler implements IMessageConsumer { @Override public StartUpMode onStartUp() { return StartUpMode.RESERVE_QUEUE; } @Override public void onInit() throws Exception { new Init().initFromDealing(); } /* 成交事件触发的持仓计算和成交明细存DB, 计算锁仓信息 */ @consume(ExecTradeListChangedEvent.class) ConsumeResult onHandleExecTradeListChangedEvent(ExecTradeListChangedEvent event) throws Exception { new TradeListHandler().saveHostingExecTrade(event.getNewTradeList(), TradeDetailSource.XQ_TRADE, event.getExecOrder().getSource()); return ConsumeResult.CONSUME_OK; } @consume(XQOrderGuardEvent.class) ConsumeResult onHandlerXQOrderGuardEventType(XQOrderGuardEvent guardEvent) throws ErrorInfo { if (!XQOrderGuardEventType.XQ_ORDER_TRADELIST_CHANGED_GUARD.equals(guardEvent.getType())) { return ConsumeResult.CONSUME_OK; } long execOrderId = Long.valueOf(guardEvent.getOrderId()); IHostingDealingApi dealingApi = Globals.getInstance().queryInterfaceForSure(IHostingDealingApi.class); List<HostingExecTrade> trades = dealingApi.getOrderTrades(execOrderId); HostingExecOrder execOrder = dealingApi.getOrder(execOrderId); new TradeListHandler().saveHostingExecTrade(trades, TradeDetailSource.XQ_TRADE, execOrder.getSource()); return ConsumeResult.CONSUME_OK; } }
b3d723e90cce738ade42fdfe7e807aefa242ec25
c2ae49e76f885f9745ebf9530b275d80a7ca1a1f
/java/jpsgcs/alun/animate/Paintable.java
2bf6793be3a3f7f16d5a22ee8c0de6b2b0a4259d
[]
no_license
cran/rviewgraph
f9100f245e27a267985c99c6a581e4f2803cb228
67fa4edc7f2f546681dfc5484191ce1601b23d0e
refs/heads/master
2023-06-01T08:24:19.029111
2023-05-10T16:50:02
2023-05-10T16:50:02
145,905,702
0
0
null
null
null
null
UTF-8
Java
false
false
120
java
package jpsgcs.alun.animate; import java.awt.Graphics; public interface Paintable { public void paint(Graphics g); }
f7595c6a3ce7a63d780e4039e0849c0c8fadac59
e23078dcd665400e3037b5aa2b3ea092d71a5874
/app/src/main/java/com/music/clocklive/wallpaper/custom/CustomEditText.java
a429c49f952914cb9fc72cd091dff56859202a55
[]
no_license
Dhruva22/MyClockWallPaper
a8a221f9bd6b3a2e22d3bd2e0fe6cc4e2e41c17e
95d647c96a1d812ebcb8483c69ed6c904c2b6930
refs/heads/master
2021-01-22T07:52:11.048758
2017-02-13T19:19:35
2017-02-13T19:19:35
81,861,456
0
0
null
null
null
null
UTF-8
Java
false
false
4,883
java
package com.music.clocklive.wallpaper.custom; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.support.v7.widget.AppCompatEditText; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ScaleXSpan; import android.util.AttributeSet; import com.music.clocklive.wallpaper.R; public class CustomEditText extends AppCompatEditText { public static final String FONT_PATH = "fonts/"; private Context context; private int textFont; private int lineHeight = 1; private String textFontType; private int lineSpacing = 1; private int letterSpacing = 1; /** * Constructor with one param * * @param context */ public CustomEditText(Context context) { super(context); this.context = context; } /** * Constructor with two params * * @param context * @param attrs */ public CustomEditText(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; initCustomEditText(context, attrs); } /** * Constructor with three params * * @param context * @param attrs * @param defStyleAttr */ public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; initCustomEditText(context, attrs); } /** * @param context * @param attrs This method initializes all the attributes and respective methods are called based on the attributes */ private void initCustomEditText(Context context, AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText); textFont = ta.getInt(R.styleable.CustomEditText_custom_font, 0); lineHeight = ta.getDimensionPixelSize(R.styleable.CustomEditText_edt_txt_line_height, lineHeight); lineSpacing = ta.getDimensionPixelSize(R.styleable.CustomEditText_edt_txt_line_spacing, lineSpacing); letterSpacing = ta.getDimensionPixelSize(R.styleable.CustomEditText_edt_txt_letter_spacing, letterSpacing); /** * A custom view uses isInEditMode() to determine whether or not it is being rendered inside the editor * and if so then loads test data instead of real data. */ if (!isInEditMode()) { switch (textFont) { case 1: textFontType = "avenir_heavy.otf"; break; case 2: textFontType = "avenir_light.otf"; break; case 3: textFontType="avenir_book.otf"; break; case 4: textFontType="avenir_medium.otf"; break; default: textFontType = "avenir_light.otf"; break; } setTextFont(textFontType); ta.recycle(); } } /** * Sets the type of text font that is to be applied to the TextView * * @param textFontType */ public void setTextFont(String textFontType) { setTypeface(Typeface.createFromAsset(context.getResources() .getAssets(), FONT_PATH + textFontType)); } private void setTheDrawable(GradientDrawable gradientDrawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) setBackground(gradientDrawable); else setBackgroundDrawable(gradientDrawable); } /** * Set letter spacing for the text * * @param text * @param letterSpace */ public void setTextLetterSpacing(String text, float letterSpace) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setLetterSpacing(letterSpace); } else { if (context == null || text == null) return; StringBuilder builder = new StringBuilder(); for (int i = 0; i < text.length(); i++) { String c = "" + text.charAt(i); builder.append(c.toLowerCase()); if (i + 1 < text.length()) { builder.append("\u00A0"); } } SpannableString finalText = new SpannableString(builder.toString()); if (builder.toString().length() > 1) { for (int i = 1; i < builder.toString().length(); i += 2) { finalText.setSpan(new ScaleXSpan((letterSpace + 1)), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } super.setText(finalText, BufferType.SPANNABLE); } } }
9044d90db3032f216bb7d0241d1009a1e97d1f41
0fc5310ccb398444f0c8e6eaa0487894e7a5af00
/AHome/11.01/PaintJava3/src/GUI/StatusBar.java
59b1700da4b9305cb9787b38d61836931e2c446e
[]
no_license
Veargan/Study
8dcff2d407665dde7b258f5f208c3fa4abaaf619
a76771954a0e6df7d0f38dfc9b8a5997c53c9fbc
refs/heads/master
2020-12-24T06:52:35.698062
2017-03-24T10:53:28
2017-03-24T10:53:28
73,393,554
1
0
null
null
null
null
UTF-8
Java
false
false
1,182
java
package GUI; import javax.swing.JLabel; import javax.swing.JPanel; import API.xData; public class StatusBar extends JPanel { public static JLabel xLabel; public static JLabel yLabel; private JLabel colorLabel; private JLabel widthLabel; private JLabel typeLabel;public StatusBar() { setLayout(null); xLabel = new JLabel("X: "); yLabel = new JLabel("Y: "); colorLabel = new JLabel("Color: "); widthLabel = new JLabel("Width: "); typeLabel = new JLabel("Type: "); xLabel.setBounds(0, 0, 60, 20); yLabel.setBounds(60, 0, 60, 20); colorLabel.setBounds(120, 0, 200, 20); widthLabel.setBounds(320, 0, 120, 20); typeLabel.setBounds(440, 0, 120, 20); add(xLabel); add(yLabel); add(colorLabel); add(widthLabel); add(typeLabel); } public void setCoords(int x, int y) { xLabel.setText("X: "+x); yLabel.setText("Y: "+y); } public void setData(xData data) { colorLabel.setText("Color: "+data.color); widthLabel.setText("Width: "+data.width); typeLabel.setText("Type: "+data.type); } }
30d7885acb4ad95c10a6cb64d194bd4bca3464d8
703744e005bca91a1922401e5151c4f41a6ad8ca
/Server/Legacy/common/common-protocol/src/main/java/com/engine/common/protocol/def/TypeDef.java
cb600f273bbe1f421337e9572c024351ca53c30a
[]
no_license
luoph/TanksBattle
eb9ae0ec186641ef5c8ae03eb18d9026dc95a017
9d9094fb2182e07bf9ddc542caf9ed872aeb332a
refs/heads/master
2020-08-26T16:33:14.439408
2017-09-25T14:55:27
2017-09-25T14:55:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,724
java
package com.engine.common.protocol.def; import java.beans.PropertyDescriptor; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.mina.core.buffer.IoBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.engine.common.protocol.annotation.Ignore; import com.engine.common.protocol.exception.ObjectProxyException; import com.engine.common.utils.reflect.ReflectionUtility; /** * 传输类型定义 * */ public class TypeDef implements Comparable<TypeDef> { private static Logger log = LoggerFactory.getLogger(TypeDef.class); public static TypeDef NULL = TypeDef.valueOf(-1, Object.class); // 排序比较器 private static final Comparator<PropertyDescriptor> CAMPARATOR = new Comparator<PropertyDescriptor>() { public int compare(PropertyDescriptor o1, PropertyDescriptor o2) { return new CompareToBuilder().append(o1.getName(), o2.getName()).toComparison(); } }; private int code; private Class<?> type; private List<FieldDef> fields; private Constructor<?> constructor; public static TypeDef valueOf(int code, Class<?> type) { // 构造属性列表 PropertyDescriptor[] descs = ReflectionUtility.getPropertyDescriptors(type); List<PropertyDescriptor> list = Arrays.asList(descs); Collections.sort(list, CAMPARATOR); List<FieldDef> fields = new ArrayList<FieldDef>(descs.length); int index = 0; for (PropertyDescriptor d : list) { String name = d.getName(); if (name.equals("class")) { continue; } Method getter = d.getReadMethod(); if (getter == null) { continue; } if (getter.isAnnotationPresent(Ignore.class)) { continue; } Method setter = d.getWriteMethod(); if (setter == null) { System.out.print(""); } Class<?> fieldType = d.getPropertyType(); FieldDef f = FieldDef.valueOf(index, name, fieldType, getter, setter); fields.add(f); index++; } return TypeDef.valueOf(code, type, fields); } public static TypeDef valueOf(int code, Class<?> type, List<FieldDef> fields) { TypeDef e = new TypeDef(); e.code = code; e.type = type; e.fields = fields; if (type == null) { return e; } // 获取默认构造器 for (Constructor<?> c : type.getDeclaredConstructors()) { if (c.getParameterTypes().length == 0) { c.setAccessible(true); e.constructor = c; break; } } if (e.constructor == null) { // throw new IllegalArgumentException("类型[" + type + "]默认构造器不存在..."); log.info("类型[{}]默认构造器不存在...", type); } return e; } public static TypeDef valueOf(ByteBuffer buf) throws IOException { // 类型, 类标识, (类名长度, 类名字节), 属性数量, (名字长度, 名字字节).... short code = buf.getShort(); short nLen = buf.getShort(); byte[] nBytes = new byte[nLen]; buf.get(nBytes); String clzName = new String(nBytes); Class<?> clz; try { clz = Class.forName(clzName); } catch (ClassNotFoundException e) { // 类型不存在 log.warn("类型[{}]不存在, 当作HashMap处理"); clz = null; } int len = buf.getShort(); List<FieldDef> fields = new ArrayList<FieldDef>(len); for (int i = 0; i < len; i++) { // 属性名 int nField = buf.getShort(); byte[] aField = new byte[nField]; buf.get(aField); String name = new String(aField); Field field; Class<?> fieldType; if (clz != null) { field = ReflectionUtility.findField(clz, name); if (field == null) { fieldType = null; log.warn("类型[{}]属性[{}]无法访问", clz, name); } else { fieldType = field.getType(); } } else { field = null; fieldType = null; } fields.add(FieldDef.valueOf(i, name, fieldType, field)); } return TypeDef.valueOf(code, clz, fields); } public void describe(IoBuffer buf) { // 类型, 类标识, (类名长度, 类名字节), 属性数量, (名字长度, 名字字节), (类型长度, 类型字节).... // 类型, 类标识, (类名长度, 类名字节), 属性数量, (名字长度, 名字字节).... int code = this.getCode(); Class<?> clzType = this.getType(); byte[] defBytes = clzType.getName().getBytes(); buf.put((byte) 0x01); buf.putShort((short) code); buf.putShort((short) defBytes.length); buf.put(defBytes); List<FieldDef> fields = this.getFields(); Collections.sort(fields); buf.putShort((short) fields.size()); for (FieldDef d : fields) { byte[] fieldBytes = d.getName().getBytes(); buf.putShort((short) fieldBytes.length); buf.put(fieldBytes); // byte[] ftBytes = d.getType().getName().getBytes(); // buf.putShort((short) ftBytes.length); // buf.put(ftBytes); } } public Object newInstance() throws Exception { if (type == null) { return new HashMap<String, Object>(); } if (constructor == null) { throw new ObjectProxyException(new IllegalAccessException("类型[" + type + "]默认构造器不存在...")); } return constructor.newInstance(); } public int getCode() { return code; } public Class<?> getType() { return type; } public List<FieldDef> getFields() { return fields; } public Object getValue(Object instance, int index) throws Exception { if (index < fields.size()) { FieldDef fieldDef = fields.get(index); if (fieldDef != null) { Object value = fieldDef.getValue(instance); if (log.isDebugEnabled()) { log.debug("对象[{}]属性[{}:{}]取值[{}]", new Object[] { instance, index, fieldDef.getName(), value }); } return value; } } return null; } public void setValue(Object instance, int index, Object value) throws Exception { if (index < fields.size()) { FieldDef fieldDef = fields.get(index); if (fieldDef != null) { if (fieldDef.isReadonly()) { log.debug("对象[{}]属性[{}:{}]*只读*无法赋值[{}]", new Object[] { instance, index, fieldDef.getName(), value }); return; } fieldDef.setValue(instance, value); if (log.isDebugEnabled()) { log.debug("对象[{}]属性[{}:{}]赋值[{}]", new Object[] { instance, index, fieldDef.getName(), value }); } } } } @Override public int compareTo(TypeDef o) { return new CompareToBuilder().append(this.code, o.code).append(this.type.getName(), o.type.getName()) .toComparison(); } @Override public String toString() { return "TypeDef [" + code + ", " + type.getName() + "]"; } }
0f6570cebce81fc2f2a78cf6dda14befc4dda625
34ee77f14d9f5ca384d01042d1ae9af22295c1df
/spring-boot-demo-mybatis-generator/src/main/java/com/demo/mybatis/generator/SpringBootDemoMybatisGeneratorApplication.java
731856d1fb9a3a5d39e23af1cfec01b900d798aa
[]
no_license
Hupeng7/spring-boot-demo1
d8cb46cb8949d0bebfbc9ae829581475022ab31b
0d6c052845bdf05f5780a717d8dd88bf690ae3d9
refs/heads/master
2023-06-13T01:12:43.168992
2023-05-26T07:29:46
2023-05-26T07:29:46
214,409,453
1
0
null
2022-11-16T11:35:04
2019-10-11T10:34:57
Java
UTF-8
Java
false
false
379
java
package com.demo.mybatis.generator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDemoMybatisGeneratorApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDemoMybatisGeneratorApplication.class, args); } }
93416a0bd59b2247ed19c20004605fad722b0933
f59a4c92aa5f47128dd1ad5b5b30289818eca852
/02-jdbc-member-dao/src/test2/MemberVO.java
358a1ccd113462bf6fa0a276e66f349b9705696b
[]
no_license
jenkwon92/Kosta_jdbc-workspace
8fb246f7fd9d1c5dbfb548d72009a81316506a22
326f20941f99c776fec1f6256c4afbddf5157d7c
refs/heads/main
2023-07-28T03:15:47.631336
2021-09-14T03:25:02
2021-09-14T03:25:02
401,638,459
0
0
null
null
null
null
UTF-8
Java
false
false
1,033
java
package test2; /* * VO : Value Object * DTO : Data Transfer Object */ public class MemberVO { //컬럼과 mapping이 됨 private String id; private String password; private String name; private String address; public MemberVO() { super(); } public MemberVO(String id, String password, String name, String address) { super(); this.id = id; this.password = password; this.name = name; this.address = address; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "MemberVO [id=" + id + ", password=" + password + ", name=" + name + ", address=" + address + "]"; } }
76050f8c7379a976223eb2b5608feb51a89cca62
a1eb1bdc48ed8885891cc0eaca319672566489a9
/app/src/main/java/com/example/qzhu1/myapplication/PieChartFragment.java
512beb35dc2acf4971050282a1b3f0fbaf2a1d33
[]
no_license
zhuqinzhou/knots
68014719cb560c8e9acabc7d67b820ceec516055
a3e7d0801feed15798806c5cd7bab5c56f04ca7f
refs/heads/master
2021-01-13T11:38:04.135466
2016-07-22T02:51:11
2016-07-22T02:51:11
58,286,395
0
0
null
null
null
null
UTF-8
Java
false
false
5,753
java
package com.example.qzhu1.myapplication; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.Query; import com.firebase.client.ValueEventListener; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class PieChartFragment extends SimpleFragment { final Firebase ref = new Firebase("https://knotedb.firebaseio.com"); float[] values = new float[2]; public static Fragment newInstance() { return new PieChartFragment(); } private PieChart mChart; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_simple_pie, container, false); mChart = (PieChart) v.findViewById(R.id.pieChart1); mChart.setDescription(""); Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Bold.ttf"); mChart.setCenterTextTypeface(tf); mChart.setCenterText(generateCenterText()); mChart.setCenterTextSize(10f); mChart.setCenterTextTypeface(tf); // radius of the center hole in percent of maximum radius mChart.setHoleRadius(55f); mChart.setTransparentCircleRadius(60f); Legend l = mChart.getLegend(); l.setPosition(LegendPosition.RIGHT_OF_CHART); // Total owe Query qOwe = ref.child("bill").orderByChild("owe").equalTo(KnotsApplication.email); qOwe.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { values[0] = 0; HashMap<?, ?> hashMap = (HashMap) snapshot.getValue(); if(hashMap!=null) { Set set = hashMap.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); HashMap<?, ?> e = (HashMap) me.getValue(); String n = (String) e.get("amount"); values[0] += Float.parseFloat(n); } mChart.setData(getPieData()); } } @Override public void onCancelled(FirebaseError firebaseError) { } }); // Total pay Query qPay = ref.child("bill").orderByChild("pay").equalTo(KnotsApplication.email); qPay.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { values[1] = 0; HashMap<?, ?> hashMap = (HashMap) snapshot.getValue(); if(hashMap!=null) { Set set = hashMap.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); HashMap<?, ?> e = (HashMap) me.getValue(); String n = (String) e.get("amount"); values[1] += Float.parseFloat(n); } mChart.setData(getPieData()); } } @Override public void onCancelled(FirebaseError firebaseError) { } }); // mChart.setData(getPieData()); return v; } private SpannableString generateCenterText() { SpannableString s; try { s = new SpannableString("Balance\n" + KnotsApplication.email.substring(0, KnotsApplication.email.indexOf("@"))); }catch (Exception e){ System.out.println("==================== email null ===================="); e.printStackTrace(); s = new SpannableString("Balance\nUser"); }finally { //continue } s.setSpan(new RelativeSizeSpan(2f), 0, 8, 0); s.setSpan(new ForegroundColorSpan(Color.GRAY), 8, s.length(), 0); return s; } public static final int[] MY_COLORS = { Color.rgb(217, 80, 138), Color.rgb(106, 167, 134), Color.rgb(254, 247, 120), Color.rgb(106, 167, 134), Color.rgb(53, 194, 209) }; private PieData getPieData() { ArrayList<Entry> entries1 = new ArrayList<Entry>(); ArrayList<String> xVals = new ArrayList<String>(); xVals.add("Owe"); xVals.add("Pay"); entries1.add(new Entry(values[0], 0)); entries1.add(new Entry(values[1], 1)); PieDataSet ds1 = new PieDataSet(entries1, "Total Balance"); ds1.setColors(MY_COLORS); ds1.setSliceSpace(2f); ds1.setValueTextColor(Color.WHITE); ds1.setValueTextSize(12f); PieData d = new PieData(xVals, ds1); d.setValueTypeface(Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf")); return d; } }
bc2d1b87ededdd438bc30bafeb77714ce163622e
2a28fbc6f1b88b9ce0dc4754e3cbf217f331ccce
/content/programming-realm/code_problems/src/main/java/com/satyam/problem/leetcode/medium/LC347TopKFrequentElements.java
886883f7abcf5ecf86e3146c97154cbaa496fd73
[ "MIT" ]
permissive
imsatyam/techlearn
e968bcd331e42c36fa9e97db87947c61174fdfb4
83b88e6c143289aa648bd16ca8778674bbda760e
refs/heads/master
2022-07-05T06:58:49.416559
2020-05-14T12:02:31
2020-05-14T12:02:31
113,745,259
19
7
MIT
2020-05-09T10:51:59
2017-12-10T11:44:31
HTML
UTF-8
Java
false
false
1,548
java
package com.satyam.problem.leetcode.medium; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; /** LC #347 Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. Idea: Use priority queue Submission Detail Link: https://leetcode.com/submissions/detail/308192324/ Runtime: 10 ms Memory: 42.3 MB */ public class LC347TopKFrequentElements { public List<Integer> topKFrequent(int[] nums, int k) { Map<Integer, Integer> numFreqMap = new HashMap<>(); for (int n : nums) { int freq = numFreqMap.getOrDefault(n, 0); numFreqMap.put(n, freq + 1); } PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((a, b) -> a.getValue() - b.getValue()); for (Map.Entry<Integer, Integer> entry : numFreqMap.entrySet()) { pq.add(entry); if (pq.size() > k) { pq.poll(); } } List<Integer> result = new ArrayList<>(); while (!pq.isEmpty()) { result.add(pq.poll().getKey()); } Collections.reverse(result); return result; } }
5ec396dabd11729b3e00559693cadf64bd1ed470
75013790a9740fb185a37b70afdaf2e3e2985552
/Algorithms/leetcode_java/problem344/Solution1.java
30178eef1a02352aa5b03e209811bf0a0c50af42
[]
no_license
AnkitaTapadia/leetcode
27a6145291c95716f6808b4c70ff303479dd3279
4b5cbf8aae4b236574f579bd965bb0999bd26eff
refs/heads/master
2022-01-23T23:07:28.094579
2019-06-01T08:16:37
2019-06-01T08:16:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
386
java
package leetcode_java.problem344; class Solution1 { public String reverseString(String s) { char[] ns = s.toCharArray(); int i = 0; int j = ns.length - 1; while(i < j){ char t = ns[i]; ns[i] = ns[j]; ns[j] = t; i ++; j --; } return new String(ns); } }
eb3616e0407d3fa69c011ffb9f02ed035acf8c9a
c44c1cec10594c19dc24755ca97026b73b057f7d
/src/main/java/com/zrkj/service/IPrizeService.java
0ea82dafe0e78f4027f6a7787faed7d2c8fe2ea5
[]
no_license
dream0708/luckybigwheel
d7aec313273fb17977dc537cf5173847a5c94aff
1b663d7219021f801cb9e4193c41d0d864c1f061
refs/heads/master
2021-01-15T21:24:51.685232
2017-06-29T14:16:02
2017-06-29T14:16:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
704
java
package com.zrkj.service; import com.zrkj.pojo.Prize; import com.zrkj.pojo.Record; import com.zrkj.pojo.User; import javax.servlet.http.HttpSession; import java.util.List; import java.util.Map; /** * Created by gaowenfeng on 2017/6/16. */ public interface IPrizeService { Prize obtainPrizeById(Integer id); List<Prize> obtainPrizeList(); Map<String,Object> obtainPrizeListInUse(Integer storeId); Map<String,Object> obtainUseNum(); Map<String,Object> doCreatePrize(Prize prize); Map<String,Object> doUpdatePrize(Prize prize); Map<String,Object> doCreateRecord(HttpSession session,String prizeName); Map<String,Object> doCancelAfterVerification(String code); }
d4b7e4c735265f03e9925b416b4d8d6cca7021fa
c2fb6846d5b932928854cfd194d95c79c723f04c
/java_backup/my java/amlan/dd.java
c0b5ae81c109a95f84686623f7dd0d32bdd5b738
[ "MIT" ]
permissive
Jimut123/code-backup
ef90ccec9fb6483bb6dae0aa6a1f1cc2b8802d59
8d4c16b9e960d352a7775786ea60290b29b30143
refs/heads/master
2022-12-07T04:10:59.604922
2021-04-28T10:22:19
2021-04-28T10:22:19
156,666,404
9
5
MIT
2022-12-02T20:27:22
2018-11-08T07:22:48
Jupyter Notebook
UTF-8
Java
false
false
66
java
class dd { int k; void input() { k=10; System.out.println(k); } }
f7740886fbf7c8ca3ee6dd7694979acfa0e7d200
8db5fa58426f03e398674d0583c2db4057ea9d1b
/dts-ops/src/main/java/com/bkjk/platform/dts/ops/controller/GlobalDtsController.java
56f438bc550d8b6448ee3b35d0fa6e958e9212b5
[ "Apache-2.0" ]
permissive
javalibrary/dts
7ebb093555c4e7c6373a040909117db9d237d677
fdba780fad40885e29c620fb224d797d28ada7a3
refs/heads/master
2020-07-02T00:43:42.966299
2019-04-26T05:12:21
2019-04-26T05:12:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,136
java
package com.bkjk.platform.dts.ops.controller; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; 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 com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.bkjk.platform.dts.ops.dao.GlobalRecordMapper; import com.bkjk.platform.dts.ops.domain.GlobalRecord; import com.bkjk.platform.dts.ops.vo.GlobalRecordVo; import com.bkjk.platform.dts.ops.vo.PageVO; @RestController @RequestMapping(value = "/globalRecord") public class GlobalDtsController { @Autowired private GlobalRecordMapper globalRecordMapper; private Date formatDate(String param) { if (StringUtils.isEmpty(param)) { return null; } try { return new SimpleDateFormat("yyyy-mm-dd HH:mm").parse(param); } catch (ParseException e) { return null; } } @RequestMapping(method = RequestMethod.GET) public PageVO<GlobalRecordVo> getGlobalRecord(@RequestParam Map<String, Object> params) { int offset = Integer.parseInt(params.get("offset").toString()); int pageSize = Integer.parseInt(params.get("limit").toString()); int state = Integer.parseInt(params.get("state").toString()); Date startTime = formatDate(params.get("startTime").toString()); Date endTime = formatDate(params.get("endTime").toString()); int current = offset / pageSize + 1; Page pageRequest = new Page(current, pageSize); QueryWrapper<GlobalRecord> query = Wrappers.<GlobalRecord>query(); if (state > 0) { query.eq("state", state); } query.orderByDesc("gmt_created", "gmt_modified"); if (!Objects.isNull(startTime)) { if (!Objects.isNull(endTime)) { query.between("gmt_created", startTime, endTime); } else { query.ge("gmt_created", startTime); } } else if (!Objects.isNull(endTime)) { query.le("gmt_created", endTime); } IPage<GlobalRecord> records = globalRecordMapper.selectPage(pageRequest, query); List<GlobalRecordVo> vos = records.getRecords().stream().map(domain -> { GlobalRecordVo vo = new GlobalRecordVo(); BeanUtils.copyProperties(domain, vo); return vo; }).collect(Collectors.toList()); PageVO vo = new PageVO(vos, records.getTotal(), current, pageSize); return vo; } }
bf4f0d52ec15ccba485ba8f82b5973e719159473
c7d59151c3dbb11f47f715df2966af5ff705836b
/InterStudents/InterStudents/src/com/internousdev/InterStudents/action/StudyCreateAction.java
e4b78cb30c06313135706dc37c3a677fa4f38884
[]
no_license
bluedaichi/originalProduction
d9b16c58db156c6ca739624462ec30862445267f
05f123caddfef945a56066447640d7ef7ace3742
refs/heads/master
2020-08-03T12:16:58.253444
2019-09-30T07:55:58
2019-09-30T07:55:58
211,749,777
0
0
null
null
null
null
UTF-8
Java
false
false
209
java
package com.internousdev.InterStudents.action; import com.opensymphony.xwork2.ActionSupport; public class StudyCreateAction extends ActionSupport { public String execute() { return SUCCESS; } }
9d3662d3b846d18744f29411db08abf2f2905208
df6d1ee08ac28a0d18a0687ec58029bc393dc198
/src/game/Passage.java
6b6308b116bb35dd9774f5cfb41affe96371bbb1
[]
no_license
MaaaxiKing/Abandoned-Asylum
f9dd6bb393f4c5dd014bee49332e4926af4e8627
19831a1d18dfb90076b2d317e73a64c522b30fb1
refs/heads/main
2023-05-24T11:46:15.591303
2021-06-12T18:39:19
2021-06-12T18:39:19
375,825,249
0
1
null
null
null
null
UTF-8
Java
false
false
63
java
package game; public class Passage { boolean open = true; }