answer stringlengths 17 10.2M |
|---|
package net.spy.memcached;
import java.nio.ByteBuffer;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import net.spy.memcached.compat.SyncThread;
import net.spy.memcached.internal.BulkFuture;
import net.spy.memcached.internal.GetFuture;
import net.spy.memcached.internal.OperationFuture;
import net.spy.memcached.ops.OperationErrorType;
import net.spy.memcached.ops.OperationException;
import net.spy.memcached.transcoders.SerializingTranscoder;
import net.spy.memcached.transcoders.Transcoder;
public abstract class ProtocolBaseCase extends ClientBaseCase {
public void testAssertions() {
boolean caught=false;
try {
assert false;
} catch(AssertionError e) {
caught=true;
}
assertTrue("Assertions are not enabled!", caught);
}
public void testGetStats() throws Exception {
Map<SocketAddress, Map<String, String>> stats = client.getStats();
System.out.println("Stats: " + stats);
assertEquals(1, stats.size());
Map<String, String> oneStat=stats.values().iterator().next();
assertTrue(oneStat.containsKey("curr_items"));
}
public void testGetStatsSlabs() throws Exception {
if (isMembase() || isMoxi()) {
return;
}
// There needs to at least have been one value set or there may be
// no slabs to check.
client.set("slabinitializer", 0, "hi");
Map<SocketAddress, Map<String, String>> stats = client.getStats("slabs");
System.out.println("Stats: " + stats);
assertEquals(1, stats.size());
Map<String, String> oneStat=stats.values().iterator().next();
assertTrue(oneStat.containsKey("1:chunk_size"));
}
public void testGetStatsSizes() throws Exception {
if (isMembase() || isMoxi()) {
return;
}
// There needs to at least have been one value set or there may
// be no sizes to check. Note the protocol says
// flushed/expired items may come back in stats sizes and we
// use flush when testing, so we check that there's at least
// one.
client.set("sizeinitializer", 0, "hi");
Map<SocketAddress, Map<String, String>> stats = client.getStats("sizes");
System.out.println("Stats sizes: " + stats);
assertEquals(1, stats.size());
Map<String, String> oneStat=stats.values().iterator().next();
String noItemsSmall = oneStat.get("96");
assertTrue(Integer.parseInt(noItemsSmall) >= 1);
}
public void testGetStatsCacheDump() throws Exception {
if (isMembase() || isMoxi()) {
return;
}
// There needs to at least have been one value set or there
// won't be anything to dump
client.set("dumpinitializer", 0, "hi");
Map<SocketAddress, Map<String, String>> stats =
client.getStats("cachedump 1 10000");
System.out.println("Stats cachedump: " + stats);
assertEquals(1, stats.size());
Map<String, String> oneStat=stats.values().iterator().next();
String val = oneStat.get("dumpinitializer");
assertTrue(val + "doesn't match", val.matches("\\[2 b; \\d+ s\\]"));
}
public void testDelayedFlush() throws Exception {
assertNull(client.get("test1"));
assert client.set("test1", 5, "test1value").getStatus().isSuccess();
assert client.set("test2", 5, "test2value").getStatus().isSuccess();
assertEquals("test1value", client.get("test1"));
assertEquals("test2value", client.get("test2"));
assert client.flush(2).getStatus().isSuccess();
Thread.sleep(2100);
assertNull(client.get("test1"));
assertNull(client.get("test2"));
assert !client.asyncGet("test1").getStatus().isSuccess();
assert !client.asyncGet("test2").getStatus().isSuccess();
}
public void testNoop() {
// This runs through the startup/flush cycle
}
public void testDoubleShutdown() {
client.shutdown();
client.shutdown();
}
public void testSimpleGet() throws Exception {
assertNull(client.get("test1"));
client.set("test1", 5, "test1value");
assertEquals("test1value", client.get("test1"));
}
public void testSimpleCASGets() throws Exception {
assertNull(client.gets("test1"));
assert client.set("test1", 5, "test1value").getStatus().isSuccess();
assertEquals("test1value", client.gets("test1").getValue());
}
public void testCAS() throws Exception {
final String key="castestkey";
// First, make sure it doesn't work for a non-existing value.
assertSame("Expected error CASing with no existing value.",
CASResponse.NOT_FOUND,
client.cas(key, 0x7fffffffffL, "bad value"));
// OK, stick a value in here.
assertTrue(client.add(key, 5, "original value").get());
CASValue<?> getsVal = client.gets(key);
assertEquals("original value", getsVal.getValue());
// Now try it with an existing value, but wrong CAS id
assertSame("Expected error CASing with invalid id",
CASResponse.EXISTS,
client.cas(key, getsVal.getCas() + 1, "broken value"));
// Validate the original value is still in tact.
assertEquals("original value", getsVal.getValue());
// OK, now do a valid update
assertSame("Expected successful CAS with correct id ("
+ getsVal.getCas() + ")",
CASResponse.OK,
client.cas(key, getsVal.getCas(), "new value"));
assertEquals("new value", client.get(key));
// Test a CAS replay
assertSame("Expected unsuccessful CAS with replayed id",
CASResponse.EXISTS,
client.cas(key, getsVal.getCas(), "crap value"));
assertEquals("new value", client.get(key));
}
public void testReallyLongCASId() throws Exception {
String key = "this-is-my-key";
assertSame("Expected error CASing with no existing value.",
CASResponse.NOT_FOUND,
client.cas(key, 9223372036854775807l, "bad value"));
}
public void testExtendedUTF8Key() throws Exception {
String key="\u2013\u00ba\u2013\u220f\u2014\u00c4";
assertNull(client.get(key));
assert client.set(key, 5, "test1value").getStatus().isSuccess();
assertEquals("test1value", client.get(key));
}
public void testInvalidKey1() throws Exception {
try {
client.get("key with spaces");
fail("Expected IllegalArgumentException getting key with spaces");
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKey2() throws Exception {
try {
StringBuilder longKey=new StringBuilder();
for(int i=0; i<251; i++) {
longKey.append("a");
}
client.get(longKey.toString());
fail("Expected IllegalArgumentException getting too long of a key");
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKey3() throws Exception {
try {
Object val=client.get("Key\n");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKey4() throws Exception {
try {
Object val=client.get("Key\r");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKey5() throws Exception {
try {
Object val=client.get("Key\0");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKeyBlank() throws Exception {
try {
Object val=client.get("");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKeyBulk() throws Exception {
try {
Object val=client.getBulk("Key key2");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testParallelSetGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
for(int i=0; i<10; i++) {
assert client.set("test" + i, 5, "value" + i).getStatus().isSuccess();
assertEquals("value" + i, client.get("test" + i));
}
for(int i=0; i<10; i++) {
assertEquals("value" + i, client.get("test" + i));
}
return Boolean.TRUE;
}});
assertEquals(1, cnt);
}
public void testParallelSetMultiGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
for(int i=0; i<10; i++) {
assert client.set("test" + i, 5, "value" + i).getStatus().isSuccess();
assertEquals("value" + i, client.get("test" + i));
}
Map<String, Object> m=client.getBulk("test0", "test1", "test2",
"test3", "test4", "test5", "test6", "test7", "test8",
"test9", "test10"); // Yes, I intentionally ran over.
for(int i=0; i<10; i++) {
assertEquals("value" + i, m.get("test" + i));
}
return Boolean.TRUE;
}});
assertEquals(1, cnt);
}
public void testParallelSetAutoMultiGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
assert client.set("testparallel", 5, "parallelvalue").getStatus().isSuccess();
for(int i=0; i<10; i++) {
assertEquals("parallelvalue", client.get("testparallel"));
}
return Boolean.TRUE;
}});
assertEquals(1, cnt);
}
public void testAdd() throws Exception {
assertNull(client.get("test1"));
assert !client.asyncGet("test1").getStatus().isSuccess();
assertTrue(client.set("test1", 5, "test1value").get());
assertEquals("test1value", client.get("test1"));
assert client.asyncGet("test1").getStatus().isSuccess();
assertFalse(client.add("test1", 5, "ignoredvalue").get());
assert !client.add("test1", 5, "ignoredvalue").getStatus().isSuccess();
// Should return the original value
assertEquals("test1value", client.get("test1"));
}
public void testAddWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertNull(client.get("test1", t));
assert !client.asyncGet("test1", t).getStatus().isSuccess();
assertTrue(client.set("test1", 5, "test1value", t).get());
assertEquals("test1value", client.get("test1", t));
assertFalse(client.add("test1", 5, "ignoredvalue", t).get());
assert !client.add("test1", 5, "ignoredvalue", t).getStatus().isSuccess();
// Should return the original value
assertEquals("test1value", client.get("test1", t));
}
public void testAddNotSerializable() throws Exception {
try {
client.add("t1", 5, new Object());
fail("expected illegal argument exception");
} catch(IllegalArgumentException e) {
assertEquals("Non-serializable object", e.getMessage());
}
}
public void testSetNotSerializable() throws Exception {
try {
client.set("t1", 5, new Object());
fail("expected illegal argument exception");
} catch(IllegalArgumentException e) {
assertEquals("Non-serializable object", e.getMessage());
}
}
public void testReplaceNotSerializable() throws Exception {
try {
client.replace("t1", 5, new Object());
fail("expected illegal argument exception");
} catch(IllegalArgumentException e) {
assertEquals("Non-serializable object", e.getMessage());
}
}
public void testUpdate() throws Exception {
assertNull(client.get("test1"));
client.replace("test1", 5, "test1value");
assert !client.replace("test1", 5, "test1value").getStatus().isSuccess();
assertNull(client.get("test1"));
}
public void testUpdateWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertNull(client.get("test1", t));
client.replace("test1", 5, "test1value", t);
assert !client.replace("test1", 5, "test1value", t).getStatus().isSuccess();
assertNull(client.get("test1", t));
}
// Just to make sure the sequence is being handled correctly
public void testMixedSetsAndUpdates() throws Exception {
Collection<Future<Boolean>> futures=new ArrayList<Future<Boolean>>();
Collection<String> keys=new ArrayList<String>();
for(int i=0; i<100; i++) {
String key="k" + i;
futures.add(client.set(key, 10, key));
futures.add(client.add(key, 10, "a" + i));
keys.add(key);
}
Map<String, Object> m=client.getBulk(keys);
assertEquals(100, m.size());
for(Map.Entry<String, Object> me : m.entrySet()) {
assertEquals(me.getKey(), me.getValue());
}
for(Iterator<Future<Boolean>> i=futures.iterator();i.hasNext();) {
assertTrue(i.next().get());
assertFalse(i.next().get());
}
}
public void testGetBulk() throws Exception {
Collection<String> keys=Arrays.asList("test1", "test2", "test3");
assertEquals(0, client.getBulk(keys).size());
client.set("test1", 5, "val1");
client.set("test2", 5, "val2");
Map<String, Object> vals=client.getBulk(keys);
assert client.asyncGetBulk(keys).getStatus().isSuccess();
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
}
public void testGetBulkVararg() throws Exception {
assertEquals(0, client.getBulk("test1", "test2", "test3").size());
client.set("test1", 5, "val1");
client.set("test2", 5, "val2");
Map<String, Object> vals=client.getBulk("test1", "test2", "test3");
assert client.asyncGetBulk("test1", "test2", "test3").getStatus().isSuccess();
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
}
public void testGetBulkVarargWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertEquals(0, client.getBulk(t, "test1", "test2", "test3").size());
client.set("test1", 5, "val1", t);
client.set("test2", 5, "val2", t);
Map<String, String> vals=client.getBulk(t, "test1", "test2", "test3");
assert client.asyncGetBulk(t, "test1", "test2", "test3").getStatus().isSuccess();
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
}
public void testAsyncGetBulkVarargWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertEquals(0, client.getBulk(t, "test1", "test2", "test3").size());
client.set("test1", 5, "val1", t);
client.set("test2", 5, "val2", t);
BulkFuture<Map<String, String>> vals=client.asyncGetBulk(t,
"test1", "test2", "test3");
assert vals.getStatus().isSuccess();
assertEquals(2, vals.get().size());
assertEquals("val1", vals.get().get("test1"));
assertEquals("val2", vals.get().get("test2"));
}
public void testAsyncGetBulkWithTranscoderIterator() throws Exception {
ArrayList<String> keys = new ArrayList<String>();
keys.add("test1");
keys.add("test2");
keys.add("test3");
ArrayList<Transcoder<String>> tcs = new ArrayList<Transcoder<String>>(keys.size());
for (String key : keys) {
tcs.add(new TestWithKeyTranscoder(key));
}
// Any transcoders listed after list of keys should be
// ignored.
for (String key : keys) {
tcs.add(new TestWithKeyTranscoder(key));
}
assertEquals(0, client.asyncGetBulk(keys, tcs.listIterator()).get().size());
client.set(keys.get(0), 5, "val1", tcs.get(0));
client.set(keys.get(1), 5, "val2", tcs.get(1));
Future<Map<String, String>> vals=client.asyncGetBulk(keys, tcs.listIterator());
assertEquals(2, vals.get().size());
assertEquals("val1", vals.get().get(keys.get(0)));
assertEquals("val2", vals.get().get(keys.get(1)));
// Set with one transcoder with the proper key and get
// with another transcoder with the wrong key.
keys.add(0, "test4");
Transcoder<String> encodeTranscoder = new TestWithKeyTranscoder(keys.get(0));
client.set(keys.get(0), 5, "val4", encodeTranscoder).get();
Transcoder<String> decodeTranscoder = new TestWithKeyTranscoder("not " + keys.get(0));
tcs.add(0, decodeTranscoder);
try {
client.asyncGetBulk(keys, tcs.listIterator()).get();
fail("Expected ExecutionException caused by key mismatch");
} catch (java.util.concurrent.ExecutionException e) {
// pass
}
}
public void testAvailableServers() {
client.getVersions();
assertEquals(new ArrayList<String>(
Collections.singleton(getExpectedVersionSource())),
stringify(client.getAvailableServers()));
}
public void testUnavailableServers() {
client.getVersions();
assertEquals(Collections.emptyList(), client.getUnavailableServers());
}
protected abstract String getExpectedVersionSource();
public void testGetVersions() throws Exception {
Map<SocketAddress, String> vs=client.getVersions();
assertEquals(1, vs.size());
Map.Entry<SocketAddress, String> me=vs.entrySet().iterator().next();
assertEquals(getExpectedVersionSource(), me.getKey().toString());
assertNotNull(me.getValue());
}
public void testNonexistentMutate() throws Exception {
assertEquals(-1, client.incr("nonexistent", 1));
assert !client.asyncIncr("nonexistent", 1).getStatus().isSuccess();
assertEquals(-1, client.decr("nonexistent", 1));
assert !client.asyncDecr("nonexistent", 1).getStatus().isSuccess();
}
public void testMutateWithDefault() throws Exception {
assertEquals(3, client.incr("mtest", 1, 3));
assertEquals(4, client.incr("mtest", 1, 3));
assertEquals(3, client.decr("mtest", 1, 9));
assertEquals(9, client.decr("mtest2", 1, 9));
}
public void testMutateWithDefaultAndExp() throws Exception {
assertEquals(3, client.incr("mtest", 1, 3, 1));
assertEquals(4, client.incr("mtest", 1, 3, 1));
assertEquals(3, client.decr("mtest", 1, 9, 1));
assertEquals(9, client.decr("mtest2", 1, 9, 1));
Thread.sleep(2000);
assertNull(client.get("mtest"));
assert ! client.asyncGet("mtest").getStatus().isSuccess();
}
public void testAsyncIncrement() throws Exception {
String k="async-incr";
client.set(k, 0, "5");
Future<Long> f = client.asyncIncr(k, 1);
assertEquals(6, (long)f.get());
}
public void testAsyncIncrementNonExistent() throws Exception {
String k="async-incr-non-existent";
Future<Long> f = client.asyncIncr(k, 1);
assertEquals(-1, (long)f.get());
}
public void testAsyncDecrement() throws Exception {
String k="async-decr";
client.set(k, 0, "5");
Future<Long> f = client.asyncDecr(k, 1);
assertEquals(4, (long)f.get());
}
public void testAsyncDecrementNonExistent() throws Exception {
String k="async-decr-non-existent";
Future<Long> f = client.asyncDecr(k, 1);
assertEquals(-1, (long)f.get());
}
public void testConcurrentMutation() throws Throwable {
int num=SyncThread.getDistinctResultCount(10, new Callable<Long>(){
public Long call() throws Exception {
return client.incr("mtest", 1, 11);
}});
assertEquals(10, num);
}
public void testImmediateDelete() throws Exception {
assertNull(client.get("test1"));
client.set("test1", 5, "test1value");
assertEquals("test1value", client.get("test1"));
assert client.delete("test1").getStatus().isSuccess();
assertNull(client.get("test1"));
}
public void testFlush() throws Exception {
assertNull(client.get("test1"));
client.set("test1", 5, "test1value");
client.set("test2", 5, "test2value");
assertEquals("test1value", client.get("test1"));
assertEquals("test2value", client.get("test2"));
assertTrue(client.flush().get());
assertNull(client.get("test1"));
assertNull(client.get("test2"));
}
public void testGracefulShutdown() throws Exception {
for(int i=0; i<1000; i++) {
client.set("t" + i, 10, i);
}
assertTrue("Couldn't shut down within five seconds",
client.shutdown(5, TimeUnit.SECONDS));
// Get a new client
initClient();
Collection<String> keys=new ArrayList<String>();
for(int i=0; i<1000; i++) {
keys.add("t" + i);
}
Map<String, Object> m=client.getBulk(keys);
assertEquals(1000, m.size());
for(int i=0; i<1000; i++) {
assertEquals(i, m.get("t" + i));
}
}
public void testSyncGetTimeouts() throws Exception {
final String key="timeoutTestKey";
final String value="timeoutTestValue";
int j = 0;
boolean set = false;
do {
set = client.set(key, 0, value).get();
j++;
} while (!set && j < 10);
assert set == true;
// Shutting down the default client to get one with a short timeout.
assertTrue("Couldn't shut down within five seconds",
client.shutdown(5, TimeUnit.SECONDS));
initClient(new DefaultConnectionFactory() {
@Override
public long getOperationTimeout() {
return 2;
}
@Override
public int getTimeoutExceptionThreshold() {
return 1000000;
}
});
Thread.sleep(100); // allow connections to be established
int i = 0;
GetFuture<Object> g = null;
try {
for(i = 0; i < 1000000; i++) {
g = client.asyncGet(key);
g.get();
}
throw new Exception("Didn't get a timeout.");
} catch(Exception e) {
assert !g.getStatus().isSuccess();
System.out.println("Got a timeout at iteration " + i + ".");
}
Thread.sleep(100); // let whatever caused the timeout to pass
try {
if (value.equals(client.asyncGet(key).get(30, TimeUnit.SECONDS))) {
System.out.println("Got the right value.");
} else {
throw new Exception("Didn't get the expected value.");
}
} catch (java.util.concurrent.TimeoutException timeoutException) {
debugNodeInfo(client.getNodeLocator().getAll());
throw new Exception("Unexpected timeout after 30 seconds waiting", timeoutException);
}
}
private void debugNodeInfo(Collection<MemcachedNode> nodes) {
System.err.println("Debug nodes:");
for (MemcachedNode node : nodes) {
System.err.println(node);
System.err.println("Is active? " + node.isActive());
System.err.println("Has read operation? " + node.hasReadOp() + " Has write operation? " + node.hasWriteOp());
try {
System.err.println("Has timed out this many times: " + node.getContinuousTimeout());
System.err.println("Write op: " + node.getCurrentWriteOp());
System.err.println("Read op: " + node.getCurrentReadOp());
} catch (UnsupportedOperationException e) {
System.err.println("Node does not support full interface, likely read only.");
}
}
}
public void xtestGracefulShutdownTooSlow() throws Exception {
for(int i=0; i<10000; i++) {
client.set("t" + i, 10, i);
}
assertFalse("Weird, shut down too fast",
client.shutdown(1, TimeUnit.MILLISECONDS));
try {
Map<SocketAddress, String> m = client.getVersions();
fail("Expected failure, got " + m);
} catch(IllegalStateException e) {
assertEquals("Shutting down", e.getMessage());
}
// Get a new client
initClient();
}
public void testStupidlyLargeSetAndSizeOverride() throws Exception {
if (isMembase()) {
return;
}
Random r=new Random();
SerializingTranscoder st=new SerializingTranscoder(Integer.MAX_VALUE);
st.setCompressionThreshold(Integer.MAX_VALUE);
byte data[]=new byte[21*1024*1024];
r.nextBytes(data);
try {
client.set("bigassthing", 60, data, st).get();
fail("Didn't fail setting bigass thing.");
} catch(ExecutionException e) {
System.err.println("Successful failure setting bigassthing. Ass size " + data.length + " bytes doesn't fit.");
e.printStackTrace();
OperationException oe=(OperationException)e.getCause();
assertSame(OperationErrorType.SERVER, oe.getType());
}
// But I should still be able to do something.
client.set("k", 5, "Blah");
assertEquals("Blah", client.get("k"));
}
public void testStupidlyLargeSet() throws Exception {
Random r=new Random();
SerializingTranscoder st=new SerializingTranscoder();
st.setCompressionThreshold(Integer.MAX_VALUE);
byte data[]=new byte[21*1024*1024];
r.nextBytes(data);
try {
client.set("bigassthing", 60, data, st).get();
fail("Didn't fail setting bigass thing.");
} catch(IllegalArgumentException e) {
assertEquals("Cannot cache data larger than "
+ CachedData.MAX_SIZE + " bytes "
+ "(you tried to cache a " + data.length + " byte object)",
e.getMessage());
}
// But I should still be able to do something.
client.set("k", 5, "Blah");
assertEquals("Blah", client.get("k"));
}
public void testQueueAfterShutdown() throws Exception {
client.shutdown();
try {
Object o=client.get("k");
fail("Expected IllegalStateException, got " + o);
} catch(IllegalStateException e) {
} finally {
initClient(); // init for tearDown
}
}
public void testMultiReqAfterShutdown() throws Exception {
client.shutdown();
try {
Map<String, ?> m=client.getBulk("k1", "k2", "k3");
fail("Expected IllegalStateException, got " + m);
} catch(IllegalStateException e) {
} finally {
initClient(); // init for tearDown
}
}
public void testBroadcastAfterShutdown() throws Exception {
client.shutdown();
try {
Future<?> f=client.flush();
fail("Expected IllegalStateException, got " + f.get());
} catch(IllegalStateException e) {
} finally {
initClient(); // init for tearDown
}
}
public void testABunchOfCancelledOperations() throws Exception {
final String k="bunchOCancel";
Collection<Future<?>> futures=new ArrayList<Future<?>>();
for(int i=0; i<1000; i++) {
futures.add(client.set(k, 5, "xval"));
futures.add(client.asyncGet(k));
}
OperationFuture<Boolean> sf=client.set(k, 5, "myxval");
GetFuture<Object> gf=client.asyncGet(k);
for(Future<?> f : futures) {
f.cancel(true);
}
assertTrue(sf.get());
assert sf.getStatus().isSuccess();
assertEquals("myxval", gf.get());
assert gf.getStatus().isSuccess();
}
public void testUTF8Key() throws Exception {
final String key = "junit.Здравствуйте." + System.currentTimeMillis();
final String value = "Skiing rocks if you can find the time to go!";
assertTrue(client.set(key, 6000, value).get());
Object output = client.get(key);
assertNotNull("output is null", output);
assertEquals("output is not equal", value, output);
}
public void testUTF8KeyDelete() throws Exception {
final String key = "junit.Здравствуйте." + System.currentTimeMillis();
final String value = "Skiing rocks if you can find the time to go!";
assertTrue(client.set(key, 6000, value).get());
assertTrue(client.delete(key).get());
assertNull(client.get(key));
}
public void testUTF8MultiGet() throws Exception {
final String value = "Skiing rocks if you can find the time to go!";
Collection<String> keys=new ArrayList<String>();
for(int i=0; i<50; i++) {
final String key = "junit.Здравствуйте."
+ System.currentTimeMillis() + "." + i;
assertTrue(client.set(key, 6000, value).get());
keys.add(key);
}
Map<String, Object> vals = client.getBulk(keys);
assertEquals(keys.size(), vals.size());
for(Object o : vals.values()) {
assertEquals(value, o);
}
assertTrue(keys.containsAll(vals.keySet()));
}
public void testUTF8Value() throws Exception {
final String key = "junit.plaintext." + System.currentTimeMillis();
final String value = "Здравствуйте Здравствуйте Здравствуйте "
+ "Skiing rocks if you can find the time to go!";
assertTrue(client.set(key, 6000, value).get());
Object output = client.get(key);
assertNotNull("output is null", output);
assertEquals("output is not equal", value, output);
}
public void testAppend() throws Exception {
final String key="append.key";
assertTrue(client.set(key, 5, "test").get());
OperationFuture<Boolean> op = client.append(0, key, "es");
assertTrue(op.get());
assert op.getStatus().isSuccess();
assertEquals("testes", client.get(key));
}
public void testPrepend() throws Exception {
final String key="prepend.key";
assertTrue(client.set(key, 5, "test").get());
OperationFuture<Boolean> op = client.prepend(0, key, "es");
assertTrue(op.get());
assert op.getStatus().isSuccess();
assertEquals("estest", client.get(key));
}
public void testAppendNoSuchKey() throws Exception {
final String key="append.missing";
assertFalse(client.append(0, key, "es").get());
assertNull(client.get(key));
}
public void testPrependNoSuchKey() throws Exception {
final String key="prepend.missing";
assertFalse(client.prepend(0, key, "es").get());
assertNull(client.get(key));
}
private static class TestTranscoder implements Transcoder<String> {
private static final int flags=238885206;
public String decode(CachedData d) {
assert d.getFlags() == flags
: "expected " + flags + " got " + d.getFlags();
return new String(d.getData());
}
public CachedData encode(String o) {
return new CachedData(flags, o.getBytes(), getMaxSize());
}
public int getMaxSize() {
return CachedData.MAX_SIZE;
}
public boolean asyncDecode(CachedData d) {
return false;
}
}
private static class TestWithKeyTranscoder implements Transcoder<String> {
private static final int flags=238885207;
private final String key;
TestWithKeyTranscoder(String k) {
key = k;
}
public String decode(CachedData d) {
assert d.getFlags() == flags
: "expected " + flags + " got " + d.getFlags();
ByteBuffer bb = ByteBuffer.wrap(d.getData());
int keyLength = bb.getInt();
byte[] keyBytes = new byte[keyLength];
bb.get(keyBytes);
String k = new String(keyBytes);
assertEquals(key, k);
int valueLength = bb.getInt();
byte[] valueBytes = new byte[valueLength];
bb.get(valueBytes);
return new String(valueBytes);
}
public CachedData encode(String o) {
byte[] keyBytes = key.getBytes();
byte[] valueBytes = o.getBytes();
int length = 4 + keyBytes.length + 4 + valueBytes.length;
byte[] bytes = new byte[length];
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.putInt(keyBytes.length).put(keyBytes);
bb.putInt(valueBytes.length).put(valueBytes);
return new CachedData(flags, bytes, getMaxSize());
}
public int getMaxSize() {
return CachedData.MAX_SIZE;
}
public boolean asyncDecode(CachedData d) {
return false;
}
}
} |
package net.spy.memcached;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import net.spy.memcached.ops.OperationErrorType;
import net.spy.memcached.ops.OperationException;
import net.spy.memcached.transcoders.BaseSerializingTranscoder;
import net.spy.memcached.transcoders.SerializingTranscoder;
import net.spy.memcached.transcoders.Transcoder;
import net.spy.test.SyncThread;
public abstract class ProtocolBaseCase extends ClientBaseCase {
public void testAssertions() {
boolean caught=false;
try {
assert false;
} catch(AssertionError e) {
caught=true;
}
assertTrue("Assertions are not enabled!", caught);
}
public void testGetStats() throws Exception {
Map<SocketAddress, Map<String, String>> stats = client.getStats();
System.out.println("Stats: " + stats);
assertEquals(1, stats.size());
Map<String, String> oneStat=stats.values().iterator().next();
assertTrue(oneStat.containsKey("total_items"));
}
public void testGetStatsSlabs() throws Exception {
// There needs to at least have been one value set or there may be
// no slabs to check.
client.set("slabinitializer", 0, "hi");
Map<SocketAddress, Map<String, String>> stats = client.getStats("slabs");
System.out.println("Stats: " + stats);
assertEquals(1, stats.size());
Map<String, String> oneStat=stats.values().iterator().next();
assertTrue(oneStat.containsKey("1:chunk_size"));
}
public void testDelayedFlush() throws Exception {
assertNull(client.get("test1"));
client.set("test1", 5, "test1value");
client.set("test2", 5, "test2value");
assertEquals("test1value", client.get("test1"));
assertEquals("test2value", client.get("test2"));
client.flush(2);
Thread.sleep(2100);
assertNull(client.get("test1"));
assertNull(client.get("test2"));
}
public void testNoop() {
// This runs through the startup/flush cycle
}
public void testDoubleShutdown() {
client.shutdown();
client.shutdown();
}
public void testSimpleGet() throws Exception {
assertNull(client.get("test1"));
client.set("test1", 5, "test1value");
assertEquals("test1value", client.get("test1"));
}
public void testSimpleCASGets() throws Exception {
assertNull(client.gets("test1"));
client.set("test1", 5, "test1value");
assertEquals("test1value", client.gets("test1").getValue());
}
public void testCAS() throws Exception {
final String key="castestkey";
// First, make sure it doesn't work for a non-existing value.
assertSame("Expected error CASing with no existing value.",
CASResponse.NOT_FOUND,
client.cas(key, 0x7fffffffffL, "bad value"));
// OK, stick a value in here.
assertTrue(client.add(key, 5, "original value").get());
CASValue<?> getsVal = client.gets(key);
assertEquals("original value", getsVal.getValue());
// Now try it with an existing value, but wrong CAS id
assertSame("Expected error CASing with invalid id",
CASResponse.EXISTS,
client.cas(key, getsVal.getCas() + 1, "broken value"));
// Validate the original value is still in tact.
assertEquals("original value", getsVal.getValue());
// OK, now do a valid update
assertSame("Expected successful CAS with correct id ("
+ getsVal.getCas() + ")",
CASResponse.OK,
client.cas(key, getsVal.getCas(), "new value"));
assertEquals("new value", client.get(key));
// Test a CAS replay
assertSame("Expected unsuccessful CAS with replayed id",
CASResponse.EXISTS,
client.cas(key, getsVal.getCas(), "crap value"));
assertEquals("new value", client.get(key));
}
public void testExtendedUTF8Key() throws Exception {
String key="\u2013\u00ba\u2013\u220f\u2014\u00c4";
assertNull(client.get(key));
client.set(key, 5, "test1value");
assertEquals("test1value", client.get(key));
}
public void testInvalidKey1() throws Exception {
try {
client.get("key with spaces");
fail("Expected IllegalArgumentException getting key with spaces");
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKey2() throws Exception {
try {
StringBuilder longKey=new StringBuilder();
for(int i=0; i<251; i++) {
longKey.append("a");
}
client.get(longKey.toString());
fail("Expected IllegalArgumentException getting too long of a key");
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKey3() throws Exception {
try {
Object val=client.get("Key\n");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKey4() throws Exception {
try {
Object val=client.get("Key\r");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKey5() throws Exception {
try {
Object val=client.get("Key\0");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidKeyBulk() throws Exception {
try {
Object val=client.getBulk("Key key2");
fail("Expected IllegalArgumentException, got " + val);
} catch(IllegalArgumentException e) {
// pass
}
}
public void testInvalidTranscoder() {
try {
client.setTranscoder(null);
fail("Allowed null transcoder.");
} catch(NullPointerException e) {
assertEquals("Can't use a null transcoder", e.getMessage());
}
}
public void testSetTranscoder() {
Transcoder<Object> tc=client.getTranscoder();
assertTrue(tc instanceof BaseSerializingTranscoder);
Transcoder<Object> tmptc=new Transcoder<Object>(){
public Object decode(CachedData d) {
throw new RuntimeException("Not implemented.");
}
public CachedData encode(Object o) {
throw new RuntimeException("Not implemented.");
}};
client.setTranscoder(tmptc);
assertSame(tmptc, client.getTranscoder());
}
public void testParallelSetGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
for(int i=0; i<10; i++) {
client.set("test" + i, 5, "value" + i);
assertEquals("value" + i, client.get("test" + i));
}
for(int i=0; i<10; i++) {
assertEquals("value" + i, client.get("test" + i));
}
return Boolean.TRUE;
}});
assertEquals(1, cnt);
}
public void testParallelSetMultiGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
for(int i=0; i<10; i++) {
client.set("test" + i, 5, "value" + i);
assertEquals("value" + i, client.get("test" + i));
}
Map<String, Object> m=client.getBulk("test0", "test1", "test2",
"test3", "test4", "test5", "test6", "test7", "test8",
"test9", "test10"); // Yes, I intentionally ran over.
for(int i=0; i<10; i++) {
assertEquals("value" + i, m.get("test" + i));
}
return Boolean.TRUE;
}});
assertEquals(1, cnt);
}
public void testParallelSetAutoMultiGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
client.set("testparallel", 5, "parallelvalue");
for(int i=0; i<10; i++) {
assertEquals("parallelvalue", client.get("testparallel"));
}
return Boolean.TRUE;
}});
assertEquals(1, cnt);
}
public void testAdd() throws Exception {
assertNull(client.get("test1"));
assertTrue(client.set("test1", 5, "test1value").get());
assertEquals("test1value", client.get("test1"));
assertFalse(client.add("test1", 5, "ignoredvalue").get());
// Should return the original value
assertEquals("test1value", client.get("test1"));
}
public void testAddWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertNull(client.get("test1", t));
assertTrue(client.set("test1", 5, "test1value", t).get());
assertEquals("test1value", client.get("test1", t));
assertFalse(client.add("test1", 5, "ignoredvalue", t).get());
// Should return the original value
assertEquals("test1value", client.get("test1", t));
}
public void testAddNotSerializable() throws Exception {
try {
client.add("t1", 5, new Object());
fail("expected illegal argument exception");
} catch(IllegalArgumentException e) {
assertEquals("Non-serializable object", e.getMessage());
}
}
public void testSetNotSerializable() throws Exception {
try {
client.set("t1", 5, new Object());
fail("expected illegal argument exception");
} catch(IllegalArgumentException e) {
assertEquals("Non-serializable object", e.getMessage());
}
}
public void testReplaceNotSerializable() throws Exception {
try {
client.replace("t1", 5, new Object());
fail("expected illegal argument exception");
} catch(IllegalArgumentException e) {
assertEquals("Non-serializable object", e.getMessage());
}
}
public void testUpdate() throws Exception {
assertNull(client.get("test1"));
client.replace("test1", 5, "test1value");
assertNull(client.get("test1"));
}
public void testUpdateWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertNull(client.get("test1", t));
client.replace("test1", 5, "test1value", t);
assertNull(client.get("test1", t));
}
// Just to make sure the sequence is being handled correctly
public void testMixedSetsAndUpdates() throws Exception {
Collection<Future<Boolean>> futures=new ArrayList<Future<Boolean>>();
Collection<String> keys=new ArrayList<String>();
for(int i=0; i<100; i++) {
String key="k" + i;
futures.add(client.set(key, 10, key));
futures.add(client.add(key, 10, "a" + i));
keys.add(key);
}
Map<String, Object> m=client.getBulk(keys);
assertEquals(100, m.size());
for(Map.Entry<String, Object> me : m.entrySet()) {
assertEquals(me.getKey(), me.getValue());
}
for(Iterator<Future<Boolean>> i=futures.iterator();i.hasNext();) {
assertTrue(i.next().get());
assertFalse(i.next().get());
}
}
public void testGetBulk() throws Exception {
Collection<String> keys=Arrays.asList("test1", "test2", "test3");
assertEquals(0, client.getBulk(keys).size());
client.set("test1", 5, "val1");
client.set("test2", 5, "val2");
Map<String, Object> vals=client.getBulk(keys);
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
}
public void testGetBulkVararg() throws Exception {
assertEquals(0, client.getBulk("test1", "test2", "test3").size());
client.set("test1", 5, "val1");
client.set("test2", 5, "val2");
Map<String, Object> vals=client.getBulk("test1", "test2", "test3");
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
}
public void testGetBulkVarargWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertEquals(0, client.getBulk(t, "test1", "test2", "test3").size());
client.set("test1", 5, "val1", t);
client.set("test2", 5, "val2", t);
Map<String, String> vals=client.getBulk(t, "test1", "test2", "test3");
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
}
public void testAsyncGetBulkVarargWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertEquals(0, client.getBulk(t, "test1", "test2", "test3").size());
client.set("test1", 5, "val1", t);
client.set("test2", 5, "val2", t);
Future<Map<String, String>> vals=client.asyncGetBulk(t,
"test1", "test2", "test3");
assertEquals(2, vals.get().size());
assertEquals("val1", vals.get().get("test1"));
assertEquals("val2", vals.get().get("test2"));
}
public void testAvailableServers() {
client.getVersions();
assertEquals(new ArrayList<String>(
Collections.singleton(getExpectedVersionSource())),
stringify(client.getAvailableServers()));
}
public void testUnavailableServers() {
client.getVersions();
assertEquals(Collections.emptyList(), client.getUnavailableServers());
}
protected abstract String getExpectedVersionSource();
public void testGetVersions() throws Exception {
Map<SocketAddress, String> vs=client.getVersions();
assertEquals(1, vs.size());
Map.Entry<SocketAddress, String> me=vs.entrySet().iterator().next();
assertEquals(getExpectedVersionSource(), me.getKey().toString());
assertNotNull(me.getValue());
}
public void testNonexistentMutate() throws Exception {
assertEquals(-1, client.incr("nonexistent", 1));
assertEquals(-1, client.decr("nonexistent", 1));
}
public void testMutateWithDefault() throws Exception {
assertEquals(3, client.incr("mtest", 1, 3));
assertEquals(4, client.incr("mtest", 1, 3));
assertEquals(3, client.decr("mtest", 1, 9));
assertEquals(9, client.decr("mtest2", 1, 9));
}
public void testMutateWithDefaultAndExp() throws Exception {
assertEquals(3, client.incr("mtest", 1, 3, 1));
assertEquals(4, client.incr("mtest", 1, 3, 1));
assertEquals(3, client.decr("mtest", 1, 9, 1));
assertEquals(9, client.decr("mtest2", 1, 9, 1));
Thread.sleep(2000);
assertNull(client.get("mtest"));
}
public void testAsyncIncrement() throws Exception {
String k="async-incr";
client.set(k, 0, "5");
Future<Long> f = client.asyncIncr(k, 1);
assertEquals(6, (long)f.get());
}
public void testAsyncIncrementNonExistent() throws Exception {
String k="async-incr-non-existent";
Future<Long> f = client.asyncIncr(k, 1);
assertEquals(-1, (long)f.get());
}
public void testAsyncDecrement() throws Exception {
String k="async-decr";
client.set(k, 0, "5");
Future<Long> f = client.asyncDecr(k, 1);
assertEquals(4, (long)f.get());
}
public void testAsyncDecrementNonExistent() throws Exception {
String k="async-decr-non-existent";
Future<Long> f = client.asyncDecr(k, 1);
assertEquals(-1, (long)f.get());
}
public void testConcurrentMutation() throws Throwable {
int num=SyncThread.getDistinctResultCount(10, new Callable<Long>(){
public Long call() throws Exception {
return client.incr("mtest", 1, 11);
}});
assertEquals(10, num);
}
public void testImmediateDelete() throws Exception {
assertNull(client.get("test1"));
client.set("test1", 5, "test1value");
assertEquals("test1value", client.get("test1"));
client.delete("test1");
assertNull(client.get("test1"));
}
public void testFlush() throws Exception {
assertNull(client.get("test1"));
client.set("test1", 5, "test1value");
client.set("test2", 5, "test2value");
assertEquals("test1value", client.get("test1"));
assertEquals("test2value", client.get("test2"));
assertTrue(client.flush().get());
assertNull(client.get("test1"));
assertNull(client.get("test2"));
}
public void testGracefulShutdown() throws Exception {
for(int i=0; i<1000; i++) {
client.set("t" + i, 10, i);
}
assertTrue("Couldn't shut down within five seconds",
client.shutdown(5, TimeUnit.SECONDS));
// Get a new client
initClient();
Collection<String> keys=new ArrayList<String>();
for(int i=0; i<1000; i++) {
keys.add("t" + i);
}
Map<String, Object> m=client.getBulk(keys);
assertEquals(1000, m.size());
for(int i=0; i<1000; i++) {
assertEquals(i, m.get("t" + i));
}
}
public void testSyncGetTimeouts() throws Exception {
final String key="timeoutTestKey";
final String value="timeoutTestValue";
// Shutting down the default client to get one with a short timeout.
assertTrue("Couldn't shut down within five seconds",
client.shutdown(5, TimeUnit.SECONDS));
initClient(new DefaultConnectionFactory() {
@Override
public long getOperationTimeout() {
return 1;
}
});
client.set(key, 0, value);
try {
for(int i=0; i<1000000; i++) {
client.get(key);
}
throw new Exception("Didn't get a timeout.");
} catch(OperationTimeoutException e) {
System.out.println("Got a timeout.");
}
if(value.equals(client.asyncGet(key).get(1, TimeUnit.SECONDS))) {
System.out.println("Got the right value.");
} else {
throw new Exception("Didn't get the expected value.");
}
}
public void xtestGracefulShutdownTooSlow() throws Exception {
for(int i=0; i<10000; i++) {
client.set("t" + i, 10, i);
}
assertFalse("Weird, shut down too fast",
client.shutdown(1, TimeUnit.MILLISECONDS));
try {
Map<SocketAddress, String> m = client.getVersions();
fail("Expected failure, got " + m);
} catch(IllegalStateException e) {
assertEquals("Shutting down", e.getMessage());
}
// Get a new client
initClient();
}
public void testStupidlyLargeSetAndSizeOverride() throws Exception {
Random r=new Random();
SerializingTranscoder st=new SerializingTranscoder(Integer.MAX_VALUE);
st.setCompressionThreshold(Integer.MAX_VALUE);
client.setTranscoder(st);
byte data[]=new byte[10*1024*1024];
r.nextBytes(data);
try {
client.set("bigassthing", 60, data).get();
fail("Didn't fail setting bigass thing.");
} catch(ExecutionException e) {
e.printStackTrace();
OperationException oe=(OperationException)e.getCause();
assertSame(OperationErrorType.SERVER, oe.getType());
}
// But I should still be able to do something.
client.set("k", 5, "Blah");
assertEquals("Blah", client.get("k"));
}
public void testStupidlyLargeSet() throws Exception {
Random r=new Random();
SerializingTranscoder st=new SerializingTranscoder();
st.setCompressionThreshold(Integer.MAX_VALUE);
client.setTranscoder(st);
byte data[]=new byte[10*1024*1024];
r.nextBytes(data);
try {
client.set("bigassthing", 60, data).get();
fail("Didn't fail setting bigass thing.");
} catch(IllegalArgumentException e) {
assertEquals("Cannot cache data larger than 1MB "
+ "(you tried to cache a " + data.length + " byte object)",
e.getMessage());
}
// But I should still be able to do something.
client.set("k", 5, "Blah");
assertEquals("Blah", client.get("k"));
}
public void testQueueAfterShutdown() throws Exception {
client.shutdown();
try {
Object o=client.get("k");
fail("Expected IllegalStateException, got " + o);
} catch(IllegalStateException e) {
} finally {
initClient(); // init for tearDown
}
}
public void testMultiReqAfterShutdown() throws Exception {
client.shutdown();
try {
Map<String, ?> m=client.getBulk("k1", "k2", "k3");
fail("Expected IllegalStateException, got " + m);
} catch(IllegalStateException e) {
} finally {
initClient(); // init for tearDown
}
}
public void testBroadcastAfterShutdown() throws Exception {
client.shutdown();
try {
Future<?> f=client.flush();
fail("Expected IllegalStateException, got " + f.get());
} catch(IllegalStateException e) {
} finally {
initClient(); // init for tearDown
}
}
public void testABunchOfCancelledOperations() throws Exception {
final String k="bunchOCancel";
Collection<Future<?>> futures=new ArrayList<Future<?>>();
for(int i=0; i<1000; i++) {
futures.add(client.set(k, 5, "xval"));
futures.add(client.asyncGet(k));
}
Future<Boolean> sf=client.set(k, 5, "myxval");
Future<Object> gf=client.asyncGet(k);
for(Future<?> f : futures) {
f.cancel(true);
}
assertTrue(sf.get());
assertEquals("myxval", gf.get());
}
public void testUTF8Key() throws Exception {
final String key = "junit.Здравствуйте." + System.currentTimeMillis();
final String value = "Skiing rocks if you can find the time to go!";
assertTrue(client.set(key, 6000, value).get());
Object output = client.get(key);
assertNotNull("output is null", output);
assertEquals("output is not equal", value, output);
}
public void testUTF8KeyDelete() throws Exception {
final String key = "junit.Здравствуйте." + System.currentTimeMillis();
final String value = "Skiing rocks if you can find the time to go!";
assertTrue(client.set(key, 6000, value).get());
assertTrue(client.delete(key).get());
assertNull(client.get(key));
}
public void testUTF8MultiGet() throws Exception {
final String value = "Skiing rocks if you can find the time to go!";
Collection<String> keys=new ArrayList<String>();
for(int i=0; i<50; i++) {
final String key = "junit.Здравствуйте."
+ System.currentTimeMillis() + "." + i;
assertTrue(client.set(key, 6000, value).get());
keys.add(key);
}
Map<String, Object> vals = client.getBulk(keys);
assertEquals(keys.size(), vals.size());
for(Object o : vals.values()) {
assertEquals(value, o);
}
assertTrue(keys.containsAll(vals.keySet()));
}
public void testUTF8Value() throws Exception {
final String key = "junit.plaintext." + System.currentTimeMillis();
final String value = "Здравствуйте Здравствуйте Здравствуйте "
+ "Skiing rocks if you can find the time to go!";
assertTrue(client.set(key, 6000, value).get());
Object output = client.get(key);
assertNotNull("output is null", output);
assertEquals("output is not equal", value, output);
}
public void testAppend() throws Exception {
final String key="append.key";
assertTrue(client.set(key, 5, "test").get());
assertTrue(client.append(0, key, "es").get());
assertEquals("testes", client.get(key));
}
public void testPrepend() throws Exception {
final String key="prepend.key";
assertTrue(client.set(key, 5, "test").get());
assertTrue(client.prepend(0, key, "es").get());
assertEquals("estest", client.get(key));
}
public void testAppendNoSuchKey() throws Exception {
final String key="append.missing";
assertFalse(client.append(0, key, "es").get());
assertNull(client.get(key));
}
public void testPrependNoSuchKey() throws Exception {
final String key="prepend.missing";
assertFalse(client.prepend(0, key, "es").get());
assertNull(client.get(key));
}
private static class TestTranscoder implements Transcoder<String> {
private static final int flags=238885206;
public String decode(CachedData d) {
assert d.getFlags() == flags
: "expected " + flags + " got " + d.getFlags();
return new String(d.getData());
}
public CachedData encode(String o) {
return new CachedData(flags, o.getBytes());
}
}
} |
package org.hfeng.leet.util;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import static org.junit.Assert.assertEquals;
public class TreeNodeHelper {
public static TreeNode createListFromArray(int[] array) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if (array.length == 0) {
return null;
}
TreeNode root = new TreeNode(array[0]);
queue.offer(root);
int count = 0;
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (++count < array.length) {
cur.left = array[count] == -1 ? null : new TreeNode(array[count]);
queue.offer(cur.left);
} else {
cur.left = null;
}
if (++count < array.length) {
cur.right = array[count] == -1 ? null : new TreeNode(array[count]);
queue.offer(cur.right);
} else {
cur.right = null;
}
}
return root;
}
public static void assertEqualTree(TreeNode left, TreeNode right) {
// From //
Assert.assertThat(preOrderTree(right), IsIterableContainingInOrder.contains(preOrderTree(left).toArray()));
}
public static List<Integer> preOrderTree(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
preOrderSub(root, ret);
return ret;
}
private static void preOrderSub(TreeNode root, List<Integer> ret) {
if (root == null) {
return;
}
ret.add(root.val);
if (root.left != null) {
preOrderSub(root.left, ret);
}
if (root.right != null) {
preOrderSub(root.right, ret);
}
}
} |
package org.apache.commons.lang;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit tests {@link org.apache.commons.lang.NumberUtils}.
*
* @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
* @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a>
* @version $Id: NumberUtilsTest.java,v 1.2 2002/09/15 10:27:56 scolebourne Exp $
*/
public class NumberUtilsTest extends TestCase {
public NumberUtilsTest(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite(NumberUtilsTest.class);
suite.setName("NumberUtils Tests");
return suite;
}
/**
* Test for int stringToInt(String)
*/
public void testStringToIntString() {
assertTrue("stringToInt(String) 1 failed", NumberUtils.stringToInt("12345") == 12345);
assertTrue("stringToInt(String) 2 failed", NumberUtils.stringToInt("abc") == 0);
}
/**
* Test for int stringToInt(String, int)
*/
public void testStringToIntStringI() {
assertTrue("stringToInt(String,int) 1 failed", NumberUtils.stringToInt("12345", 5) == 12345);
assertTrue("stringToInt(String,int) 2 failed", NumberUtils.stringToInt("1234.5", 5) == 5);
}
public void testCreateNumber() {
//a lot of things can go wrong
assertEquals("createNumber(String) 1 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5"));
assertEquals("createNumber(String) 2 failed", new Integer("12345"), NumberUtils.createNumber("12345"));
assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5D"));
assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5F"));
assertEquals("createNumber(String) 5 failed", new Long(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L)));
assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345L"));
assertEquals("createNumber(String) 7 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5"));
assertEquals("createNumber(String) 8 failed", new Integer("-12345"), NumberUtils.createNumber("-12345"));
assertTrue("createNumber(String) 9 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue());
assertTrue("createNumber(String) 10 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue());
assertEquals("createNumber(String) 11 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200"));
assertEquals("createNumber(String) 12 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20"));
assertEquals("createNumber(String) 13 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200"));
assertEquals("createNumber(String) 14 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200"));
assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils.createNumber("1.1E-700F"));
assertEquals(
"createNumber(String) 16 failed",
new Long("10" + Integer.MAX_VALUE),
NumberUtils.createNumber("10" + Integer.MAX_VALUE + "L"));
assertEquals(
"createNumber(String) 17 failed",
new Long("10" + Integer.MAX_VALUE),
NumberUtils.createNumber("10" + Integer.MAX_VALUE));
assertEquals(
"createNumber(String) 18 failed",
new BigInteger("10" + Long.MAX_VALUE),
NumberUtils.createNumber("10" + Long.MAX_VALUE));
}
public void testCreateFloat() {
assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5"));
}
public void testCreateDouble() {
assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5"));
}
public void testCreateInteger() {
assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345"));
}
public void testCreateLong() {
assertEquals("createInteger(String) failed", new Long("12345"), NumberUtils.createLong("12345"));
}
public void testCreateBigInteger() {
assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345"));
}
public void testCreateBigDecimal() {
assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5"));
}
public void testMinimumLong() {
assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.minimum(12345L, 12345L + 1L, 12345L + 2L));
assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L, 12345 + 2L));
assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L + 2L, 12345L));
assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L, 12345L));
assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.minimum(12345L, 12345L, 12345L));
}
public void testMinimumInt() {
assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.minimum(12345, 12345 + 1, 12345 + 2));
assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.minimum(12345 + 1, 12345, 12345 + 2));
assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.minimum(12345 + 1, 12345 + 2, 12345));
assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.minimum(12345 + 1, 12345, 12345));
assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.minimum(12345, 12345, 12345));
}
public void testMaximumLong() {
assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.maximum(12345L, 12345L - 1L, 12345L - 2L));
assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L, 12345L - 2L));
assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L - 2L, 12345L));
assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L, 12345L));
assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.maximum(12345L, 12345L, 12345L));
}
public void testMaximumInt() {
assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.maximum(12345, 12345 - 1, 12345 - 2));
assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.maximum(12345 - 1, 12345, 12345 - 2));
assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.maximum(12345 - 1, 12345 - 2, 12345));
assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.maximum(12345 - 1, 12345, 12345));
assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.maximum(12345, 12345, 12345));
}
public void testCompareDouble() {
assertTrue(NumberUtils.compare(Double.NaN, Double.NaN) == 0);
assertTrue(NumberUtils.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2d, 1.2d) == 0);
assertTrue(NumberUtils.compare(1.2d, 0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -1.2d) == +1);
assertTrue(NumberUtils.compare(1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(0.0d, 0.0d) == 0);
assertTrue(NumberUtils.compare(0.0d, -0.0d) == +1);
assertTrue(NumberUtils.compare(0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-0.0d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-0.0d, -0.0d) == 0);
assertTrue(NumberUtils.compare(-0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(-0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-1.2d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -1.2d) == 0);
assertTrue(NumberUtils.compare(-1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0);
}
public void testCompareFloat() {
assertTrue(NumberUtils.compare(Float.NaN, Float.NaN) == 0);
assertTrue(NumberUtils.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2f, 1.2f) == 0);
assertTrue(NumberUtils.compare(1.2f, 0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -1.2f) == +1);
assertTrue(NumberUtils.compare(1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(0.0f, 0.0f) == 0);
assertTrue(NumberUtils.compare(0.0f, -0.0f) == +1);
assertTrue(NumberUtils.compare(0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-0.0f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-0.0f, -0.0f) == 0);
assertTrue(NumberUtils.compare(-0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(-0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-1.2f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -1.2f) == 0);
assertTrue(NumberUtils.compare(-1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0);
}
public void testIsDigits() {
assertEquals("isDigits(null) failed", false, NumberUtils.isDigits(null));
assertEquals("isDigits('') failed", false, NumberUtils.isDigits(""));
assertEquals("isDigits(String) failed", true, NumberUtils.isDigits("12345"));
assertEquals("isDigits(String) neg 1 failed", false, NumberUtils.isDigits("1234.5"));
assertEquals("isDigits(String) neg 3 failed", false, NumberUtils.isDigits("1ab"));
assertEquals("isDigits(String) neg 4 failed", false, NumberUtils.isDigits("abc"));
}
/**
* Tests isNumber(String) and tests that createNumber(String) returns
* a valid number iff isNumber(String) returns false.
*/
public void testIsNumber() {
String val = "12345";
assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val));
val = "1234.5";
assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val));
val = ".12345";
assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val));
val = "1234E5";
assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val));
val = "1234E+5";
assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val));
val = "1234E-5";
assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val));
val = "123.4E5";
assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val));
val = "-1234";
assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val));
val = "-1234.5";
assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val));
val = "-.12345";
assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val));
val = "-1234E5";
assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val));
val = "0";
assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val));
val = "-0";
assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val));
val = "01234";
assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val));
val = "-01234";
assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val));
val = "0xABC123";
assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val));
val = "0x0";
assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val));
val = "123.4E21D";
assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val));
val = "-221.23F";
assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val));
val = "22338L";
assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val));
val = null;
assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val));
val = "";
assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val));
val = "--2.3";
assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val));
val = ".12.3";
assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val));
val = "-123E";
assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val));
val = "-123E+-212";
assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val));
val = "-123E2.12";
assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val));
val = "0xGF";
assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val));
val = "0xFAE-1";
assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val));
val = ".";
assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val));
val = "-0ABC123";
assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val));
val = "123.4E-D";
assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val));
val = "123.4ED";
assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val));
val = "1234E5l";
assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val));
assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val));
}
private boolean checkCreateNumber(String val) {
try {
Object obj = NumberUtils.createNumber(val);
if(obj == null) {
return false;
}
return true;
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}
} |
package org.apache.commons.lang;
import java.util.Arrays;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* Unit tests {@link org.apache.commons.lang.StringUtils}.
*
* @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
* @author <a href="mailto:bayard@generationjava.com">Henri Yandell</a>
* @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a>
* @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a>
* @author <a href="mailto:fredrik@westermarck.com>Fredrik Westermarck</a>
* @version $Id: StringUtilsTest.java,v 1.9 2002/11/23 00:41:19 bayard Exp $
*/
public class StringUtilsTest extends TestCase
{
private static final String[] ARRAY_LIST = { "foo", "bar", "baz" };
private static final String SEPARATOR = ",";
private static final String TEXT_LIST = "foo,bar,baz";
private static final String FOO = "foo";
private static final String BAR = "bar";
private static final String CAP_FOO = "Foo";
private static final String SENTENCE = "foo bar baz";
public StringUtilsTest(String name) {
super(name);
}
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(StringUtilsTest.class);
suite.setName("StringUtilsTest Tests");
return suite;
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testCaseFunctions()
{
assertEquals("capitalise(String) failed",
CAP_FOO, StringUtils.capitalise(FOO) );
assertEquals("capitalise(empty-string) failed",
"", StringUtils.capitalise("") );
assertEquals("capitaliseAllWords(String) failed",
"Foo Bar Baz", StringUtils.capitaliseAllWords(SENTENCE) );
assertEquals("capitaliseAllWords(empty-string) failed",
"", StringUtils.capitaliseAllWords("") );
assertEquals("uncapitalise(String) failed",
FOO, StringUtils.uncapitalise(CAP_FOO) );
assertEquals("uncapitalise(empty-string) failed",
"", StringUtils.uncapitalise("") );
assertEquals("uncapitaliseAllWords(String) failed",
SENTENCE, StringUtils.uncapitaliseAllWords("Foo Bar Baz") );
assertEquals("uncapitaliseAllWords(empty-string) failed",
"", StringUtils.uncapitaliseAllWords("") );
assertEquals("upperCase(String) failed",
"FOO TEST THING", StringUtils.upperCase("fOo test THING") );
assertEquals("upperCase(empty-string) failed",
"", StringUtils.upperCase("") );
assertEquals("lowerCase(String) failed",
"foo test thing", StringUtils.lowerCase("fOo test THING") );
assertEquals("lowerCase(empty-string) failed",
"", StringUtils.lowerCase("") );
assertEquals("swapCase(empty-string) failed",
"", StringUtils.swapCase("") );
assertEquals("swapCase(String-with-numbers) failed",
"a123RgYu", StringUtils.swapCase("A123rGyU") );
assertEquals("swapCase(String) failed",
"Hello aPACHE", StringUtils.swapCase("hELLO Apache") );
}
public void testJoin()
{
assertEquals("concatenate(Object[]) failed",
"foobarbaz", StringUtils.concatenate(ARRAY_LIST));
assertEquals("join(Object[], String) failed", TEXT_LIST,
StringUtils.join(ARRAY_LIST, SEPARATOR));
assertEquals("join(Iterator, String) failed", TEXT_LIST,
StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(),
SEPARATOR));
}
public void testSplit()
{
String[] result = StringUtils.split(TEXT_LIST, SEPARATOR, 2);
String[] expected = { "foo", "bar,baz" };
assertEquals("split(Object[], String, int) yielded unexpected length",
expected.length, result.length);
for (int i = 0; i < result.length; i++)
{
assertEquals("split(Object[], String, int) failed", expected[i],
result[i]);
}
result = StringUtils.split(TEXT_LIST, SEPARATOR, 0);
expected = ARRAY_LIST;
assertEquals("split(Object[], String, int) yielded unexpected length",
expected.length, result.length);
for (int i = 0; i < result.length; i++)
{
assertEquals("split(Object[], String, int) failed", expected[i],
result[i]);
}
result = StringUtils.split(TEXT_LIST, SEPARATOR, -1);
expected = ARRAY_LIST;
assertEquals("split(Object[], String, int) yielded unexpected length",
expected.length, result.length);
for (int i = 0; i < result.length; i++)
{
assertEquals("split(Object[], String, int) failed", expected[i],
result[i]);
}
result = StringUtils.split("one two three four five six", null, 2);
assertEquals("split(Object[], null, int)[0] failed", "one", result[0]);
assertEquals("split(Object[], null, int)[1] failed", "two", result[1]);
assertEquals("split(Object[], null, int)[2] failed", "three four five six", result[2]);
}
public void testReplaceFunctions()
{
assertEquals("replace(String, String, String, int) failed",
FOO, StringUtils.replace("oo" + FOO, "o", "", 2));
assertEquals("replace(String, String, String) failed",
"", StringUtils.replace(FOO + FOO + FOO, FOO, ""));
assertEquals("replaceOnce(String, String, String) failed",
FOO, StringUtils.replaceOnce(FOO + FOO, FOO, ""));
assertEquals("carriage-return replace(String,String,String) failed",
"test123", StringUtils.replace("test\r1\r2\r3", "\r", ""));
}
public void testOverlayString()
{
assertEquals("overlayString(String, String, int, int) failed",
"foo foor baz", StringUtils.overlayString(SENTENCE, FOO, 4, 6) );
}
public void testRepeat()
{
assertEquals("repeat(String, int) failed",
FOO + FOO + FOO, StringUtils.repeat(FOO, 3) );
}
public void testCenter()
{
assertEquals("center(String, int) failed",
" "+FOO+" ", StringUtils.center(FOO, 9) );
}
public void testChompFunctions()
{
assertEquals("chomp(String) failed",
FOO, StringUtils.chomp(FOO + "\n" + FOO) );
assertEquals("chompLast(String) failed",
FOO, StringUtils.chompLast(FOO + "\n") );
assertEquals("getChomp(String, String) failed",
"\n" + FOO, StringUtils.getChomp(FOO + "\n" + FOO, "\n") );
assertEquals("prechomp(String, String) failed",
FOO, StringUtils.prechomp(FOO + "\n" + FOO, "\n") );
assertEquals("getPrechomp(String, String) failed",
FOO + "\n", StringUtils.getPrechomp(FOO + "\n" + FOO, "\n") );
assertEquals("chop(String, String) failed",
FOO, StringUtils.chop(FOO + "\r\n") );
assertEquals("chopNewline(String, String) failed",
FOO, StringUtils.chopNewline(FOO + "\r\n") );
}
public void testPadFunctions()
{
assertEquals("rightPad(String, int) failed",
"1234 ", StringUtils.rightPad ("1234", 8) );
assertEquals("rightPad(String, int, String) failed",
"1234-+-+", StringUtils.rightPad ("1234", 8, "-+") );
assertEquals("rightPad(String, int, String) failed",
"123456-+~", StringUtils.rightPad ("123456", 9, "-+~") );
assertEquals("leftPad(String, int) failed",
" 1234", StringUtils.leftPad("1234", 8) );
assertEquals("leftPad(String, int, String) failed",
"-+-+1234", StringUtils.leftPad("1234", 8, "-+") );
assertEquals("leftPad(String, int, String) failed",
"-+~123456", StringUtils.leftPad("123456", 9, "-+~") );
}
public void testReverseFunctions() {
assertEquals("reverse(String) failed",
"sdrawkcab", StringUtils.reverse("backwards") );
assertEquals("reverse(empty-string) failed",
"", StringUtils.reverse("") );
assertEquals("reverseDelimitedString(String,'.') failed",
"org.apache.test",
StringUtils.reverseDelimitedString("test.apache.org", ".") );
assertEquals("reverseDelimitedString(empty-string,'.') failed",
"",
StringUtils.reverseDelimitedString("", ".") );
assertEquals("reverseDelimitedString(String,' ') failed",
"once upon a time",
StringUtils.reverseDelimitedString("time a upon once"," ") );
}
public void testDefaultFunctions() {
assertEquals("defaultString(empty-string) failed",
"", StringUtils.defaultString("") );
assertEquals("defaultString(String) failed",
FOO, StringUtils.defaultString(FOO) );
assertEquals("defaultString(null) failed",
"", StringUtils.defaultString(null) );
assertEquals("defaultString(empty-string,String) failed",
"", StringUtils.defaultString("", BAR) );
assertEquals("defaultString(String,String) failed",
FOO, StringUtils.defaultString(FOO, BAR) );
assertEquals("defaultString(null,String) failed",
BAR, StringUtils.defaultString(null, BAR) );
}
public void testEscapeFunctions() {
assertEquals("escape(empty-string) failed",
"", StringUtils.escape("") );
assertEquals("escape(String) failed",
FOO, StringUtils.escape(FOO) );
assertEquals("escape(String) failed",
"\\t", StringUtils.escape("\t") );
assertEquals("escape(String) failed",
"\\\\", StringUtils.escape("\\") );
assertEquals("escape(String) failed",
"\\\\\\b\\t\\r", StringUtils.escape("\\\b\t\r") );
assertEquals("escape(String) failed",
"\\u1234", StringUtils.escape("\u1234") );
assertEquals("escape(String) failed",
"\\u0234", StringUtils.escape("\u0234") );
assertEquals("escape(String) failed",
"\\u00fd", StringUtils.escape("\u00fd") );
}
public void testGetLevenshteinDistance() {
assertEquals("getLevenshteinDistance(empty-string, empty-string) failed",
0, StringUtils.getLevenshteinDistance("", "") );
assertEquals("getLevenshteinDistance(empty-string, String) failed",
1, StringUtils.getLevenshteinDistance("", "a") );
assertEquals("getLevenshteinDistance(String, empty-string) failed",
7, StringUtils.getLevenshteinDistance("aaapppp", "") );
assertEquals("getLevenshteinDistance(String, String) failed",
1, StringUtils.getLevenshteinDistance("frog", "fog") );
assertEquals("getLevenshteinDistance(String, String) failed",
3, StringUtils.getLevenshteinDistance("fly", "ant") );
assertEquals("getLevenshteinDistance(String, String) failed",
7, StringUtils.getLevenshteinDistance("elephant", "hippo") );
assertEquals("getLevenshteinDistance(String, String) failed",
7, StringUtils.getLevenshteinDistance("hippo", "elephant") );
assertEquals("getLevenshteinDistance(String, String) failed",
1, StringUtils.getLevenshteinDistance("hello", "hallo") );
}
public void testContainsOnly() {
String str1 = "a";
String str2 = "b";
String str3 = "ab";
char[] chars1= {'b'};
char[] chars2= {'a'};
char[] chars3= {'a', 'b'};
char[] emptyChars = new char[0];
assertEquals("containsOnly(null, null) failed", false, StringUtils.containsOnly(null, null));
assertEquals("containsOnly(empty-string, null) failed", false, StringUtils.containsOnly("", null));
assertEquals("containsOnly(null, empty-string) failed", false, StringUtils.containsOnly(null, emptyChars));
assertEquals("containsOnly(str1, empty-char-array) failed", false, StringUtils.containsOnly(str1, emptyChars));
assertEquals("containsOnly(empty-string, empty-char-array) failed", true, StringUtils.containsOnly("", emptyChars));
assertEquals("containsOnly(empty-string, chars1) failed", true, StringUtils.containsOnly("", chars1));
assertEquals("containsOnly(str1, chars1) failed", false, StringUtils.containsOnly(str1, chars1));
assertEquals("containsOnly(str1, chars1) failed", false, StringUtils.containsOnly(str1, chars1));
assertEquals("containsOnly(str1, chars1) success", true, StringUtils.containsOnly(str1, chars2));
assertEquals("containsOnly(str1, chars1) success", true, StringUtils.containsOnly(str1, chars3));
assertEquals("containsOnly(str2, chars2) success", true, StringUtils.containsOnly(str2, chars1));
assertEquals("containsOnly(str2, chars2) failed", false, StringUtils.containsOnly(str2, chars2));
assertEquals("containsOnly(str2, chars2) success", true, StringUtils.containsOnly(str2, chars3));
assertEquals("containsOnly(String3, chars3) failed", false, StringUtils.containsOnly(str3, chars1));
assertEquals("containsOnly(String3, chars3) failed", false, StringUtils.containsOnly(str3, chars2));
assertEquals("containsOnly(String3, chars3) success", true, StringUtils.containsOnly(str3, chars3));
}
} |
package uk.org.ownage.dmdirc.ui.components;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import uk.org.ownage.dmdirc.Config;
import uk.org.ownage.dmdirc.Error;
import uk.org.ownage.dmdirc.logger.ErrorLevel;
import uk.org.ownage.dmdirc.logger.Logger;
import uk.org.ownage.dmdirc.ui.interfaces.StatusErrorNotifier;
import uk.org.ownage.dmdirc.ui.interfaces.StatusMessageNotifier;
/**
* Status bar, shows message and info on the gui.
*/
public final class StatusBar extends JPanel implements MouseListener,
ActionListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** message label. */
private final JLabel messageLabel;
/** icon label. */
private final JLabel iconLabel;
/** current status bar message notifier. */
private StatusMessageNotifier messageNotifier;
/** current status bar error notifier. */
private StatusErrorNotifier errorNotifier;
/** non error state image icon. */
private final ImageIcon normalIcon;
/** Error history storage. */
private final List<Error> errors;
/** Timer to clear the error. */
private TimerTask errorTimer;
/** Timer to clear the message. */
private TimerTask messageTimer;
/** Popupmenu for this frame. */
private final JPopupMenu popup;
/** Creates a new instance of StatusBar. */
public StatusBar() {
super();
final BorderLayout layout = new BorderLayout(5, 5);
errors = new ArrayList<Error>();
popup = new JPopupMenu();
JMenuItem mi = new JMenuItem("No errors");
mi.addActionListener(this);
mi.setActionCommand("None");
popup.add(mi);
setBorder(new EmptyBorder(0, 5, 5, 5));
messageLabel = new JLabel();
iconLabel = new JLabel();
messageLabel.setBorder(new EtchedBorder());
iconLabel.setBorder(new EtchedBorder());
messageLabel.addMouseListener(this);
iconLabel.addMouseListener(this);
this.setLayout(layout);
add(messageLabel, BorderLayout.CENTER);
add(iconLabel, BorderLayout.LINE_END);
setPreferredSize(new Dimension(Short.MAX_VALUE, 26));
iconLabel.setPreferredSize(new Dimension(21, 26));
normalIcon = new ImageIcon(this.getClass()
.getClassLoader().getResource("uk/org/ownage/dmdirc/res/normal.png"));
clearMessage();
clearError();
}
/**
* Sets the message in the status bar with a specified callback event
* using the default timeout.
*
* @param newMessage Message to display
* @param newNotifier status message notifier to be notified for events on
* this message
*/
public void setMessage(final String newMessage,
final StatusMessageNotifier newNotifier) {
int timeout = 5;
if (Config.hasOption("statusBar", "messageDisplayLength")) {
try {
timeout = Integer.parseInt(Config.getOption("statusBar", "messageDisplayLength"));
} catch (NumberFormatException e) {
Logger.error(ErrorLevel.WARNING, "Invalid message display length", e);
}
}
setMessage(newMessage, newNotifier, timeout);
}
/**
* Sets the message in the status bar with a specified callback event for
* a specified time.
*
* @param newMessage Message to display
* @param newNotifier status message notifier to be notified for events on
* this message
* @param timeout message timeout in seconds
*/
public void setMessage(final String newMessage,
final StatusMessageNotifier newNotifier, final int timeout) {
messageLabel.setText(newMessage);
messageNotifier = newNotifier;
if (messageTimer != null && (System.currentTimeMillis() -
messageTimer.scheduledExecutionTime()) <= 0) {
messageTimer.cancel();
}
messageTimer = new TimerTask() {
public void run() {
clearMessage();
}
};
new Timer().schedule(messageTimer,
new Date(System.currentTimeMillis() + timeout * 1000));
}
/**
* sets the message in the status bar.
*
* @param newMessage Message to display
*/
public void setMessage(final String newMessage) {
setMessage(newMessage, null);
}
/**
* Removes the message from the status bar.
*/
public void clearMessage() {
setMessage("Ready.");
}
/**
* sets the icon in the status bar with a specified callback event.
*
* @param newIcon Icon to display
* @param newNotifier status error notifier to be notified for events on
* this error
*/
public void setError(final ImageIcon newIcon,
final StatusErrorNotifier newNotifier) {
addToHistory(newIcon, newNotifier);
iconLabel.setIcon(newIcon);
errorNotifier = newNotifier;
if (errorTimer != null && (System.currentTimeMillis() -
errorTimer.scheduledExecutionTime()) <= 0) {
errorTimer.cancel();
}
if (newIcon != normalIcon) {
int displayLength = 10000;
if (Config.hasOption("statusBar", "errorDisplayLength")) {
try {
displayLength = Integer.parseInt(
Config.getOption("statusBar", "errorDisplayLength"));
} catch (NumberFormatException e) {
Logger.error(ErrorLevel.WARNING, "Invalid error display length", e);
}
}
errorTimer = new TimerTask() {
public void run() {
clearError();
}
};
new Timer().schedule(errorTimer,
new Date(System.currentTimeMillis() + displayLength));
}
}
/**
* sets the icon in the status bar.
*
* @param newIcon Icon to display
*/
public void setError(final ImageIcon newIcon) {
setError(newIcon, null);
}
/**
* Removes the error state from the status bar.
*/
public void clearError() {
setError(normalIcon);
}
/**
* Invoked when a mouse button has been pressed on a component.
*
* @param mouseEvent mouse event
*/
public void mousePressed(final MouseEvent mouseEvent) {
processMouseEvent(mouseEvent);
}
/**
* Invoked when a mouse button has been released on a component.
*
* @param mouseEvent mouse event
*/
public void mouseReleased(final MouseEvent mouseEvent) {
processMouseEvent(mouseEvent);
}
/**
* Invoked when the mouse enters a component.
*
* @param mouseEvent mouse event
*/
public void mouseEntered(final MouseEvent mouseEvent) {
//Ignore.
}
/**
* Invoked when the mouse exits a component.
*
* @param mouseEvent mouse event
*/
public void mouseExited(final MouseEvent mouseEvent) {
//Ignore.
}
/**
* Invoked when the mouse button has been clicked (pressed and released)
* on a component.
*
* @param mouseEvent mouse event
*/
public void mouseClicked(final MouseEvent mouseEvent) {
if (mouseEvent.getSource() == messageLabel && messageNotifier != null) {
messageNotifier.clickReceived(mouseEvent);
} else if (mouseEvent.getSource() == iconLabel && errorNotifier != null) {
errorNotifier.clickReceived();
}
processMouseEvent(mouseEvent);
}
/**
* Processes every mouse button event to check for a popup trigger.
* @param e mouse event
*/
public void processMouseEvent(final MouseEvent e) {
if (e.isPopupTrigger() && e.getSource() == iconLabel) {
final Point point = this.getMousePosition();
popup.show(this, (int) point.getX(), (int) point.getY());
} else {
super.processMouseEvent(e);
}
}
/**
* Adds the error to the history.
* @param icon error icon
* @param notifier error notifier
*/
private void addToHistory(final Icon icon, final StatusErrorNotifier notifier) {
if (icon != null && notifier != null) {
JMenuItem mi;
final Error error = new Error(icon, notifier);
int errorHistory = 10;
if (Config.hasOption("statusBar", "errorHistory")) {
try {
errorHistory = Integer.parseInt(
Config.getOption("statusBar", "errorHistory"));
} catch (NumberFormatException ex) {
Logger.error(ErrorLevel.WARNING, "Invalid history size", ex);
}
}
errors.add(error);
popup.removeAll();
while (errors.size() >= errorHistory) {
errors.remove(0);
}
for (Error thisError : errors) {
mi = new JMenuItem(thisError.getDate().toString(), icon);
mi.addActionListener(this);
mi.setActionCommand(String.valueOf(errors.indexOf(thisError)));
popup.add(mi);
}
popup.addSeparator();
mi = new JMenuItem("Clear errors");
mi.addActionListener(this);
mi.setActionCommand("Clear");
popup.add(mi);
}
}
/**
* Shows the error from the history. {@inheritDoc}
*/
public void actionPerformed(final ActionEvent e) {
if ("Clear".equals(e.getActionCommand())) {
errors.clear();
popup.removeAll();
JMenuItem mi = new JMenuItem("No errors");
mi.addActionListener(this);
mi.setActionCommand("Clear");
popup.add(mi);
clearError();
} else if ("None".equals(e.getActionCommand())) {
//Ignore
} else {
errors.get(Integer.valueOf(e.getActionCommand())).getNotifier().clickReceived();
}
}
} |
package org.strongback.drive;
import org.strongback.annotation.Experimental;
import org.strongback.command.Command;
import org.strongback.command.Requirable;
import org.strongback.components.AngleSensor;
import org.strongback.components.Motor;
import org.strongback.components.Stoppable;
import org.strongback.function.DoubleToDoubleFunction;
import org.strongback.util.Values;
/**
* Control logic for a {@link MecanumDrive mecanum drive system}. This controller provides
* {@link #absoluteCartesian(double, double, double) cartesian} and {@link #relativePolar(double, double, double) polar} inputs.
* <p>
* This drive train will work for these configurations:
* <ul>
* <li>Mecanum - 4 mecanum wheels on the four corners of the robot; or</li>
* <li>Holonomic - 4 omni wheels arranged so that the front and back wheels are toed in 45 degrees, which form an X across the
* robot when viewed from above.</li>
* </ul>
* <p>
* This drive implements {@link Requirable} so that {@link Command}s can use it directly when {@link Command#execute()
* executing}. It is also designed to be driven by joystick axes.
*
* <p>
* <em>NOTE: This class is experimental and needs to be thoroughly tested and debugged using actual hardware.</em>
*
* @author Randall Hauch
*/
@Experimental
public class MecanumDrive implements Stoppable, Requirable {
public static final double DEFAULT_MINIMUM_SPEED = 0.02;
public static final double DEFAULT_MAXIMUM_SPEED = 1.0;
public static final DoubleToDoubleFunction DEFAULT_SPEED_LIMITER = Values.symmetricLimiter(DEFAULT_MINIMUM_SPEED,
DEFAULT_MAXIMUM_SPEED);
private static final double SQRT_OF_TWO = Math.sqrt(2.0);
private static final int NUMBER_OF_MOTORS = 4;
private static final int LEFT_FRONT = 0;
private static final int RIGHT_FRONT = 1;
private static final int LEFT_REAR = 2;
private static final int RIGHT_REAR = 3;
private static final double OUTPUT_SCALE_FACTOR = 1.0;
private final Motor leftFront;
private final Motor leftRear;
private final Motor rightFront;
private final Motor rightRear;
private final AngleSensor gyro;
private final DoubleToDoubleFunction speedLimiter;
/**
* Creates a new DriveSystem subsystem that uses the supplied drive train and no shifter. The voltage send to the drive
* train is limited to [-1.0,1.0].
*
* @param leftFront the left front motor on the drive train for the robot; may not be null
* @param leftRear the left rear motor on the drive train for the robot; may not be null
* @param rightFront the right front motor on the drive train for the robot; may not be null
* @param rightRear the right rear motor on the drive train for the robot; may not be null
* @param gyro the gyroscope that will be used to determine the robot's direction for field-orientated controls; may not be
* null
*/
public MecanumDrive(Motor leftFront, Motor leftRear, Motor rightFront, Motor rightRear, AngleSensor gyro) {
this(leftFront, leftRear, rightFront, rightRear, gyro, null);
}
/**
* Creates a new DriveSystem subsystem that uses the supplied drive train and optional shifter. The voltage send to the
* drive train is limited by the given function.
*
* @param leftFront the left front motor on the drive train for the robot; may not be null
* @param leftRear the left rear motor on the drive train for the robot; may not be null
* @param rightFront the right front motor on the drive train for the robot; may not be null
* @param rightRear the right rear motor on the drive train for the robot; may not be null
* @param gyro the gyroscope that will be used to determine the robot's direction for field-orientated controls; may not be
* null
* @param speedLimiter the function that limits the speed sent to the drive train; if null, then a default clamping function
* is used to limit to the range [-1.0,1.0]
*/
public MecanumDrive(Motor leftFront, Motor leftRear, Motor rightFront, Motor rightRear, AngleSensor gyro,
DoubleToDoubleFunction speedLimiter) {
this.leftFront = leftFront;
this.leftRear = leftRear;
this.rightFront = rightFront;
this.rightRear = rightRear;
this.gyro = gyro;
this.speedLimiter = speedLimiter != null ? speedLimiter : DEFAULT_SPEED_LIMITER;
}
/**
* Stop the drive train. This sets all motors to 0.
*/
@Override
public void stop() {
leftFront.stop();
rightFront.stop();
leftRear.stop();
rightRear.stop();
}
/**
* Does the same as {@link #absoluteCartesian(double, double, double)}.
*
* @deprecated in favor of {@link #absoluteCartesian(double, double, double)}. Kept for backwards compatibility.
*/
@Deprecated
public void cartesian(double x, double y, double rotation) {
absoluteCartesian(x, y, rotation);
}
/**
* Does the same as {@link #relativePolar(double, double, double)}.
*
* @deprecated in favor of {@link #relativePolar(double, double, double)}. Kept for backwards compatibility.
*/
@Deprecated
public void polar(double magnitude, double direction, double rotation) {
relativePolar(magnitude, direction, rotation);
}
/**
* Cartesian drive method that specifies speeds in terms of the field longitudinal and lateral directions, using the drive's
* angle sensor to automatically determine the robot's orientation relative to the field.
* <p>
* Using this method, the robot will move away from the drivers when the joystick is pushed forwards, and towards the
* drivers when it is pulled towards them - regardless of what direction the robot is facing.
*
* @param x The speed that the robot should drive in the X (horizontal) direction. Positive is right. [-1.0..1.0]
* @param y The speed that the robot should drive in the Y (vertical) direction. Positive is forward. [-1.0..1.0]
* @param rotation The rate of rotation for the robot that is completely independent of the translation. Positive is
* counter-clockwise. [-1.0..1.0]
*/
public void absoluteCartesian(double x, double y, double rotation) {
// Compensate for gyro angle.
double rotated[] = rotateVector(x, y, -gyro.getAngle());
relativeCartesian(rotated[0], rotated[1], rotation);
}
/**
* Polar drive method that specifies speeds in terms of magnitude and direction, using the drive's
* angle sensor so calculations compensate for the robot's orientation.
*
* @param magnitude The speed that the robot should drive in a given direction.
* @param direction The direction the robot should drive in degrees. The direction and magnitude are independent of the
* rotation rate. Zero is away from the drivers; positive is counterclockwise.
* @param rotation The rate of rotation for the robot that is completely independent of the magnitude or direction.
* Positive is counter-clockwise. [-1.0..1.0]
*/
public void absolutePolar(double magnitude, double direction, double rotation) {
relativePolar(magnitude, direction - gyro.getAngle(), rotation);
}
/**
* Cartesian drive method that specifies speeds in terms of the robot's relative coordinate system.
* <p>
* Using this method, the robot will drive similar to conventional driving. Pushing the stick forward will make the
* robot drive front-first, backward causes it to drive rear-first.
*
* @param x The speed that the robot should drive in the X (horizontal) direction. Positive is right. [-1.0..1.0]
* @param y The speed that the robot should drive in the Y (vertical) direction. Positive is forward. [-1.0..1.0]
* @param rotation The rate of rotation for the robot that is completely independent of the translation. Positive is
* counter-clockwise. [-1.0..1.0]
*/
public void relativeCartesian(double x, double y, double rotation) {
double wheelSpeeds[] = new double[NUMBER_OF_MOTORS];
wheelSpeeds[LEFT_FRONT] = -x + y + rotation;
wheelSpeeds[RIGHT_FRONT] = x + y - rotation;
wheelSpeeds[LEFT_REAR] = x + y + rotation;
wheelSpeeds[RIGHT_REAR] = -x + y - rotation;
normalize(wheelSpeeds);
scale(wheelSpeeds, OUTPUT_SCALE_FACTOR);
leftFront.setSpeed(wheelSpeeds[LEFT_FRONT]);
leftRear.setSpeed(wheelSpeeds[LEFT_REAR]);
rightFront.setSpeed(wheelSpeeds[RIGHT_FRONT]);
rightRear.setSpeed(wheelSpeeds[RIGHT_REAR]);
}
/**
* Polar drive method that specifies speeds in terms of magnitude and direction. This method does not use the drive's angle
* sensor.
*
* @param magnitude The speed that the robot should drive in a given direction.
* @param direction The direction the robot should drive in degrees. The direction and magnitude are independent of the
* rotation rate. Zero degrees is forward; positive is counterclockwise.
* @param rotation The rate of rotation for the robot that is completely independent of the magnitude or direction.
* Positive is counter-clockwise. [-1.0..1.0]
*/
public void relativePolar(double magnitude, double direction, double rotation) {
// Normalized for full power along the Cartesian axes.
magnitude = speedLimiter.applyAsDouble(magnitude) * SQRT_OF_TWO;
// The rollers are at 45 degree angles.
double dirInRad = Math.toRadians(direction + 45.0);
double cosD = Math.cos(dirInRad);
double sinD = Math.sin(dirInRad);
double wheelSpeeds[] = new double[NUMBER_OF_MOTORS];
wheelSpeeds[LEFT_FRONT] = (sinD * magnitude + rotation);
wheelSpeeds[RIGHT_FRONT] = (cosD * magnitude - rotation);
wheelSpeeds[LEFT_REAR] = (cosD * magnitude + rotation);
wheelSpeeds[RIGHT_REAR] = (sinD * magnitude - rotation);
normalize(wheelSpeeds);
scale(wheelSpeeds, OUTPUT_SCALE_FACTOR);
leftFront.setSpeed(wheelSpeeds[LEFT_FRONT]);
leftRear.setSpeed(wheelSpeeds[LEFT_REAR]);
rightFront.setSpeed(wheelSpeeds[RIGHT_FRONT]);
rightRear.setSpeed(wheelSpeeds[RIGHT_REAR]);
}
/**
* Normalize all wheel speeds if the magnitude of any wheel is greater than 1.0.
* @param wheelSpeeds the speed of each motor
*/
protected static void normalize(double wheelSpeeds[]) {
double maxMagnitude = Math.abs(wheelSpeeds[0]);
for (int i = 1; i < NUMBER_OF_MOTORS; i++) {
double temp = Math.abs(wheelSpeeds[i]);
if (maxMagnitude < temp) maxMagnitude = temp;
}
if (maxMagnitude > 1.0) {
for (int i = 0; i < NUMBER_OF_MOTORS; i++) {
wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude;
}
}
}
/**
* Scale all speeds.
* @param wheelSpeeds the speed of each motor
* @param scaleFactor the scale factor to apply to the motor speeds
*/
protected static void scale(double wheelSpeeds[], double scaleFactor) {
for (int i = 1; i < NUMBER_OF_MOTORS; i++) {
wheelSpeeds[i] = wheelSpeeds[i] * scaleFactor;
}
}
/**
* Rotate a vector in Cartesian space.
* @param x the x value of the vector
* @param y the y value of the vector
* @param angle the angle to rotate
* @return the vector of x and y values
*/
protected static double[] rotateVector(double x, double y, double angle) {
double angleInRadians = Math.toRadians(angle);
double cosA = Math.cos(angleInRadians);
double sinA = Math.sin(angleInRadians);
double out[] = new double[2];
out[0] = x * cosA - y * sinA;
out[1] = x * sinA + y * cosA;
return out;
}
} |
package afc.ant.modular;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.PropertyHelper;
import org.apache.tools.ant.types.Path;
import junit.framework.TestCase;
// TODO test multiple classpath attributes
public class GetModuleClasspathTest extends TestCase
{
private GetModuleClasspath task;
private Project project;
@Override
protected void setUp()
{
task = new GetModuleClasspath();
project = new Project();
task.setProject(project);
}
@Override
protected void tearDown()
{
project = null;
task = null;
}
public void testNoModuleProperty()
{
task.setOutputProperty("out");
task.setSourceAttribute("cp");
try {
task.execute();
fail();
}
catch (BuildException ex)
{
assertEquals("The attribute 'moduleProperty' is undefined.", ex.getMessage());
}
assertEquals(null, PropertyHelper.getProperty(project, "out"));
}
public void testNoOutputProperty()
{
final Module module = new Module("foo");
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setSourceAttribute("cp");
try {
task.execute();
fail();
}
catch (BuildException ex)
{
assertEquals("The attribute 'outputProperty' is undefined.", ex.getMessage());
}
assertSame(module, PropertyHelper.getProperty(project, "in"));
}
public void testNoClasspathAttributes()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
try {
task.execute();
fail();
}
catch (BuildException ex)
{
assertEquals("Source attributes are not defined.", ex.getMessage());
}
assertEquals(null, PropertyHelper.getProperty(project, "out"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
}
public void testClasspathAttributeWithUndefinedName_SingleAttribute()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
PropertyHelper.setProperty(project, "in", module);
task.setSourceAttribute(null);
task.setModuleProperty("in");
task.setOutputProperty("out");
try {
task.execute();
fail();
}
catch (BuildException ex)
{
assertEquals("A source attribute with undefined name is specified.", ex.getMessage());
}
assertEquals(null, PropertyHelper.getProperty(project, "out"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
}
public void testClasspathAttributeWithUndefinedName_MultipleAttributes()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
PropertyHelper.setProperty(project, "in", module);
task.createSourceAttribute().setName("foo");
task.createSourceAttribute().setName(null);
task.setModuleProperty("in");
task.setOutputProperty("out");
try {
task.execute();
fail();
}
catch (BuildException ex)
{
assertEquals("A source attribute with undefined name is specified.", ex.getMessage());
}
assertEquals(null, PropertyHelper.getProperty(project, "out"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
}
public void testNoModuleUnderThePropery()
{
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
try {
task.execute();
fail();
}
catch (BuildException ex)
{
assertEquals("No module is found under the property 'in'.", ex.getMessage());
}
assertEquals(null, PropertyHelper.getProperty(project, "out"));
assertSame(null, PropertyHelper.getProperty(project, "in"));
}
public void testInvalidModuleType()
{
final Object invalidModule = Long.valueOf(0);
PropertyHelper.setProperty(project, "in", invalidModule);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
try {
task.execute();
fail();
}
catch (BuildException ex)
{
assertEquals("Invalid module type is found under the property 'in'. " +
"Expected: 'afc.ant.modular.Module', found: 'java.lang.Long'.", ex.getMessage());
}
assertEquals(null, PropertyHelper.getProperty(project, "out"));
assertSame(invalidModule, PropertyHelper.getProperty(project, "in"));
}
public void testSingleClasspathAttribute_ClasspathPropertyWithWrongType()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3", "cp", "12345"));
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
try {
task.execute();
fail();
}
catch (BuildException ex) {
assertEquals("The attribute 'cp' of the module 'foo' is not an Ant path.", ex.getMessage());
}
assertEquals(null, PropertyHelper.getProperty(project, "out"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3", "cp", "12345"), module.getAttributes());
}
public void testSingleClasspathAttribute_DependeeModuleWithCPPropertyWithWrongType()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
final Module dep = new Module("bar");
dep.setAttributes(TestUtil.map("cp", Integer.valueOf(2)));
module.addDependency(dep);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.setIncludeDependencies(true);
try {
task.execute();
fail();
}
catch (BuildException ex) {
assertEquals("The attribute 'cp' of the module 'bar' is not an Ant path.", ex.getMessage());
}
assertEquals(null, PropertyHelper.getProperty(project, "out"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
assertEquals(TestUtil.map("cp", Integer.valueOf(2)), dep.getAttributes());
}
public void testSingleClasspathAttribute_DependeeModuleWithCPPropertyWithWrongType_DepsNotIncludedImplicitly()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
final Module dep = new Module("bar");
dep.setAttributes(TestUtil.map("cp", Integer.valueOf(2)));
module.addDependency(dep);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
final Path classpath = (Path) outObject;
assertEquals(0, classpath.size());
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
assertEquals(TestUtil.map("cp", Integer.valueOf(2)), dep.getAttributes());
}
public void testSingleClasspathAttribute_NoClasspathProperty_NoDependencies()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
final Path classpath = (Path) outObject;
assertEquals(0, classpath.size());
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
}
public void testSingleClasspathAttribute_NoClasspathProperty_NoDependencies_OutputPropertyAlreadyDefined()
{
final Object value = new Object();
PropertyHelper.setProperty(project, "out", value);
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.execute();
assertSame(value, PropertyHelper.getProperty(project, "out"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
}
public void testSingleClasspathAttribute_NoClasspathProperty_WithDependencies()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
final Module dep1 = new Module("bar");
dep1.setAttributes(TestUtil.map("x", "y"));
module.addDependency(dep1);
final Module dep2 = new Module("bar");
dep2.setAttributes(TestUtil.map("b", "c"));
module.addDependency(dep2);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
final Path classpath = (Path) outObject;
assertEquals(0, classpath.size());
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
assertEquals(TestUtil.map("x", "y"), dep1.getAttributes());
assertEquals(TestUtil.map("b", "c"), dep2.getAttributes());
}
public void testSingleClasspathAttribute_NoClasspathProperty_DependencyLoop()
{
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3"));
final Module dep1 = new Module("bar");
dep1.setAttributes(TestUtil.map("x", "y"));
module.addDependency(dep1);
final Module dep2 = new Module("bar");
dep2.setAttributes(TestUtil.map("b", "c"));
dep1.addDependency(dep2);
dep2.addDependency(module);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
final Path classpath = (Path) outObject;
assertEquals(0, classpath.size());
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3"), module.getAttributes());
assertEquals(TestUtil.map("x", "y"), dep1.getAttributes());
assertEquals(TestUtil.map("b", "c"), dep2.getAttributes());
}
public void testSingleClasspathAttribute_WithClasspathProperty_SingleModule()
{
final Path path = new Path(project);
path.createPathElement().setPath("a");
path.createPathElement().setPath("b");
path.createPathElement().setPath("c/d/e");
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path));
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
assertClasspath((Path) outObject, new File("a"), new File("b"), new File("c/d/e"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path), module.getAttributes());
}
public void testSingleClasspathAttribute_WithClasspathProperty_ModuleWithSingleDependency_DepsIncluded()
{
final Path path1 = new Path(project);
path1.createPathElement().setPath("b");
path1.createPathElement().setPath("a");
path1.createPathElement().setPath("c/d/e");
final Path path2 = new Path(project);
path2.createPathElement().setPath("88/ee");
path2.createPathElement().setPath("555");
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path1));
final Module dep = new Module("bar");
dep.setAttributes(TestUtil.map("cp", path2, "1", "2"));
module.addDependency(dep);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.setIncludeDependencies(true);
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
assertClasspath((Path) outObject, new File("b"), new File("a"), new File("c/d/e"),
new File("88/ee"), new File("555"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path1), module.getAttributes());
assertEquals(TestUtil.map("cp", path2, "1", "2"), dep.getAttributes());
}
public void testSingleClasspathAttribute_WithClasspathProperty_ModuleWithSingleDependency_DepsNotIncluded()
{
final Path path1 = new Path(project);
path1.createPathElement().setPath("b");
path1.createPathElement().setPath("a");
path1.createPathElement().setPath("c/d/e");
final Path path2 = new Path(project);
path2.createPathElement().setPath("88/ee");
path2.createPathElement().setPath("555");
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path1));
final Module dep = new Module("bar");
dep.setAttributes(TestUtil.map("cp", path2, "1", "2"));
module.addDependency(dep);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.setIncludeDependencies(false);
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
assertClasspath((Path) outObject, new File("b"), new File("a"), new File("c/d/e"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path1), module.getAttributes());
assertEquals(TestUtil.map("cp", path2, "1", "2"), dep.getAttributes());
}
public void testSingleClasspathAttribute_WithClasspathProperty_ModuleWithSingleDependency_DefaultDepsIncluded()
{
final Path path1 = new Path(project);
path1.createPathElement().setPath("b");
path1.createPathElement().setPath("a");
path1.createPathElement().setPath("c/d/e");
final Path path2 = new Path(project);
path2.createPathElement().setPath("88/ee");
path2.createPathElement().setPath("555");
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path1));
final Module dep = new Module("bar");
dep.setAttributes(TestUtil.map("cp", path2, "1", "2"));
module.addDependency(dep);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
assertClasspath((Path) outObject, new File("b"), new File("a"), new File("c/d/e"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path1), module.getAttributes());
assertEquals(TestUtil.map("cp", path2, "1", "2"), dep.getAttributes());
}
public void testSingleClasspathAttribute_CyclingDependency()
{
final Path path1 = new Path(project);
path1.createPathElement().setPath("b");
path1.createPathElement().setPath("a");
path1.createPathElement().setPath("c/d/e");
final Path path2 = new Path(project);
path2.createPathElement().setPath("88/ee");
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path1));
final Module dep = new Module("bar");
dep.setAttributes(TestUtil.map("cp", path2, "1", "2"));
module.addDependency(dep);
dep.addDependency(module);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.setIncludeDependencies(true);
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
assertClasspath((Path) outObject, new File("b"), new File("a"), new File("c/d/e"), new File("88/ee"));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("attrib", "1", "attrib2", "3", "cp", path1), module.getAttributes());
assertEquals(TestUtil.map("cp", path2, "1", "2"), dep.getAttributes());
}
public void testSingleClasspathAttribute_DiamondDependencyStructure()
{
final Path path1 = new Path(project);
path1.createPathElement().setPath("b");
path1.createPathElement().setPath("a");
path1.createPathElement().setPath("c/d/e");
final Path path2 = new Path(project);
path2.createPathElement().setPath("88/ee");
final Path path3 = new Path(project);
path3.createPathElement().setPath("aaa");
final Path path4 = new Path(project);
path4.createPathElement().setPath("bbb");
path4.createPathElement().setPath("555");
final Module module = new Module("foo");
module.setAttributes(TestUtil.map("cp", path1));
final Module dep1 = new Module("bar");
dep1.setAttributes(TestUtil.map("cp", path2, "1", "2"));
final Module dep2 = new Module("bar");
dep2.setAttributes(TestUtil.map("cp", path3));
final Module dep3 = new Module("bar");
dep3.setAttributes(TestUtil.map("cp", path4));
module.addDependency(dep1);
module.addDependency(dep2);
dep1.addDependency(dep3);
dep2.addDependency(dep3);
PropertyHelper.setProperty(project, "in", module);
task.setModuleProperty("in");
task.setOutputProperty("out");
task.setSourceAttribute("cp");
task.setIncludeDependencies(true);
task.execute();
final Object outObject = PropertyHelper.getProperty(project, "out");
assertTrue(outObject instanceof Path);
assertClasspath((Path) outObject, new File[]{new File("b"), new File("a"), new File("c/d/e")},
TestUtil.set(new File("88/ee"), new File("555"), new File("aaa"), new File("bbb")));
assertSame(module, PropertyHelper.getProperty(project, "in"));
assertEquals(TestUtil.map("cp", path1), module.getAttributes());
assertEquals(TestUtil.map("cp", path2, "1", "2"), dep1.getAttributes());
assertEquals(TestUtil.map("cp", path3), dep2.getAttributes());
assertEquals(TestUtil.map("cp", path4), dep3.getAttributes());
}
private void assertClasspath(final Path classpath, final File... elements)
{
assertNotNull(classpath);
final String[] locations = classpath.list();
assertEquals(elements.length, locations.length);
for (int i = 0; i < locations.length; ++i) {
assertEquals(elements[i].getAbsolutePath(), locations[i]);
}
}
// Primary elements are the paths defined in the main module. Other elements are the other paths.
private void assertClasspath(final Path classpath, final File[] primaryElements, final Set<File> otherElements)
{
assertNotNull(classpath);
final String[] locations = classpath.list();
assertEquals(primaryElements.length + otherElements.size(), locations.length);
for (int i = 0; i < primaryElements.length; ++i) {
assertEquals(primaryElements[i].getAbsolutePath(), locations[i]);
}
final HashSet<String> actualOtherElements = new HashSet<String>();
for (int i = primaryElements.length; i < locations.length; ++i) {
actualOtherElements.add(locations[i]);
}
assertEquals(otherElements.size(), actualOtherElements.size());
for (final File e : otherElements) {
assertTrue(actualOtherElements.contains(e.getAbsolutePath()));
}
}
} |
package alluxio;
import alluxio.client.file.FileSystemMasterClient;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import java.util.Random;
/**
* Util methods for writing integration tests.
*/
public final class IntegrationTestUtils {
/**
* Convenience method for calling {@link #waitForPersist(LocalAlluxioClusterResource, long, long)}
* with a default timeout.
*
* @param localAlluxioClusterResource the cluster for the worker that will persist the file
* @param uri the file uri to wait to be persisted
*/
public static void waitForPersist(LocalAlluxioClusterResource localAlluxioClusterResource,
AlluxioURI uri) {
waitForPersist(localAlluxioClusterResource, uri, 15 * Constants.SECOND_MS);
}
/**
* Blocks until the specified file is persisted or a timeout occurs.
*
* @param localAlluxioClusterResource the cluster for the worker that will persist the file
* @param uri the uri to wait to be persisted
* @param timeoutMs the number of milliseconds to wait before giving up and throwing an exception
*/
public static void waitForPersist(final LocalAlluxioClusterResource localAlluxioClusterResource,
final AlluxioURI uri, int timeoutMs) {
final FileSystemMasterClient client =
new FileSystemMasterClient(localAlluxioClusterResource.get().getMaster().getAddress(),
localAlluxioClusterResource.getTestConf());
try {
CommonTestUtils.waitFor(new Function<Void, Boolean>() {
@Override
public Boolean apply(Void input) {
try {
return client.getStatus(uri).isPersisted();
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}, timeoutMs);
} finally {
client.close();
}
}
/**
* @return a random sequence of characters from 'a' to 'z' of random length up to 100 characters
*/
public static String randomString() {
Random random = new Random();
int length = random.nextInt(100) + 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append((char) (random.nextInt(26) + 97));
}
return sb.toString();
}
private IntegrationTestUtils() {} // This is a utils class not intended for instantiation
} |
package com.intellij.ide.actions;
import com.intellij.CommonBundle;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.util.IconLoader;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class ContextHelpAction extends AnAction {
private static final Icon myIcon=IconLoader.getIcon("/actions/help.png");
private final String myHelpID;
public ContextHelpAction() {
this(null);
}
public ContextHelpAction(@NonNls String helpID) {
myHelpID = helpID;
}
public void actionPerformed(AnActionEvent e) {
DataContext dataContext = e.getDataContext();
final String helpId = getHelpId(dataContext);
if (helpId != null) {
HelpManager.getInstance().invokeHelp(helpId);
}
}
@Nullable
protected String getHelpId(DataContext dataContext) {
if (myHelpID != null) {
return myHelpID;
}
Object helpIDObj = dataContext.getData(DataConstants.HELP_ID);
if (helpIDObj != null) {
return helpIDObj.toString();
}
return null;
}
public void update(AnActionEvent event){
Presentation presentation = event.getPresentation();
if (ActionPlaces.MAIN_MENU.equals(event.getPlace())) {
DataContext dataContext = event.getDataContext();
presentation.setEnabled(getHelpId(dataContext) != null);
}
else {
presentation.setIcon(myIcon);
presentation.setText(CommonBundle.getHelpButtonText());
}
}
} |
package com.intellij.util;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.ResolveResult;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadLocalRandom;
public class IdempotenceChecker {
private static final Logger LOG = Logger.getInstance(IdempotenceChecker.class);
private static final Set<Class> ourReportedValueClasses = Collections.synchronizedSet(ContainerUtil.newTroveSet());
private static final RecursionGuard ourGuard = RecursionManager.createGuard("IdempotenceChecker");
private static final ThreadLocal<Integer> ourRandomCheckNesting = ThreadLocal.withInitial(() -> 0);
private static final RegistryValue ourRateCheckProperty = Registry.get("platform.random.idempotence.check.rate");
/**
* Perform some basic checks whether the two given objects are equivalent and interchangeable,
* as described in e.g {@link com.intellij.psi.util.CachedValue} contract. This method should be used
* in places caching results of various computations, which are expected to be idempotent:
* they can be performed several times, or on multiple threads, and the results should be interchangeable.<p></p>
*
* What to do if you get an error from here:
* <ul>
* <li>
* Start by looking carefully at the computation (which usually can be found by navigating the stack trace)
* and find out why it could be non-idempotent. See common culprits below.</li>
* <li>
* If the computation is complex and depends on other caches, you could try to perform
* {@code IdempotenceChecker.checkEquivalence()} for their results as well, localizing the error.</li>
* <li>
* If it's a test, you could try reproducing and debugging it. To increase the probability of failure,
* you can temporarily add {@code Registry.get("platform.random.idempotence.check.rate").setValue(1, getTestRootDisposable())}
* to perform the idempotence check on every cache access. Note that this can make your test much slower.
* </li>
* </ul>
*
* Common culprits:
* <ul>
* <li>Caching and returning a mutable object (e.g. array or List), which clients then mutate from different threads;
* to fix, either clone the return value or use unmodifiable wrappers</li>
* <li>Depending on a {@link ThreadLocal} or method parameters with different values.</li>
* <li>For failures from {@link #applyForRandomCheck}: outdated cached value (not all dependencies are specified, or their modification counters aren't properly incremented)</li>
* </ul>
*
* @param existing the value computed on the first invocation
* @param fresh the value computed a bit later, expected to be equivalent
* @param providerClass a class of the function performing the computation, used to prevent reporting the same error multiple times
*/
public static <T> void checkEquivalence(@Nullable T existing, @Nullable T fresh, @NotNull Class providerClass) {
String s = checkValueEquivalence(existing, fresh);
if (s != null &&
ourReportedValueClasses.add(providerClass)) {
LOG.error(s);
}
}
private static String objAndClass(Object o) {
if (o == null) return "null";
String s = o.toString();
return s.contains(o.getClass().getSimpleName()) || o instanceof String || o instanceof Number || o instanceof Class
? s
: s + " (class " + o.getClass().getName() + ")";
}
private static String checkValueEquivalence(@Nullable Object existing, @Nullable Object fresh) {
if (existing == fresh) return null;
String eqMsg = checkClassEquivalence(existing, fresh);
if (eqMsg != null) return eqMsg;
Object[] eArray = asArray(existing);
if (eArray != null) {
return checkArrayEquivalence(eArray, Objects.requireNonNull(asArray(fresh)), existing);
}
if (existing instanceof CachedValueBase.Data) {
return checkCachedValueData((CachedValueBase.Data)existing, (CachedValueBase.Data)fresh);
}
if (existing instanceof List || isOrderedSet(existing)) {
return checkCollectionElements((Collection)existing, (Collection)fresh);
}
if (isOrderedMap(existing)) {
return checkCollectionElements(((Map)existing).entrySet(), ((Map)fresh).entrySet());
}
if (existing instanceof Set) {
return whichIsField("size", existing, fresh, checkCollectionSizes(((Set)existing).size(), ((Set)fresh).size()));
}
if (existing instanceof Map) {
if (existing instanceof ConcurrentMap) {
return null; // likely to be filled lazily
}
return whichIsField("size", existing, fresh, checkCollectionSizes(((Map)existing).size(), ((Map)fresh).size()));
}
if (existing instanceof PsiNamedElement) {
return checkPsiEquivalence((PsiElement)existing, (PsiElement)fresh);
}
if (existing instanceof ResolveResult) {
PsiElement existingPsi = ((ResolveResult)existing).getElement();
PsiElement freshPsi = ((ResolveResult)fresh).getElement();
if (existingPsi != freshPsi) {
String s = checkClassEquivalence(existingPsi, freshPsi);
if (s == null) s = checkPsiEquivalence(existingPsi, freshPsi);
return whichIsField("element", existing, fresh, s);
}
return null;
}
if (isExpectedToHaveSaneEquals(existing) && !existing.equals(fresh)) {
return reportProblem(existing, fresh);
}
return null;
}
private static boolean isOrderedMap(Object o) {
return o instanceof LinkedHashMap || o instanceof SortedMap;
}
private static boolean isOrderedSet(Object o) {
return o instanceof LinkedHashSet || o instanceof SortedSet;
}
private static String whichIsField(@NotNull String field, @NotNull Object existing, @NotNull Object fresh, @Nullable String msg) {
return msg == null ? null : appendDetail(msg, "which is " + field + " of " + existing + " and " + fresh);
}
@Nullable
private static Object[] asArray(Object o) {
if (o instanceof Object[]) return (Object[])o;
if (o instanceof Map.Entry) return new Object[]{((Map.Entry)o).getKey(), ((Map.Entry)o).getValue()};
if (o instanceof Pair) return new Object[]{((Pair)o).first, ((Pair)o).second};
if (o instanceof Trinity) return new Object[]{((Trinity)o).first, ((Trinity)o).second, ((Trinity)o).third};
return null;
}
private static String checkCachedValueData(@NotNull CachedValueBase.Data existing, @NotNull CachedValueBase.Data fresh) {
Object[] deps1 = existing.getDependencies();
Object[] deps2 = fresh.getDependencies();
Object eValue = existing.get();
Object fValue = fresh.get();
if (deps1 != null && deps2 != null && deps1.length != deps2.length) {
String msg = reportProblem(deps1.length, deps2.length);
msg = appendDetail(msg, "which is length of CachedValue dependencies: " + Arrays.toString(deps1) + " and " + Arrays.toString(deps2));
msg = appendDetail(msg, "where values are " + objAndClass(eValue) + " and " + objAndClass(fValue));
return msg;
}
return checkValueEquivalence(eValue, fValue);
}
private static boolean isExpectedToHaveSaneEquals(@NotNull Object existing) {
return existing instanceof Comparable;
}
@Contract("null,_->!null;_,null->!null")
private static String checkClassEquivalence(@Nullable Object existing, @Nullable Object fresh) {
if (existing == null || fresh == null) {
return reportProblem(existing, fresh);
}
Class<?> c1 = existing.getClass();
Class<?> c2 = fresh.getClass();
if (c1 != c2 && !objectsOfDifferentClassesCanStillBeEquivalent(existing, fresh)) {
return whichIsField("class", existing, fresh, reportProblem(c1, c2));
}
return null;
}
private static boolean objectsOfDifferentClassesCanStillBeEquivalent(@NotNull Object existing, @NotNull Object fresh) {
if (existing instanceof Map && fresh instanceof Map && isOrderedMap(existing) == isOrderedMap(fresh)) return true;
if (existing instanceof Set && fresh instanceof Set && isOrderedSet(existing) == isOrderedSet(fresh)) return true;
if (existing instanceof List && fresh instanceof List) return true;
return false;
}
private static String checkPsiEquivalence(@NotNull PsiElement existing, @NotNull PsiElement fresh) {
if (!existing.equals(fresh) &&
!existing.isEquivalentTo(fresh) && !fresh.isEquivalentTo(existing) &&
(seemsToBeResolveTarget(existing) || seemsToBeResolveTarget(fresh))) {
return reportProblem(existing, fresh);
}
return null;
}
private static boolean seemsToBeResolveTarget(@NotNull PsiElement psi) {
if (psi.isPhysical()) return true;
PsiElement nav = psi.getNavigationElement();
return nav != null && nav.isPhysical();
}
private static String checkCollectionElements(@NotNull Collection existing, @NotNull Collection fresh) {
if (fresh.isEmpty()) {
return null; // for cases when an empty collection is cached and then filled lazily on request
}
return checkArrayEquivalence(existing.toArray(), fresh.toArray(), existing);
}
private static String checkCollectionSizes(int size1, int size2) {
if (size2 == 0) {
return null; // for cases when an empty collection is cached and then filled lazily on request
}
if (size1 != size2) {
return reportProblem(size1, size2);
}
return null;
}
private static String checkArrayEquivalence(Object[] a1, Object[] a2, Object original1) {
int len1 = a1.length;
int len2 = a2.length;
if (len1 != len2) {
return appendDetail(reportProblem(len1, len2), "which is length of " + Arrays.toString(a1) + " and " + Arrays.toString(a2));
}
for (int i = 0; i < len1; i++) {
String msg = checkValueEquivalence(a1[i], a2[i]);
if (msg != null) {
return whichIsField(original1 instanceof Map.Entry ? (i == 0 ? "key" : "value") : i + "th element",
Arrays.toString(a1), Arrays.toString(a2), msg);
}
}
return null;
}
private static String reportProblem(Object o1, Object o2) {
return appendDetail("Non-idempotent computation: it returns different results when invoked multiple times or on different threads:",
objAndClass(o1) + " != " + objAndClass(o2));
}
private static String appendDetail(String message, String detail) {
return message + "\n " + StringUtil.trimLog(detail, 10_000);
}
/**
* @return whether random checks are enabled and it makes sense to call a potentially expensive {@link #applyForRandomCheck} at all.
*/
public static boolean areRandomChecksEnabled() {
return ApplicationManager.getApplication().isUnitTestMode() && !ApplicationInfoImpl.isInStressTest();
}
/**
* Call this when accessing an already cached value, so that once in a while
* (depending on "platform.random.idempotence.check.rate" registry value)
* the computation is re-run and checked for consistency with that cached value.
*/
public static <T> void applyForRandomCheck(T data, Object provider, Computable<? extends T> recomputeValue) {
if (areRandomChecksEnabled() && shouldPerformRandomCheck()) {
RecursionGuard.StackStamp stamp = ourGuard.markStack();
Integer prevNesting = ourRandomCheckNesting.get();
ourRandomCheckNesting.set(prevNesting + 1);
try {
T fresh = recomputeValue.compute();
if (stamp.mayCacheNow()) {
checkEquivalence(data, fresh, provider.getClass());
}
}
finally {
ourRandomCheckNesting.set(prevNesting);
}
}
}
private static boolean shouldPerformRandomCheck() {
int rate = ourRateCheckProperty.asInteger();
return rate > 0 && ThreadLocalRandom.current().nextInt(rate) == 0;
}
@TestOnly
public static boolean isCurrentThreadInsideRandomCheck() {
return ourRandomCheckNesting.get() > 0;
}
} |
package org.mockito.runners;
import static org.mockito.Mockito.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.InitializationError;
import org.mockito.Mock;
import org.mockito.internal.debugging.DebuggingInfo;
import org.mockito.internal.progress.ThreadSafeMockingProgress;
import org.mockito.internal.util.MockitoLoggerImpl;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
public class VerboseMockitoJUnitRunnerTest extends TestBase {
@Mock private IMethods mock;
private VerboseMockitoJUnitRunner runner;
private MockitoLoggerStub loggerStub;
private RunNotifier notifier;
@Before
public void setup() throws InitializationError {
loggerStub = new MockitoLoggerStub();
notifier = new RunNotifier();
runner = new VerboseMockitoJUnitRunner(this.getClass(), loggerStub);
}
@Test
public void shouldLogUnusedStubbingWarningWhenTestFails() throws Exception {
runner = new VerboseMockitoJUnitRunner(this.getClass(), loggerStub) {
@Override
public void runTest(RunNotifier notifier) {
//this is what happens when the test runs:
//first, unused stubbing:
unusedStubbingThatQualifiesForWarning();
//then, let's make the test fail so that warnings are printed
notifier.fireTestFailure(null);
//assert
String loggedInfo = loggerStub.getLoggedInfo();
assertContains("[Mockito] Warning - this stub was not used", loggedInfo);
assertContains("mock.simpleMethod(123);", loggedInfo);
assertContains(".unusedStubbingThatQualifiesForWarning(", loggedInfo);
}
};
runner.run(notifier);
}
@Test
public void shouldLogUnstubbedMethodWarningWhenTestFails() throws Exception {
runner = new VerboseMockitoJUnitRunner(this.getClass(), loggerStub) {
@Override
public void runTest(RunNotifier notifier) {
callUnstubbedMethodThatQualifiesForWarning();
notifier.fireTestFailure(null);
String loggedInfo = loggerStub.getLoggedInfo();
assertContains("[Mockito] Warning - this method was not stubbed", loggedInfo);
assertContains("mock.simpleMethod(456);", loggedInfo);
assertContains(".callUnstubbedMethodThatQualifiesForWarning(", loggedInfo);
}
};
runner.run(notifier);
}
@Test
public void shouldLogStubCalledWithDifferentArgumentsWhenTestFails() throws Exception {
runner = new VerboseMockitoJUnitRunner(this.getClass(), loggerStub) {
@Override
public void runTest(RunNotifier notifier) {
someStubbing();
callStubbedMethodWithDifferentArgs();
notifier.fireTestFailure(null);
String loggedInfo = loggerStub.getLoggedInfo();
assertContains("[Mockito] Warning - stubbed method called with different arguments", loggedInfo);
assertContains("Stubbed this way:", loggedInfo);
assertContains("mock.simpleMethod(789);", loggedInfo);
assertContains(".someStubbing(", loggedInfo);
assertContains("But called with different arguments:", loggedInfo);
assertContains("mock.simpleMethod(10);", loggedInfo);
assertContains(".callStubbedMethodWithDifferentArgs(", loggedInfo);
}
};
runner.run(notifier);
}
@Test
public void shouldNotLogAnythingWhenStubCalledCorrectly() throws Exception {
runner = new VerboseMockitoJUnitRunner(this.getClass(), loggerStub) {
@Override
public void runTest(RunNotifier notifier) {
when(mock.simpleMethod(1)).thenReturn("foo");
mock.simpleMethod(1);
notifier.fireTestFailure(null);
assertEquals("", loggerStub.getLoggedInfo());
}
};
runner.run(notifier);
}
@Test
public void shouldNotLogWhenTestPasses() throws Exception {
runner = new VerboseMockitoJUnitRunner(this.getClass(), loggerStub) {
@Override
public void runTest(RunNotifier notifier) {
when(mock.simpleMethod()).thenReturn("foo");
notifier.fireTestFinished(null);
assertEquals("", loggerStub.getLoggedInfo());
}
};
runner.run(notifier);
}
public void shouldClearDebuggingDataAfterwards() throws Exception {
//given
final DebuggingInfo debuggingInfo = new ThreadSafeMockingProgress().getDebuggingInfo();
runner = new VerboseMockitoJUnitRunner(this.getClass(), loggerStub) {
@Override
public void runTest(RunNotifier notifier) {
unusedStubbingThatQualifiesForWarning();
notifier.fireTestFailure(null);
assertTrue(debuggingInfo.hasData());
}
};
//when
runner.run(notifier);
//then
assertFalse(debuggingInfo.hasData());
}
private void unusedStubbingThatQualifiesForWarning() {
when(mock.simpleMethod(123)).thenReturn("foo");
}
private void callUnstubbedMethodThatQualifiesForWarning() {
mock.simpleMethod(456);
}
private void someStubbing() {
when(mock.simpleMethod(789)).thenReturn("foo");
}
private void callStubbedMethodWithDifferentArgs() {
mock.simpleMethod(10);
}
public class MockitoLoggerStub extends MockitoLoggerImpl {
StringBuilder loggedInfo = new StringBuilder();
public void log(Object what) {
super.log(what);
loggedInfo.append(what);
}
public String getLoggedInfo() {
return loggedInfo.toString();
}
}
} |
/*
* $Id: TestGenericFileCachedUrlSet.java,v 1.34 2003-04-30 23:44:22 tal Exp $
*/
package org.lockss.plugin;
import java.io.*;
import java.util.*;
import java.net.MalformedURLException;
import org.lockss.daemon.*;
import org.lockss.repository.*;
import org.lockss.state.*;
import org.lockss.test.*;
import org.lockss.plugin.simulated.SimulatedArchivalUnit;
import org.lockss.util.StreamUtil;
import org.lockss.hasher.HashService;
/**
* This is the test class for
* org.lockss.plugin.simulated.GenericFileCachedUrlSet.
*
* @author Emil Aalto
* @version 0.0
*/
public class TestGenericFileCachedUrlSet extends LockssTestCase {
private LockssRepository repo;
private NodeManager nodeMan;
private MockGenericFileArchivalUnit mgfau;
private MockLockssDaemon theDaemon;
public void setUp() throws Exception {
super.setUp();
String tempDirPath = getTempDir().getAbsolutePath() + File.separator;
String s = LockssRepositoryServiceImpl.PARAM_CACHE_LOCATION + "=" +
tempDirPath +"\n";
String s2 = HistoryRepositoryImpl.PARAM_HISTORY_LOCATION + "=" +
tempDirPath;
TestConfiguration.setCurrentConfigFromString(s + s2);
theDaemon = new MockLockssDaemon();
theDaemon.getLockssRepositoryService().startService();
theDaemon.getHistoryRepository().startService();
theDaemon.getHashService().startService();
theDaemon.getSystemMetrics().startService();
mgfau = new MockGenericFileArchivalUnit();
MockPlugin plugin = new MockPlugin();
plugin.setDefiningConfigKeys(Collections.EMPTY_LIST);
mgfau.setPlugin(plugin);
repo = theDaemon.getLockssRepository(mgfau);
nodeMan = theDaemon.getNodeManager(mgfau);
((NodeManagerImpl)nodeMan).killTreeWalk();
}
public void tearDown() throws Exception {
repo.stopService();
nodeMan.stopService();
theDaemon.getLockssRepositoryService().stopService();
theDaemon.getHistoryRepository().stopService();
theDaemon.stopDaemon();
super.tearDown();
}
public void testFlatSetIterator() throws Exception {
createLeaf("http:
createLeaf("http:
createLeaf("http:
createLeaf("http:
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(rSpec);
Iterator setIt = fileSet.flatSetIterator();
ArrayList childL = new ArrayList(3);
while (setIt.hasNext()) {
childL.add(((CachedUrlSetNode)setIt.next()).getUrl());
}
// should be sorted
String[] expectedA = new String[] {
"http:
"http:
"http:
};
assertIsomorphic(expectedA, childL);
}
public void testFlatSetIteratorSingleNodeSpec() throws Exception {
createLeaf("http:
createLeaf("http:
createLeaf("http:
createLeaf("http:
CachedUrlSetSpec spec =
new SingleNodeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(spec);
Iterator setIt = fileSet.flatSetIterator();
assertFalse(setIt.hasNext());
}
public void testFlatSetIteratorThrowsOnBogusURL() throws Exception {
createLeaf("http:
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("no_such_protoco:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(rSpec);
try {
fileSet.flatSetIterator();
fail("Call to flatSetIterator() should have thrown when given "
+"malformed url");
} catch(RuntimeException e){
}
}
public void testFlatSetIteratorClassCreation() throws Exception {
createLeaf("http:
createLeaf("http:
createLeaf("http:
"test stream", null);
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(rSpec);
Iterator setIt = fileSet.flatSetIterator();
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
}
public void testHashIterator() throws Exception {
createLeaf("http:
"test stream", null);
createLeaf("http:
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(rSpec);
Iterator setIt = fileSet.contentHashIterator();
ArrayList childL = new ArrayList(7);
while (setIt.hasNext()) {
childL.add(((CachedUrlSetNode)setIt.next()).getUrl());
}
// should be sorted
String[] expectedA = new String[] {
"http:
"http:
"http:
"http:
"http:
"http:
"http:
};
assertIsomorphic(expectedA, childL);
// add content to an internal node
// should behave normally
createLeaf("http:
rSpec = new RangeCachedUrlSetSpec("http:
fileSet = mgfau.makeCachedUrlSet(rSpec);
setIt = fileSet.contentHashIterator();
childL = new ArrayList(3);
while (setIt.hasNext()) {
childL.add(((CachedUrlSetNode)setIt.next()).getUrl());
}
assertFalse(setIt.hasNext());
try {
setIt.next();
fail("setIt.next() should have thrown when it has no elements");
} catch (NoSuchElementException e) {
}
// should be sorted
expectedA = new String[] {
"http:
"http:
"http:
};
assertIsomorphic(expectedA, childL);
}
public void testHashIteratorSingleNode() throws Exception {
createLeaf("http:
"test stream", null);
createLeaf("http:
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
CachedUrlSetSpec spec =
new SingleNodeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(spec);
Iterator setIt = fileSet.contentHashIterator();
ArrayList childL = new ArrayList(1);
while (setIt.hasNext()) {
childL.add(((CachedUrlSetNode)setIt.next()).getUrl());
}
// should be sorted
String[] expectedA = new String[] {
"http:
};
assertIsomorphic(expectedA, childL);
}
public void testHashIteratorThrowsOnBogusUrl() throws Exception {
createLeaf("http:
"test stream", null);
CachedUrlSetSpec spec =
new RangeCachedUrlSetSpec("bad_protocol:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(spec);
try {
Iterator setIt = fileSet.contentHashIterator();
fail("Bogus url should have caused a RuntimeException");
} catch (RuntimeException e){
}
}
public void testHashIteratorVariations() throws Exception {
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("http:
"/leaf1", "/leaf2");
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(rSpec);
Iterator setIt = fileSet.contentHashIterator();
ArrayList childL = new ArrayList(2);
while (setIt.hasNext()) {
childL.add(((CachedUrlSetNode)setIt.next()).getUrl());
}
// should exclude 'branch1'
String[] expectedA = new String[] {
"http:
"http:
};
assertIsomorphic(expectedA, childL);
CachedUrlSetSpec snSpec =
new SingleNodeCachedUrlSetSpec("http:
fileSet = mgfau.makeCachedUrlSet(snSpec);
setIt = fileSet.contentHashIterator();
childL = new ArrayList(1);
while (setIt.hasNext()) {
childL.add(((CachedUrlSetNode)setIt.next()).getUrl());
}
// should include only 'branch1'
expectedA = new String[] {
"http:
};
assertIsomorphic(expectedA, childL);
}
public void testHashIteratorClassCreation() throws Exception {
createLeaf("http:
createLeaf("http:
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test stream", null);
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(rSpec);
Iterator setIt = fileSet.contentHashIterator();
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
false);
assertRightClass((CachedUrlSetNode)setIt.next(),
"http:
}
private void assertRightClass(CachedUrlSetNode element,
String url, boolean isCus) {
assertEquals(url, element.getUrl());
if (isCus) {
assertEquals(CachedUrlSetNode.TYPE_CACHED_URL_SET, element.getType());
assertTrue(element instanceof CachedUrlSet);
assertFalse(element.isLeaf());
} else {
assertEquals(CachedUrlSetNode.TYPE_CACHED_URL, element.getType());
assertTrue(element instanceof CachedUrl);
assertTrue(element.isLeaf());
}
}
public void testNodeCounting() throws Exception {
createLeaf("http:
"test streamAA", null);
createLeaf("http:
"test stream", null);
createLeaf("http:
"test streamB", null);
createLeaf("http:
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("http:
GenericFileCachedUrlSet fileSet =
(GenericFileCachedUrlSet)mgfau.makeCachedUrlSet(rSpec);
fileSet.calculateNodeSize();
// assertEquals(4, ((GenericFileCachedUrlSet)fileSet).contentNodeCount);
assertEquals(48, ((GenericFileCachedUrlSet)fileSet).totalNodeSize);
}
public void testHashEstimation() throws Exception {
byte[] bytes = new byte[100];
Arrays.fill(bytes, (byte)1);
String testString = new String(bytes);
for (int ii=0; ii<10; ii++) {
createLeaf("http:
}
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(rSpec);
long estimate = fileSet.estimatedHashDuration();
assertTrue(estimate > 0);
assertEquals(estimate,
nodeMan.getNodeState(fileSet).getAverageHashDuration());
// test return of stored duration
long estimate2 = fileSet.estimatedHashDuration();
assertEquals(estimate, estimate2);
assertEquals(estimate,
nodeMan.getNodeState(fileSet).getAverageHashDuration());
// test averaging of durations
fileSet.storeActualHashDuration(estimate2 + 200, null);
long estimate3 = fileSet.estimatedHashDuration();
assertEquals(estimate2 + 100, estimate3);
assertEquals(estimate3,
nodeMan.getNodeState(fileSet).getAverageHashDuration());
}
public void testSingleNodeHashEstimation() throws Exception {
byte[] bytes = new byte[1000];
Arrays.fill(bytes, (byte)1);
String testString = new String(bytes);
// check that estimation is special for single nodes, and isn't stored
createLeaf("http:
CachedUrlSetSpec sSpec =
new SingleNodeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(sSpec);
long estimate = fileSet.estimatedHashDuration();
// tk - fix this with a MockSystemMetrics so we can set the hash speed
// assertTrue(estimate > 0);
long expectedEstimate = 1000 /
SystemMetrics.getSystemMetrics().getBytesPerMsHashEstimate();
assertEquals(expectedEstimate, estimate);
// check that estimation isn't stored for single node sets
assertEquals(-1, nodeMan.getNodeState(fileSet).getAverageHashDuration());
}
public void testIrregularHashStorage() throws Exception {
// check that estimation isn't changed for single node sets
createLeaf("http:
CachedUrlSetSpec sSpec =
new SingleNodeCachedUrlSetSpec("http:
CachedUrlSet fileSet = mgfau.makeCachedUrlSet(sSpec);
fileSet.storeActualHashDuration(123, null);
assertEquals(-1, nodeMan.getNodeState(fileSet).getAverageHashDuration());
// check that estimation isn't changed for ranged sets
CachedUrlSetSpec rSpec =
new RangeCachedUrlSetSpec("http:
fileSet = mgfau.makeCachedUrlSet(rSpec);
fileSet.storeActualHashDuration(123, null);
assertEquals(-1, nodeMan.getNodeState(fileSet).getAverageHashDuration());
// check that estimation isn't changed for exceptions
rSpec = new RangeCachedUrlSetSpec("http:
fileSet = mgfau.makeCachedUrlSet(rSpec);
fileSet.storeActualHashDuration(123, new Exception("bad"));
assertEquals(-1, nodeMan.getNodeState(fileSet).getAverageHashDuration());
// check that estimation is grown for timeout exceptions
rSpec = new RangeCachedUrlSetSpec("http:
fileSet = mgfau.makeCachedUrlSet(rSpec);
fileSet.storeActualHashDuration(100, null);
assertEquals(100, nodeMan.getNodeState(fileSet).getAverageHashDuration());
fileSet.storeActualHashDuration(10, new HashService.Timeout("test"));
assertEquals(150, nodeMan.getNodeState(fileSet).getAverageHashDuration());
}
private RepositoryNode createLeaf(String url, String content,
Properties props) throws Exception {
return TestRepositoryNodeImpl.createLeaf(repo, url, content, props);
}
public static void main(String[] argv) {
String[] testCaseList = {TestGenericFileCachedUrlSet.class.getName()};
junit.swingui.TestRunner.main(testCaseList);
}
} |
package com.zc741.thinking;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zc741.thinking.ItemDrawerleft.AboutActivity;
import com.zc741.thinking.ItemDrawerleft.ContributeActivity;
import com.zc741.thinking.ItemDrawerleft.PublishActivity;
import com.zc741.thinking.ItemDrawerleft.ThinkerActivity;
import com.zc741.thinking.ItemDrawerleft.VersionActivity;
import com.zc741.thinking.domain.Content;
import com.zc741.thinking.domain.Utils.DpToPx;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
ListView mListview;
ActionBarDrawerToggle mActionBarDrawerToggle;
private LinearLayout mLinearLayout;
TextView mTv_word;
ImageView mIv_pic;
private Content mData;
OnekeyShare oks;
private NetworkInfo mNetworkInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
initItem();
initDrawerToggle();
getDataFromServer();
//ShareSDK
ShareSDK.initSDK(this);
showDate();
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = connectivity.getActiveNetworkInfo();
}
private void showDate() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
Date currentTime = new Date(System.currentTimeMillis());
String date = simpleDateFormat.format(currentTime);
TextView tv_date = (TextView) findViewById(R.id.tv_date);
tv_date.setText(date);
}
protected void initDrawerToggle() {
mActionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.open_string, R.string.close_string);
mActionBarDrawerToggle.syncState();
drawerLayout.setDrawerListener(mActionBarDrawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
protected void initItem() {
//listItem
final int[] pics = new int[]{
R.mipmap.ic_chat_black_18dp,
R.mipmap.ic_chat_black_18dp,
R.mipmap.ic_markunread_black_18dp,
R.mipmap.ic_markunread_black_18dp,
R.mipmap.ic_markunread_black_18dp
};
final String[] items = new String[]{
" ",
" ",
" ",
" ",
" "
};
mListview = (ListView) findViewById(R.id.lv_left);
BaseAdapter adapter = new BaseAdapter() {
@Override
public int getCount() {
return pics.length;
}
@Override
public Object getItem(int position) {
return pics[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//System.out.println(items[position]);
mLinearLayout = new LinearLayout(MainActivity.this);
mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
mLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(pics[position]);
imageView.setPadding(28, 0, 0, 0);
TextView textView = new TextView(MainActivity.this);
textView.setText(items[position]);
textView.setTextSize(14);
textView.setHeight(DpToPx.dip2px(getApplicationContext(), 40));
textView.setGravity(Gravity.CENTER);
mLinearLayout.addView(imageView);
mLinearLayout.addView(textView);
return mLinearLayout;
}
};
mListview.setAdapter(adapter);
mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("position==" + position + "; items==" + items[position] + "; pics==" + pics[position]);
switch (position) {
case 0:
Intent intent0 = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(intent0);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
break;
case 1:
Intent intent1 = new Intent(getApplicationContext(), ContributeActivity.class);
startActivity(intent1);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
break;
case 2:
Intent intent2 = new Intent(getApplicationContext(), PublishActivity.class);
startActivity(intent2);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
break;
case 3:
Intent intent3 = new Intent(getApplicationContext(), VersionActivity.class);
startActivity(intent3);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
break;
case 4:
Intent intent4 = new Intent(getApplicationContext(), ThinkerActivity.class);
startActivity(intent4);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
break;
default:
break;
}
// MainActivity
drawerLayout.closeDrawer(GravityCompat.START);
}
});
}
//MainActivityDrawerlayout
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
//Home
super.onBackPressed();//,back
/* Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);*/
}
overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
public void getDataFromServer() {
HttpUtils utils = new HttpUtils();
String uri = "http:
utils.send(HttpMethod.GET, uri, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
String result = responseInfo.result;
System.out.println("result=" + result);
parseJson(result);
}
@Override
public void onFailure(HttpException e, String s) {
//Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
/**
* json
*
* @param result
*/
private void parseJson(String result) {
Gson gson = new Gson();
mData = gson.fromJson(result, Content.class);
//System.out.println(mData);
TextView tv_num = (TextView) findViewById(R.id.tv_num);
mTv_word = (TextView) findViewById(R.id.tv_word);
mIv_pic = (ImageView) findViewById(R.id.iv_pic);
tv_num.setText("No." + mData.getNum());
mTv_word.setText(mData.getWord());
BitmapUtils bitmapUtils = new BitmapUtils(this);
bitmapUtils.display(mIv_pic, mData.getPic());
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/cache.png");
if (file.exists()) {
//System.out.println(",");
} else {
//System.out.println("");
cachePng();
}
}
private void cachePng() {
HttpUtils httpUtils = new HttpUtils();
String url = mData.getPic();
String downloadPath = Environment.getExternalStorageDirectory().getPath() + "/cache.png";
httpUtils.download(url, downloadPath, new RequestCallBack<File>() {
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
super.onLoading(total, current, isUploading);
//System.out.println(":" + current + "/" + total);
}
@Override
public void onFailure(HttpException e, String s) {
e.printStackTrace();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawers();
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
return true;
} else if (id == R.id.menu_share) {
if (mNetworkInfo != null) {
if (mNetworkInfo.isAvailable() && mNetworkInfo.isConnected()) {
System.out.println("");
shareFunction();
}
} else {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
alertDialog();
}
}
return super.onOptionsItemSelected(item);
}
private void alertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("~, ");
builder.setTitle("");
builder.setPositiveButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent setting = new Intent(Settings.ACTION_SETTINGS);
startActivity(setting);
dialog.dismiss();
//finish();
startActivity(new Intent(MainActivity.this, SplashActivity.class));
finish();
}
});
builder.setNegativeButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
private void shareFunction() {
ShareSDK.initSDK(this);
oks = new OnekeyShare();
//sso
oks.disableSSOWhenAuthorize();
//oks.setTheme(OnekeyShareTheme.CLASSIC);//
// Notification 2.5.9
//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
// titleQQ
oks.setTitle(getString(R.string.share));
// titleUrlQQ
oks.setTitleUrl("http:
// text
oks.setText(mData.getWord());
// imagePathLinked-In //
oks.setImagePath(Environment.getExternalStorageDirectory().getPath() + "/cache.png");//SDcard "/sdcard/test.jpg"
// url
oks.setUrl("http:
// commentQQ
oks.setComment("Thinking");
// siteQQ
oks.setSite(getString(R.string.app_name));
// siteUrlQQ
oks.setSiteUrl("http:
// GUI
oks.show(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.share, menu);
MenuItem mi = menu.findItem(R.id.menu_share);
ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(mi);
//shareActionProvider.setShareIntent(getDefaultIntent());
return super.onCreateOptionsMenu(menu);
}
} |
package am.userInterface.vertex;
import java.io.Serializable;
import javax.swing.tree.DefaultMutableTreeNode;
import am.GlobalStaticVariables;
import am.app.ontology.Node;
import com.hp.hpl.jena.ontology.OntModel;
/**
* Vertex class contains all the information about the node or vertex of the XML tree.
* Some of the information include tbe name of the vertex, the location on the canvas,
* if the vertex is visible, if it is mapped, and the actual mapping.
*
* @author ADVIS Laboratory
* @version 11/27/2004
*/
// TODO: Vertex should not extend DefaultMutableTreeNode because it does not support multiple inheritance
public class Vertex extends DefaultMutableTreeNode implements Serializable
{
// instance variables
static int key =0; // unique number assigned by the program
static final long serialVersionUID = 1;
private int arcHeight; // arc height of the rectangular node
private int arcWidth; // arc width of the rectangular node
private String description; // description of the vertex
private int height; // height of the node/vertex
private int id; // assign the unique number here
private OntModel ontModel;
private String uri;
private boolean isMapped; // is the vertex mapped by the user
private boolean isMappedByContext; // is the vertex mapped by context
private boolean isMappedByDef; // is the vertex mapped by definition
private boolean isSelected; // is the node or vertex selected
private boolean isVisible; // is the node/vertex visible
private String name; // name of the vertex (may not be unique)
private int nodeType; // the type of node (global or local)
//private VertexDescriptionPane vertexDescription; //stores the description of the OWL classes
private int ontNode; //the type of vertex; XML or OWL -> 0 for XML and 1 for OWL
private boolean shouldCollapse; // keeps track if the node or vertex should collapse or not.
private int width; // width of the node/vertex
private int x; // coordinate x location on canvas
private int x2; // coordinate x2 = x+width location on canvas
private int y; // coordinate y location on canvas
private int y2; // coordinate y2 = y+width location on canvas
private Node node; //the node containing the ontology information of this vertex, there is a double link from the node to the vertex and from the vertex to the node.
/**
* Constructor for objects of class Vertex
* @param name name of the vertex
*/
public Vertex(String name, int sourceOrTarget) {
super(name);
// initialize instance variables
setID(key++);
setName(name);
setDesc("");
this.ontModel = null;
setIsMapped(false);
setIsMappedByContext(false);
setIsMappedByDef(false);
setX(-1);
setX2(-1);
setY(-1);
setY2(-1);
setWidth(-1);
setHeight(-1);
setArcWidth(-1);
setArcHeight(-1);
setIsVisible(true);
isSelected = false;
setNodeType(sourceOrTarget);
setOntNode(GlobalStaticVariables.XMLFILE);
setShouldCollapse(false);
//vertexDescription = (VertexDescriptionPane)jDescriptionPanel;
}
public Vertex(String name, String uri, OntModel m,int sourceOrTarget) {
super(name);
// initialize instance variables
setID(key++);
setName(name);
setDesc("");
this.uri = uri;
setIsMapped(false);
setIsMappedByContext(false);
setIsMappedByDef(false);
setX(-1);
setX2(-1);
setY(-1);
setY2(-1);
setWidth(-1);
setHeight(-1);
setArcWidth(-1);
setArcHeight(-1);
setIsVisible(true);
isSelected = false;
setNodeType(sourceOrTarget);
setOntNode(GlobalStaticVariables.ONTFILE);
setShouldCollapse(false);
//vertexDescription = (VertexDescriptionPane)jDescriptionPanel;
}
/**
* Accessor method which returns arcHeight of the node
*
* @return arcHeight arc height of the vertex
*/
public int getArcHeight()
{
return arcHeight;
}
/**
* Accessor method which returns arcWidth of the node
*
* @return arcWidth arc width of the vertex
*/
public int getArcWidth()
{
return arcWidth;
}
/**
* Accessor method which returns description
*
* @return description description of the vertex
*/
public String getDesc() {
return description;
}
/**
* Accessor method which returns height of the node
*
* @return height height of the vertex
*/
public int getHeight()
{
return height;
}
/**
* Accessor method which returns key
*
* @return id unique identifier of the vertex
*/
public int getID()
{
return id;
}
/**
* Accessor method which returns true if vertex is mapped else false
*
* @return isMapped boolean value indicating if the vertex is mapped or not
*/
public boolean getIsMapped()
{
return isMapped;
}
/**
* Accessor method which returns true if vertex is mapped by context else false
*
* @return isMapped boolean value indicating if the vertex is mapped by context or not
*/
public boolean getIsMappedByContext()
{
return isMappedByContext;
}
/**
* Accessor method which returns true if vertex is mapped by defintion else false
*
* @return isMapped boolean value indicating if the vertex is mapped by definition or not
*/
public boolean getIsMappedByDef()
{
return isMappedByDef;
}
/**
* Accessor method which returns isSelected
*
* @return isSelected boolean value which indicates if the vertex is selected or not
*/
public boolean getIsSelected()
{
return isSelected;
}
/**
* Accessor method which returns name of the vertex
*
* @return name name of the vertex
*/
public String getName()
{
return name;
}
/**
* Accessor method which returns nodeType
*
* @return nodeType node type indicating if the node is global (1) or local (2)
*/
public int getNodeType()
{
return nodeType;
}
/**
* Accessor method which returns description for OWL Class vertices
*
* @return description description of the vertex
*/
public String getOWLDesc() {
return OntVertexDescription.getVertexDescription(this.name,this.ontModel);
}
/**
* Accessor method which returns OWLNode
*
* @return OWLNode indicating if the node is for XML file or OWL file
*/
public int getOntNode() {
return ontNode;
}
/**
* Accessor method which returns shouldCollapse
*
* @return shouldCollapse boolean value indicating if the vertex should collapse or not
*/
public boolean getShouldCollapse()
{
return shouldCollapse;
}
/**
* Accessor method which returns width of the node
*
* @return width width of the vertex
*/
public int getWidth()
{
return width;
}
/**
* Accessor method which returns x value
*
* @return x x location of the top left corner of vertex
*/
public int getX()
{
return x;
}
/**
* Accessor method which returns x2 value
*
* @return x2 x location of the bottom right corner of vertex
*/
public int getX2()
{
return x2;
}
/**
* Accessor method which returns y value
*
* @return y y location of the top left corner of vertex
*/
public int getY()
{
return y;
}
/**
* Accessor method which returns y2 value
*
* @return y2 y location of the bottom right corner of vertex
*/
public int getY2()
{
return y2;
}
/**
* Accessor method which returns isVisible
*
* @return isVisible boolean value which indicates if the vertex if visible or not
*/
public boolean isVisible()
{
return isVisible;
}
/**
* Modifier method which sets archeight
*
* @param ah height of arc
*/
public void setArcHeight(int ah)
{
arcHeight = ah;
}
/**
* Modifier method which sets arcWidth
*
* @param aw width of the arc
*/
public void setArcWidth(int aw)
{
arcWidth= aw;
}
/**
* Modifier method which sets description of the vertex
*
* @param desc description of the vertex
*/
public void setDesc(String desc)
{
description = desc;
}
public OntModel getOntModel() {
return ontModel;
}
public void setOntModel(OntModel ontModel) {
this.ontModel = ontModel;
}
/**
* Modifier method which sets description of the vertex if it is for OWL class
*
* @param pCls the OWL named class
*/
/*public void setDesc(String name, OWLModel ontModel)
{
vertexDescription = new VertexDescriptionPane(name, ontModel);
} */
/**
* Modifier method which sets height
*
* @param h height of node
*/
public void setHeight(int h)
{
height = h;
}
/**
* Modifier method which sets unique id of vertex
*
* @param num unique identifier
*/
public void setID(int num)
{
id = num;
}
/**
* Modifier method which sets the boolean isMapped to true or false
*
* @param mapped boolean value which indicates if the vertex is mapped
*/
public void setIsMapped(boolean mapped)
{
isMapped = mapped;
}
/**
* Modifier method which sets the boolean isMappedByContext to true or false
*
* @param mapped boolean value which indicates if the vertex is mapped by context
*/
public void setIsMappedByContext(boolean mapped)
{
isMappedByContext = mapped;
}
/**
* Modifier method which sets the boolean isMappedByDef to true or false
*
* @param mapped boolean value which indicates if the vertex is mapped by definition
*/
public void setIsMappedByDef(boolean mapped)
{
isMappedByDef = mapped;
}
/**
* Modifier method which sets isSelected
*
* @param selected boolean value indicating if the vertex is selected
*/
public void setIsSelected(boolean selected)
{
isSelected = selected;
}
/**
* Modifier method which sets isVisible
*
* @param visible boolean value which indicates if the vertex is visible
*/
public void setIsVisible(boolean visible)
{
isVisible = visible;
}
/**
* Modifier method which sets name of vertex
*
* @param tempName name of the vertex
*/
public void setName(String tempName)
{
name = tempName;
}
/**
* Modifier method which sets nodeType
*
* @param type integer value indicating if the vertex is global (1) or local (2)
*/
public void setNodeType(int type)
{
nodeType = type;
}
/**
* Modifier method which set OWLNode
*
* @param type integer value indicating if the vertex is for XML file or OWL file
*/
public void setOntNode(int type)
{
ontNode = type;
}
/**
* Modifier method which sets shouldCollapse
*
* @param collapse boolean value indicating if the vertex should collapse
*/
public void setShouldCollapse(boolean collapse)
{
shouldCollapse = collapse;
}
/**
* Modifier method which sets width
*
* @param w width of node
*/
public void setWidth(int w)
{
width = w;
}
/**
* Modifier method which sets x value
*
* @param xvalue x location of the top left corner
*/
public void setX(int xvalue)
{
x = xvalue;
}
/**
* Modifier method which sets x2 value
*
* @param x2value x location of the bottom right corner
*/
public void setX2(int x2value)
{
x2 = x2value;
}
/**
* Modifier method which sets y value
*
* @param yvalue y location of the top left corner
*/
public void setY(int yvalue)
{
y = yvalue;
}
/**
* Modifier method which sets y2 value
*
* @param y2value y location of the bottom right corner
*/
public void setY2(int y2value)
{
y2 = y2value;
}
/**
* @return Returns the uri.
*/
public String getUri() {
return this.uri;
}
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
public boolean isFake() {
return node == null;
}
public boolean isSourceOrGlobal() {
return this.getNodeType() == GlobalStaticVariables.SOURCENODE;
}
public boolean isTargetOrLocal() {
return this.getNodeType() == GlobalStaticVariables.TARGETNODE;
}
/**Attention we are checking if they are part of the same tree, so if one is source and one is target the may be equals even if they shouldn't be*/
/*
public boolean equals(Object o) {
if(o instanceof Vertex) {
Vertex v = (Vertex)o;
if(v.getX() == x && v.getX2() == x2 && v.getY() == y && v.getY2() == y2) {
return true;
}
}
return false;
}
*/
} |
package yuku.alkitab.base.sync;
import android.support.annotation.NonNull;
import com.google.gson.Gson;
import yuku.alkitab.base.S;
import yuku.alkitab.base.U;
import yuku.alkitab.base.model.SyncShadow;
import yuku.alkitab.base.util.Sqlitil;
import yuku.alkitab.model.Label;
import yuku.alkitab.model.Marker;
import yuku.alkitab.model.Marker_Label;
import java.util.ArrayList;
import java.util.List;
import static yuku.alkitab.base.util.Literals.List;
public class Sync {
public enum Opkind {
add, mod, del,
}
public static class Operation<C> {
public Opkind opkind;
public String kind;
public String gid;
public C content;
public Operation(final Opkind opkind, final String kind, final String gid, final C content) {
this.opkind = opkind;
this.kind = kind;
this.gid = gid;
this.content = content;
}
@Override
public String toString() {
return "{" + opkind +
" " + kind +
" " + gid.substring(0, 10) +
" " + content +
'}';
}
}
public static class Delta<C> {
public List<Operation<C>> operations;
public Delta() {
operations = new ArrayList<>();
}
@Override
public String toString() {
return "Delta{" +
"operations=" + operations +
'}';
}
}
public static class Entity<C> {
public static final String KIND_MARKER = "Marker";
public static final String KIND_LABEL = "Label";
public static final String KIND_MARKER_LABEL = "Marker_Label";
/** Kind of this entity. Currently can be {@link #KIND_MARKER}, {@link #KIND_LABEL}, {@link #KIND_MARKER_LABEL}. */
public String kind;
public String gid;
public C content;
}
/**
* Entity content for {@link yuku.alkitab.model.Marker} and {@link yuku.alkitab.model.Label}.
*/
public static class MabelContent {
public Integer ari; // marker
public Integer kind; // marker
public String caption; // marker
public Integer verseCount; // marker
public Integer createTime; // marker
public Integer modifyTime; // marker
public String title; // label
public Integer ordering; // label
public String backgroundColor; // label
public String marker_gid; // marker_label
public String label_gid; // marker_label
//region boilerplate equals and hashCode methods
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final MabelContent that = (MabelContent) o;
if (ari != null ? !ari.equals(that.ari) : that.ari != null) return false;
if (backgroundColor != null ? !backgroundColor.equals(that.backgroundColor) : that.backgroundColor != null) return false;
if (caption != null ? !caption.equals(that.caption) : that.caption != null) return false;
if (createTime != null ? !createTime.equals(that.createTime) : that.createTime != null) return false;
if (kind != null ? !kind.equals(that.kind) : that.kind != null) return false;
if (label_gid != null ? !label_gid.equals(that.label_gid) : that.label_gid != null) return false;
if (marker_gid != null ? !marker_gid.equals(that.marker_gid) : that.marker_gid != null) return false;
if (modifyTime != null ? !modifyTime.equals(that.modifyTime) : that.modifyTime != null) return false;
if (ordering != null ? !ordering.equals(that.ordering) : that.ordering != null) return false;
if (title != null ? !title.equals(that.title) : that.title != null) return false;
if (verseCount != null ? !verseCount.equals(that.verseCount) : that.verseCount != null) return false;
return true;
}
@Override
public int hashCode() {
int result = ari != null ? ari.hashCode() : 0;
result = 31 * result + (kind != null ? kind.hashCode() : 0);
result = 31 * result + (caption != null ? caption.hashCode() : 0);
result = 31 * result + (verseCount != null ? verseCount.hashCode() : 0);
result = 31 * result + (createTime != null ? createTime.hashCode() : 0);
result = 31 * result + (modifyTime != null ? modifyTime.hashCode() : 0);
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (ordering != null ? ordering.hashCode() : 0);
result = 31 * result + (backgroundColor != null ? backgroundColor.hashCode() : 0);
result = 31 * result + (marker_gid != null ? marker_gid.hashCode() : 0);
result = 31 * result + (label_gid != null ? label_gid.hashCode() : 0);
return result;
}
//endregion
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("{");
if (ari != null) sb.append(ari).append(' ');
if (kind != null) sb.append(kind).append(' ');
if (caption != null) sb.append(q(caption)).append(' ');
if (verseCount != null) sb.append(verseCount).append(' ');
if (createTime != null) sb.append(createTime).append(' ');
if (modifyTime != null) sb.append(modifyTime).append(' ');
if (title != null) sb.append(q(title)).append(' ');
if (ordering != null) sb.append(ordering).append(' ');
if (backgroundColor != null) sb.append(backgroundColor).append(' ');
if (marker_gid != null) sb.append(marker_gid.substring(0, 10)).append(' ');
if (label_gid != null) sb.append(label_gid.substring(0, 10)).append(' ');
sb.setLength(sb.length() - 1);
sb.append('}');
return sb.toString();
}
@NonNull static String q(@NonNull String s) {
final String c;
if (s.length() > 20) {
c = s.substring(0, 19).replace("\n", "\\n") + "…";
} else {
c = s.replace("\n", "\\n");
}
return "'" + c + "'";
}
}
public static class SyncShadowMabelDataJson {
public List<Entity<MabelContent>> entities;
}
public static class MabelClientState {
public int base_revno;
@NonNull public Delta<MabelContent> delta;
public MabelClientState(final int base_revno, final @NonNull Delta<MabelContent> delta) {
this.base_revno = base_revno;
this.delta = delta;
}
}
/**
* @return base revno, delta of shadow -> current.
*/
public static MabelClientState getMabelClientState() {
final SyncShadow ss = S.getDb().getSyncShadowBySyncSetName(SyncShadow.SYNC_SET_MABEL);
final List<Entity<MabelContent>> srcs = ss == null? List(): getMabelEntitiesFromShadow(ss);
final List<Entity<MabelContent>> dsts = getMabelEntitiesFromCurrent();
final Delta<MabelContent> delta = new Delta<>();
// additions and modifications
for (final Entity<MabelContent> dst : dsts) {
final Entity<MabelContent> existing = findMabelEntity(srcs, dst.gid, dst.kind);
if (existing == null) {
delta.operations.add(new Operation<>(Opkind.add, dst.kind, dst.gid, dst.content));
} else {
if (!isSameMabelContent(dst, existing)) { // only when it changes
delta.operations.add(new Operation<>(Opkind.mod, dst.kind, dst.gid, dst.content));
}
}
}
// deletions
for (final Entity<MabelContent> src : srcs) {
final Entity<MabelContent> still_have = findMabelEntity(dsts, src.gid, src.kind);
if (still_have == null) {
delta.operations.add(new Operation<>(Opkind.del, src.kind, src.gid, null));
}
}
return new MabelClientState(ss == null ? 0 : ss.revno, delta);
}
private static boolean isSameMabelContent(final Entity<MabelContent> a, final Entity<MabelContent> b) {
if (!U.equals(a.gid, b.gid)) return false;
if (!U.equals(a.kind, b.kind)) return false;
return U.equals(a.content, b.content);
}
private static Entity<MabelContent> findMabelEntity(final List<Entity<MabelContent>> list, final String gid, final String kind) {
for (final Entity<MabelContent> entity : list) {
if (U.equals(gid, entity.gid) && U.equals(kind, entity.kind)) {
return entity;
}
}
return null;
}
private static List<Entity<MabelContent>> getMabelEntitiesFromShadow(@NonNull final SyncShadow ss) {
final SyncShadowMabelDataJson data = new Gson().fromJson(U.utf8BytesToString(ss.data), SyncShadowMabelDataJson.class);
return data.entities;
}
private static List<Entity<MabelContent>> getMabelEntitiesFromCurrent() {
final List<Entity<MabelContent>> res = new ArrayList<>();
{ // markers
for (final Marker marker : S.getDb().listAllMarkers()) {
final Entity<MabelContent> entity = new Entity<>();
entity.kind = Entity.KIND_MARKER;
entity.gid = marker.gid;
final MabelContent content = entity.content = new MabelContent();
content.ari = marker.ari;
content.caption = marker.caption;
content.kind = marker.kind.code;
content.verseCount = marker.verseCount;
content.createTime = Sqlitil.toInt(marker.createTime);
content.modifyTime = Sqlitil.toInt(marker.modifyTime);
res.add(entity);
}
}
{ // labels
for (final Label label : S.getDb().listAllLabels()) {
final Entity<MabelContent> entity = new Entity<>();
entity.kind = Entity.KIND_LABEL;
entity.gid = label.gid;
final MabelContent content = entity.content = new MabelContent();
content.title = label.title;
content.backgroundColor = label.backgroundColor;
content.ordering = label.ordering;
res.add(entity);
}
}
{ // marker_labels
for (final Marker_Label marker_label : S.getDb().listAllMarker_Labels()) {
final Entity<MabelContent> entity = new Entity<>();
entity.kind = Entity.KIND_MARKER_LABEL;
entity.gid = marker_label.gid;
final MabelContent content = entity.content = new MabelContent();
content.marker_gid = marker_label.marker_gid;
content.label_gid = marker_label.label_gid;
res.add(entity);
}
}
return res;
}
} |
package at.GT.GoogleAuthentication;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import at.GT.HttpHelper.*;
public class GoogleAuthenticateLogin {
//for providing insight on how to solve this issue
// and:
// self.opener.open(self.url_CookieCheck)
// self.opener.open(self.url_PrefCookie)
// URLConnection conn = url.openConnection();
// // Set the cookie value to send
// conn.setRequestProperty("Cookie", "name1=value1; name2=value2");
// // Send the request to the server
// conn.connect();
private String _email = "";
private String _password = "";
private String _galx = "";
private boolean _isLoggedIn = false;
private String galx(){
String galx = null;
HttpGet get;
HttpClient client = HttpClients.createDefault();
try {
Pattern pattern = Pattern.compile("name=\"GALX\" type=\"hidden\"\n *value=\"(.+)\"");
get = new HttpGet("https://accounts.google.com/trends");
HttpResponse response = client.execute(get);
String html = HttpHelper.ReadEntity(response.getEntity());
get.releaseConnection();
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
galx = matcher.group(1);
}
if (galx == null) {
throw new Exception();
}
} catch (Exception e){
System.out.println("GALX is incorrect.");
}
if (galx != null){
_galx = galx;
}
return galx;
}
public List<NameValuePair> formLoginParams(){
List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
loginParams.add(new BasicNameValuePair("Email", _email));
loginParams.add(new BasicNameValuePair("Passwd", _password));
loginParams.add(new BasicNameValuePair("GALX", _galx));
return loginParams;
}
public boolean isLoggedIn(){
return _isLoggedIn;
}
public boolean login(){
if(!_isLoggedIn){
HttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://accounts.google.com/ServiceLoginAuth");
try {
httpPost.setEntity(new UrlEncodedFormEntity(formLoginParams()));
HttpResponse response = client.execute(httpPost);
String res = HttpHelper.ReadEntity(response.getEntity());
httpPost.releaseConnection();
} catch (UnsupportedOperationException | IOException e) {
e.printStackTrace();
}
_isLoggedIn = true;
}
return true;
}
public boolean authenticate(){
_galx = galx();
return login();
}
public static void main(String[] args) {
}
} |
package imj2.tools;
import static java.lang.Math.pow;
import static java.lang.Math.round;
import static java.lang.Math.sqrt;
import static net.sourceforge.aprog.swing.SwingTools.horizontalBox;
import static net.sourceforge.aprog.swing.SwingTools.show;
import static net.sourceforge.aprog.tools.Tools.array;
import static net.sourceforge.aprog.tools.Tools.debug;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import imj.IntList;
import imj2.tools.Image2DComponent.Painter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.sourceforge.aprog.swing.SwingTools;
import net.sourceforge.aprog.tools.MathTools.Statistics;
import net.sourceforge.aprog.tools.TicToc;
import net.sourceforge.aprog.tools.Tools;
import org.junit.Test;
/**
* @author codistmonk (creation 2014-04-09)
*/
@SuppressWarnings("unchecked")
public final class BitwiseQuantizationTest {
// @Test
public final void test1() {
final TreeMap<double[], String> lines = new TreeMap<double[], String>(DoubleArrayComparator.INSTANCE);
for (int qR0 = 0; qR0 <= 7; ++qR0) {
final int qR = qR0;
for (int qG0 = 0; qG0 <= 7; ++qG0) {
final int qG = qG0;
for (int qB0 = 0; qB0 <= 7; ++qB0) {
final int qB = qB0;
MultiThreadTools.getExecutor().submit(new Runnable() {
@Override
public final void run() {
final int[] rgb = new int[3];
final int[] qRGB = rgb.clone();
final float[] xyz = new float[3];
final float[] cielab = new float[3];
final float[] qCIELAB = cielab.clone();
final Statistics error = new Statistics();
for (int color = 0; color <= 0x00FFFFFF; ++color) {
rgbToRGB(color, rgb);
rgbToXYZ(rgb, xyz);
xyzToCIELAB(xyz, cielab);
quantize(rgb, qR, qG, qB, qRGB);
rgbToXYZ(qRGB, xyz);
xyzToCIELAB(xyz, qCIELAB);
error.addValue(distance2(cielab, qCIELAB));
}
final double[] key = { qR + qG + qB, error.getMean() };
final String line = "qRGB: " + qR + " " + qG + " " + qB + " " + ((qR + qG + qB)) +
" error: " + error.getMinimum() + " <= " + error.getMean() +
" ( " + sqrt(error.getVariance()) + " ) <= " + error.getMaximum();
synchronized (lines) {
lines.put(key, line);
System.out.println(line);
}
}
});
}
}
}
for (int qH0 = 0; qH0 <= 7; ++qH0) {
final int qH = qH0;
for (int qS0 = 0; qS0 <= 7; ++qS0) {
final int qS = qS0;
for (int qV0 = 0; qV0 <= 7; ++qV0) {
final int qV = qV0;
MultiThreadTools.getExecutor().submit(new Runnable() {
@Override
public final void run() {
final int[] rgb = new int[3];
final int[] qRGB = rgb.clone();
final float[] xyz = new float[3];
final float[] cielab = new float[3];
final float[] qCIELAB = cielab.clone();
final int[] hsv = new int[3];
final int[] qHSV = hsv.clone();
final Statistics error = new Statistics();
for (int color = 0; color <= 0x00FFFFFF; ++color) {
rgbToRGB(color, rgb);
rgbToXYZ(rgb, xyz);
xyzToCIELAB(xyz, cielab);
rgbToHSV(rgb, hsv);
quantize(hsv, qH, qS, qV, qHSV);
hsvToRGB(qHSV, qRGB);
rgbToXYZ(qRGB, xyz);
xyzToCIELAB(xyz, qCIELAB);
error.addValue(distance2(cielab, qCIELAB));
}
final double[] key = { qH + qS + qV, error.getMean() };
final String line = "qHSV: " + qH + " " + qS + " " + qV + " " + ((qH + qS + qV)) +
" error: " + error.getMinimum() + " <= " + error.getMean() +
" ( " + sqrt(error.getVariance()) + " ) <= " + error.getMaximum();
synchronized (lines) {
lines.put(key, line);
System.out.println(line);
}
}
});
}
}
}
shutdownAndWait(MultiThreadTools.getExecutor(), Long.MAX_VALUE);
System.out.println();
for (final String line : lines.values()) {
System.out.println(line);
}
}
@Test
public final void test2() {
final Color contourColor = Color.GREEN;
debugPrint(quantizers);
final SimpleImageView imageView = new SimpleImageView();
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(19, 0, quantizers.size() - 1, 1));
imageView.getPainters().add(new Painter<SimpleImageView>() {
private Canvas labels = new Canvas();
@Override
public final void paint(final Graphics2D g, final SimpleImageView component,
final int width, final int height) {
final TicToc timer = new TicToc();
timer.tic();
final ColorQuantizer quantizer = quantizers.get(((Number) spinner.getValue()).intValue());
final BufferedImage image = imageView.getImage();
final BufferedImage buffer = imageView.getBufferImage();
final int w = buffer.getWidth();
final int h = buffer.getHeight();
this.labels.setFormat(w, h, BufferedImage.TYPE_3BYTE_BGR);
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
this.labels.getImage().setRGB(x, y, quantizer.pack(image.getRGB(x, y)));
}
}
final SchedulingData schedulingData = new SchedulingData();
int totalPixelCount = 0;
final IntList small = new IntList();
for (int y = 0, pixel = 0, labelId = 0xFF000000; y < h; ++y) {
for (int x = 0; x < w; ++x, ++pixel) {
if (!schedulingData.getDone().get(pixel)) {
schedulingData.getTodo().add(pixel);
final int rgb = this.labels.getImage().getRGB(x, y);
for (int i = 0; i < schedulingData.getTodo().size(); ++i) {
final int p = schedulingData.getTodo().get(i);
this.labels.getImage().setRGB(p % w, p / w, labelId);
this.process(w, h, schedulingData, p % w, p / w, p, labelId, rgb);
}
final int componentPixelCount = schedulingData.getTodo().size();
++labelId;
totalPixelCount += componentPixelCount;
if (componentPixelCount <= 100) {
small.add(pixel);
}
schedulingData.getTodo().clear();
}
}
}
schedulingData.getDone().clear();
while (!small.isEmpty()) {
final int pixel = small.remove(0);
final int x = pixel % w;
final int y = pixel / w;
final int labelId = this.labels.getImage().getRGB(x, y);
if (!schedulingData.getDone().get(pixel)) {
schedulingData.getTodo().add(pixel);
final int rgb = this.labels.getImage().getRGB(x, y);
for (int i = 0; i < schedulingData.getTodo().size(); ++i) {
final int p = schedulingData.getTodo().get(i);
this.process(w, h, schedulingData, p % w, p / w, p, labelId, rgb);
}
final int componentPixelCount = schedulingData.getTodo().size();
if (componentPixelCount <= 100) {
final IntList neighborLabels = new IntList();
for (int i = 0; i < schedulingData.getTodo().size(); ++i) {
final int p = schedulingData.getTodo().get(i);
final int xx = p % w;
final int yy = p / w;
if (0 < yy) {
final int neighborLabel = this.labels.getImage().getRGB(xx, yy - 1);
if (neighborLabel != labelId) {
neighborLabels.add(neighborLabel);
}
}
if (0 < xx) {
final int neighborLabel = this.labels.getImage().getRGB(xx - 1, yy);
if (neighborLabel != labelId) {
neighborLabels.add(neighborLabel);
}
}
if (xx + 1 < w) {
final int neighborLabel = this.labels.getImage().getRGB(xx + 1, yy);
if (neighborLabel != labelId) {
neighborLabels.add(neighborLabel);
}
}
if (yy + 1 < h) {
final int neighborLabel = this.labels.getImage().getRGB(xx, yy + 1);
if (neighborLabel != labelId) {
neighborLabels.add(neighborLabel);
}
}
}
neighborLabels.sort();
int highestNeighborCount = 0;
int neighborLabel = -1;
for (int i = 0, count = 1, previousLabel = -1; i < neighborLabels.size(); ++i, ++count) {
final int label = neighborLabels.get(i);
if (label != previousLabel) {
count = 1;
}
if (highestNeighborCount < count) {
highestNeighborCount = count;
neighborLabel = label;
}
}
for (int i = 0; i < schedulingData.getTodo().size(); ++i) {
final int p = schedulingData.getTodo().get(i);
final int xx = p % w;
final int yy = p / w;
this.labels.getImage().setRGB(xx, yy, neighborLabel);
}
}
schedulingData.getTodo().clear();
}
}
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
int north = 0;
int west = 0;
int east = 0;
int south = 0;
if (0 < y) {
north = this.labels.getImage().getRGB(x, y - 1);
}
if (0 < x) {
west = this.labels.getImage().getRGB(x - 1, y);
}
if (x + 1 < w) {
east = this.labels.getImage().getRGB(x + 1, y);
}
if (y + 1 < h) {
south = this.labels.getImage().getRGB(x, y + 1);
}
final int center = this.labels.getImage().getRGB(x, y);
if (min(north, west, east, south) < center) {
buffer.setRGB(x, y, contourColor.getRGB());
}
}
}
if (w * h != totalPixelCount) {
System.err.println(debug(Tools.DEBUG_STACK_OFFSET, "Error:", "expected:", w * h, "actual:", totalPixelCount));
}
debugPrint(timer.toc());
}
private final void process(final int w, final int h,
final SchedulingData schedulingData, final int x, final int y,
final int pixel, final int labelId, final int rgb) {
schedulingData.getDone().set(pixel);
if (0 < y && this.labels.getImage().getRGB(x, y - 1) == rgb) {
final int neighbor = pixel - w;
if (!schedulingData.getDone().get(neighbor)) {
schedulingData.getDone().set(neighbor);
schedulingData.getTodo().add(neighbor);
}
}
if (0 < x && this.labels.getImage().getRGB(x - 1, y) == rgb) {
final int neighbor = pixel - 1;
if (!schedulingData.getDone().get(neighbor)) {
schedulingData.getDone().set(neighbor);
schedulingData.getTodo().add(neighbor);
}
}
if (x + 1 < w && this.labels.getImage().getRGB(x + 1, y) == rgb) {
final int neighbor = pixel + 1;
if (!schedulingData.getDone().get(neighbor)) {
schedulingData.getDone().set(neighbor);
schedulingData.getTodo().add(neighbor);
}
}
if (y + 1 < h && this.labels.getImage().getRGB(x, y + 1) == rgb) {
final int neighbor = pixel + w;
if (!schedulingData.getDone().get(neighbor)) {
schedulingData.getDone().set(neighbor);
schedulingData.getTodo().add(neighbor);
}
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = 8306989611117085093L;
});
final JPanel panel = new JPanel(new BorderLayout());
SwingTools.setCheckAWT(false);
spinner.addChangeListener(new ChangeListener() {
@Override
public final void stateChanged(final ChangeEvent event) {
imageView.refreshBuffer();
}
});
panel.add(horizontalBox(spinner), BorderLayout.NORTH);
panel.add(imageView, BorderLayout.CENTER);
show(panel, this.getClass().getSimpleName(), true);
}
private static final List<Object[]> table = new ArrayList<Object[]>();
static final List<ColorQuantizer> quantizers = new ArrayList<ColorQuantizer>();
static {
table.add(array("qRGB", 0, 0, 0, 0.0));
table.add(array("qHSV", 0, 0, 0, 0.6955260904279362));
table.add(array("qRGB", 1, 0, 0, 0.32641454294213));
table.add(array("qRGB", 0, 0, 1, 0.6240309742241252));
table.add(array("qRGB", 0, 1, 0, 0.7514458393503941));
table.add(array("qHSV", 0, 0, 1, 0.8751917410004951));
table.add(array("qHSV", 0, 1, 0, 1.126961289651885));
table.add(array("qHSV", 1, 0, 0, 1.7813204349626734));
table.add(array("qRGB", 1, 0, 1, 0.8583117538819247));
table.add(array("qRGB", 1, 1, 0, 0.8692188281204635));
table.add(array("qRGB", 2, 0, 0, 0.9808307435374101));
table.add(array("qRGB", 0, 1, 1, 1.0380778379038296));
table.add(array("qHSV", 0, 0, 2, 1.1659382941554577));
table.add(array("qHSV", 0, 1, 1, 1.2559919477363735));
table.add(array("qHSV", 1, 0, 1, 1.8951245566432926));
table.add(array("qRGB", 0, 0, 2, 1.8980446031157745));
table.add(array("qHSV", 1, 1, 0, 2.092400382244634));
table.add(array("qHSV", 0, 2, 0, 2.115374741291907));
table.add(array("qRGB", 0, 2, 0, 2.265005588909907));
table.add(array("qHSV", 2, 0, 0, 4.528551120210534));
table.add(array("qRGB", 1, 1, 1, 1.1180287803753424));
table.add(array("qRGB", 2, 1, 0, 1.2748883526552783));
table.add(array("qRGB", 2, 0, 1, 1.4067111100652796));
table.add(array("qHSV", 0, 1, 2, 1.5203314800623147));
table.add(array("qHSV", 0, 0, 3, 1.809747264609731));
table.add(array("qRGB", 0, 1, 2, 1.9618195348396559));
table.add(array("qRGB", 1, 0, 2, 2.064893103362241));
table.add(array("qHSV", 1, 0, 2, 2.1016815466827374));
table.add(array("qHSV", 1, 1, 1, 2.177229033053775));
table.add(array("qHSV", 0, 2, 1, 2.2173938408647693));
table.add(array("qRGB", 1, 2, 0, 2.2504013406529717));
table.add(array("qRGB", 0, 2, 1, 2.2932977370369603));
table.add(array("qRGB", 3, 0, 0, 2.2959598157696686));
table.add(array("qHSV", 1, 2, 0, 2.8907950047008057));
table.add(array("qHSV", 0, 3, 0, 4.270360710208371));
table.add(array("qRGB", 0, 0, 3, 4.52553090293637));
table.add(array("qHSV", 2, 0, 1, 4.592369919131593));
table.add(array("qHSV", 2, 1, 0, 4.722213766837409));
table.add(array("qRGB", 0, 3, 0, 5.333067162914784));
table.add(array("qHSV", 3, 0, 0, 10.133061431545565));
table.add(array("qRGB", 2, 1, 1, 1.4880175209433724));
table.add(array("qRGB", 1, 1, 2, 2.0282165668025764));
table.add(array("qHSV", 0, 1, 3, 2.152929318600153));
table.add(array("qRGB", 1, 2, 1, 2.2559129235446513));
table.add(array("qRGB", 3, 1, 0, 2.370351273948446));
table.add(array("qHSV", 1, 1, 2, 2.3731733681910288));
table.add(array("qRGB", 2, 2, 0, 2.389170595189107));
table.add(array("qHSV", 0, 2, 2, 2.450676449335271));
table.add(array("qRGB", 2, 0, 2, 2.4962070471616475));
table.add(array("qHSV", 1, 0, 3, 2.614980863199656));
table.add(array("qRGB", 3, 0, 1, 2.61968019557456));
table.add(array("qRGB", 0, 2, 2, 2.775659263227969));
table.add(array("qHSV", 1, 2, 1, 2.9645149300940132));
table.add(array("qHSV", 0, 0, 4, 3.308055191838597));
table.add(array("qRGB", 0, 1, 3, 4.3145002832409265));
table.add(array("qHSV", 0, 3, 1, 4.356094355535418));
table.add(array("qRGB", 1, 0, 3, 4.6480678384750584));
table.add(array("qHSV", 2, 0, 2, 4.720369162242616));
table.add(array("qHSV", 2, 1, 1, 4.771642243384687));
table.add(array("qHSV", 1, 3, 0, 4.820816066888919));
table.add(array("qRGB", 4, 0, 0, 4.951001286754124));
table.add(array("qRGB", 0, 3, 1, 5.179776824191323));
table.add(array("qRGB", 1, 3, 0, 5.245476477957572));
table.add(array("qHSV", 2, 2, 0, 5.275040700873244));
table.add(array("qHSV", 0, 4, 0, 8.608606861303441));
table.add(array("qRGB", 0, 0, 4, 10.005984804008115));
table.add(array("qHSV", 3, 0, 1, 10.16591826453798));
table.add(array("qHSV", 3, 1, 0, 10.246741129698233));
table.add(array("qRGB", 0, 4, 0, 11.621132862924227));
table.add(array("qHSV", 4, 0, 0, 21.441441059860917));
table.add(array("qRGB", 2, 1, 2, 2.345664153459157));
table.add(array("qRGB", 2, 2, 1, 2.3803760800798126));
table.add(array("qRGB", 3, 1, 1, 2.548324173801728));
table.add(array("qRGB", 1, 2, 2, 2.7386225128738215));
table.add(array("qHSV", 1, 1, 3, 2.890959844279944));
table.add(array("qHSV", 0, 2, 3, 3.039789316612684));
table.add(array("qRGB", 3, 2, 0, 3.0876627555063707));
table.add(array("qHSV", 1, 2, 2, 3.149855857626206));
table.add(array("qRGB", 3, 0, 2, 3.5456082043397177));
table.add(array("qHSV", 0, 1, 4, 3.6408406868479344));
table.add(array("qHSV", 1, 0, 4, 3.9301965018206424));
table.add(array("qRGB", 1, 1, 3, 4.377510140614242));
table.add(array("qRGB", 0, 2, 3, 4.55417176057843));
table.add(array("qHSV", 0, 3, 2, 4.558363544642229));
table.add(array("qRGB", 4, 1, 0, 4.866263779024119));
table.add(array("qHSV", 1, 3, 1, 4.890021661874276));
table.add(array("qHSV", 2, 1, 2, 4.896690972204208));
table.add(array("qRGB", 2, 0, 3, 4.975510162691538));
table.add(array("qHSV", 2, 0, 3, 5.073700328823798));
table.add(array("qRGB", 1, 3, 1, 5.076416388035941));
table.add(array("qRGB", 2, 3, 0, 5.186407432321236));
table.add(array("qRGB", 4, 0, 1, 5.18922966136709));
table.add(array("qRGB", 0, 3, 2, 5.253668905846729));
table.add(array("qHSV", 2, 2, 1, 5.321301853278064));
table.add(array("qHSV", 2, 3, 0, 6.78099035432321));
table.add(array("qHSV", 0, 0, 5, 6.8001379002246205));
table.add(array("qHSV", 0, 4, 1, 8.6804212735382));
table.add(array("qHSV", 1, 4, 0, 8.96150522653321));
table.add(array("qRGB", 0, 1, 4, 9.621269654573805));
table.add(array("qRGB", 1, 0, 4, 10.10082618502018));
table.add(array("qHSV", 3, 0, 2, 10.239604490826345));
table.add(array("qHSV", 3, 1, 1, 10.273738901017087));
table.add(array("qRGB", 5, 0, 0, 10.357214019008278));
table.add(array("qHSV", 3, 2, 0, 10.595095232353103));
table.add(array("qRGB", 0, 4, 1, 11.345079146799256));
table.add(array("qRGB", 1, 4, 0, 11.499694035514397));
table.add(array("qHSV", 0, 5, 0, 16.979860091230222));
table.add(array("qHSV", 4, 0, 1, 21.447935998355156));
table.add(array("qHSV", 4, 1, 0, 21.462964882808116));
table.add(array("qRGB", 0, 0, 5, 21.56144319342579));
table.add(array("qRGB", 0, 5, 0, 24.732918303318232));
table.add(array("qHSV", 5, 0, 0, 43.77691374160295));
table.add(array("qRGB", 2, 2, 2, 2.852922516764376));
table.add(array("qRGB", 3, 2, 1, 3.0828291421052723));
table.add(array("qRGB", 3, 1, 2, 3.3041165241821764));
table.add(array("qHSV", 1, 2, 3, 3.6541400074569506));
table.add(array("qHSV", 1, 1, 4, 4.215862457035969));
table.add(array("qHSV", 0, 2, 4, 4.460470627495945));
table.add(array("qRGB", 1, 2, 3, 4.539080994752359));
table.add(array("qRGB", 2, 1, 3, 4.6363242231465));
table.add(array("qRGB", 2, 3, 1, 5.004329263328033));
table.add(array("qRGB", 4, 1, 1, 5.011027074098335));
table.add(array("qHSV", 0, 3, 3, 5.062496531035296));
table.add(array("qHSV", 1, 3, 2, 5.063458476675465));
table.add(array("qRGB", 1, 3, 2, 5.147515511354933));
table.add(array("qRGB", 4, 2, 0, 5.167587135912787));
table.add(array("qHSV", 2, 1, 3, 5.260392593892533));
table.add(array("qRGB", 3, 3, 0, 5.432007270000069));
table.add(array("qHSV", 2, 2, 2, 5.446669044137193));
table.add(array("qRGB", 3, 0, 3, 5.825331577595821));
table.add(array("qRGB", 4, 0, 2, 5.931000598479003));
table.add(array("qHSV", 2, 0, 4, 6.082311495314012));
table.add(array("qRGB", 0, 3, 3, 6.254886430030773));
table.add(array("qHSV", 2, 3, 1, 6.830073389040216));
table.add(array("qHSV", 0, 1, 5, 7.122838491638112));
table.add(array("qHSV", 1, 0, 5, 7.218793962972602));
table.add(array("qHSV", 0, 4, 2, 8.848843990753025));
table.add(array("qHSV", 1, 4, 1, 9.024514418743152));
table.add(array("qRGB", 0, 2, 4, 9.322599398655775));
table.add(array("qRGB", 1, 1, 4, 9.682368743150985));
table.add(array("qRGB", 5, 1, 0, 10.172020644792356));
table.add(array("qHSV", 3, 1, 2, 10.346634555923645));
table.add(array("qRGB", 2, 0, 4, 10.349131860405612));
table.add(array("qHSV", 2, 4, 0, 10.378143392591879));
table.add(array("qHSV", 3, 0, 3, 10.46174533248007));
table.add(array("qRGB", 5, 0, 1, 10.533497144893856));
table.add(array("qHSV", 3, 2, 1, 10.62143108459401));
table.add(array("qRGB", 0, 4, 2, 11.08684873356561));
table.add(array("qRGB", 1, 4, 1, 11.212816854561149));
table.add(array("qRGB", 2, 4, 0, 11.32752806549405));
table.add(array("qHSV", 3, 3, 0, 11.635117350399002));
table.add(array("qHSV", 0, 0, 6, 15.668032586962413));
table.add(array("qHSV", 0, 5, 1, 17.04482075137555));
table.add(array("qHSV", 1, 5, 0, 17.187108424535914));
table.add(array("qRGB", 0, 1, 5, 21.08512918203094));
table.add(array("qHSV", 4, 1, 1, 21.469367174690095));
table.add(array("qHSV", 4, 0, 2, 21.473931969823585));
table.add(array("qRGB", 6, 0, 0, 21.532049376223195));
table.add(array("qHSV", 4, 2, 0, 21.59445165396762));
table.add(array("qRGB", 1, 0, 5, 21.638632549717023));
table.add(array("qRGB", 0, 5, 1, 24.37721172994415));
table.add(array("qRGB", 1, 5, 0, 24.60734851909329));
table.add(array("qHSV", 0, 6, 0, 32.73574351446413));
table.add(array("qHSV", 5, 1, 0, 43.751204156283656));
table.add(array("qHSV", 5, 0, 1, 43.76416717883281));
table.add(array("qRGB", 0, 0, 6, 46.13239365025457));
table.add(array("qRGB", 0, 6, 0, 52.70802175522528));
table.add(array("qHSV", 6, 0, 0, 83.81508873246744));
table.add(array("qRGB", 3, 2, 2, 3.527362691503131));
table.add(array("qRGB", 2, 2, 3, 4.653057616366176));
table.add(array("qHSV", 1, 2, 4, 4.950383818907108));
table.add(array("qRGB", 2, 3, 2, 5.068365988414407));
table.add(array("qRGB", 4, 2, 1, 5.178832026758057));
table.add(array("qRGB", 3, 3, 1, 5.253549057030269));
table.add(array("qRGB", 3, 1, 3, 5.433232494141032));
table.add(array("qHSV", 1, 3, 3, 5.516563492291423));
table.add(array("qRGB", 4, 1, 2, 5.635111396603524));
table.add(array("qHSV", 2, 2, 3, 5.816758192084616));
table.add(array("qRGB", 1, 3, 3, 6.166399561123543));
table.add(array("qHSV", 2, 1, 4, 6.289879138851597));
table.add(array("qHSV", 0, 3, 4, 6.345495263856095));
table.add(array("qRGB", 4, 3, 0, 6.783776610747946));
table.add(array("qHSV", 2, 3, 2, 6.958393497024418));
table.add(array("qHSV", 1, 1, 5, 7.514279390344463));
table.add(array("qHSV", 0, 2, 5, 7.850523125363171));
table.add(array("qRGB", 4, 0, 3, 7.909364447767676));
table.add(array("qHSV", 2, 0, 5, 8.893228803404542));
table.add(array("qHSV", 1, 4, 2, 9.177754256712644));
table.add(array("qHSV", 0, 4, 3, 9.270509807166043));
table.add(array("qRGB", 1, 2, 4, 9.33366729062409));
table.add(array("qRGB", 2, 1, 4, 9.890118915323102));
table.add(array("qRGB", 0, 3, 4, 9.929929778266683));
table.add(array("qRGB", 5, 2, 0, 10.138080062468157));
table.add(array("qRGB", 5, 1, 1, 10.29114858366));
table.add(array("qHSV", 2, 4, 1, 10.428669001108311));
table.add(array("qHSV", 3, 1, 3, 10.577000076352872));
table.add(array("qHSV", 3, 2, 2, 10.69795588995799));
table.add(array("qRGB", 1, 4, 2, 10.949224161393213));
table.add(array("qRGB", 3, 0, 4, 11.00602110019438));
table.add(array("qRGB", 2, 4, 1, 11.02877492642026));
table.add(array("qRGB", 5, 0, 2, 11.102983007881091));
table.add(array("qHSV", 3, 0, 4, 11.158505372879214));
table.add(array("qRGB", 3, 4, 0, 11.227760965671465));
table.add(array("qRGB", 0, 4, 3, 11.309405765689151));
table.add(array("qHSV", 3, 3, 1, 11.664870489106614));
table.add(array("qHSV", 3, 4, 0, 14.395372498170593));
table.add(array("qHSV", 1, 0, 6, 15.901936420764862));
table.add(array("qHSV", 0, 1, 6, 15.991471787000199));
table.add(array("qHSV", 0, 5, 2, 17.176936549609696));
table.add(array("qHSV", 1, 5, 1, 17.247695065696494));
table.add(array("qHSV", 2, 5, 0, 18.082575505826718));
table.add(array("qRGB", 0, 2, 5, 20.405035493287702));
table.add(array("qRGB", 1, 1, 5, 21.14347635507767));
table.add(array("qRGB", 6, 1, 0, 21.293096999751032));
table.add(array("qHSV", 4, 1, 2, 21.496241062179358));
table.add(array("qHSV", 4, 0, 3, 21.580207287110984));
table.add(array("qHSV", 4, 2, 1, 21.602329841806487));
table.add(array("qRGB", 6, 0, 1, 21.67462497600947));
table.add(array("qRGB", 2, 0, 5, 21.830723642418008));
table.add(array("qHSV", 4, 3, 0, 22.133768474410587));
table.add(array("qRGB", 0, 5, 2, 23.86359478382961));
table.add(array("qRGB", 1, 5, 1, 24.244431205525952));
table.add(array("qRGB", 2, 5, 0, 24.39691267076655));
table.add(array("qHSV", 0, 6, 1, 32.80316538441022));
table.add(array("qHSV", 1, 6, 0, 32.842233350233535));
table.add(array("qHSV", 5, 2, 0, 43.74076975658067));
table.add(array("qHSV", 5, 1, 1, 43.742010947423));
table.add(array("qHSV", 5, 0, 2, 43.7562916943628));
table.add(array("qHSV", 0, 0, 7, 44.92160259247629));
table.add(array("qRGB", 7, 0, 0, 45.176087377745176));
table.add(array("qRGB", 0, 1, 6, 45.62356017773505));
table.add(array("qRGB", 1, 0, 6, 46.196411417482125));
table.add(array("qRGB", 0, 6, 1, 52.301160399275815));
table.add(array("qRGB", 1, 6, 0, 52.61193218654751));
table.add(array("qHSV", 0, 7, 0, 61.80730533010471));
table.add(array("qHSV", 6, 1, 0, 83.63587197808127));
table.add(array("qHSV", 6, 0, 1, 83.76551042010584));
table.add(array("qRGB", 0, 0, 7, 98.58169362835481));
table.add(array("qRGB", 0, 7, 0, 113.80279045303948));
table.add(array("qHSV", 7, 0, 0, 156.02265105719644));
table.add(array("qRGB", 3, 2, 3, 5.253916642742753));
table.add(array("qRGB", 3, 3, 2, 5.313590650823462));
table.add(array("qRGB", 4, 2, 2, 5.575899042570833));
table.add(array("qRGB", 2, 3, 3, 6.102583333976196));
table.add(array("qRGB", 4, 3, 1, 6.637861657250586));
table.add(array("qHSV", 1, 3, 4, 6.720167065205978));
table.add(array("qHSV", 2, 2, 4, 6.853957182198859));
table.add(array("qHSV", 2, 3, 3, 7.313034588867101));
table.add(array("qRGB", 4, 1, 3, 7.4952032204868));
table.add(array("qHSV", 1, 2, 5, 8.19464651896803));
table.add(array("qHSV", 2, 1, 5, 9.128864210622176));
table.add(array("qRGB", 2, 2, 4, 9.45054024064088));
table.add(array("qHSV", 0, 3, 5, 9.50272830656282));
table.add(array("qHSV", 1, 4, 3, 9.57225682172096));
table.add(array("qRGB", 1, 3, 4, 9.878300576656232));
table.add(array("qRGB", 5, 2, 1, 10.168317697289462));
table.add(array("qHSV", 0, 4, 4, 10.325282646966802));
table.add(array("qRGB", 3, 1, 4, 10.513446996566712));
table.add(array("qHSV", 2, 4, 2, 10.553962637282169));
table.add(array("qRGB", 2, 4, 2, 10.754583231629907));
table.add(array("qRGB", 5, 1, 2, 10.78334660852396));
table.add(array("qRGB", 3, 4, 1, 10.923400572688765));
table.add(array("qHSV", 3, 2, 3, 10.940245342238159));
table.add(array("qRGB", 5, 3, 0, 10.948747935514554));
table.add(array("qRGB", 1, 4, 3, 11.177647318386894));
table.add(array("qHSV", 3, 1, 4, 11.292017176980279));
table.add(array("qHSV", 3, 3, 2, 11.749442609095881));
table.add(array("qRGB", 4, 4, 0, 11.754305664224468));
table.add(array("qRGB", 4, 0, 4, 12.707821916090875));
table.add(array("qRGB", 5, 0, 3, 12.721094610289231));
table.add(array("qHSV", 3, 0, 5, 13.321914762530062));
table.add(array("qRGB", 0, 4, 4, 13.462907410406403));
table.add(array("qHSV", 3, 4, 1, 14.428941545444602));
table.add(array("qHSV", 1, 1, 6, 16.213530849741776));
table.add(array("qHSV", 0, 2, 6, 16.595732776692728));
table.add(array("qHSV", 2, 0, 6, 16.990247872051476));
table.add(array("qHSV", 1, 5, 2, 17.37262548192689));
table.add(array("qHSV", 0, 5, 3, 17.50097970500494));
table.add(array("qHSV", 2, 5, 1, 18.135576856216254));
table.add(array("qRGB", 0, 3, 5, 19.920991125299423));
table.add(array("qRGB", 1, 2, 5, 20.43422559355158));
table.add(array("qHSV", 3, 5, 0, 20.953539337715004));
table.add(array("qRGB", 6, 2, 0, 21.039614618747564));
table.add(array("qRGB", 2, 1, 5, 21.311634080572432));
table.add(array("qRGB", 6, 1, 1, 21.402040306383505));
table.add(array("qHSV", 4, 1, 3, 21.607639767259705));
table.add(array("qHSV", 4, 2, 2, 21.635546199656854));
table.add(array("qHSV", 4, 0, 4, 21.980255130529887));
table.add(array("qRGB", 6, 0, 2, 22.113679071750695));
table.add(array("qHSV", 4, 3, 1, 22.144316336683882));
table.add(array("qRGB", 3, 0, 5, 22.328417765460777));
table.add(array("qRGB", 0, 5, 3, 23.401054294240303));
table.add(array("qRGB", 1, 5, 2, 23.725014384855967));
table.add(array("qHSV", 4, 4, 0, 23.862897375364486));
table.add(array("qRGB", 2, 5, 1, 24.024643580435026));
table.add(array("qRGB", 3, 5, 0, 24.123412933265822));
table.add(array("qHSV", 0, 6, 2, 32.89667758007501));
table.add(array("qHSV", 1, 6, 1, 32.90781890164448));
table.add(array("qHSV", 2, 6, 0, 33.32236993216267));
table.add(array("qHSV", 5, 2, 1, 43.73216585611982));
table.add(array("qHSV", 5, 1, 2, 43.73285247357186));
table.add(array("qHSV", 5, 0, 3, 43.773924275773595));
table.add(array("qHSV", 5, 3, 0, 43.87212842657174));
table.add(array("qRGB", 0, 2, 6, 44.73957191563254));
table.add(array("qRGB", 7, 1, 0, 44.91994210785489));
table.add(array("qHSV", 1, 0, 7, 45.012075852208746));
table.add(array("qRGB", 7, 0, 1, 45.321510970753366));
table.add(array("qHSV", 0, 1, 7, 45.3975990469012));
table.add(array("qRGB", 1, 1, 6, 45.67720247527094));
table.add(array("qRGB", 2, 0, 6, 46.3468570278201));
table.add(array("qRGB", 0, 6, 2, 51.60143636551707));
table.add(array("qRGB", 1, 6, 1, 52.200354051560105));
table.add(array("qRGB", 2, 6, 0, 52.442942082617805));
table.add(array("qHSV", 1, 7, 0, 61.84624110147413));
table.add(array("qHSV", 0, 7, 1, 61.98559575821476));
table.add(array("qHSV", 6, 2, 0, 83.31021735981916));
table.add(array("qHSV", 6, 1, 1, 83.59644325622138));
table.add(array("qHSV", 6, 0, 2, 83.70003079189063));
table.add(array("qRGB", 0, 1, 7, 98.09175375687065));
table.add(array("qRGB", 1, 0, 7, 98.63222463427425));
table.add(array("qRGB", 0, 7, 1, 113.35848060108387));
table.add(array("qRGB", 1, 7, 0, 113.79100745068551));
table.add(array("qHSV", 7, 1, 0, 155.76875083166007));
table.add(array("qHSV", 7, 0, 1, 155.9388815899415));
table.add(array("qRGB", 3, 3, 3, 6.340866483189372));
table.add(array("qRGB", 4, 3, 2, 6.709653006265603));
table.add(array("qRGB", 4, 2, 3, 7.129963963236756));
table.add(array("qHSV", 2, 3, 4, 8.320823808478119));
table.add(array("qHSV", 2, 2, 5, 9.692344955617365));
table.add(array("qHSV", 1, 3, 5, 9.779610923631795));
table.add(array("qRGB", 2, 3, 4, 9.857522392338288));
table.add(array("qRGB", 3, 2, 4, 9.950763892439424));
table.add(array("qRGB", 5, 2, 2, 10.507557830242826));
table.add(array("qHSV", 1, 4, 4, 10.584318858953525));
table.add(array("qRGB", 3, 4, 2, 10.638399022749269));
table.add(array("qRGB", 5, 3, 1, 10.85649017076917));
table.add(array("qHSV", 2, 4, 3, 10.886674213271974));
table.add(array("qRGB", 2, 4, 3, 10.986209294528791));
table.add(array("qRGB", 4, 4, 1, 11.46652530930045));
table.add(array("qHSV", 3, 2, 4, 11.673906598335554));
table.add(array("qHSV", 3, 3, 3, 11.994609999866599));
table.add(array("qRGB", 4, 1, 4, 12.20218340832902));
table.add(array("qRGB", 5, 1, 3, 12.312975745853725));
table.add(array("qHSV", 0, 4, 5, 13.149357181796196));
table.add(array("qRGB", 1, 4, 4, 13.35518595291978));
table.add(array("qHSV", 3, 1, 5, 13.487052808959266));
table.add(array("qHSV", 3, 4, 2, 14.518904965426142));
table.add(array("qRGB", 5, 4, 0, 14.556491367623703));
table.add(array("qHSV", 1, 2, 6, 16.799177364455836));
table.add(array("qRGB", 5, 0, 4, 16.923951577513773));
table.add(array("qHSV", 2, 1, 6, 17.266229614644402));
table.add(array("qHSV", 1, 5, 3, 17.683854172496947));
table.add(array("qHSV", 0, 3, 6, 18.027459361336454));
table.add(array("qHSV", 2, 5, 2, 18.246274714415243));
table.add(array("qHSV", 0, 5, 4, 18.349046936514938));
table.add(array("qRGB", 1, 3, 5, 19.907650136450783));
table.add(array("qHSV", 3, 0, 6, 20.31449096221656));
table.add(array("qRGB", 2, 2, 5, 20.549489748044554));
table.add(array("qHSV", 3, 5, 1, 20.994690069622262));
table.add(array("qRGB", 6, 2, 1, 21.093244874228947));
table.add(array("qRGB", 6, 3, 0, 21.19254912139334));
table.add(array("qRGB", 0, 4, 5, 21.246600560116846));
table.add(array("qHSV", 4, 2, 3, 21.75875632193585));
table.add(array("qRGB", 3, 1, 5, 21.78644893297665));
table.add(array("qRGB", 6, 1, 2, 21.79250600681563));
table.add(array("qHSV", 4, 1, 4, 22.02443261543551));
table.add(array("qHSV", 4, 3, 2, 22.186876867524546));
table.add(array("qRGB", 1, 5, 3, 23.260883706223176));
table.add(array("qRGB", 6, 0, 3, 23.386703338692957));
table.add(array("qHSV", 4, 0, 5, 23.427093643965375));
table.add(array("qRGB", 2, 5, 2, 23.493924375351092));
table.add(array("qRGB", 4, 0, 5, 23.642266327011406));
table.add(array("qRGB", 3, 5, 1, 23.741972884777905));
table.add(array("qHSV", 4, 4, 1, 23.879017394229695));
table.add(array("qRGB", 0, 5, 4, 23.943637893089022));
table.add(array("qRGB", 4, 5, 0, 24.063262335361493));
table.add(array("qHSV", 4, 5, 0, 28.615899360492723));
table.add(array("qHSV", 1, 6, 2, 32.99827811369083));
table.add(array("qHSV", 0, 6, 3, 33.1286253581266));
table.add(array("qHSV", 2, 6, 1, 33.3839421900219));
table.add(array("qHSV", 3, 6, 0, 35.009802069537756));
table.add(array("qRGB", 0, 3, 6, 43.460896182311956));
table.add(array("qHSV", 5, 2, 2, 43.73202855891318));
table.add(array("qHSV", 5, 1, 3, 43.7535637956447));
table.add(array("qHSV", 5, 3, 1, 43.86640260615535));
table.add(array("qHSV", 5, 0, 4, 43.92909101484812));
table.add(array("qHSV", 5, 4, 0, 44.55571124845371));
table.add(array("qRGB", 7, 2, 0, 44.55833251204558));
table.add(array("qRGB", 1, 2, 6, 44.776897391602574));
table.add(array("qRGB", 7, 1, 1, 45.04637978612198));
table.add(array("qHSV", 1, 1, 7, 45.482246920674726));
table.add(array("qHSV", 2, 0, 7, 45.51365112224777));
table.add(array("qRGB", 7, 0, 2, 45.70512868979869));
table.add(array("qRGB", 2, 1, 6, 45.813611637632384));
table.add(array("qHSV", 0, 2, 7, 45.89436224260916));
table.add(array("qRGB", 3, 0, 6, 46.720243380629405));
table.add(array("qRGB", 0, 6, 3, 50.56913459912434));
table.add(array("qRGB", 1, 6, 2, 51.495507349823036));
table.add(array("qRGB", 2, 6, 1, 52.024598427168634));
table.add(array("qRGB", 3, 6, 0, 52.19106917882459));
table.add(array("qHSV", 0, 7, 2, 62.01143653140464));
table.add(array("qHSV", 1, 7, 1, 62.023247577307245));
table.add(array("qHSV", 2, 7, 0, 62.02579926667945));
table.add(array("qHSV", 6, 3, 0, 82.76435853485751));
table.add(array("qHSV", 6, 2, 1, 83.27401911307462));
table.add(array("qHSV", 6, 1, 2, 83.53199900326042));
table.add(array("qHSV", 6, 0, 3, 83.58759338540732));
table.add(array("qRGB", 0, 2, 7, 97.16239083873536));
table.add(array("qRGB", 1, 1, 7, 98.13677798324206));
table.add(array("qRGB", 2, 0, 7, 98.74559245319055));
table.add(array("qRGB", 0, 7, 2, 112.52326535326874));
table.add(array("qRGB", 1, 7, 1, 113.34355286396212));
table.add(array("qRGB", 2, 7, 0, 113.78207678079858));
table.add(array("qHSV", 7, 2, 0, 155.26271089738088));
table.add(array("qHSV", 7, 1, 1, 155.69921989766797));
table.add(array("qHSV", 7, 0, 2, 155.81640234578813));
table.add(array("qRGB", 4, 3, 3, 7.688442546008208));
table.add(array("qRGB", 3, 3, 4, 10.095141022638085));
table.add(array("qRGB", 3, 4, 3, 10.864897114402869));
table.add(array("qRGB", 5, 3, 2, 10.951615663240458));
table.add(array("qHSV", 2, 3, 5, 11.070154272260991));
table.add(array("qRGB", 4, 4, 2, 11.191632862199885));
table.add(array("qRGB", 4, 2, 4, 11.52598396241005));
table.add(array("qHSV", 2, 4, 4, 11.782463229695244));
table.add(array("qRGB", 5, 2, 3, 11.819634155213707));
table.add(array("qHSV", 3, 3, 4, 12.734447695338403));
table.add(array("qRGB", 2, 4, 4, 13.198005564072307));
table.add(array("qHSV", 1, 4, 5, 13.349700851194054));
table.add(array("qHSV", 3, 2, 5, 13.89682265182176));
table.add(array("qRGB", 5, 4, 1, 14.322611845014073));
table.add(array("qHSV", 3, 4, 3, 14.765915006914788));
table.add(array("qRGB", 5, 1, 4, 16.431998213672987));
table.add(array("qHSV", 2, 2, 6, 17.794743002263));
table.add(array("qHSV", 1, 3, 6, 18.19966125131184));
table.add(array("qHSV", 1, 5, 4, 18.509866614595577));
table.add(array("qHSV", 2, 5, 3, 18.52725317113241));
table.add(array("qRGB", 2, 3, 5, 19.933533714232336));
table.add(array("qHSV", 3, 1, 6, 20.533316034673383));
table.add(array("qHSV", 0, 5, 5, 20.662238654155118));
table.add(array("qRGB", 3, 2, 5, 20.95052655636009));
table.add(array("qHSV", 3, 5, 2, 21.083018105884644));
table.add(array("qHSV", 0, 4, 6, 21.110219649964062));
table.add(array("qRGB", 6, 3, 1, 21.161371921806357));
table.add(array("qRGB", 1, 4, 5, 21.18027776782719));
table.add(array("qRGB", 6, 2, 2, 21.38663005776269));
table.add(array("qHSV", 4, 2, 4, 22.196381149547953));
table.add(array("qHSV", 4, 3, 3, 22.32389197746879));
table.add(array("qRGB", 6, 1, 3, 23.0029729164763));
table.add(array("qRGB", 2, 5, 3, 23.022684799085344));
table.add(array("qRGB", 4, 1, 5, 23.086305798726343));
table.add(array("qRGB", 3, 5, 2, 23.194828446980296));
table.add(array("qRGB", 6, 4, 0, 23.288580709898017));
table.add(array("qHSV", 4, 1, 5, 23.501867553611202));
table.add(array("qRGB", 4, 5, 1, 23.68088624329254));
table.add(array("qRGB", 1, 5, 4, 23.811048702797404));
table.add(array("qHSV", 4, 4, 2, 23.930560280338014));
table.add(array("qRGB", 5, 5, 0, 25.402895483675284));
table.add(array("qRGB", 6, 0, 4, 26.864638036544115));
table.add(array("qRGB", 5, 0, 5, 27.081377578441117));
table.add(array("qRGB", 0, 5, 5, 28.54063915420294));
table.add(array("qHSV", 4, 5, 1, 28.641730651838913));
table.add(array("qHSV", 4, 0, 6, 28.854331775352687));
table.add(array("qHSV", 1, 6, 3, 33.22460294147693));
table.add(array("qHSV", 2, 6, 2, 33.46921764781381));
table.add(array("qHSV", 0, 6, 4, 33.702579763034635));
table.add(array("qHSV", 3, 6, 1, 35.06389034413055));
table.add(array("qHSV", 4, 6, 0, 40.137731481784115));
table.add(array("qRGB", 0, 4, 6, 42.525753512691516));
table.add(array("qRGB", 1, 3, 6, 43.47286860289719));
table.add(array("qHSV", 5, 2, 3, 43.75703255179147));
table.add(array("qHSV", 5, 3, 2, 43.86973635535911));
table.add(array("qHSV", 5, 1, 4, 43.9193503618413));
table.add(array("qRGB", 7, 3, 0, 44.309567106007385));
table.add(array("qHSV", 5, 4, 1, 44.55595283640167));
table.add(array("qRGB", 7, 2, 1, 44.652283598962846));
table.add(array("qHSV", 5, 0, 5, 44.70057087412785));
table.add(array("qRGB", 2, 2, 6, 44.88342483911719));
table.add(array("qRGB", 7, 1, 2, 45.40073048149536));
table.add(array("qHSV", 2, 1, 7, 45.957826377522295));
table.add(array("qHSV", 1, 2, 7, 45.97438884520198));
table.add(array("qRGB", 3, 1, 6, 46.171046220192245));
table.add(array("qRGB", 7, 0, 3, 46.74410786531797));
table.add(array("qHSV", 0, 3, 7, 46.94047509487422));
table.add(array("qHSV", 5, 5, 0, 46.98065616162865));
table.add(array("qHSV", 3, 0, 7, 47.31084724651443));
table.add(array("qRGB", 4, 0, 6, 47.69348627992129));
table.add(array("qRGB", 0, 6, 4, 49.58886169746684));
table.add(array("qRGB", 1, 6, 3, 50.45815908106512));
table.add(array("qRGB", 2, 6, 2, 51.30975863355777));
table.add(array("qRGB", 3, 6, 1, 51.76398032287591));
table.add(array("qRGB", 4, 6, 0, 51.98456631116456));
table.add(array("qHSV", 1, 7, 2, 62.0476400938254));
table.add(array("qHSV", 0, 7, 3, 62.08910702114573));
table.add(array("qHSV", 2, 7, 1, 62.19923587229031));
table.add(array("qHSV", 3, 7, 0, 62.71396179748241));
table.add(array("qHSV", 6, 4, 0, 82.01003193662558));
table.add(array("qHSV", 6, 3, 1, 82.73396479269887));
table.add(array("qHSV", 6, 2, 2, 83.2140183000991));
table.add(array("qHSV", 6, 1, 3, 83.4241302922701));
table.add(array("qHSV", 6, 0, 4, 83.43394427208376));
table.add(array("qRGB", 0, 3, 7, 95.5024295094967));
table.add(array("qRGB", 1, 2, 7, 97.19867684302076));
table.add(array("qRGB", 2, 1, 7, 98.2421679833705));
table.add(array("qRGB", 3, 0, 7, 99.01508349160125));
table.add(array("qRGB", 0, 7, 3, 111.04199670996694));
table.add(array("qRGB", 1, 7, 2, 112.50410102149714));
table.add(array("qRGB", 2, 7, 1, 113.32974893931791));
table.add(array("qRGB", 3, 7, 0, 113.8193934779908));
table.add(array("qHSV", 7, 3, 0, 154.25179097350306));
table.add(array("qHSV", 7, 2, 1, 155.19759088118153));
table.add(array("qHSV", 7, 0, 3, 155.5731316317515));
table.add(array("qHSV", 7, 1, 2, 155.57639462650135));
table.add(array("qRGB", 4, 3, 4, 11.300385291883343));
table.add(array("qRGB", 4, 4, 3, 11.413287765007333));
table.add(array("qRGB", 5, 3, 3, 11.835590580277925));
table.add(array("qRGB", 3, 4, 4, 13.105170302239044));
table.add(array("qRGB", 5, 4, 2, 14.102725593278263));
table.add(array("qHSV", 2, 4, 5, 14.342172542032769));
table.add(array("qHSV", 3, 3, 5, 14.946261925820883));
table.add(array("qHSV", 3, 4, 4, 15.46518525367638));
table.add(array("qRGB", 5, 2, 4, 15.6937208294619));
table.add(array("qHSV", 2, 3, 6, 19.079145485722293));
table.add(array("qHSV", 2, 5, 4, 19.290435137212366));
table.add(array("qRGB", 3, 3, 5, 20.16864052990391));
table.add(array("qHSV", 1, 5, 5, 20.791984112466153));
table.add(array("qHSV", 3, 2, 6, 20.96089276744169));
table.add(array("qRGB", 2, 4, 5, 21.08938909810169));
table.add(array("qHSV", 1, 4, 6, 21.243770468351563));
table.add(array("qRGB", 6, 3, 2, 21.288110810768334));
table.add(array("qHSV", 3, 5, 3, 21.312307819388156));
table.add(array("qRGB", 4, 2, 5, 22.178404640544578));
table.add(array("qRGB", 6, 2, 3, 22.45089367092038));
table.add(array("qRGB", 3, 5, 3, 22.70561761512323));
table.add(array("qHSV", 4, 3, 4, 22.783387113717136));
table.add(array("qRGB", 4, 5, 2, 23.12311052644533));
table.add(array("qRGB", 6, 4, 1, 23.13965229796283));
table.add(array("qRGB", 2, 5, 4, 23.581710343484367));
table.add(array("qHSV", 4, 2, 5, 23.712242409809047));
table.add(array("qHSV", 4, 4, 3, 24.08132103092352));
table.add(array("qRGB", 5, 5, 1, 25.045878832584336));
table.add(array("qRGB", 6, 1, 4, 26.409192843237044));
table.add(array("qRGB", 5, 1, 5, 26.529047924439634));
table.add(array("qHSV", 0, 5, 6, 27.63065202910769));
table.add(array("qRGB", 1, 5, 5, 28.431190265339374));
table.add(array("qHSV", 4, 5, 2, 28.6992567436543));
table.add(array("qHSV", 4, 1, 6, 28.982662338530055));
table.add(array("qRGB", 6, 5, 0, 31.698950614604737));
table.add(array("qHSV", 2, 6, 3, 33.68213058054486));
table.add(array("qHSV", 1, 6, 4, 33.78916238071692));
table.add(array("qHSV", 3, 6, 2, 35.137672403014726));
table.add(array("qHSV", 0, 6, 5, 35.38285901058025));
table.add(array("qRGB", 6, 0, 5, 35.798088797723715));
table.add(array("qHSV", 4, 6, 1, 40.17942007592115));
table.add(array("qRGB", 1, 4, 6, 42.499987755993985));
table.add(array("qRGB", 2, 3, 6, 43.52716203099239));
table.add(array("qHSV", 5, 3, 3, 43.906895816832254));
table.add(array("qHSV", 5, 2, 4, 43.935627297756106));
table.add(array("qRGB", 7, 3, 1, 44.349719267806194));
table.add(array("qHSV", 5, 4, 2, 44.56590570376091));
table.add(array("qHSV", 5, 1, 5, 44.70977685547477));
table.add(array("qRGB", 7, 2, 2, 44.94814474219706));
table.add(array("qRGB", 0, 5, 6, 45.098262849514896));
table.add(array("qRGB", 3, 2, 6, 45.19680023082748));
table.add(array("qRGB", 7, 4, 0, 45.24050897140638));
table.add(array("qRGB", 7, 1, 3, 46.397617749593216));
table.add(array("qHSV", 2, 2, 7, 46.42892542288154));
table.add(array("qHSV", 5, 5, 1, 46.98756966975928));
table.add(array("qHSV", 1, 3, 7, 47.01472807679523));
table.add(array("qRGB", 4, 1, 6, 47.12882395174464));
table.add(array("qHSV", 3, 1, 7, 47.69825145609503));
table.add(array("qHSV", 5, 0, 6, 48.30892314902963));
table.add(array("qHSV", 0, 4, 7, 49.13722160795946));
table.add(array("qRGB", 1, 6, 4, 49.47449215886267));
table.add(array("qRGB", 7, 0, 4, 49.56445112803157));
table.add(array("qRGB", 2, 6, 3, 50.26044398911863));
table.add(array("qRGB", 5, 0, 6, 50.31137045369451));
table.add(array("qRGB", 0, 6, 5, 50.568076039984064));
table.add(array("qRGB", 3, 6, 2, 51.032435381608266));
table.add(array("qRGB", 4, 6, 1, 51.548862763853826));
table.add(array("qRGB", 5, 6, 0, 52.552285583869214));
table.add(array("qHSV", 4, 0, 7, 52.8129511776001));
table.add(array("qHSV", 5, 6, 0, 54.13995592279949));
table.add(array("qHSV", 1, 7, 3, 62.123968137878016));
table.add(array("qHSV", 2, 7, 2, 62.221939996879684));
table.add(array("qHSV", 0, 7, 4, 62.31871516714029));
table.add(array("qHSV", 3, 7, 1, 62.87714478304283));
table.add(array("qHSV", 4, 7, 0, 65.07473789181662));
table.add(array("qHSV", 6, 5, 0, 81.4408397301875));
table.add(array("qHSV", 6, 4, 1, 81.98400997685754));
table.add(array("qHSV", 6, 3, 2, 82.67858543292775));
table.add(array("qHSV", 6, 2, 3, 83.11171679692882));
table.add(array("qHSV", 6, 1, 4, 83.27724778864844));
table.add(array("qHSV", 6, 0, 5, 83.41585847422323));
table.add(array("qRGB", 0, 4, 7, 92.95641588673492));
table.add(array("qRGB", 1, 3, 7, 95.52435465074312));
table.add(array("qRGB", 2, 2, 7, 97.28774943440655));
table.add(array("qRGB", 3, 1, 7, 98.50079273033025));
table.add(array("qRGB", 4, 0, 7, 99.70123907935444));
table.add(array("qRGB", 0, 7, 4, 108.70942567609441));
table.add(array("qRGB", 1, 7, 3, 111.01652069235655));
table.add(array("qRGB", 2, 7, 2, 112.48198468055303));
table.add(array("qRGB", 3, 7, 1, 113.35964114383401));
table.add(array("qRGB", 4, 7, 0, 114.08455335800612));
table.add(array("qHSV", 7, 4, 0, 152.26767295140053));
table.add(array("qHSV", 7, 3, 1, 154.18872685701697));
table.add(array("qHSV", 7, 2, 2, 155.07487080911943));
table.add(array("qHSV", 7, 0, 4, 155.09750765195514));
table.add(array("qHSV", 7, 1, 3, 155.33090566219985));
table.add(array("qRGB", 4, 4, 4, 13.635492369684071));
table.add(array("qRGB", 5, 4, 3, 14.339651153267729));
table.add(array("qRGB", 5, 3, 4, 15.105009711688462));
table.add(array("qHSV", 3, 4, 5, 17.613021066244166));
table.add(array("qRGB", 3, 4, 5, 21.06899986017425));
table.add(array("qRGB", 4, 3, 5, 21.163357953208294));
table.add(array("qHSV", 2, 5, 5, 21.459022937564324));
table.add(array("qHSV", 3, 5, 4, 21.953548327784002));
table.add(array("qHSV", 2, 4, 6, 21.953794391617667));
table.add(array("qHSV", 3, 3, 6, 22.015191420102827));
table.add(array("qRGB", 6, 3, 3, 22.057818941088346));
table.add(array("qRGB", 4, 5, 3, 22.611345132538872));
table.add(array("qRGB", 6, 4, 2, 23.01722632330868));
table.add(array("qRGB", 3, 5, 4, 23.26583544312819));
table.add(array("qHSV", 4, 3, 5, 24.334741391416884));
table.add(array("qRGB", 5, 5, 2, 24.513149100441726));
table.add(array("qHSV", 4, 4, 4, 24.54206993455648));
table.add(array("qRGB", 5, 2, 5, 25.583221839197073));
table.add(array("qRGB", 6, 2, 4, 25.672319962794653));
table.add(array("qHSV", 1, 5, 6, 27.723584486538304));
table.add(array("qRGB", 2, 5, 5, 28.24066686271142));
table.add(array("qHSV", 4, 5, 3, 28.858335408264463));
table.add(array("qHSV", 4, 2, 6, 29.245750524384043));
table.add(array("qRGB", 6, 5, 1, 31.41318872510949));
table.add(array("qHSV", 2, 6, 4, 34.22040714241764));
table.add(array("qRGB", 6, 1, 5, 35.27323810665261));
table.add(array("qHSV", 3, 6, 3, 35.32334270831286));
table.add(array("qHSV", 1, 6, 5, 35.45535791369207));
table.add(array("qHSV", 4, 6, 2, 40.23476684721952));
table.add(array("qHSV", 0, 6, 6, 40.75582097662498));
table.add(array("qRGB", 2, 4, 6, 42.47457324801316));
table.add(array("qRGB", 3, 3, 6, 43.743810942045144));
table.add(array("qHSV", 5, 3, 4, 44.10013792348927));
table.add(array("qRGB", 7, 3, 2, 44.5399115043061));
table.add(array("qHSV", 5, 4, 3, 44.61240036097907));
table.add(array("qHSV", 5, 2, 5, 44.75074825138069));
table.add(array("qRGB", 1, 5, 6, 45.02628653090765));
table.add(array("qRGB", 7, 4, 1, 45.19548827530423));
table.add(array("qRGB", 7, 2, 3, 45.85128412568048));
table.add(array("qRGB", 4, 2, 6, 46.104706678281275));
table.add(array("qHSV", 5, 5, 2, 47.00216719845255));
table.add(array("qHSV", 2, 3, 7, 47.434430403929944));
table.add(array("qHSV", 3, 2, 7, 48.113864245075504));
table.add(array("qHSV", 5, 1, 6, 48.35414705431072));
table.add(array("qRGB", 7, 1, 4, 49.16085177151545));
table.add(array("qHSV", 1, 4, 7, 49.200744348108195));
table.add(array("qRGB", 2, 6, 4, 49.26688031984588));
table.add(array("qRGB", 5, 1, 6, 49.736293373767865));
table.add(array("qRGB", 3, 6, 3, 49.95796953990217));
table.add(array("qRGB", 1, 6, 5, 50.455210971385455));
table.add(array("qRGB", 4, 6, 2, 50.79571129684579));
table.add(array("qRGB", 7, 5, 0, 51.06486999908676));
table.add(array("qRGB", 5, 6, 1, 52.116365829212135));
table.add(array("qHSV", 4, 1, 7, 53.10463249735915));
table.add(array("qHSV", 0, 5, 7, 53.78015545839082));
table.add(array("qHSV", 5, 6, 1, 54.159747593732384));
table.add(array("qRGB", 6, 6, 0, 56.65347676334426));
table.add(array("qRGB", 7, 0, 5, 57.05088417395533));
table.add(array("qRGB", 6, 0, 6, 57.387399296171345));
table.add(array("qRGB", 0, 6, 6, 59.83107919981765));
table.add(array("qHSV", 2, 7, 3, 62.295216190063));
table.add(array("qHSV", 1, 7, 4, 62.35076210418596));
table.add(array("qHSV", 3, 7, 2, 62.89298902640965));
table.add(array("qHSV", 0, 7, 5, 63.112997894458175));
table.add(array("qHSV", 4, 7, 1, 65.22501380465377));
table.add(array("qHSV", 5, 0, 7, 67.35803299473069));
table.add(array("qHSV", 5, 7, 0, 72.5529842358517));
table.add(array("qHSV", 6, 5, 1, 81.41961158006531));
table.add(array("qHSV", 6, 4, 2, 81.93752641201267));
table.add(array("qHSV", 6, 3, 3, 82.59066390393983));
table.add(array("qHSV", 6, 6, 0, 82.68591896276428));
table.add(array("qHSV", 6, 2, 4, 82.97878839973524));
table.add(array("qHSV", 6, 1, 5, 83.27251053606977));
table.add(array("qHSV", 6, 0, 6, 84.8281185595414));
table.add(array("qRGB", 0, 5, 7, 90.63206534182964));
table.add(array("qRGB", 1, 4, 7, 92.95451501587132));
table.add(array("qRGB", 2, 3, 7, 95.58421617689663));
table.add(array("qRGB", 3, 2, 7, 97.52004006544156));
table.add(array("qRGB", 4, 1, 7, 99.1720497524499));
table.add(array("qRGB", 5, 0, 7, 101.56712234851004));
table.add(array("qRGB", 0, 7, 5, 105.99908554244503));
table.add(array("qRGB", 1, 7, 4, 108.67401118003978));
table.add(array("qRGB", 2, 7, 3, 110.9808282044467));
table.add(array("qRGB", 3, 7, 2, 112.49699129233186));
table.add(array("qRGB", 4, 7, 1, 113.61400042659453));
table.add(array("qRGB", 5, 7, 0, 115.24588503540951));
table.add(array("qHSV", 7, 5, 0, 148.4866525222472));
table.add(array("qHSV", 7, 4, 1, 152.20702004897882));
table.add(array("qHSV", 7, 3, 2, 154.06650658928004));
table.add(array("qHSV", 7, 0, 5, 154.22820386668872));
table.add(array("qHSV", 7, 2, 3, 154.8302458267778));
table.add(array("qHSV", 7, 1, 4, 154.85496721006646));
table.add(array("qRGB", 5, 4, 4, 16.452327018216238));
table.add(array("qRGB", 4, 4, 5, 21.576691496711987));
table.add(array("qRGB", 4, 5, 4, 23.151504858179628));
table.add(array("qRGB", 6, 4, 3, 23.29238320073896));
table.add(array("qHSV", 3, 5, 5, 23.855937179825872));
table.add(array("qRGB", 5, 5, 3, 24.010895759787857));
table.add(array("qRGB", 5, 3, 5, 24.345372151173603));
table.add(array("qHSV", 3, 4, 6, 24.483664759259558));
table.add(array("qRGB", 6, 3, 4, 24.84121606806918));
table.add(array("qHSV", 4, 4, 5, 26.121861030618177));
table.add(array("qRGB", 3, 5, 5, 27.975681776202745));
table.add(array("qHSV", 2, 5, 6, 28.22285519819319));
table.add(array("qHSV", 4, 5, 4, 29.326939071136668));
table.add(array("qHSV", 4, 3, 6, 29.941881324210264));
table.add(array("qRGB", 6, 5, 2, 30.97884589500067));
table.add(array("qRGB", 6, 2, 5, 34.346490652277055));
table.add(array("qHSV", 3, 6, 4, 35.80586465661823));
table.add(array("qHSV", 2, 6, 5, 35.831301740769405));
table.add(array("qHSV", 4, 6, 3, 40.37922211577201));
table.add(array("qHSV", 1, 6, 6, 40.81321272585543));
table.add(array("qRGB", 3, 4, 6, 42.525019656531576));
table.add(array("qRGB", 4, 3, 6, 44.51060848937224));
table.add(array("qHSV", 5, 4, 4, 44.81908847853915));
table.add(array("qRGB", 2, 5, 6, 44.902350932273606));
table.add(array("qHSV", 5, 3, 5, 44.954338178029914));
table.add(array("qRGB", 7, 4, 2, 45.209654110379404));
table.add(array("qRGB", 7, 3, 3, 45.25226318990082));
table.add(array("qHSV", 5, 5, 3, 47.067622456344374));
table.add(array("qHSV", 5, 2, 6, 48.43284417039696));
table.add(array("qRGB", 7, 2, 4, 48.48082801682692));
table.add(array("qRGB", 5, 2, 6, 48.67260126855884));
table.add(array("qRGB", 3, 6, 4, 48.93754909302421));
table.add(array("qHSV", 3, 3, 7, 49.02681684469041));
table.add(array("qHSV", 2, 4, 7, 49.56029119812139));
table.add(array("qRGB", 4, 6, 3, 49.67978878365301));
table.add(array("qRGB", 2, 6, 5, 50.2467901034742));
table.add(array("qRGB", 7, 5, 1, 50.89632581346104));
table.add(array("qRGB", 5, 6, 2, 51.349978241781436));
table.add(array("qHSV", 4, 2, 7, 53.40986543747504));
table.add(array("qHSV", 1, 5, 7, 53.832715409307504));
table.add(array("qHSV", 5, 6, 2, 54.17452931216259));
table.add(array("qRGB", 6, 6, 1, 56.24604742164139));
table.add(array("qRGB", 7, 1, 5, 56.576264479355444));
table.add(array("qRGB", 6, 1, 6, 56.814909591996674));
table.add(array("qRGB", 1, 6, 6, 59.72839648703533));
table.add(array("qHSV", 2, 7, 4, 62.51176621430742));
table.add(array("qHSV", 3, 7, 3, 62.96174689694058));
table.add(array("qHSV", 1, 7, 5, 63.14358049455555));
table.add(array("qHSV", 0, 6, 7, 63.465936946588535));
table.add(array("qHSV", 4, 7, 2, 65.23155454626794));
table.add(array("qHSV", 0, 7, 6, 66.36369767041624));
table.add(array("qHSV", 5, 1, 7, 67.49295507997199));
table.add(array("qRGB", 7, 6, 0, 72.32032989402973));
table.add(array("qHSV", 5, 7, 1, 72.6504972897907));
table.add(array("qRGB", 7, 0, 6, 76.11764832983383));
table.add(array("qHSV", 6, 5, 2, 81.38302809602966));
table.add(array("qHSV", 6, 4, 3, 81.86192037913459));
table.add(array("qHSV", 6, 3, 4, 82.47611149206824));
table.add(array("qHSV", 6, 6, 1, 82.67225695734406));
table.add(array("qHSV", 6, 2, 5, 83.00311321520888));
table.add(array("qHSV", 6, 1, 6, 84.70426204696611));
table.add(array("qHSV", 6, 7, 0, 90.32392117480995));
table.add(array("qRGB", 1, 5, 7, 90.59284659085877));
table.add(array("qRGB", 2, 4, 7, 92.96533250892645));
table.add(array("qRGB", 0, 6, 7, 94.23816148736213));
table.add(array("qRGB", 3, 3, 7, 95.76126172444539));
table.add(array("qHSV", 6, 0, 7, 96.77929387101405));
table.add(array("qRGB", 4, 2, 7, 98.15417423649613));
table.add(array("qRGB", 5, 1, 7, 101.01783865813661));
table.add(array("qRGB", 1, 7, 5, 105.9478151508339));
table.add(array("qRGB", 0, 7, 6, 106.2108223866618));
table.add(array("qRGB", 6, 0, 7, 106.88184436821574));
table.add(array("qRGB", 2, 7, 4, 108.61661495825513));
table.add(array("qRGB", 3, 7, 3, 110.9684674837774));
table.add(array("qRGB", 4, 7, 2, 112.72714747788302));
table.add(array("qRGB", 5, 7, 1, 114.76166638761399));
table.add(array("qRGB", 6, 7, 0, 119.55559324301412));
table.add(array("qHSV", 7, 6, 0, 141.64444052630054));
table.add(array("qHSV", 7, 5, 1, 148.4251492515059));
table.add(array("qHSV", 7, 4, 2, 152.0899192589707));
table.add(array("qHSV", 7, 0, 6, 153.00264635518943));
table.add(array("qHSV", 7, 3, 3, 153.83156011108096));
table.add(array("qHSV", 7, 1, 5, 153.98670951089673));
table.add(array("qHSV", 7, 2, 4, 154.36075363667933));
table.add(array("qRGB", 5, 4, 5, 24.071811935682792));
table.add(array("qRGB", 5, 5, 4, 24.519064488681344));
table.add(array("qRGB", 6, 4, 4, 25.197573119249448));
table.add(array("qRGB", 4, 5, 5, 27.88679667800512));
table.add(array("qHSV", 3, 5, 6, 30.125155623703037));
table.add(array("qRGB", 6, 5, 3, 30.57235916304928));
table.add(array("qHSV", 4, 5, 5, 30.80517648683717));
table.add(array("qHSV", 4, 4, 6, 31.699842078117207));
table.add(array("qRGB", 6, 3, 5, 32.99240577170763));
table.add(array("qHSV", 3, 6, 5, 37.271137072988665));
table.add(array("qHSV", 4, 6, 4, 40.75410626562716));
table.add(array("qHSV", 2, 6, 6, 41.107826122575894));
table.add(array("qRGB", 4, 4, 6, 42.983901487038864));
table.add(array("qRGB", 3, 5, 6, 44.73696740093618));
table.add(array("qRGB", 7, 4, 3, 45.575935181665926));
table.add(array("qHSV", 5, 4, 5, 45.73706665815075));
table.add(array("qRGB", 5, 3, 6, 46.93140066470426));
table.add(array("qHSV", 5, 5, 4, 47.31457765402981));
table.add(array("qRGB", 7, 3, 4, 47.57904720235397));
table.add(array("qRGB", 4, 6, 4, 48.59959709126427));
table.add(array("qHSV", 5, 3, 6, 48.70967709693754));
table.add(array("qRGB", 3, 6, 5, 49.90415093680079));
table.add(array("qRGB", 5, 6, 3, 50.19162493994238));
table.add(array("qRGB", 7, 5, 2, 50.64474510643907));
table.add(array("qHSV", 3, 4, 7, 50.97542315094293));
table.add(array("qHSV", 2, 5, 7, 54.10765028158217));
table.add(array("qHSV", 4, 3, 7, 54.119314448377594));
table.add(array("qHSV", 5, 6, 3, 54.240483810016585));
table.add(array("qRGB", 6, 6, 2, 55.51362394958891));
table.add(array("qRGB", 7, 2, 5, 55.72738548239443));
table.add(array("qRGB", 6, 2, 6, 55.74309141050442));
table.add(array("qRGB", 2, 6, 6, 59.53589671516055));
table.add(array("qHSV", 3, 7, 4, 63.157139098842364));
table.add(array("qHSV", 2, 7, 5, 63.28833907338459));
table.add(array("qHSV", 1, 6, 7, 63.50457128922028));
table.add(array("qHSV", 4, 7, 3, 65.29115018166584));
table.add(array("qHSV", 1, 7, 6, 66.39194736243954));
table.add(array("qHSV", 5, 2, 7, 67.61437384583752));
table.add(array("qRGB", 7, 6, 1, 71.99761869066867));
table.add(array("qHSV", 5, 7, 2, 72.62668860926118));
table.add(array("qRGB", 7, 1, 6, 75.56911192801118));
table.add(array("qHSV", 6, 5, 3, 81.33113264372975));
table.add(array("qHSV", 6, 4, 4, 81.78259962534494));
table.add(array("qHSV", 6, 3, 5, 82.54804950625551));
table.add(array("qHSV", 6, 6, 2, 82.64653580433713));
table.add(array("qHSV", 0, 7, 7, 82.98009795855553));
table.add(array("qHSV", 6, 2, 6, 84.49086288438515));
table.add(array("qHSV", 6, 7, 1, 90.3539481096517));
table.add(array("qRGB", 2, 5, 7, 90.52673250324939));
table.add(array("qRGB", 3, 4, 7, 93.04225296123272));
table.add(array("qRGB", 1, 6, 7, 94.15118331333835));
table.add(array("qRGB", 4, 3, 7, 96.30652031331188));
table.add(array("qHSV", 6, 1, 7, 96.66311028783815));
table.add(array("qRGB", 5, 2, 7, 99.9525311596843));
table.add(array("qRGB", 2, 7, 5, 105.85586615081006));
table.add(array("qRGB", 1, 7, 6, 106.13379451983877));
table.add(array("qRGB", 6, 1, 7, 106.30844111204077));
table.add(array("qRGB", 3, 7, 4, 108.55788479941238));
table.add(array("qRGB", 4, 7, 3, 111.1485560507927));
table.add(array("qRGB", 5, 7, 2, 113.84057827200076));
table.add(array("qRGB", 6, 7, 1, 119.0611377850553));
table.add(array("qRGB", 0, 7, 7, 121.61122326525965));
table.add(array("qRGB", 7, 0, 7, 122.22938888033444));
table.add(array("qHSV", 7, 7, 0, 130.39792724870412));
table.add(array("qRGB", 7, 7, 0, 133.93140854155877));
table.add(array("qHSV", 7, 6, 1, 141.57678709847553));
table.add(array("qHSV", 7, 5, 2, 148.3157517124646));
table.add(array("qHSV", 7, 4, 3, 151.85812919582494));
table.add(array("qHSV", 7, 1, 6, 152.75698339389902));
table.add(array("qHSV", 7, 3, 4, 153.36844533228413));
table.add(array("qHSV", 7, 2, 5, 153.50798443432024));
table.add(array("qHSV", 7, 0, 7, 154.42826003900322));
table.add(array("qRGB", 5, 5, 5, 29.16035761415699));
table.add(array("qRGB", 6, 5, 4, 31.076711561370868));
table.add(array("qRGB", 6, 4, 5, 32.067109009705945));
table.add(array("qHSV", 4, 5, 6, 36.083595936249296));
table.add(array("qHSV", 4, 6, 5, 41.964190211364595));
table.add(array("qHSV", 3, 6, 6, 42.29930100726572));
table.add(array("qRGB", 4, 5, 6, 44.727040748103285));
table.add(array("qRGB", 5, 4, 6, 44.968623478214795));
table.add(array("qRGB", 7, 4, 4, 47.278835169696876));
table.add(array("qHSV", 5, 5, 5, 48.217951512529));
table.add(array("qRGB", 5, 6, 4, 49.01993078520322));
table.add(array("qRGB", 4, 6, 5, 49.51021618599725));
table.add(array("qHSV", 5, 4, 6, 49.547304173959944));
table.add(array("qRGB", 7, 5, 3, 50.45381424547857));
table.add(array("qRGB", 6, 3, 6, 53.916454183431405));
table.add(array("qRGB", 6, 6, 3, 54.37236041600201));
table.add(array("qRGB", 7, 3, 5, 54.41183262515647));
table.add(array("qHSV", 5, 6, 4, 54.45350302726497));
table.add(array("qHSV", 3, 5, 7, 55.244904587366044));
table.add(array("qHSV", 4, 4, 7, 55.64610512093585));
table.add(array("qRGB", 3, 6, 6, 59.209737174708884));
table.add(array("qHSV", 2, 6, 7, 63.6751728390727));
table.add(array("qHSV", 3, 7, 5, 63.88987040305082));
table.add(array("qHSV", 4, 7, 4, 65.43916877735103));
table.add(array("qHSV", 2, 7, 6, 66.50671872962488));
table.add(array("qHSV", 5, 3, 7, 67.9918424704696));
table.add(array("qRGB", 7, 6, 2, 71.40548869524387));
table.add(array("qHSV", 5, 7, 3, 72.65552942805532));
table.add(array("qRGB", 7, 2, 6, 74.539198911411));
table.add(array("qHSV", 6, 5, 4, 81.28294078298102));
table.add(array("qHSV", 6, 4, 5, 81.90954861718659));
table.add(array("qHSV", 6, 6, 3, 82.60810662817708));
table.add(array("qHSV", 1, 7, 7, 83.01474461331952));
table.add(array("qHSV", 6, 3, 6, 84.12128748832396));
table.add(array("qHSV", 6, 7, 2, 90.30191795302524));
table.add(array("qRGB", 3, 5, 7, 90.44343880501384));
table.add(array("qRGB", 4, 4, 7, 93.39992710387831));
table.add(array("qRGB", 2, 6, 7, 93.98542612049617));
table.add(array("qHSV", 6, 2, 7, 96.531808332587));
table.add(array("qRGB", 5, 3, 7, 97.98623863661277));
table.add(array("qRGB", 6, 2, 7, 105.18986761294468));
table.add(array("qRGB", 3, 7, 5, 105.72241391531153));
table.add(array("qRGB", 2, 7, 6, 105.9861999725296));
table.add(array("qRGB", 4, 7, 4, 108.64397196690527));
table.add(array("qRGB", 5, 7, 3, 112.1823057298339));
table.add(array("qRGB", 6, 7, 2, 118.1068250687499));
table.add(array("qRGB", 1, 7, 7, 121.49344484417644));
table.add(array("qRGB", 7, 1, 7, 121.63454416537526));
table.add(array("qHSV", 7, 7, 1, 130.27815752171145));
table.add(array("qRGB", 7, 7, 1, 133.45192537538827));
table.add(array("qHSV", 7, 6, 2, 141.4759110619432));
table.add(array("qHSV", 7, 5, 3, 148.09813296839445));
table.add(array("qHSV", 7, 4, 4, 151.41705304769513));
table.add(array("qHSV", 7, 2, 6, 152.30122027302545));
table.add(array("qHSV", 7, 3, 5, 152.53646872834864));
table.add(array("qHSV", 7, 1, 7, 154.0768707620358));
table.add(array("qRGB", 6, 5, 5, 35.400137435029016));
table.add(array("qRGB", 5, 5, 6, 45.8233771590495));
table.add(array("qHSV", 4, 6, 6, 46.40245579086771));
table.add(array("qRGB", 5, 6, 5, 49.782515993143186));
table.add(array("qRGB", 7, 5, 4, 51.041409413692236));
table.add(array("qRGB", 6, 4, 6, 51.54216148099061));
table.add(array("qHSV", 5, 5, 6, 51.940531483076605));
table.add(array("qRGB", 7, 4, 5, 53.137756535881834));
table.add(array("qRGB", 6, 6, 4, 53.14396294559098));
table.add(array("qHSV", 5, 6, 5, 55.228715876666485));
table.add(array("qRGB", 4, 6, 6, 58.79585620026274));
table.add(array("qHSV", 4, 5, 7, 59.203972102699964));
table.add(array("qHSV", 3, 6, 7, 64.44018880057266));
table.add(array("qHSV", 4, 7, 5, 66.07804953551427));
table.add(array("qHSV", 3, 7, 6, 67.02198891573136));
table.add(array("qHSV", 5, 4, 7, 68.82377873985625));
table.add(array("qRGB", 7, 6, 3, 70.45097650807729));
table.add(array("qHSV", 5, 7, 4, 72.72379724972508));
table.add(array("qRGB", 7, 3, 6, 72.7496334594355));
table.add(array("qHSV", 6, 5, 5, 81.45839848659669));
table.add(array("qHSV", 6, 6, 4, 82.57432023168315));
table.add(array("qHSV", 2, 7, 7, 83.09689252187526));
table.add(array("qHSV", 6, 4, 6, 83.60367097668954));
table.add(array("qHSV", 6, 7, 3, 90.24254703335666));
table.add(array("qRGB", 4, 5, 7, 90.47157622213018));
table.add(array("qRGB", 3, 6, 7, 93.69327279840577));
table.add(array("qRGB", 5, 4, 7, 94.78848826316275));
table.add(array("qHSV", 6, 3, 7, 96.34074236006498));
table.add(array("qRGB", 6, 3, 7, 103.09409877318586));
table.add(array("qRGB", 4, 7, 5, 105.64751778991774));
table.add(array("qRGB", 3, 7, 6, 105.73289902046317));
table.add(array("qRGB", 5, 7, 4, 109.50856313511423));
table.add(array("qRGB", 6, 7, 3, 116.35263661572063));
table.add(array("qRGB", 7, 2, 7, 120.47091510995996));
table.add(array("qRGB", 2, 7, 7, 121.25909325650642));
table.add(array("qHSV", 7, 7, 2, 130.189412070187));
table.add(array("qRGB", 7, 7, 2, 132.51054904265393));
table.add(array("qHSV", 7, 6, 3, 141.2750518038755));
table.add(array("qHSV", 7, 5, 4, 147.68593530869273));
table.add(array("qHSV", 7, 4, 5, 150.63169725118138));
table.add(array("qHSV", 7, 3, 6, 151.39341368885468));
table.add(array("qHSV", 7, 2, 7, 153.7261405181208));
table.add(array("qRGB", 6, 5, 6, 51.16588678216485));
table.add(array("qRGB", 6, 6, 5, 53.65792546587413));
table.add(array("qRGB", 7, 5, 5, 54.86314628308258));
table.add(array("qHSV", 5, 6, 6, 58.5541643813996));
table.add(array("qRGB", 5, 6, 6, 58.88231069937044));
table.add(array("qHSV", 4, 6, 7, 67.29232843725568));
table.add(array("qHSV", 4, 7, 6, 68.98398547192));
table.add(array("qRGB", 7, 6, 4, 69.35909510351173));
table.add(array("qRGB", 7, 4, 6, 70.20612999951547));
table.add(array("qHSV", 5, 5, 7, 70.9522982391356));
table.add(array("qHSV", 5, 7, 5, 73.15155535858463));
table.add(array("qHSV", 6, 6, 5, 82.78120697495775));
table.add(array("qHSV", 6, 5, 6, 83.28443665149418));
table.add(array("qHSV", 3, 7, 7, 83.45320638949539));
table.add(array("qHSV", 6, 7, 4, 90.172638730084));
table.add(array("qRGB", 5, 5, 7, 91.24646560431594));
table.add(array("qRGB", 4, 6, 7, 93.2732797260707));
table.add(array("qHSV", 6, 4, 7, 96.09723782084295));
table.add(array("qRGB", 6, 4, 7, 99.54726990857749));
table.add(array("qRGB", 4, 7, 6, 105.39366045848752));
table.add(array("qRGB", 5, 7, 5, 106.18657681840735));
table.add(array("qRGB", 6, 7, 4, 113.434492479518));
table.add(array("qRGB", 7, 3, 7, 118.27215956840143));
table.add(array("qRGB", 3, 7, 7, 120.8193361510788));
table.add(array("qHSV", 7, 7, 3, 130.01513071046674));
table.add(array("qRGB", 7, 7, 3, 130.72885419357505));
table.add(array("qHSV", 7, 6, 4, 140.9012578035098));
table.add(array("qHSV", 7, 5, 5, 146.95565866567614));
table.add(array("qHSV", 7, 4, 6, 149.59413316853056));
table.add(array("qHSV", 7, 3, 7, 153.00106824868672));
table.add(array("qRGB", 6, 6, 6, 62.13342555613777));
table.add(array("qRGB", 7, 5, 6, 68.76461465385874));
table.add(array("qRGB", 7, 6, 5, 69.64939924785347));
table.add(array("qHSV", 5, 7, 6, 75.49661507284307));
table.add(array("qHSV", 5, 6, 7, 76.37570829713836));
table.add(array("qHSV", 6, 6, 6, 84.60279131029957));
table.add(array("qHSV", 4, 7, 7, 84.87036525141197));
table.add(array("qHSV", 6, 7, 5, 90.25307437485817));
table.add(array("qRGB", 5, 6, 7, 93.09297348388682));
table.add(array("qRGB", 6, 5, 7, 95.09765215140195));
table.add(array("qHSV", 6, 5, 7, 96.05791272541956));
table.add(array("qRGB", 5, 7, 6, 105.35293816829977));
table.add(array("qRGB", 6, 7, 5, 109.55213823708338));
table.add(array("qRGB", 7, 4, 7, 114.43406884005788));
table.add(array("qRGB", 4, 7, 7, 120.06463886098378));
table.add(array("qRGB", 7, 7, 4, 127.61800680953633));
table.add(array("qHSV", 7, 7, 4, 129.69888897137199));
table.add(array("qHSV", 7, 6, 5, 140.26914343765014));
table.add(array("qHSV", 7, 5, 6, 146.10742102345884));
table.add(array("qHSV", 7, 4, 7, 151.5596422793711));
table.add(array("qRGB", 7, 6, 6, 76.82768387008761));
table.add(array("qHSV", 5, 7, 7, 89.91254983728324));
table.add(array("qHSV", 6, 7, 6, 91.6934546217888));
table.add(array("qRGB", 6, 6, 7, 95.13524389792414));
table.add(array("qHSV", 6, 6, 7, 97.3143392560389));
table.add(array("qRGB", 6, 7, 6, 107.54519533200947));
table.add(array("qRGB", 7, 5, 7, 109.04192747205848));
table.add(array("qRGB", 5, 7, 7, 119.07036843710114));
table.add(array("qRGB", 7, 7, 5, 123.04945636715787));
table.add(array("qHSV", 7, 7, 5, 129.19031913082105));
table.add(array("qHSV", 7, 6, 6, 139.72383239068853));
table.add(array("qHSV", 7, 5, 7, 148.72214401655344));
table.add(array("qHSV", 6, 7, 7, 103.02970911320593));
table.add(array("qRGB", 7, 6, 7, 106.51658523554815));
table.add(array("qRGB", 6, 7, 7, 119.09765442358427));
table.add(array("qRGB", 7, 7, 6, 119.10670119292193));
table.add(array("qHSV", 7, 7, 6, 129.00909805599323));
table.add(array("qHSV", 7, 6, 7, 143.4394848729931));
table.add(array("qRGB", 7, 7, 7, 126.23189633081189));
table.add(array("qHSV", 7, 7, 7, 134.22861938161395));
for (final Object[] row : table) {
final String type = (String) row[0];
/*if ("qHSV".equals(type))*/ {
final int qA = ((Number) row[1]).intValue();
final int qB = ((Number) row[2]).intValue();
final int qC = ((Number) row[3]).intValue();
final int q = qA + qB + qC;
if (quantizers.size() <= q) {
quantizers.add(ColorQuantizer.newQuantizer(type, qA, qB, qC));
}
}
}
}
/**
* @author codistmonk (creation 2014-04-10)
*/
public static abstract class ColorQuantizer implements Serializable {
private final int qA;
private final int qB;
private final int qC;
protected ColorQuantizer(final int qA, final int qB, final int qC) {
this.qA = qA;
this.qB = qB;
this.qC = qC;
}
public final int quantize(final int rgb) {
final int[] abc = new int[3];
this.rgbToABC(rgb, abc);
abc[0] = ((abc[0] & 0xFF) >> this.qA) << this.qA;
abc[1] = ((abc[1] & 0xFF) >> this.qB) << this.qB;
abc[2] = ((abc[2] & 0xFF) >> this.qC) << this.qC;
this.abcToRGB(abc, abc);
return (abc[0] << 16) | (abc[1] << 8) | (abc[2] << 0);
}
public final int pack(final int rgb) {
final int[] abc = new int[3];
this.rgbToABC(rgb, abc);
final int a = (abc[0] & 0xFF) >> this.qA;
final int b = (abc[1] & 0xFF) >> this.qB;
final int c = (abc[2] & 0xFF) >> this.qC;
return (a << (16 - this.qB - this.qC)) | (b << (8 - this.qC)) | (c << 0);
}
public final String getType() {
if (this instanceof RGBQuantizer) {
return "qRGB";
}
if (this instanceof HSVQuantizer) {
return "qHSV";
}
return this.getClass().getSimpleName();
}
@Override
public final String toString() {
return this.getType() + this.qA + "" + this.qB + "" + this.qC;
}
protected abstract void rgbToABC(final int rgb, final int[] abc);
protected abstract void abcToRGB(final int[] abc, final int[] rgb);
/**
* {@value}.
*/
private static final long serialVersionUID = -5601399591176973099L;
public static final ColorQuantizer newQuantizer(final String type, final int qA, final int qB, final int qC) {
if ("qRGB".equals(type)) {
return new RGBQuantizer(qA, qC, qB);
}
if ("qHSV".equals(type)) {
return new HSVQuantizer(qA, qC, qB);
}
throw new IllegalArgumentException();
}
}
/**
* @author codistmonk (creation 2014-04-10)
*/
public static final class RGBQuantizer extends ColorQuantizer {
public RGBQuantizer(final int qR, final int qG, final int qB) {
super(qR, qG, qB);
}
@Override
protected final void rgbToABC(final int rgb, final int[] abc) {
rgbToRGB(rgb, abc);
}
@Override
protected final void abcToRGB(final int[] abc, final int[] rgb) {
System.arraycopy(abc, 0, rgb, 0, abc.length);
}
/**
* {@value}.
*/
private static final long serialVersionUID = -739890245396913487L;
}
/**
* @author codistmonk (creation 2014-04-10)
*/
public static final class HSVQuantizer extends ColorQuantizer {
public HSVQuantizer(final int qH, final int qS, final int qV) {
super(qH, qS, qV);
}
@Override
protected final void rgbToABC(final int rgb, final int[] abc) {
rgbToRGB(rgb, abc);
rgbToHSV(abc, abc);
}
@Override
protected final void abcToRGB(final int[] abc, final int[] rgb) {
hsvToRGB(abc, rgb);
}
/**
* {@value}.
*/
private static final long serialVersionUID = -739890245396913487L;
}
public static final void shutdownAndWait(final ExecutorService executor, final long milliseconds) {
executor.shutdown();
try {
executor.awaitTermination(milliseconds, TimeUnit.MILLISECONDS);
} catch (final InterruptedException exception) {
exception.printStackTrace();
}
}
public static final int[] rgbToRGB(final int rgb, final int[] result) {
result[0] = (rgb >> 16) & 0xFF;
result[1] = (rgb >> 8) & 0xFF;
result[2] = (rgb >> 0) & 0xFF;
return result;
}
public static final int[] rgbToHSV(final int[] rgb, final int[] result) {
final float[] hsv = new float[3];
Color.RGBtoHSB(rgb[0], rgb[1], rgb[2], hsv);
result[0] = round(hsv[0] * 255F);
result[1] = round(hsv[1] * 255F);
result[2] = round(hsv[2] * 255F);
return result;
}
public static final int[] hsvToRGB(final int[] hsv, final int[] result) {
return rgbToRGB(Color.HSBtoRGB(hsv[0] / 255F, hsv[1] / 255F, hsv[2] / 255F), result);
}
public static final float[] rgbToXYZ(final int[] rgb, final float[] result) {
final float r = rgb[0] / 255F;
final float g = rgb[1] / 255F;
final float b = rgb[2] / 255F;
final float b21 = 0.17697F;
result[0] = (0.49F * r + 0.31F * g + 0.20F * b) / b21;
result[1] = (b21 * r + 0.81240F * g + 0.01063F * b) / b21;
result[2] = (0.00F * r + 0.01F * g + 0.99F * b) / b21;
return result;
}
public static final int[] xyzToRGB(final float[] xyz, final int[] result) {
final float x = xyz[0];
final float y = xyz[1];
final float z = xyz[2];
result[0] = round(255F * (0.41847F * x - 0.15866F * y - 0.082835F * z));
result[1] = round(255F * (-0.091169F * x + 0.25243F * y + 0.015708F * z));
result[2] = round(255F * (0.00092090F * x - 0.0025498F * y + 0.17860F * z));
return result;
}
public static final float[] xyzToCIELAB(final float[] xyz, final float[] result) {
final float d65X = 0.95047F;
final float d65Y = 1.0000F;
final float d65Z = 1.08883F;
final float fX = f(xyz[0] / d65X);
final float fY = f(xyz[1] / d65Y);
final float fZ = f(xyz[2] / d65Z);
result[0] = 116F * fY - 16F;
result[1] = 500F * (fX - fY);
result[2] = 200F * (fY - fZ);
return result;
}
public static final float[] cielabToXYZ(final float[] cielab, final float[] result) {
final float d65X = 0.95047F;
final float d65Y = 1.0000F;
final float d65Z = 1.08883F;
final float lStar = cielab[0];
final float aStar = cielab[1];
final float bStar = cielab[2];
final float c = (lStar + 16F) / 116F;
result[0] = d65X * fInv(c + aStar / 500F);
result[1] = d65Y * fInv(c);
result[2] = d65Z * fInv(c - bStar / 200F);
return result;
}
public static final float f(final float t) {
return cube(6F / 29F) < t ? (float) pow(t, 1.0 / 3.0) : square(29F / 6F) * t / 3F + 4F / 29F;
}
public static final float fInv(final float t) {
return 6F / 29F < t ? cube(t) : 3F * square(6F / 29F) * (t - 4F / 29F);
}
public static final float square(final float value) {
return value * value;
}
public static final float cube(final float value) {
return value * value * value;
}
public static final int[] quantize(final int[] abc, final int q, final int[] result) {
return quantize(abc, q, q, q, result);
}
public static final int[] quantize(final int[] abc, final int qA, final int qB, final int qC, final int[] result) {
result[0] = abc[0] & ((~0) << qA);
result[1] = abc[1] & ((~0) << qB);
result[2] = abc[2] & ((~0) << qC);
return result;
}
public static final double distance2(final float[] abc1, final float[] abc2) {
final int n = abc1.length;
double sum = 0.0;
for (int i = 0; i < n; ++i) {
sum += square(abc1[i] - abc2[i]);
}
return sqrt(sum);
}
public static final int min(final int... values) {
int result = Integer.MAX_VALUE;
for (final int value : values) {
if (value < result) {
result = value;
}
}
return result;
}
public static final int max(final int... values) {
int result = Integer.MIN_VALUE;
for (final int value : values) {
if (result < value) {
result = value;
}
}
return result;
}
/**
* @author codistmonk (creation 2014-04-10)
*/
public static final class DoubleArrayComparator implements Serializable, Comparator<double[]> {
@Override
public final int compare(final double[] array1, final double[] array2) {
final int n1 = array1.length;
final int n2 = array2.length;
final int n = Math.min(n1, n2);
for (int i = 0; i < n; ++i) {
final int comparison = Double.compare(array1[i], array2[i]);
if (comparison != 0) {
return comparison;
}
}
return n1 - n2;
}
/**
* {@value}.
*/
private static final long serialVersionUID = -88586465954519984L;
public static final DoubleArrayComparator INSTANCE = new DoubleArrayComparator();
}
} |
package com.ehpefi.iforgotthat;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Performs CRUD operations on lists in the 'I Forgot This' app.
*
* @author Even Holthe
* @since 1.0
*/
public class ListHelper extends SQLiteOpenHelper {
// Important constants for handling the database
private static final int VERSION = 1;
private static final String DATABASE_NAME = "ift.db";
private static final String TABLE_NAME = "list";
// Column names in the database
private static final String COL_ID = "_id";
private static final String COL_TITLE = "title";
private static final String COL_TIMESTAMP = "created_timestamp";
// Specify which class which logs messages
private static final String TAG = "ListHelper";
/**
* Constructs a new instance of the ListHelper class
*
* @param context The context in which the new instance should be created, usually 'this'.
* @since 1.0
*/
public ListHelper(Context context) {
// Call the super class' constructor
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate() was called. Creating the table '" + TABLE_NAME
+ "'...");
// SQL to create the 'list' table
String createListsSQL = String
.format("CREATE TABLE %s (%s integer PRIMARY KEY AUTOINCREMENT NOT NULL, %s varchar(255) NOT NULL, %s DATETIME DEFAULT CURRENT_TIMESTAMP)",
TABLE_NAME, COL_ID, COL_TITLE, COL_TIMESTAMP);
// Create the table
try {
db.execSQL(createListsSQL);
Log.i(TAG, "The table '" + TABLE_NAME
+ "' was successfully created");
} catch (SQLException sqle) {
Log.e(TAG, "Invalid SQL detected", sqle);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "onUpgrade() was called, but nothing to upgrade...");
}
/**
* Creates a new list in the database.
*
* @param listTitle The title of the list
* @return A boolean indication whether a new list was created or not
* @since 1.0
*/
public boolean createNewList(String listTitle) {
// Create a pointer to the database
SQLiteDatabase db = getWritableDatabase();
// Create the data to insert
ContentValues values = new ContentValues();
values.put(COL_TITLE, listTitle);
// Try to save the list
try {
// Check for success
if (db.insertOrThrow(TABLE_NAME, null, values) != -1) {
// Success
Log.i(TAG, "The list '" + listTitle
+ "' was successfully saved");
// Close the database connection
db.close();
return true;
}
// Failure
Log.e(TAG, "Could not save the list '" + listTitle
+ "'. That's all I know...");
// Close the database connection
db.close();
return false;
} catch (SQLException sqle) {
// Something wrong with the SQL
Log.e(TAG, "Error in inserting the list named " + listTitle, sqle);
// Close the database connection
db.close();
return false;
}
}
/**
* Drops the list table completely (including all data) and re-creates a blank list table - use for
* testing/debugging purposes only!
*
* @since 1.0
*/
public void dropAndRecreateListTable() {
// Create a pointer to the database
SQLiteDatabase db = getWritableDatabase();
// Try to drop the table
try {
db.execSQL("DROP TABLE " + TABLE_NAME);
Log.d(TAG, "The table '" + TABLE_NAME
+ "' was dropped");
} catch (SQLException sqle) {
Log.e(TAG, "Invalid SQL detected", sqle);
}
// Recreate
this.onCreate(db);
// Close the database connection
db.close();
}
} |
/*
* $Log: Misc.java,v $
* Revision 1.27 2009-12-28 12:53:07 m168309
* cosmetic changes
*
* Revision 1.26 2009/12/24 08:27:55 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added methods getResponseBodySizeWarnByDefault and getResponseBodySizeErrorByDefault
*
* Revision 1.25 2009/11/12 12:36:04 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* Pipeline: added attributes messageSizeWarn and messageSizeError
*
* Revision 1.24 2009/11/10 10:27:40 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* method getEnvironmentVariables splitted for J2SE 1.4 and J2SE 5.0
*
* Revision 1.23 2009/01/29 07:02:29 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* removed "j2c.properties resource path" from getEnvironmentVariables()
*
* Revision 1.22 2009/01/28 11:21:29 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added "j2c.properties resource path" to getEnvironmentVariables()
*
* Revision 1.21 2008/12/15 12:21:06 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added getApplicationDeploymentDescriptor
*
* Revision 1.20 2008/12/15 09:39:45 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* getDeployedApplicationBindings: replaced property WAS_HOMES by user.install.root
*
* Revision 1.19 2008/12/08 13:06:58 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added createNumericUUID
*
* Revision 1.18 2008/11/25 10:17:10 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added getDeployedApplicationName and getDeployedApplicationBindings
*
* Revision 1.17 2008/09/08 15:00:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* avoid NPE in getEnvironmentVariables
*
* Revision 1.16 2008/08/27 16:24:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* made closeInput optional in streamToStream
*
* Revision 1.15 2007/09/05 13:05:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added function to copy context
*
* Revision 1.14 2007/06/12 11:24:24 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added getHostname()
*
* Revision 1.13 2005/10/27 08:43:36 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* moved getEnvironmentVariables to Misc
*
* Revision 1.12 2005/10/17 11:26:58 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* addded concatString and compression-functions
*
* Revision 1.11 2005/09/22 15:54:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added replace function
*
* Revision 1.10 2005/07/19 11:37:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* added stream copying functions
*
* Revision 1.9 2004/10/26 15:36:36 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* set UTF-8 as default inputstream encoding
*
*/
package nl.nn.adapterframework.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.rmi.server.UID;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.Inflater;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* Miscellanous conversion functions.
* @version Id
*/
public class Misc {
public static final String version="$RCSfile: Misc.java,v $ $Revision: 1.27 $ $Date: 2009-12-28 12:53:07 $";
static Logger log = LogUtil.getLogger(Misc.class);
public static final int BUFFERSIZE=20000;
public static final String DEFAULT_INPUT_STREAM_ENCODING="UTF-8";
public static final String MESSAGE_SIZE_WARN_BY_DEFAULT_KEY = "message.size.warn.default";
public static final String MESSAGE_SIZE_ERROR_BY_DEFAULT_KEY = "message.size.error.default";
public static final String RESPONSE_BODY_SIZE_WARN_BY_DEFAULT_KEY = "response.body.size.warn.default";
public static final String RESPONSE_BODY_SIZE_ERROR_BY_DEFAULT_KEY = "response.body.size.error.default";
private static Long messageSizeWarnByDefault = null;
private static Long messageSizeErrorByDefault = null;
private static Long responseBodySizeWarnByDefault = null;
private static Long responseBodySizeErrorByDefault = null;
public static String createSimpleUUID_old() {
StringBuffer sb = new StringBuffer();
sb.append(System.currentTimeMillis());
sb.append('-');
sb.append(Math.round(Math.random() * 1000000));
return sb.toString();
}
/**
* Creates a Universally Unique Identifier, via the java.rmi.server.UID class.
*/
public static String createSimpleUUID() {
UID uid = new UID();
// Replace semi colons by underscores, so IBIS will support it
String uidString = uid.toString().replace(':', '_');
return uidString;
}
/**
* Creates a Universally Unique Identifier.
*
* Similar to javax.mail.internet.UniqueValue, this implementation
* generates a unique value by random number, the current
* time (in milliseconds), and this system's hostname generated by
* <code>InternetAddress.getLocalAddress()</code>.
* @return A unique identifier is returned.
*/
static public String createUUID() {
String user = System.getProperty("user.name");
String ipAddress = getIPAddress();
StringBuffer s = new StringBuffer();
//Unique string is <ipaddress>.<currentTime>.<username>.<hashcode>
s.append(ipAddress).append('.').append(System.currentTimeMillis()).append('.').append(user).append('.').append(
Math.round(Math.random() * 1000000));
return s.toString();
}
static private String getIPAddress() {
InetAddress inetAddress = null;
String ipAddress = null;
try {
inetAddress = InetAddress.getLocalHost();
return inetAddress.getHostAddress();
}
catch (UnknownHostException uhe) {
return "127.0.0.1";
}
}
static public String createNumericUUID() {
String ipAddress = getIPAddress();
DecimalFormat df = new DecimalFormat("000");
String[] iaArray = ipAddress.split("[.]");
String ia1 = df.format(Integer.parseInt(iaArray[0]));
String ia2 = df.format(Integer.parseInt(iaArray[1]));
String ia3 = df.format(Integer.parseInt(iaArray[2]));
String ia4 = df.format(Integer.parseInt(iaArray[3]));
String ia = ia1 + ia2 + ia3 + ia4;
long hashL = Math.round(Math.random() * 1000000);
df = new DecimalFormat("000000");
String hash = df.format(hashL);
//Unique string is <ipaddress with length 4*3><currentTime with length 13><hashcode with length 6>
StringBuffer s = new StringBuffer();
s.append(ia).append(getCurrentTimeMillis()).append(hash);
return s.toString();
}
public static synchronized long getCurrentTimeMillis(){
return System.currentTimeMillis();
}
public static void fileToWriter(String filename, Writer writer) throws IOException {
readerToWriter(new FileReader(filename), writer);
}
public static void fileToStream(String filename, OutputStream output) throws IOException {
streamToStream(new FileInputStream(filename), output);
}
public static void streamToStream(InputStream input, OutputStream output) throws IOException {
streamToStream(input,output,true);
}
public static void streamToStream(InputStream input, OutputStream output, boolean closeInput) throws IOException {
if (input!=null) {
byte buffer[]=new byte[BUFFERSIZE];
int bytesRead;
while ((bytesRead=input.read(buffer,0,BUFFERSIZE))>0) {
output.write(buffer,0,bytesRead);
}
if (closeInput) {
input.close();
}
}
}
public static void readerToWriter(Reader reader, Writer writer) throws IOException {
if (reader!=null) {
char buffer[]=new char[BUFFERSIZE];
int charsRead;
while ((charsRead=reader.read(buffer,0,BUFFERSIZE))>0) {
writer.write(buffer,0,charsRead);
}
reader.close();
}
}
/**
* Please consider using resourceToString() instead of relying on files.
*/
public static String fileToString(String fileName) throws IOException {
return fileToString(fileName, null, false);
}
/**
* Please consider using resourceToString() instead of relying on files.
*/
public static String fileToString(String fileName, String endOfLineString) throws IOException {
return fileToString(fileName, endOfLineString, false);
}
/**
* Please consider using resourceToString() instead of relying on files.
*/
public static String fileToString(String fileName, String endOfLineString, boolean xmlEncode) throws IOException {
FileReader reader = new FileReader(fileName);
try {
return readerToString(reader, endOfLineString, xmlEncode);
}
finally {
reader.close();
}
}
public static String readerToString(Reader reader, String endOfLineString, boolean xmlEncode) throws IOException {
StringBuffer sb = new StringBuffer();
int curChar = -1;
int prevChar = -1;
while ((curChar = reader.read()) != -1 || prevChar == '\r') {
if (prevChar == '\r' || curChar == '\n') {
if (endOfLineString == null) {
if (prevChar == '\r')
sb.append((char) prevChar);
if (curChar == '\n')
sb.append((char) curChar);
}
else {
sb.append(endOfLineString);
}
}
if (curChar != '\r' && curChar != '\n' && curChar != -1) {
String appendStr =""+(char) curChar;
sb.append(xmlEncode ? (XmlUtils.encodeChars(appendStr)):(appendStr));
}
prevChar = curChar;
}
return sb.toString();
}
public static String streamToString(InputStream stream, String endOfLineString, String streamEncoding, boolean xmlEncode)
throws IOException {
return readerToString(new InputStreamReader(stream,streamEncoding), endOfLineString, xmlEncode);
}
public static String streamToString(InputStream stream, String endOfLineString, boolean xmlEncode)
throws IOException {
return streamToString(stream,endOfLineString, DEFAULT_INPUT_STREAM_ENCODING, xmlEncode);
}
public static String resourceToString(URL resource, String endOfLineString, boolean xmlEncode) throws IOException {
InputStream stream = resource.openStream();
try {
return streamToString(stream, endOfLineString, xmlEncode);
}
finally {
stream.close();
}
}
public static String resourceToString(URL resource) throws IOException {
return resourceToString(resource, null, false);
}
public static String resourceToString(URL resource, String endOfLineString) throws IOException {
return resourceToString(resource, endOfLineString, false);
}
public static void stringToFile(String string, String fileName) throws IOException {
FileWriter fw = new FileWriter(fileName);
try {
fw.write(string);
}
finally {
fw.close();
}
}
/**
* String replacer.
*
* @param target is the original string
* @param from is the string to be replaced
* @param to is the string which will used to replace
* @return
*/
public static String replace (String source, String from, String to) {
int start = source.indexOf(from);
if (start==-1) {
return source;
}
int fromLength = from.length();
char [] sourceArray = source.toCharArray();
StringBuffer buffer = new StringBuffer();
int srcPos=0;
while (start != -1) {
buffer.append (sourceArray, srcPos, start-srcPos);
buffer.append (to);
srcPos=start+fromLength;
start = source.indexOf (from, srcPos);
}
buffer.append (sourceArray, srcPos, sourceArray.length-srcPos);
return buffer.toString();
}
public static String concatStrings(String part1, String separator, String part2) {
if (StringUtils.isEmpty(part1)) {
return part2;
}
if (StringUtils.isEmpty(part2)) {
return part1;
}
return part1+separator+part2;
}
public static String byteArrayToString(byte[] input, String endOfLineString, boolean xmlEncode) throws IOException{
ByteArrayInputStream bis = new ByteArrayInputStream(input);
return streamToString(bis, endOfLineString, xmlEncode);
}
public static byte[] gzip(String input) throws IOException {
return gzip(input.getBytes(DEFAULT_INPUT_STREAM_ENCODING));
}
public static byte[] gzip(byte[] input) throws IOException {
// Create an expandable byte array to hold the compressed data.
// You cannot use an array that's the same size as the orginal because
// there is no guarantee that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
GZIPOutputStream gz = new GZIPOutputStream(bos);
gz.write(input);
gz.close();
bos.close();
// Get the compressed data
return bos.toByteArray();
}
public static String gunzipToString(byte[] input) throws DataFormatException, IOException {
return byteArrayToString(gunzip(input),"\n",false);
}
public static byte[] gunzip(byte[] input) throws DataFormatException, IOException {
// Create an expandable byte array to hold the decompressed data
ByteArrayInputStream bis = new ByteArrayInputStream(input);
GZIPInputStream gz = new GZIPInputStream(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
// Decompress the data
byte[] buf = new byte[1024];
while (gz.available()>0) {
int count = gz.read(buf,0,1024);
if (count>0) {
bos.write(buf, 0, count);
}
}
bos.close();
// Get the decompressed data
return bos.toByteArray();
}
public static byte[] compress(String input) throws IOException {
return compress(input.getBytes(DEFAULT_INPUT_STREAM_ENCODING));
}
public static byte[] compress(byte[] input) throws IOException {
// Create the compressor with highest level of compression
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
// Give the compressor the data to compress
compressor.setInput(input);
compressor.finish();
// Create an expandable byte array to hold the compressed data.
// You cannot use an array that's the same size as the orginal because
// there is no guarantee that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
// Compress the data
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
bos.close();
// Get the compressed data
return bos.toByteArray();
}
public static String decompressToString(byte[] input) throws DataFormatException, IOException {
return byteArrayToString(decompress(input),"\n",false);
}
public static byte[] decompress(byte[] input) throws DataFormatException, IOException {
// Create the decompressor and give it the data to compress
Inflater decompressor = new Inflater();
decompressor.setInput(input);
// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
// Decompress the data
byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
bos.close();
// Get the decompressed data
return bos.toByteArray();
}
public static Properties getEnvironmentVariables() throws IOException {
Properties props = new Properties();
try {
Method getenvs = System.class.getMethod( "getenv", (java.lang.Class[]) null );
Map env = (Map) getenvs.invoke( null, (java.lang.Object[]) null );
for (Iterator it = env.keySet().iterator(); it.hasNext();) {
String key = (String)it.next();
String value = (String)env.get(key);
props.setProperty(key,value);
}
} catch ( NoSuchMethodException e ) {
log.debug("Caught NoSuchMethodException, just not on JDK 1.5",e);
} catch ( IllegalAccessException e ) {
log.debug("Caught IllegalAccessException, using JDK 1.4 method",e);
} catch ( InvocationTargetException e ) {
log.debug("Caught InvocationTargetException, using JDK 1.4 method",e);
}
if (props.size() == 0) {
BufferedReader br = null;
Process p = null;
Runtime r = Runtime.getRuntime();
String OS = System.getProperty("os.name").toLowerCase();
if (OS.indexOf("windows 9") > -1) {
p = r.exec("command.com /c set");
} else if (
(OS.indexOf("nt") > -1)
|| (OS.indexOf("windows 20") > -1)
|| (OS.indexOf("windows xp") > -1)) {
p = r.exec("cmd.exe /c set");
} else {
//assume Unix
p = r.exec("env");
}
// props.load(p.getInputStream()); // this does not work, due to potential malformed escape sequences
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
int idx = line.indexOf('=');
if (idx>=0) {
String key = line.substring(0, idx);
String value = line.substring(idx + 1);
props.setProperty(key,value);
}
}
}
return props;
}
public static String getHostname() {
String localHost=null;
// String localIP="";
try {
InetAddress localMachine = InetAddress.getLocalHost();
//localIP = localMachine.getHostAddress();
localHost = localMachine.getHostName();
} catch(UnknownHostException uhe) {
if (localHost==null) {
localHost="unknown ("+uhe.getMessage()+")";
}
}
return localHost;
}
public static void copyContext(String keys, Map from, Map to) {
if (StringUtils.isNotEmpty(keys) && from!=null && to!=null) {
StringTokenizer st = new StringTokenizer(keys,",;");
while (st.hasMoreTokens()) {
String key=st.nextToken();
Object value=from.get(key);
to.put(key,value);
}
}
}
public static String getDeployedApplicationName() {
URL url= ClassUtils.getResourceURL(Misc.class, "");
String path = url.getPath();
log.debug("classloader resource [" + path + "]");
StringTokenizer st = new StringTokenizer(path, File.separator);
String appName = null;
while (st.hasMoreTokens() && appName == null) {
String token = st.nextToken();
if (StringUtils.upperCase(token).endsWith(".EAR")) {
appName = token.substring(0,token.length()-4);
}
}
log.debug("deployedApplicationName [" + appName + "]");
return appName;
}
public static String getDeployedApplicationBindings(String appName) throws IOException {
String appBndFile =
getApplicationDeploymentDescriptorPath(appName)
+ File.separator
+ "ibm-application-bnd.xmi";
log.debug("deployedApplicationBindingsFile [" + appBndFile + "]");
return fileToString(appBndFile);
}
public static String getApplicationDeploymentDescriptorPath(String appName) throws IOException {
String appPath =
// "${WAS_HOME}"
"${user.install.root}"
+ File.separator
+ "config"
+ File.separator
+ "cells"
+ File.separator
+ "${WAS_CELL}"
+ File.separator
+ "applications"
+ File.separator
+ appName
+ ".ear"
+ File.separator
+ "deployments"
+ File.separator
+ appName
+ File.separator
+ "META-INF";
Properties props = Misc.getEnvironmentVariables();
props.putAll(System.getProperties());
String resolvedAppPath = StringResolver.substVars(appPath, props);
return resolvedAppPath;
}
public static String getApplicationDeploymentDescriptor (String appName) throws IOException {
String appFile =
getApplicationDeploymentDescriptorPath(appName)
+ File.separator
+ "application.xml";
log.debug("applicationDeploymentDescriptor [" + appFile + "]");
return fileToString(appFile);
}
public static long toFileSize(String value, long defaultValue) {
if(value == null)
return defaultValue;
String s = value.trim().toUpperCase();
long multiplier = 1;
int index;
if((index = s.indexOf("KB")) != -1) {
multiplier = 1024;
s = s.substring(0, index);
}
else if((index = s.indexOf("MB")) != -1) {
multiplier = 1024*1024;
s = s.substring(0, index);
}
else if((index = s.indexOf("GB")) != -1) {
multiplier = 1024*1024*1024;
s = s.substring(0, index);
}
if(s != null) {
try {
return Long.valueOf(s).longValue() * multiplier;
}
catch (NumberFormatException e) {
log.error("[" + value + "] not in expected format", e);
}
}
return defaultValue;
}
public static String toFileSize(long value) {
long divider = 1024*1024*1024;
String suffix = null;
if (value>=divider) {
suffix = "GB";
} else {
divider = 1024*1024;
if (value>=divider) {
suffix = "MB";
} else {
divider = 1024;
if (value>=divider) {
suffix = "KB";
}
}
}
if (suffix==null) {
return Long.toString(value);
} else {
float f = (float)value / divider;
return Math.round(f) + suffix;
}
}
public static synchronized long getMessageSizeWarnByDefault() {
if (messageSizeWarnByDefault==null) {
String definitionString=AppConstants.getInstance().getString(MESSAGE_SIZE_WARN_BY_DEFAULT_KEY, null);
long definition=toFileSize(definitionString, -1);
messageSizeWarnByDefault = new Long(definition);
}
return messageSizeWarnByDefault.longValue();
}
public static synchronized long getMessageSizeErrorByDefault() {
if (messageSizeErrorByDefault==null) {
String definitionString=AppConstants.getInstance().getString(MESSAGE_SIZE_ERROR_BY_DEFAULT_KEY, null);
long definition=toFileSize(definitionString, -1);
messageSizeErrorByDefault = new Long(definition);
}
return messageSizeErrorByDefault.longValue();
}
public static synchronized long getResponseBodySizeWarnByDefault() {
if (responseBodySizeWarnByDefault==null) {
String definitionString=AppConstants.getInstance().getString(RESPONSE_BODY_SIZE_WARN_BY_DEFAULT_KEY, null);
long definition=toFileSize(definitionString, -1);
responseBodySizeWarnByDefault = new Long(definition);
}
return responseBodySizeWarnByDefault.longValue();
}
public static synchronized long getResponseBodySizeErrorByDefault() {
if (responseBodySizeErrorByDefault==null) {
String definitionString=AppConstants.getInstance().getString(RESPONSE_BODY_SIZE_ERROR_BY_DEFAULT_KEY, null);
long definition=toFileSize(definitionString, -1);
responseBodySizeErrorByDefault = new Long(definition);
}
return responseBodySizeErrorByDefault.longValue();
}
} |
package org.pentaho.ui.xul.gwt.tags;
import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.VetoDragException;
import com.allen_sauer.gwt.dnd.client.drop.AbstractPositioningDropController;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.widgetideas.table.client.SelectionGrid.SelectionPolicy;
import com.google.gwt.widgetideas.table.client.SourceTableSelectionEvents;
import com.google.gwt.widgetideas.table.client.TableSelectionListener;
import org.pentaho.gwt.widgets.client.buttons.ImageButton;
import org.pentaho.gwt.widgets.client.listbox.CustomListBox;
import org.pentaho.gwt.widgets.client.table.BaseTable;
import org.pentaho.gwt.widgets.client.table.ColumnComparators.BaseColumnComparator;
import org.pentaho.gwt.widgets.client.ui.Draggable;
import org.pentaho.gwt.widgets.client.utils.string.StringUtils;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulEventSource;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.binding.BindingConvertor;
import org.pentaho.ui.xul.binding.InlineBindingExpression;
import org.pentaho.ui.xul.components.XulTreeCell;
import org.pentaho.ui.xul.components.XulTreeCol;
import org.pentaho.ui.xul.containers.*;
import org.pentaho.ui.xul.dnd.DataTransfer;
import org.pentaho.ui.xul.dnd.DropEvent;
import org.pentaho.ui.xul.dnd.DropPosition;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.gwt.AbstractGwtXulContainer;
import org.pentaho.ui.xul.gwt.GwtXulHandler;
import org.pentaho.ui.xul.gwt.GwtXulParser;
import org.pentaho.ui.xul.gwt.binding.GwtBinding;
import org.pentaho.ui.xul.gwt.binding.GwtBindingContext;
import org.pentaho.ui.xul.gwt.binding.GwtBindingMethod;
import org.pentaho.ui.xul.gwt.tags.util.TreeItemWidget;
import org.pentaho.ui.xul.gwt.util.Resizable;
import org.pentaho.ui.xul.gwt.util.XulDragController;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.stereotype.Bindable;
import org.pentaho.ui.xul.util.TreeCellEditor;
import org.pentaho.ui.xul.util.TreeCellEditorCallback;
import org.pentaho.ui.xul.util.TreeCellRenderer;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class GwtTree extends AbstractGwtXulContainer implements XulTree, Resizable {
/**
* Cached elements.
*/
private Collection elements;
private GwtBindingMethod dropVetoerMethod;
private XulEventHandler dropVetoerController;
public static void register() {
GwtXulParser.registerHandler("tree",
new GwtXulHandler() {
public Element newInstance() {
return new GwtTree();
}
});
}
XulTreeCols columns = null;
XulTreeChildren rootChildren = null;
private XulDomContainer domContainer;
private Tree tree;
private boolean suppressEvents = false;
private boolean editable = false;
private boolean visible = true;
private String command;
private Map<String, TreeCellEditor> customEditors = new HashMap<String, TreeCellEditor>();
private Map<String, TreeCellRenderer> customRenderers = new HashMap<String, TreeCellRenderer>();
private List<Binding> elementBindings = new ArrayList<Binding>();
private List<Binding> expandBindings = new ArrayList<Binding>();
private DropPositionIndicator dropPosIndicator = new DropPositionIndicator();
private boolean showAllEditControls = true;
@Bindable
public boolean isVisible() {
return visible;
}
@Bindable
public void setVisible(boolean visible) {
this.visible = visible;
if(simplePanel != null) {
simplePanel.setVisible(visible);
}
}
/**
* Used when this widget is a tree. Not used when this widget is a table.
*/
private FlowPanel scrollPanel = new FlowPanel();
{
scrollPanel.setStylePrimaryName("scroll-panel");
}
/**
* The managed object. If this widget is a tree, then the tree is added to the scrollPanel, which is added to this
* simplePanel. If this widget is a table, then the table is added directly to this simplePanel.
*/
private SimplePanel simplePanel = new SimplePanel();
/**
* Clears the parent panel and adds the given widget.
* @param widget tree or table to set in parent panel
*/
protected void setWidgetInPanel(final Widget widget) {
if (isHierarchical()) {
scrollPanel.clear();
simplePanel.add(scrollPanel);
scrollPanel.add(widget);
scrollPanel.add(dropPosIndicator);
} else {
simplePanel.clear();
simplePanel.add(widget);
}
}
public GwtTree() {
super("tree");
// managedObject is neither a native GWT tree nor a table since the entire native GWT object is thrown away each
// time we call setup{Tree|Table}; because the widget is thrown away, we need to reconnect the new widget to the
// simplePanel, which is the managedObject
setManagedObject(simplePanel);
}
public void init(com.google.gwt.xml.client.Element srcEle, XulDomContainer container) {
super.init(srcEle, container);
setOnselect(srcEle.getAttribute("onselect"));
setOnedit(srcEle.getAttribute("onedit"));
setSeltype(srcEle.getAttribute("seltype"));
if (StringUtils.isEmpty(srcEle.getAttribute("pen:ondrop")) == false) {
setOndrop(srcEle.getAttribute("pen:ondrop"));
}
if (StringUtils.isEmpty(srcEle.getAttribute("pen:ondrag")) == false) {
setOndrag(srcEle.getAttribute("pen:ondrag"));
}
if (StringUtils.isEmpty(srcEle.getAttribute("pen:drageffect")) == false) {
setDrageffect(srcEle.getAttribute("pen:drageffect"));
}
setDropvetoer(srcEle.getAttribute("pen:dropvetoer"));
if(StringUtils.isEmpty(srcEle.getAttribute("pen:showalleditcontrols")) == false){
this.setShowalleditcontrols(srcEle.getAttribute("pen:showalleditcontrols").equals("true"));
}
this.setEditable("true".equals(srcEle.getAttribute("editable")));
this.domContainer = container;
}
private List<TreeItemDropController> dropHandlers = new ArrayList<TreeItemDropController>();
public void addChild(Element element) {
super.addChild(element);
if (element.getName().equals("treecols")) {
columns = (XulTreeCols)element;
} else if (element.getName().equals("treechildren")) {
rootChildren = (XulTreeChildren)element;
}
}
public void addTreeRow(XulTreeRow row) {
GwtTreeItem item = new GwtTreeItem();
item.setRow(row);
this.rootChildren.addItem(item);
// update UI
updateUI();
}
private BaseTable table;
private boolean isHierarchical = false;
private boolean firstLayout = true;
private Object[][] currentData;
// need to handle layouting
public void layout() {
if(this.getRootChildren() == null){
//most likely an overlay
return;
}
if(firstLayout){
XulTreeItem item = (XulTreeItem) this.getRootChildren().getFirstChild();
if(item != null && item.getAttributeValue("container") != null && item.getAttributeValue("container").equals("true")){
isHierarchical = true;
}
firstLayout = false;
}
if(isHierarchical()){
setupTree();
} else {
setupTable();
}
setVisible(visible);
}
private int prevSelectionPos = -1;
private void setupTree(){
if(tree == null){
tree = new Tree();
setWidgetInPanel(tree);
}
scrollPanel.setWidth("100%"); //$NON-NLS-1$
scrollPanel.setHeight("100%"); //$NON-NLS-1$
scrollPanel.getElement().getStyle().setProperty("backgroundColor", "white"); //$NON-NLS-1$//$NON-NLS-2$
if (getWidth() > 0){
scrollPanel.setWidth(getWidth()+"px"); //$NON-NLS-1$
}
if (getHeight() > 0) {
scrollPanel.setHeight(getHeight()+"px"); //$NON-NLS-1$
}
tree.addTreeListener(new TreeListener(){
public void onTreeItemSelected(TreeItem arg0) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, arg0, curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
if(pos > -1 && GwtTree.this.suppressEvents == false && prevSelectionPos != pos){
GwtTree.this.changeSupport.firePropertyChange("selectedRows",null,new int[]{pos});
GwtTree.this.changeSupport.firePropertyChange("absoluteSelectedRows",null,new int[]{pos});
GwtTree.this.fireSelectedItems();
}
prevSelectionPos = pos;
}
public void onTreeItemStateChanged(TreeItem item) {
((TreeItemWidget) item.getWidget()).getTreeItem().setExpanded(item.getState());
}
});
updateUI();
}
private class TreeCursor{
int foundPosition = -1;
int curPos;
TreeItem itemToFind;
public TreeCursor(int curPos, TreeItem itemToFind, int foundPosition){
this.foundPosition = foundPosition;
this.curPos = curPos;
this.itemToFind = itemToFind;
}
}
private TreeCursor findPosition(TreeItem curItem, TreeItem itemToFind, int curPos){
if(curItem == itemToFind){
TreeCursor p = new TreeCursor(curPos, itemToFind, curPos);
return p;
// } else if(curItem.getChildIndex(itemToFind) > -1) {
// curPos = curPos+1;
// return new TreeCursor(curPos+curItem.getChildIndex(itemToFind) , itemToFind, curPos+curItem.getChildIndex(itemToFind));
} else {
for(int i=1; i-1<curItem.getChildCount(); i++){
TreeCursor p = findPosition(curItem.getChild(i-1), itemToFind, curPos +1);
curPos = p.curPos;
if(p.foundPosition > -1){
return p;
}
}
//curPos += curItem.getChildCount() ;
return new TreeCursor(curPos, itemToFind, -1);
}
}
private void populateTree(){
tree.removeItems();
TreeItem topNode = new TreeItem("placeholder");
if(this.rootChildren == null){
this.rootChildren = (XulTreeChildren) this.children.get(1);
}
for (XulComponent c : this.rootChildren.getChildNodes()){
XulTreeItem item = (XulTreeItem) c;
TreeItem node = createNode(item);
tree.addItem(node);
}
if(StringUtils.isEmpty(this.ondrag) == false){
for (int i = 0; i < tree.getItemCount(); i++) {
madeDraggable(tree.getItem(i));
}
}
}
private void madeDraggable(TreeItem item){
XulDragController.getInstance().makeDraggable(item.getWidget());
for (int i = 0; i < item.getChildCount(); i++) {
madeDraggable(item.getChild(i));
}
}
private List<XulComponent> colCollection = new ArrayList<XulComponent>();
private void populateTable(){
int rowCount = getRootChildren().getItemCount();
// Getting column editors ends up calling getChildNodes several times. we're going to cache the column collections
// for the duration of the operation then clear it out.
colCollection = getColumns().getChildNodes();
int colCount = colCollection.size();
currentData = new Object[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
currentData[i][j] = getColumnEditor(j,i);
}
}
table.populateTable(currentData);
int totalFlex = 0;
for (int i = 0; i < colCount; i++) {
totalFlex += colCollection.get(i).getFlex();
}
if(totalFlex > 0){
table.fillWidth();
}
colCollection = new ArrayList<XulComponent>();
if(this.selectedRows != null && this.selectedRows.length > 0){
for(int i=0; i<this.selectedRows.length; i++){
int idx = this.selectedRows[i];
if(idx > -1 && idx < currentData.length){
table.selectRow(idx);
}
}
}
}
private TreeItem createNode(final XulTreeItem item){
TreeItem node = new TreeItem("empty"){
@Override
public void setSelected( boolean selected ) {
super.setSelected(selected);
if(selected){
this.getWidget().addStyleDependentName("selected");
} else {
this.getWidget().removeStyleDependentName("selected");
}
}
};
item.setManagedObject(node);
if(item == null || item.getRow() == null || item.getRow().getChildNodes().size() == 0){
return node;
}
final TreeItemWidget tWidget = new TreeItemWidget(item);
PropertyChangeListener listener = new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("image") && item.getImage() != null){
tWidget.setImage(new Image(GWT.getModuleBaseURL() + item.getImage()));
} else if(evt.getPropertyName().equals("label")){
tWidget.setLabel(item.getRow().getCell(0).getLabel());
}
}
};
((GwtTreeItem) item).addPropertyChangeListener("image", listener);
((GwtTreeCell) item.getRow().getCell(0)).addPropertyChangeListener("label", listener);;
if (item.getImage() != null) {
tWidget.setImage(new Image(GWT.getModuleBaseURL() + item.getImage()));
}
tWidget.setLabel(item.getRow().getCell(0).getLabel());
if(this.ondrop != null){
TreeItemDropController controller = new TreeItemDropController(item, tWidget);
XulDragController.getInstance().registerDropController(controller);
this.dropHandlers.add(controller);
}
node.setWidget(tWidget);
if(item.getChildNodes().size() > 1){
//has children
//TODO: make this more defensive
XulTreeChildren children = (XulTreeChildren) item.getChildNodes().get(1);
for(XulComponent c : children.getChildNodes()){
TreeItem childNode = createNode((XulTreeItem) c);
node.addItem(childNode);
}
}
return node;
}
private String extractDynamicColType(Object row, int columnPos) {
GwtBindingMethod method = GwtBindingContext.typeController.findGetMethod(row, this.columns.getColumn(columnPos).getColumntypebinding());
try{
return (String) method.invoke(row, new Object[]{});
} catch (Exception e){
System.out.println("Could not extract column type from binding");
}
return "text"; // default //$NON-NLS-1$
}
private Binding createBinding(XulEventSource source, String prop1, XulEventSource target, String prop2){
if(bindingProvider != null){
return bindingProvider.getBinding(source, prop1, target, prop2);
}
return new GwtBinding(source, prop1, target, prop2);
}
private Widget getColumnEditor(final int x, final int y){
final XulTreeCol column = (XulTreeCol) colCollection.get(x);
String colType = ((XulTreeCol) colCollection.get(x)).getType();
final GwtTreeCell cell = (GwtTreeCell) getRootChildren().getItem(y).getRow().getCell(x);
String val = cell.getLabel();
// If collection bound, bindings may need to be updated for runtime changes in column types.
if(this.elements != null){
try {
this.addBindings(column, cell, this.elements.toArray()[y]);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (XulException e) {
e.printStackTrace();
}
}
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
Object row = elements.toArray()[y];
colType = extractDynamicColType(row, x);
}
int[] selectedRows = getSelectedRows();
if((StringUtils.isEmpty(colType) || !column.isEditable()) || ((showAllEditControls == false && (selectedRows.length != 1 || selectedRows[0] != y)) && !colType.equals("checkbox"))){
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
Vector vals = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
if(colType.equalsIgnoreCase("editablecombobox")){
return new HTML(cell.getLabel());
} else if(idx < vals.size()){
return new HTML(""+vals.get(idx));
} else {
return new HTML("");
}
} else {
return new HTML(val);
}
} else if(colType.equalsIgnoreCase("text")){
try{
GwtTextbox b = (GwtTextbox) this.domContainer.getDocumentRoot().createElement("textbox");
b.setDisabled(!column.isEditable());
b.layout();
b.setValue(val);
Binding bind = createBinding(cell, "label", b, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = createBinding(cell, "disabled", b, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget) b.getManagedObject();
} catch(Exception e){
System.out.println("error creating textbox, fallback");
e.printStackTrace();
final TextBox b = new TextBox();
b.addKeyboardListener(new KeyboardListener(){
public void onKeyDown(Widget arg0, char arg1, int arg2) {}
public void onKeyPress(Widget arg0, char arg1, int arg2) {}
public void onKeyUp(Widget arg0, char arg1, int arg2) {
getRootChildren().getItem(y).getRow().getCell(x).setLabel(b.getText());
}
});
b.setText(val);
return b;
}
} else if (colType.equalsIgnoreCase("checkbox")) {
try {
GwtCheckbox checkBox = (GwtCheckbox) this.domContainer.getDocumentRoot().createElement("checkbox");
checkBox.setDisabled(!column.isEditable());
checkBox.layout();
checkBox.setChecked(Boolean.parseBoolean(val));
Binding bind = createBinding(cell, "value", checkBox, "checked");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = createBinding(cell, "disabled", checkBox, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget)checkBox.getManagedObject();
} catch (Exception e) {
final CheckBox cb = new CheckBox();
return cb;
}
} else if(colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")){
try{
final GwtMenuList glb = (GwtMenuList) this.domContainer.getDocumentRoot().createElement("menulist");
final CustomListBox lb = glb.getNativeListBox();
lb.setWidth("100%");
final String fColType = colType;
// Binding to elements of listbox not giving us the behavior we want. Menulists select the first available
// item by default. We don't want anything selected by default in these cell editors
PropertyChangeListener listener = new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
Vector vals = (Vector) cell.getValue();
lb.clear();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(fColType.equalsIgnoreCase("editablecombobox")){
lb.setValue("");
}
}
};
listener.propertyChange(null);
cell.addPropertyChangeListener("value", listener);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(fColType.equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
if(colType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
Binding bind = createBinding(cell, "selectedIndex", glb, "selectedIndex");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
if(cell.getLabel() == null){
bind.fireSourceChanged();
}
bind = createBinding(cell, "label", glb, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
} else {
Binding bind = createBinding(cell, "selectedIndex", glb, "selectedIndex");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
Binding bind = createBinding(cell, "disabled", glb, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return lb;
} catch(Exception e){
System.out.println("error creating menulist, fallback");
final String fColType = colType;
e.printStackTrace();
final CustomListBox lb = new CustomListBox();
lb.setWidth("100%");
Vector vals = (Vector) cell.getValue();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(fColType.equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(fColType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
}
lb.setValue(cell.getLabel());
return lb;
}
} else if (colType != null && customEditors.containsKey(colType)){
if(this.customRenderers.containsKey(colType)){
return new CustomCellEditorWrapper(cell, customEditors.get(colType), customRenderers.get(colType));
} else {
return new CustomCellEditorWrapper(cell, customEditors.get(colType));
}
} else {
if(val == null || val.equals("")){
return new HTML(" ");
}
return new HTML(val);
}
}
private int curSelectedRow = -1;
private void setupTable(){
List<XulComponent> colCollection = getColumns().getChildNodes();
String cols[] = new String[colCollection.size()];
SelectionPolicy selectionPolicy = null;
if ("single".equals(getSeltype())) {
selectionPolicy = SelectionPolicy.ONE_ROW;
} else if ("multiple".equals(getSeltype())) {
selectionPolicy = SelectionPolicy.MULTI_ROW;
}
int[] widths = new int[cols.length];
int totalFlex = 0;
for (int i = 0; i < cols.length; i++) {
totalFlex += colCollection.get(i).getFlex();
}
for (int i = 0; i < cols.length; i++) {
cols[i] = ((XulTreeCol) colCollection.get(i)).getLabel();
if(totalFlex > 0 && getWidth() > 0){
widths[i] = (int) (getWidth() * ((double) colCollection.get(i).getFlex() / totalFlex));
} else if(getColumns().getColumn(i).getWidth() > 0){
widths[i] = getColumns().getColumn(i).getWidth();
}
}
table = new BaseTable(cols, widths, new BaseColumnComparator[cols.length], selectionPolicy);
if (getHeight() != 0) {
table.setHeight(getHeight() + "px");
} else {
table.setHeight("100%");
}
if (getWidth() != 0) {
table.setWidth(getWidth() + "px");
} else {
table.setWidth("100%");
}
table.addTableSelectionListener(new TableSelectionListener() {
public void onAllRowsDeselected(SourceTableSelectionEvents sender) {
}
public void onCellHover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onCellUnhover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onRowDeselected(SourceTableSelectionEvents sender, int row) {
}
public void onRowHover(SourceTableSelectionEvents sender, int row) {
}
public void onRowUnhover(SourceTableSelectionEvents sender, int row) {
}
public void onRowsSelected(SourceTableSelectionEvents sender, int firstRow, int numRows) {
try {
if (getOnselect() != null && getOnselect().trim().length() > 0) {
getXulDomContainer().invoke(getOnselect(), new Object[]{});
}
Integer[] selectedRows = table.getSelectedRows().toArray(new Integer[table.getSelectedRows().size()]);
//set.toArray(new Integer[]) doesn't unwrap ><
int[] rows = new int[selectedRows.length];
for(int i=0; i<selectedRows.length; i++){
rows[i] = selectedRows[i];
}
GwtTree.this.setSelectedRows(rows);
GwtTree.this.colCollection = getColumns().getChildNodes();
if(GwtTree.this.isShowalleditcontrols() == false){
if(curSelectedRow > -1){
Object[] curSelectedRowOriginal = new Object[getColumns().getColumnCount()];
for (int j = 0; j < getColumns().getColumnCount(); j++) {
curSelectedRowOriginal[j] = getColumnEditor(j,curSelectedRow);
}
table.replaceRow(curSelectedRow, curSelectedRowOriginal);
}
curSelectedRow = rows[0];
Object[] newRow = new Object[getColumns().getColumnCount()];
for (int j = 0; j < getColumns().getColumnCount(); j++) {
newRow[j] = getColumnEditor(j,rows[0]);
}
table.replaceRow(rows[0], newRow);
}
} catch (XulException e) {
e.printStackTrace();
}
}
});
setWidgetInPanel(table);
updateUI();
}
public void updateUI() {
if(this.suppressLayout) {
return;
}
if(this.isHierarchical()){
populateTree();
for(Binding expBind : expandBindings){
try {
expBind.fireSourceChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
// expandBindings.clear();
} else {
populateTable();
};
}
public void afterLayout() {
updateUI();
}
public void clearSelection() {
this.setSelectedRows(new int[]{});
}
public int[] getActiveCellCoordinates() {
// TODO Auto-generated method stub
return null;
}
public XulTreeCols getColumns() {
return columns;
}
public Object getData() {
// TODO Auto-generated method stub
return null;
}
@Bindable
public <T> Collection<T> getElements() {
return this.elements;
}
public String getOnedit() {
return getAttributeValue("onedit");
}
public String getOnselect() {
return getAttributeValue("onselect");
}
public XulTreeChildren getRootChildren() {
return rootChildren;
}
@Bindable
public int getRows() {
if (rootChildren == null) {
return 0;
} else {
return rootChildren.getItemCount();
}
}
@Bindable
public int[] getSelectedRows() {
if(this.isHierarchical()){
TreeItem item = tree.getSelectedItem();
for(int i=0; i <tree.getItemCount(); i++){
if(tree.getItem(i) == item){
return new int[]{i};
}
}
return new int[]{};
} else {
if (table == null) {
return new int[0];
}
Set<Integer> rows = table.getSelectedRows();
int rarr[] = new int[rows.size()];
int i = 0;
for (Integer v : rows) {
rarr[i++] = v;
}
return rarr;
}
}
public int[] getAbsoluteSelectedRows() {
return getSelectedRows();
}
private int[] selectedRows;
public void setSelectedRows(int[] rows) {
if (table == null || Arrays.equals(selectedRows, rows)) {
// this only works after the table has been materialized
return;
}
int[] prevSelected = selectedRows;
selectedRows = rows;
table.deselectRows();
for (int r : rows) {
if(this.rootChildren.getChildNodes().size() > r){
table.selectRow(r);
}
}
if(this.suppressEvents == false && Arrays.equals(selectedRows, prevSelected) == false){
this.changeSupport.firePropertyChange("selectedRows", prevSelected, rows);
this.changeSupport.firePropertyChange("absoluteSelectedRows", prevSelected, rows);
}
}
public String getSeltype() {
return getAttributeValue("seltype");
}
public Object[][] getValues() {
Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns().getColumnCount()];
int y = 0;
for (XulComponent component : getRootChildren().getChildNodes()) {
XulTreeItem item = (XulTreeItem)component;
for (XulComponent childComp : item.getChildNodes()) {
XulTreeRow row = (XulTreeRow)childComp;
for (int x = 0; x < getColumns().getColumnCount(); x++) {
XulTreeCell cell = row.getCell(x);
switch (columns.getColumn(x).getColumnType()) {
case CHECKBOX:
Boolean flag = (Boolean) cell.getValue();
if (flag == null) {
flag = Boolean.FALSE;
}
data[y][x] = flag;
break;
case COMBOBOX:
Vector values = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
data[y][x] = values.get(idx);
break;
default: //label
data[y][x] = cell.getLabel();
break;
}
}
y++;
}
}
return data;
}
@Bindable
public boolean isEditable() {
return editable;
}
public boolean isEnableColumnDrag() {
return false;
}
public boolean isHierarchical() {
return isHierarchical;
}
public void removeTreeRows(int[] rows) {
// sort the rows high to low
ArrayList<Integer> rowArray = new ArrayList<Integer>();
for (int i = 0; i < rows.length; i++) {
rowArray.add(rows[i]);
}
Collections.sort(rowArray, Collections.reverseOrder());
// remove the items in that order
for (int i = 0; i < rowArray.size(); i++) {
int item = rowArray.get(i);
if (item >= 0 && item < rootChildren.getItemCount()) {
this.rootChildren.removeItem(item);
}
}
updateUI();
}
public void setActiveCellCoordinates(int row, int column) {
// TODO Auto-generated method stub
}
public void setColumns(XulTreeCols columns) {
if (getColumns() != null) {
this.removeChild(getColumns());
}
addChild(columns);
}
public void setData(Object data) {
// TODO Auto-generated method stub
}
@Bindable
public void setEditable(boolean edit) {
this.editable = edit;
}
@Bindable
public <T> void setElements(Collection<T> elements) {
try{
this.elements = elements;
suppressEvents = true;
prevSelectionPos = -1;
this.getRootChildren().removeAll();
for(Binding b : expandBindings){
b.destroyBindings();
}
this.expandBindings.clear();
for(TreeItemDropController d : this.dropHandlers){
XulDragController.getInstance().unregisterDropController(d);
}
dropHandlers.clear();
if(elements == null || elements.size() == 0){
suppressEvents = false;
updateUI();
return;
}
try {
if(table != null){
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
int colSize = this.getColumns().getChildNodes().size();
for (int x=0; x< colSize; x++) {
XulComponent col = this.getColumns().getColumn(x);
XulTreeCol column = ((XulTreeCol) col);
final XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell");
addBindings(column, (GwtTreeCell) cell, o);
row.addCell(cell);
}
}
} else { //tree
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
((XulTreeItem) row.getParent()).setBoundObject(o);
addTreeChild(o, row);
}
}
//treat as a selection change
} catch (XulException e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
}
suppressEvents = false;
this.clearSelection();
updateUI();
} catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private <T> void addTreeChild(T element, XulTreeRow row){
try{
GwtTreeCell cell = (GwtTreeCell) getDocument().createElement("treecell");
for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getBindingExpressions()) {
Binding binding = createBinding((XulEventSource) element, exp.getModelAttr(), cell, exp.getXulCompAttr());
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
XulTreeCol column = (XulTreeCol) this.getColumns().getChildNodes().get(0);
String expBind = column.getExpandedbinding();
if(expBind != null){
Binding binding = createBinding((XulEventSource) element, expBind, row.getParent(), "expanded");
elementBindings.add(binding);
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
expandBindings.add(binding);
}
String imgBind = column.getImagebinding();
if(imgBind != null){
Binding binding = createBinding((XulEventSource) element, imgBind, row.getParent(), "image");
elementBindings.add(binding);
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
row.addCell(cell);
//find children
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(element, property);
Collection<T> children = null;
if(childrenMethod != null){
children = (Collection<T>) childrenMethod.invoke(element, new Object[] {});
} else if(element instanceof Collection ){
children = (Collection<T>) element;
}
XulTreeChildren treeChildren = null;
if(children != null && children.size() > 0){
treeChildren = (XulTreeChildren) getDocument().createElement("treechildren");
row.getParent().addChild(treeChildren);
}
if (children == null) {
return;
}
for(T child : children){
row = treeChildren.addNewRow();
((XulTreeItem) row.getParent()).setBoundObject(child);
addTreeChild(child, row);
}
} catch (Exception e) {
Window.alert("error adding elements "+e.getMessage());
e.printStackTrace();
}
}
public void setEnableColumnDrag(boolean drag) {
// TODO Auto-generated method stub
}
public void setOnedit(String onedit) {
this.setAttribute("onedit", onedit);
}
public void setOnselect(String select) {
this.setAttribute("onselect", select);
}
public void setRootChildren(XulTreeChildren rootChildren) {
if (getRootChildren() != null) {
this.removeChild(getRootChildren());
}
addChild(rootChildren);
}
public void setRows(int rows) {
// TODO Auto-generated method stub
}
public void setSeltype(String type) {
// TODO Auto-generated method stub
// SINGLE, CELL, MULTIPLE, NONE
this.setAttribute("seltype", type);
}
public void update() {
layout();
}
public void adoptAttributes(XulComponent component) {
super.adoptAttributes(component);
layout();
}
public void registerCellEditor(String key, TreeCellEditor editor){
customEditors.put(key, editor);
}
public void registerCellRenderer(String key, TreeCellRenderer renderer) {
customRenderers.put(key, renderer);
}
private void addBindings(final XulTreeCol col, final GwtTreeCell cell, final Object o) throws InvocationTargetException, XulException{
for (InlineBindingExpression exp : col.getBindingExpressions()) {
String colType = col.getType();
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
colType = extractDynamicColType(o, col.getParent().getChildNodes().indexOf(col));
}
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
// Only add bindings if they haven't been already applied.
if(cell.valueBindingsAdded() == false){
Binding binding = createBinding((XulEventSource) o, col.getCombobinding(), cell, "value");
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
}
if(cell.selectedIndexBindingsAdded() == false){
Binding binding = createBinding((XulEventSource) o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
binding.setConversion(new BindingConvertor<Object, Integer>(){
@Override
public Integer sourceToTarget(Object value) {
int index = ((Vector) cell.getValue()).indexOf(value);
return index > -1 ? index : 0;
}
@Override
public Object targetToSource(Integer value) {
return ((Vector)cell.getValue()).get(value);
}
});
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setSelectedIndexBindingsAdded(true);
}
if(cell.labelBindingsAdded() == false && colType.equalsIgnoreCase("editablecombobox")){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "label");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setLabelBindingsAdded(true);
}
} else if(colType != null && this.customEditors.containsKey(colType)){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "value");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
} else if(colType != null && colType.equalsIgnoreCase("checkbox")) {
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "value");
if(col.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
} else if(o instanceof XulEventSource && StringUtils.isEmpty(exp.getModelAttr()) == false){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, exp.getXulCompAttr());
if(col.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setLabelBindingsAdded(true);
} else {
cell.setLabel(o.toString());
}
}
if(StringUtils.isEmpty(col.getDisabledbinding()) == false){
String prop = col.getDisabledbinding();
Binding bind = createBinding((XulEventSource) o, col.getDisabledbinding(), cell, "disabled");
bind.setBindingType(Binding.Type.ONE_WAY);
// the default string to string was causing issues, this is really a boolean to boolean, no conversion necessary
bind.setConversion(null);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
}
@Deprecated
public void onResize() {
// if(table != null){
// table.onResize();
}
public class CustomCellEditorWrapper extends SimplePanel implements TreeCellEditorCallback{
private TreeCellEditor editor;
private TreeCellRenderer renderer;
private Label label = new Label();
private XulTreeCell cell;
public CustomCellEditorWrapper(XulTreeCell cell, TreeCellEditor editor){
super();
this.sinkEvents(Event.MOUSEEVENTS);
this.editor = editor;
this.cell = cell;
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.setStylePrimaryName("slimTable");
SimplePanel labelWrapper = new SimplePanel();
labelWrapper.getElement().getStyle().setProperty("overflow", "hidden");
labelWrapper.setWidth("100%");
labelWrapper.add(label);
hPanel.add(labelWrapper);
hPanel.setCellWidth(labelWrapper, "100%");
ImageButton btn = new ImageButton(GWT.getModuleBaseURL() + "/images/open_new.png", GWT.getModuleBaseURL() + "/images/open_new.png", "", 29, 24);
btn.getElement().getStyle().setProperty("margin", "0px");
hPanel.add(btn);
hPanel.setSpacing(0);
hPanel.setBorderWidth(0);
hPanel.setWidth("100%");
labelWrapper.getElement().getParentElement().getStyle().setProperty("padding", "0px");
labelWrapper.getElement().getParentElement().getStyle().setProperty("border", "0px");
btn.getElement().getParentElement().getStyle().setProperty("padding", "0px");
btn.getElement().getParentElement().getStyle().setProperty("border", "0px");
this.add( hPanel );
if(cell.getValue() != null) {
this.label.setText((cell.getValue() != null) ? cell.getValue().toString() : " ");
}
}
public CustomCellEditorWrapper(XulTreeCell cell, TreeCellEditor editor, TreeCellRenderer renderer){
this(cell, editor);
this.renderer = renderer;
if(this.renderer.supportsNativeComponent()){
this.clear();
this.add((Widget) this.renderer.getNativeComponent());
} else {
this.label.setText((this.renderer.getText(cell.getValue()) != null) ? this.renderer.getText(cell.getValue()) : " ");
}
}
public void onCellEditorClosed(Object value) {
cell.setValue(value);
if(this.renderer == null){
this.label.setText(value.toString());
} else if(this.renderer.supportsNativeComponent()){
this.clear();
this.add((Widget) this.renderer.getNativeComponent());
} else {
this.label.setText((this.renderer.getText(cell.getValue()) != null) ? this.renderer.getText(cell.getValue()) : " ");
}
}
@Override
public void onBrowserEvent(Event event) {
int code = event.getTypeInt();
switch(code){
case Event.ONMOUSEUP:
editor.setValue(cell.getValue());
int col = cell.getParent().getChildNodes().indexOf(cell);
XulTreeItem item = (XulTreeItem) cell.getParent().getParent();
int row = item.getParent().getChildNodes().indexOf(item);
Object boundObj = (GwtTree.this.getElements() != null) ? GwtTree.this.getElements().toArray()[row] : null;
String columnBinding = GwtTree.this.getColumns().getColumn(col).getBinding();
editor.show(row, col, boundObj, columnBinding, this);
default:
break;
}
super.onBrowserEvent(event);
}
}
public void setBoundObjectExpanded(Object o, boolean expanded) {
throw new UnsupportedOperationException("not implemented");
}
public void setTreeItemExpanded(XulTreeItem item, boolean expanded) {
((TreeItem) item.getManagedObject()).setState(expanded);
}
public void collapseAll() {
if (this.isHierarchical()){
//TODO: Not yet implemented
}
}
public void expandAll() {
if (this.isHierarchical()){
//TODO: not implemented yet
}
}
@Bindable
public <T> Collection<T> getSelectedItems() {
// TODO Auto-generated method stub
return null;
}
@Bindable
public <T> void setSelectedItems(Collection<T> items) {
// TODO Auto-generated method stub
}
public boolean isHiddenrootnode() {
// TODO Auto-generated method stub
return false;
}
public void setHiddenrootnode(boolean hidden) {
// TODO Auto-generated method stub
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public boolean isPreserveexpandedstate() {
return false;
}
public void setPreserveexpandedstate(boolean preserve) {
}
public boolean isSortable() {
// TODO Auto-generated method stub
return false;
}
public void setSortable(boolean sort) {
// TODO Auto-generated method stub
}
public boolean isTreeLines() {
// TODO Auto-generated method stub
return false;
}
public void setTreeLines(boolean visible) {
// TODO Auto-generated method stub
}
public void setNewitembinding(String binding){
}
public String getNewitembinding(){
return null;
}
public void setAutocreatenewrows(boolean auto){
}
public boolean getAutocreatenewrows(){
return false;
}
public boolean isPreserveselection() {
// TODO This method is not fully implemented. We need to completely implement this in this class
return false;
}
public void setPreserveselection(boolean preserve) {
// TODO This method is not fully implemented. We need to completely implement this in this class
}
private void fireSelectedItems( ) {
Object selected = getSelectedItem();
this.changeSupport.firePropertyChange("selectedItem", null, selected);
}
@Bindable
public Object getSelectedItem() {
if (this.isHierarchical && this.elements != null) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, tree.getSelectedItem(), curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
int[] vals = new int[]{pos};
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(vals[0]));
return tuple != null ? tuple.selectedItem : null;
}
return null;
}
private static class FindSelectedItemTuple {
Object selectedItem = null;
int curpos = -1; // ignores first element (root)
int selectedIndex;
public FindSelectedItemTuple(int selectedIndex) {
this.selectedIndex = selectedIndex;
}
}
private FindSelectedItemTuple findSelectedItem(Object parent, String childrenMethodProperty,
FindSelectedItemTuple tuple) {
if (tuple.curpos == tuple.selectedIndex) {
tuple.selectedItem = parent;
return tuple;
}
Collection children = getChildCollection(parent, childrenMethodProperty);
if (children == null || children.size() == 0) {
return null;
}
for (Object child : children) {
tuple.curpos++;
findSelectedItem(child, childrenMethodProperty, tuple);
if (tuple.selectedItem != null) {
return tuple;
}
}
return null;
}
private static Collection getChildCollection(Object obj, String childrenMethodProperty) {
Collection children = null;
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(obj, childrenMethodProperty);
try {
if (childrenMethod != null) {
children = (Collection) childrenMethod.invoke(obj, new Object[] {});
} else if(obj instanceof Collection ){
children = (Collection) obj;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return children;
}
public boolean isShowalleditcontrols() {
return showAllEditControls;
}
public void setShowalleditcontrols(boolean showAllEditControls) {
this.showAllEditControls = showAllEditControls;
}
@Override
public void setOndrag(String ondrag) {
super.setOndrag(ondrag);
}
@Override
public void setOndrop(String ondrop) {
super.setOndrop(ondrop);
}
@Override
public void setDropvetoer(String dropVetoMethod) {
if(StringUtils.isEmpty(dropVetoMethod)){
return;
}
super.setDropvetoer(dropVetoMethod);
}
private void resolveDropVetoerMethod(){
if(dropVetoerMethod == null && !StringUtils.isEmpty(getDropvetoer())){
String id = getDropvetoer().substring(0, getDropvetoer().indexOf("."));
try {
XulEventHandler controller = getXulDomContainer().getEventHandler(id);
this.dropVetoerMethod = GwtBindingContext.typeController.findMethod(controller, getDropvetoer().substring(getDropvetoer().indexOf(".")+1, getDropvetoer().indexOf("(")));
this.dropVetoerController = controller;
} catch (XulException e) {
e.printStackTrace();
}
}
}
private class TreeItemDropController extends AbstractPositioningDropController {
private XulTreeItem xulItem;
private TreeItemWidget item;
private DropPosition curPos;
private long lasPositionPoll = 0;
public TreeItemDropController(XulTreeItem xulItem, TreeItemWidget item){
super(item);
this.xulItem = xulItem;
this.item = item;
}
@Override
public void onEnter(DragContext context) {
super.onEnter(context);
resolveDropVetoerMethod();
if(dropVetoerMethod != null){
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
event.setDropPosition(curPos);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke(dropVetoerController, new Object[]{event});
//Check to see if this drop candidate should be rejected.
if(event.isAccepted() == false){
return;
}
} catch (XulException e) {
e.printStackTrace();
}
}
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(true);
}
@Override
public void onLeave(DragContext context) {
super.onLeave(context);
item.getElement().getStyle().setProperty("border", "");
item.highLightDrop(false);
dropPosIndicator.setVisible(false);
Widget proxy = XulDragController.getInstance().getProxy();
if(proxy != null){
((Draggable) proxy).setDropValid(false);
}
}
@Override
public void onMove(DragContext context) {
super.onMove(context);
int scrollPanelX = 0;
int scrollPanelY = 0;
int scrollPanelScrollTop = 0;
int scrollPanelScrollLeft = 0;
if(System.currentTimeMillis() > lasPositionPoll+3000){
scrollPanelX = scrollPanel.getElement().getAbsoluteLeft();
scrollPanelScrollLeft = scrollPanel.getElement().getScrollLeft();
scrollPanelY = scrollPanel.getElement().getAbsoluteTop();
scrollPanelScrollTop = scrollPanel.getElement().getScrollTop();
}
int x = item.getAbsoluteLeft();
int y = item.getAbsoluteTop();
int height = item.getOffsetHeight();
int middleGround = height/4;
if(context.mouseY < (y+height/2)-middleGround){
curPos = DropPosition.ABOVE;
} else if(context.mouseY > (y+height/2)+middleGround){
curPos = DropPosition.BELOW;
} else {
curPos = DropPosition.MIDDLE;
}
resolveDropVetoerMethod();
if(dropVetoerMethod != null){
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
event.setDropPosition(curPos);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke(dropVetoerController, new Object[]{event});
//Check to see if this drop candidate should be rejected.
if(event.isAccepted() == false){
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(false);
dropPosIndicator.setVisible(false);
return;
}
} catch (XulException e) {
e.printStackTrace();
}
}
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(true);
switch (curPos) {
case ABOVE:
item.highLightDrop(false);
int posX = item.getElement().getAbsoluteLeft()
- scrollPanelX
+ scrollPanelScrollLeft;
int posY = item.getElement().getAbsoluteTop()
- scrollPanelY
+ scrollPanelScrollTop
-4;
dropPosIndicator.setPosition(posX, posY, item.getOffsetWidth());
break;
case MIDDLE:
item.highLightDrop(true);
dropPosIndicator.setVisible(false);
break;
case BELOW:
item.highLightDrop(false);
posX = item.getElement().getAbsoluteLeft()
- scrollPanelX
+ scrollPanelScrollLeft;
posY = item.getElement().getAbsoluteTop()
+ item.getElement().getOffsetHeight()
- scrollPanelY
+ scrollPanelScrollTop
-4;
dropPosIndicator.setPosition(posX, posY, item.getOffsetWidth());
break;
}
}
@Override
public void onPreviewDrop(DragContext context) throws VetoDragException {
int i=0;
}
@Override
public void onDrop(DragContext context) {
super.onDrop(context);
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
//event.setDropIndex(index);
final String method = getOndrop();
if (method != null) {
try{
Document doc = getDocument();
XulRoot window = (XulRoot) doc.getRootElement();
final XulDomContainer con = window.getXulDomContainer();
con.invoke(method, new Object[]{event});
} catch (XulException e){
e.printStackTrace();
System.out.println("Error calling ondrop event: "+ method); //$NON-NLS-1$
}
}
if (!event.isAccepted()) {
return;
}
((Draggable) context.draggable).notifyDragFinished();
if(curPos == DropPosition.MIDDLE){
String property = ((XulTreeCol) GwtTree.this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(xulItem.getBoundObject(), property);
Collection children = null;
try {
if(childrenMethod != null){
children = (Collection) childrenMethod.invoke(xulItem.getBoundObject(), new Object[] {});
} else if(xulItem.getBoundObject() instanceof Collection ){
children = (Collection) xulItem.getBoundObject();
}
for(Object o : event.getDataTransfer().getData()){
children.add(o);
}
} catch (XulException e) {
e.printStackTrace();
}
} else {
XulComponent parent = xulItem.getParent().getParent();
List parentList;
if(parent instanceof GwtTree){
parentList = (List) GwtTree.this.elements;
} else {
parentList = (List) ((XulTreeItem) parent).getBoundObject();
}
int idx = parentList.indexOf(xulItem.getBoundObject());
if (curPos == DropPosition.BELOW){
idx++;
}
for(Object o : event.getDataTransfer().getData()){
parentList.add(idx, o);
}
}
}
}
public void notifyDragFinished(XulTreeItem xulItem){
if(this.drageffect.equalsIgnoreCase("copy")){
return;
}
XulComponent parent = xulItem.getParent().getParent();
List parentList;
if(parent instanceof GwtTree){
parentList = (List) GwtTree.this.elements;
} else {
parentList = (List) ((XulTreeItem) parent).getBoundObject();
}
parentList.remove(xulItem.getBoundObject());
}
private class DropPositionIndicator extends SimplePanel{
public DropPositionIndicator(){
setStylePrimaryName("tree-drop-indicator-symbol");
SimplePanel line = new SimplePanel();
line.setStylePrimaryName("tree-drop-indicator");
add(line);
setVisible(false);
}
public void setPosition(int scrollLeft, int scrollTop, int offsetWidth) {
this.setVisible(true);
setWidth(offsetWidth+"px");
getElement().getStyle().setProperty("top", scrollTop+"px");
getElement().getStyle().setProperty("left", (scrollLeft -4)+"px");
}
}
} |
package xml2jsontest;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import xml2json.Xml2Json;
public class Xml2JsonTest {
String stringXML;
String stringJson;
@Before
public void setUp() throws Exception {
stringXML = "<?xml version=\"1.0\" ?>"
+ "<quiz>"
//+ "<!-- question: 0 -->"
+ "<question type=\"category\">"
+ "<category>"
+ "<text>$course$/Défaut pour 1SA3GL1</text>"
+ "</category>"
+ "</question>"
//+ "<!-- question: 37095 -->"
+ "<question type=\"calculated\">"
+ "<name>"
+ "<text>Aire du cercle</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>Calcul de l'aire du cercle ayant pour rayon {R}</text>"
+ "</questiontext>"
+ "<image/>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>0.1</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>0</shuffleanswers>"
+ "<answer fraction=\"100\">"
+ "<text>3.14 * {R}*{R}</text>"
+ "<tolerance>0.01</tolerance>"
+ "<tolerancetype>1</tolerancetype>"
+ "<correctanswerformat>1</correctanswerformat>"
+ "<correctanswerlength>1</correctanswerlength>"
+ "<feedback>"
+ "<text/>"
+ "</feedback>"
+ "</answer>"
+ "<units>"
+ "<unit>"
+ "<multiplier>1</multiplier>"
+ "<unit_name>m2</unit_name>"
+ "</unit>"
+ "</units>"
+ "<dataset_definitions>"
+ "<dataset_definition>"
+ "<status>"
+ "<text>shared</text>"
+ "</status>"
+ "<name>"
+ "<text>R</text>"
+ "</name>"
+ "<type>calculated</type>"
+ "<distribution>"
+ "<text>uniform</text>"
+ "</distribution>"
+ "<minimum>"
+ "<text>1</text>"
+ "</minimum>"
+ "<maximum>"
+ "<text>10</text>"
+ "</maximum>"
+ "<decimals>"
+ "<text>1</text>"
+ "</decimals>"
+ "<itemcount>10</itemcount>"
+ "<dataset_items>"
+ "<dataset_item>"
+ "<number>1</number>"
+ "<value>6.9</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>2</number>"
+ "<value>9.7</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>3</number>"
+ "<value>5.2</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>4</number>"
+ "<value>7.1</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>5</number>"
+ "<value>4.8</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>6</number>"
+ "<value>6</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>7</number>"
+ "<value>6.3</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>8</number>"
+ "<value>5</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>9</number>"
+ "<value>6.2</value>"
+ "</dataset_item>"
+ "<dataset_item>"
+ "<number>10</number>"
+ "<value>2.6</value>"
+ "</dataset_item>"
+ "</dataset_items>"
+ "<number_of_items>10</number_of_items>"
+ "</dataset_definition>"
+ "</dataset_definitions>"
+ "</question>"
//+ "<!-- question: 37096 -->"
+ "<question type=\"description\">"
+ "<name>"
+ "<text>Consigne dispositif électronique</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>Pas de calculatrice !</text>"
+ "</questiontext>"
+ "<image/>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>0</defaultgrade>"
+ "<penalty>0</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>0</shuffleanswers>"
+ "</question>"
//+ "<!-- question: 37097 -->"
+ "<question type=\"essay\">"
+ "<name>"
+ "<text>Question ouverte</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>Ecrire un programme qui affiche Hello world</text>"
+ "</questiontext>"
+ "<image/>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>0</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>0</shuffleanswers>"
+ "<answer fraction=\"0\">"
+ "<feedback>"
+ "<text/>"
+ "</feedback>"
+ "</answer>"
+ "</question>"
//+ "<!-- question: 37098 -->"
+ "<question type=\"matching\">"
+ "<name>"
+ "<text>Serveur d'application / éditeurs</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>"
+ "Relier les serveurs d'applications avec les bons éditeurs"
+ "</text>"
+ "</questiontext>"
+ "<image/>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>0.1</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>1</shuffleanswers>"
+ "<subquestion>"
+ "<text>JBOSS</text>"
+ "<answer>"
+ "<text>Redhat</text>"
+ "</answer>"
+ "</subquestion>"
+ "<subquestion>"
+ "<text>Websphere</text>"
+ "<answer>"
+ "<text>IBM</text>"
+ "</answer>"
+ "</subquestion>"
+ "<subquestion>"
+ "<text>GlassFish</text>"
+ "<answer>"
+ "<text>Oracle</text>"
+ "</answer>"
+ "</subquestion>"
+ "<subquestion>"
+ "<text>Tomcat</text>"
+ "<answer>"
+ "<text>Fondation Apache</text>"
+ "</answer>"
+ "</subquestion>"
+ "</question>"
//+ "<!-- question: 37099 -->"
+ "<question type=\"cloze\">"
+ "<name>"
+ "<text>Question \"Cloze\" (composite ?)</text>"
+ "</name>"
+ "<questiontext>"
+ "<text>"
+ "Cette question comporte du texte dans lequel on a directement intégré des réponses à choix multiples {1:MULTICHOICE:Mauvaise réponse
+ "</text>"
+ "</questiontext>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<shuffleanswers>0</shuffleanswers>"
+ "</question>"
//+ "<!-- question: 37093 -->"
+ "<question type=\"multichoice\">"
+ "<name>"
+ "<text>Architecture à 3 niveaux ?</text>"
+ "</name>"
+ "<questiontext format=\"html\">"
+ "<text>Que désigne une architecture à 3 niveaux ?</text>"
+ "</questiontext>"
+ "<image>backupdata/446px-Uncle_Sam_pointing_finger_.jpg</image>"
+ "<image_base64>"
//+ "/9j/4AAQSkZJRgABAQEAqwCrAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAJXAb4DAREAAhEBAxEB/8QAHQABAAEFAQEBAAAAAAAAAAAAAAUDBAYHCAIBCf/EAEkQAAIBAwIEBAMFBQUGBQMFAQECAwAEEQUhBhIxQQcTUWEicYEIFDKRoRUjQlKxFjNywdEkYoLh8PEXJTRDopLC0jdEc3Wjsv/EABsBAQADAQEBAQAAAAAAAAAAAAACAwQBBQYH/8QAOBEAAgICAgIABAMHAwUAAgMAAAECEQMhEjEEQRMiUWEycYEFkaGxwdHwFCPhFTNCUvEGYiQ0Q//aAAwDAQACEQMRAD8A6poBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoCnPNFBGZJ5EiQdWdgo/M1xtLsJX0R8vEOjxOUfU7TnG/KsoY/kPnUPjY/qiz4U/oy1k4t0hZHjjnlmkQ/EscDsR+m9ReeFX/Qn/psntH1eI1kTmg0zUpBuR+6C/1NR/1MfodXjSfbSKi6zcHf9l3AGM7ugPy61B+VX/j/ACOrx/rJFQarMVz+z5c+nmL/AK1z/V//AK/yH+n/AP2R5TV5mYBtNnAPfnQ/50j5d9xf8A/H/wD2RXXU1L8rW1yv+8VBH6GrF5Efoc/07q1JFWPUbVyR5jLjb40ZP6gVJeRjfsi8GRK6LiOWOQZjdW+RzVikn0ypxce0e6kcFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgIbUOJtLspGiM/n3C5zFbr5jAjsSNgfmRVUs0I+y6Pjzl6r8yPueIL6dCNPtoYeb8Mk5L/UqCP8A/qsz8z6I0R8SK/E/8/z7EZeftC6TNxrV0iAZ5bfEZPt8IBx9ao/1EpW2y/4MF1H/AD9S1h4d0gyG4ubRri4K8vm3Ll3IPUEtk1TlnzdSJQuNNPovtP0yzhyFto+oIB3x6Uj8ukdlKX1J2IBV+EBc+gq6JnkVTnuc4qTIaPPWos6ADg71ygfMYPTNGdPnNgnJNcO0CcjZiD7V1OxVFnc23mpyrK8Z/mUDNVssUtUebVtStYiFu/vBB2Djt6b1OGfKv/KzkseGT2qPS8TvDIsV3YzCTc8qDdsfy9j+da4eS3qSKZeJ7iyY0nVrTVYnezkJaM8skbqUeM4zhlO4rVGamrRklFxdMvqkRFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAR2qarHZRuEXzZh0QHAz7ntVGXPHHr2XY8Ep/YxLUtWmmiP7SnwMZ8qP4U+o6n6msOTPOXs2Y8UYvS2R1nMt0+bdfg5euMAfIVS46NCdkpbWkxCmUgN2x0qPF9Em16JFLFGUFyzfI4qagymU9lZLaJDslc40znNsrKvL0XAqVbsg3ZVUbjrVi7IMq9qmyB46jvmoVZI+gbHrUqOWfCfntUWztHg4bBO/eo9kuj6B7V1HDwcMDXGiXQwBkUSoWfHVWA5gCBv8ql3sJ0QtzJdadrUN1p8fnC5yJkB/GFHY+tWY5uEg4RyRpujMbO5ivLSG5t25opUDqfUEV6Cdq0YJRcW4v0Vq6RFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQELqWqgRMYHAj3HP/N8vb3rJlz38sTVjw1uXZhGt61AXeIS4YANld8ZrJVuzXBN7RD2ttJe3kPnc8lsq5aRm6nsBXJaL1SVozLT7aK3jHwhQRiocq7INt+yTgAdAQNh0rqplcnRcAHHTpU3ZXYxk1FIH077Y60OFQDpVhE97elT0RPhIxgdq49A8k56dahskeDkj0rm/Z0+qMYGd66Gfe3QUOFNjufWouySGfzojozknG/sa6nYqiNCLZ63bhExHcq7D0VxjOPmKtX0EpWid0SEW8M0aH935hdV/l5tyPzJP1rT498WjLnptMka0FAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAQ3Ed4sUUdt5hQynL4ODyDqB8+nyzWbyJ18i9l+GO+TNd8T6lPcc9vCpCt8IwcAVkVdLpGtJ1yZh+lEvqotj5kgC8rELt16V31pl7utozm0uI0uIuUgq3wIvpiqm9M4ruiftYsYaZh7YFQ7dsNpIlbcqThR0NWRkn0Uzv2XABbNSIdA/5VE4fOuDiunT6oJ+dSVnGVBuvSpdoiz42CD3rjQR4Hrmo6JAdq6AxGR7VwIDvmpL7g8kdf6VE7Z4kYRpkjPyrkqSJRTky2MzP8aAfCcGoJt7iW8VHTKc5B1CCSQ4igieUse3T/KtK02/sUPom9CRxp0ckoKyT5mZT/DzbgfQYFbMUaijJldy0X9WFYoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAYH4qWuoR2CapYc0kNsjfeIlGWC5yHHy3z7b9jWfNDamavG4y+Rvb6NZWF/NdBPvIDhSTzFt8+m1Z5J8tGtL76JaOGzs2T7ojCWTJaTPqelVyb9nU5Se3ov8ASyLe4We6RTP0RAfwj1qposb9IyCGd55vLG75ztUZJ1siqMjs4jHGWc4J7ZqyEeJTN3pF0QMfSpFZ5OQe1cOnpR023rtHGwB1xXUjhUHQ1NETy+Su1cfR1HgYHzqCJA9DQHzah0+jbJJqSB82wdqAt5pFjA6HfFVylRZGLZZK/JLzIMKTnFRhuRbPapnhrU6hrjWz58h41EgHdAckfI7D5GtsI8pGKUqjZmNbDIKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgPjqroyuoZWGCCMgig6NCcU6RFw7rdxaEBIGJkjI25kbJX6jBX/AIfesU48Wz1MeVzinRBaPqMdqxluiWs4ASIi/wAW52NVOMZfmTbfa7ZlegtNcWTX16iJNLIeRSc4XPw/61TOo6s77pGRadfRWyN5MYMzNgvnq3euJr2clb66JuyvjJOFkJyPyrl07IuOiYVgwBG+atspo+9Md6HD1/Cd6kcA2ArqB6B2FdTIh87Y77HNclZ1FPp6YqJIHPYZogfM/Kh0DOMHFLYPLOADk1xyS7OpFlcsp5io3A61TKafRfBNdnu1kWRccoGB6VoxSvTKciadlxoeDq1/j+BIwd+55jWvAtszZukTtaDOKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAYP4qaKdQ0qG+iUGa0JVge8b4B/I8p+WapzxTjbNXi5HCVfU0BdzxcsNlbhZJs5lYbnr39qzXab+ht4/MZBo+uLLG1lZ87NGwWIgZTB6nNUyi2+R1JJ0zLLadJdUigWQCNF2K/iZu/0qCfsPr6mVWLukiAH4eXr61CQ00TlnztynoM+tSgm2VzpIvCMjbPWrCo+k7bdKHD0CMbjc1I5R6DbDFNnKDn4RR6CWzwSB/zqN7JUzyeu9ADuaM6AMAelSBTlHMpquatEoumRl2/Ij8h6DvWe0pJGhLWy6tHDxp8IBxWvGzPNUXfDILSanMejXPIvyVFH9c1s8d2n+Zmz/wDivsTdaDOKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAU7mFLi3khlGY5FKsPY1xq1TOp07OSuNVPCvEd1bLmO5lkZVCIDz4OCfbP8AnWOpU1fR60pKSUvTPGi3Mtpd25gnaN5F5WiI9T1qM43J2jjadL2bP0uOHTI7ZmBn1GQeWMAZAJrLL6HU3JtejJLGVQyKc5O3Marf1s7dE9ZPhwuc71KOnojNaJEncn9KuKKPuTtmutCh6ZoD6Dtt0ocaDNsAaMJHk4NRO7C/EBvvXDr0Ob9DXb0co+lvapCimxO4qMiSITU5CSyv3GwzWO3fzGqEV6KunTLJNbxK6/CnMwzvW7G/lsy5Lt2T/DluYNNJYkvNK8rE+7H/ACxW3x1UEZPIdzr6EpV5SKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKA0P4/actprlnq0SAkx4ckZHXH/4/nWbIqn+Zv8eTeNr6GpNIu54NQF6HTzI3ZcN2yKhOKaeuy3cvRtLSVYW8d1M7S3E5xCDjOG/i9qyTVWixS9L0ZJBewfeGt/M5pYQFIzneq/h/Q4nezIdJuAZGwwb132FcVpoSqtE4sobIGDtjarbKqPMl1BAuZ5URR3JrnNXQ4N9ERecT6dbsP36FQd3LBV/OrY45y6RCU4x1JkFeeK3CNgZFn1aMsvVY1Ln5DA3rRDw80tqJV8eD62fY/Fng6WzjuF1eMhxnyuRvMHsVxmj8PLdUcWeL6TMf1Lxu0eDmFlp1/cYOOdgsYORtjO9Xf9NnW2jnx2/wohpfHMxMhk0VgCeizAkj8qtj+yk26Zx+RKvRRm8d5FB8rQs7nBefG35U/wCktPbOf6mcukfYvGu/kIVtFijOA396WGPnipL9mdKxPyJK6J7TvFW4uuUzaLIFJAHlSgsc+xqqf7Mfp0MfkN9om49dttRuVHM0c2PwTDlNeTk8DNjfJqz0MWeDVdExw+v+2s0rBSUCgHrTFPtMZlrRnOmoUsIFYYIQV6uL8CPNyu5uy5qwrFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAa68cNLS/wCFlkbAMbMnM3RQVJyfqi/nVGfVP7mrxW7aX0OabOZERZ2YYYgZA/CenSqmk0bE3y0Zlaa/b2OlpEyP97EnlROT8KIe5Pr2qiS2/wCIb33+Zcwa9BpAlnvGWCMMDzOSWYAbmroePKe09FWbLHr9xUbxPt1DDQ9Our+RyDzEeXGPmTvWqH7ObpMofktERqnirxBcSrFZ29tZB03IYuffBq5fs+Hve/qV/wCqd+jEbvjPV710Mt+3OGwItwBv7da0R8THB8lH2QlnyO4ybIa71E3NzL96mnZcgjLEjPyrSoQjbqmUKTr6m1fBfg+y4q0TiVdQt4hC4S2t5CmXhlALc4PXbK/OsHmeRLHkXB1Rqww1ctp/xMF4z4Y1DhHWGtL/AOLDZjkUfDKv8w/zrXgzRzK4uvqRy4uDTW0yDs7wGNVblbJJA9frVyfKPZQ4+0tFUy2zsvmxk4JyB/DvUXVSaSOfh0XF3LDFKFicuA2RkYG1TUbd1/EK0rez5BqcaOQOYpk4PoaglTWqOu5aRJ6XrggnDShljRQVLHrRxTit9nVNpEJxZ4kagzfdtLtktvKP/qXJLN8vSs8uUU6dIk4uW2VdI4441ispNTl1+9YRqDEhtgYmbG2TtWaXh4pXyW/3FsZ5klTf7/6HdOmGQ6baGZlaXyU52XoTyjJHtVcapceiuXbLmunBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQGJeKtkL/gfUI3mEKJySsxOAQrAkfXGPrVWb8Nl2B1kRxrqt9bWDPLLIkIWbmCluYkdRgVHHBTSlZry5FjdMsLjj2Bkma1sXe4JBWS5YFUx3CDrW/HhxqD/qYPi5G1vj+RbaDeXmpXlxdatIbh2I5Fl3B+Q6AYrTD5ISqjjTbUm9/Uy+2uv3Y5WMTHPKgOAalOLen9DjaTrsx29uYkUhVcz55eYdFPXBqVKo6ILu5ei0528sxgAhcMSexG+KRUKvfY5NPR7hlkcybBXGwU/wAx6YrspJJ8ZMJJVZ154PaKdG4G0+GZAlzNzXE3uzdP0ArwPJyOeVtuzeoqKpdHzxf4U/tLws7W6c1/ZgywALkuMbp9aePleHJyX6jippxfv/LOVrDTfOv2hnea1SNsSOYuYx74Pw17qtxi41Rin/tyakto9XOjQw6hL511HNaKwKSKOQvn2NcUdaXsOWrX8Spc2Vl5oLMAd/iVseh3qU/kTdHL5IoXEFvhZcg5OcR/1NHKN9+jm29Ijr5v9kPluHY5HTA+Qqal1xaCVtWYlrPmSSNzDlLHPJzbis2WPJUqLI9GwfCy8XiDirQtF1DM1jIV82EtsQqnNZcycoPRZitPTO7tOZWsLcoMJ5a4HoMVnx/hRCf4mXFTIigFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgMB8ctMvNY8O7yx024it7iSaH45c8vKJFJG3sKqzNRjbVl/j3z0cH8YaLc6NrU1re3C3ExVZfMXphhnvVuCakvoSyR3t2Q0RKAHlDMD0rUul0ynp2ZRpV5y3ES8meYd+gqyK7pElSRmUbQLb28nnpJIq4w22Ks07jXSK5xXr2Qd9MYSzc3xIOdgu4PtU9R2+6IOpO0R1zeK7Fn/DgnLA7miSilboKN/hMy4D4S1rXrjFlo89zE7xMZJEKIoyCfiO3Ss2Xy4KPyy2av8ATZI1z+X8/wCx2bAqRlUiXEaDlUHsB0rwltltaKz/AIeuD2NSZw1rxb4XafxLetf2ty2mTyuWn8scyyds4zsdqvxeVPHpdHZRhP8A7iv8jH7nwC06dXc69eLcE7ERAqB6YzVkfOyrtkfhYf8A1dfn/wAEdxB4UcIcJ6XHdazq+rXEpyiRR8oadicgBcH+tWx8/wAjI6h2Vyx41rhf5t/8Glp0dSWMaxIjsAHAJxnYfOvU5Omm9mSWpe6PvDdlFqFzIuoXSwW8f45Cp5FyPX1qGRSjuKLKb2jafh/4KWF0/wC0NQ1S21jTskpGkX48jHxHO2PSvOzeQ1Hi47NcIwW4tlzxBwLYcF8Y8Oa5w5YC2sg/3W5VCTjP8W575xVGDI5XGXsvnFSTk1tfZI6F4Um83Ro1OeaJmjOfYnH6YNTh0Ycq+a/qS9TKxQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQGK+JqueELsxHEilWX5g1m8qSUN/U0+IryUcU+NNmyapZXPlH/wBPySSKhC5ztk+u9S8WW+uy/wAiLWzWyZVlIA963pO1oyfkS2nyxwMkqElo85HrntUopae+xWmjJLiW6lsZUtpETIHKvL27jNaGoO3G7KWm+zL/AA64I4P1+WGHWeMXiuHwGtEi8olvTzG2qjNlywvjv+BNTwJ1xaf36/gdHcL+GHB3Dio+maPDLNy/+ouj57t777fkK8rJ5GWT+Zm2MtfLpP6a/wCTN1ACIiAKowMAYAx7VQ23s5SRUi7nHfaux+pyX0KhOTsAakyNHlUCJyouB7VA7dvZZa1qVvpVjJdXLfCq7L/MfSpwg5tRj2cukay1u4e68rU9RRWnGSqHcR56AV6eGDh8iZnyU/RqvjTSbe4nD2xETOTI6A/i33rVFd9Fem/mITSNLmtrG/t1BkWUhsHAI6Y+ZqzJ8rbrSOwp1RnvA+pzcLTrcGQraleW6QvhcZ/Fv3FZfIxwyx6osU+BtqOFtas3W4EFzYPiW3lQ7+oyK8qXyP7o2wkpK4vTMp4X/ciaDPXEgA/I/wBBVmGVtoo8mOk/0J6tBlFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAYz4jKrcLzK+eUyRg492ArP5MeUK+5o8Z1M0VqfCthqzXVjqSmSGQlFBbBHuB7Vj+Jx2vR6DXKrMJXwP0x7uSOPWb024bGDEoI9if8AlVy8xpJtGaWJLVfxNdca2ejWetjTuF4pGt7NjFJdyyczXEhO/tgV6PjylKClPRnlG3SRd6NY3M9tkKzLGCGAOMY6mt2LJHh+Kt+ymeNt0tleOwWO8haaBry3zzmFiVJAHapufcnv0RVJ0nVGxuC/FGbhq/gtrR7i60fo1lcMGeH/AAN/kazZvHjlvWzsZyVuPf61/wAHRXC3EencTaPBqGlTeZDIMlDsyN3Vh2NeTmwzxSqRrhkUte16J2I5Bx1qpOkTkVWxXWyB5/PPQVx7OmA+IV3JaahZq4YW5yQMbM/ue1bPEUW2vZXlUlHnWv5GD65rttd6Pbw6eGWWIMkmcZ5s9/at2LE1O37M7n9UYHq1wFZTIRzIMYz0PfNXWtaIVfRYDUBG/IgBiZBzDOelclFO6LVOu+yF401ZjoUkD8oM+U3HUZzRpK/R2T3Zs/7MXGz6xbXGhXxC3VoiGMKNnTpn6bV5nlRTSki7HPdezecLz2V0blsLbwPljn8Ubfi/LY/SsUZ8GpGmUVkXFdv+Zlo3GRXonmigIa/4jsLS6a0jc3V6vWCDDMv+I9F+pFUZM8Meu2WRxSlvpHxbu7eJri6dLaJQT5anOB7sf+VUPPKSt6LVjjHvbIrh7jzR9X1H9nx3Si6wzYbbo3L1+dWYc/JfMQyY6ejL61FIoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQEBxwpbQGI5cLNExLdAA4rP5K+T9UX+M6no0wHL65dT/BGPMPKXG4rzmlxZ6jXGrMI8TeNYdFsW0u1m5dQvti4z+6Tu/wA/Stfj4Y5PxdIz58nCVM1vNYR2unWQt0Ek0rH4sYPzNeupttU10ZJIlOELptMs7+WVSwZTC5c5HKeuPQ1PHG0k67srnKqSZ9GoWN5eRRW0DK8ankLdfzq2cYu20VqTSqRVXUbGwMjvYwTh1ML7fEh/m+ddeN70Lb9mxfs8RPLxpfyQXEkltHZFpAGPKWZlxkevX8jWHztRSZbjXuujopCFf515Jq9Ht54lcK8yKxHQsAasUWytyS0yoCMAg8w65FRejq2WWq2EGp2MttdRq8bjqRnlPYj3rkZOL5I6n9Dm/iUNw/rF9p8/MZI38yNmTlMgPQ17uCazQUq2ZMkPhyoxzUszXhnePDSrzAKO4q78PH62VVXssbORjEoZJGl90wBUJP0m+y2K6sxbjyNBDbTSyscOQ2Sd8nqBXZur2c+yNi/ZUtZ7fjO+Etuo8+0MwkLfFEqsNsehz+lef5iUVcmv7F2K3tdE54reN1rLqN9ougYntLcNE9wrYE0vTYj+EHv3qnxfGc6nJHZ5K2mbN8JPFu04j4KjuL2zul1C1P3d4oIzIJWUD8B6bjuxA671PNkhhlxKoY5yVv8Af6Jg6hqfEahtQuW0qxbrZ2rnnYejzDB+iY9MmsWTO5Pj/L+5pjijFcuyRig0rRrVZIlhit48sMYVV9Sf9ayzccbtltuXXZr7ibj6HWWubbTLpGs7c/vGVsc5/lB71ZFt96ISg0rME8N9LfVeLbp5maOGLmnvZP4I4xkpGD6k4z7A1PO1HGt//SUbe2dH8B6zNrfD8dxdRlJVZkBJz5iAkK/1A/MGtfjZHOC5dmbyMahPXRkVaCgUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUBD8YWk99w1fwWnL94KcyBhsSpBx+lU548sbSLvHaWROXRpK3EeoXVyedQIXXzf5R7f5V5quPzI9RtPs598frYw+I1zOoIhureKWEH+XHKQPqpr0fCl8jS1s8/yEuSIXhvWJpTHbSFW8lcr2LD3rcrdvWkUN06MosWVdPcMCss7EsvNkJjvWrFjaSaSOZJcWWfD2BqUrylyq82WHr6Cu8nxXy+zi1r6lxL5MqXsRiPmXDAxgN8Q361yfFq1fZykmb8+zXpZteHNY1MjlS8uhFFzdeSMYJ+XMT+VeZ+0J8snH6GvHFKKaJDxX8VbThKyltNNeK61yVSIYuYFYv9+T0A7DvVHi+O88taS9nMk+OkaNsZ9Tlkh1PiJ7p1v+Z2aWXLE+pX+EZ/SvdxwSShGK0Y5qvmtfoZzofFl/psqfsy/uIliYBYZTzxsPcHtVWXx4zVuP7jinx1Zsjhzxa0+eQ22vRCycYAukPNE59+6/WvPyeFJK49F0c29lp458PJr3Cn9oNOeOebTIzLlCCHg6vg+o6/Q1V4uV+POpaXsuqOWPy1/wA/Q5+i1OOdYmEkbgfCmDvivcUlaV9mJppaK51bT4JXFxOYT/Cucg7YrnyprZ1SRa31rNrkNtcWOl3VzaNJ5aOIiUdgfXt86z5PIxxXBtX9C5YsklyS/U2Nwvwjf6NoPEVjc6zb2N5qsEdoklgDcSRRhgXGRjqoI6968fyfLjnqlrtmjHj1q3/AhtL8BYLW9t5riW4vbXqRKBEvtkZzVc/2hS+WP7zsfHfbaX8TZGiW+i8N6YLTTXt4ogWCpFJ8BPck152XNLJK2zZCCeiN1XxDtdJgkVZzNOOiY+FTiuxhKW1on8OmtGtNR4p1zjjURaTXH3e0YnmiRuQyL3FaVihii5PcvuRcKfymSW1p5cCaNoUSI3IDLMBlYQf4Sf5jvXXOTfOT0UyjF9mS8MXNjZLFwvpDKZpG87UJ85278x9eoFQ+HLI1OfSCkrpeujfPDViLKwXChAyqqoP4UA+Efqfzr0cEGk5P2Ys01J0iXq8pFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFACcDJ6UBi3EHFi2LeRp0MdzcFiuZZPLjXbOc4JP/W9Zn5KbqH7zTHx6XKbpGKz+ID2iGTU9a01BnlKWNu8pB9MnP9Kpl5Duoy/ci2OCMvwxk/4FH/xREqILG11S4J2Ektp5Sn33FVvNmXf9Cx+Kn0l+8+y+I14vKzwXMKkY3iDYP5ZqDz51u/5En40Etr+JWtfFBFVFu3gSUty/vEZM/nVkfKy3WiiXjQXtr9Cz8ReKNa4k8PdRtuB3t49WlCr5q3SqyoW+PkPTmI23Pc98VevIbdTjoqeCKf4kcraPxHxtouuvpRiuZboPiW0uIuY5J6kgdN+ta3ijlSb2RTlCTUX/ABNw+Nfhjd8S8OafqWlRiXiCziCyW0bZE0eMsFz/ABA9B3zj0rzcOb4eRxa0zY4LLCr2uv7fqcw27SW1yrAFXBwexHqDXtwVq67MEl6Zkdpq5NtJHzDm5gwcnJPbHyrVijHqvRXJOy/S+sbfSZboXoa/Nx5P3MgjMZXPMD86inUoq9HE7e+/r6LYa4sdvLdKj+aw+AbYXHpUnkio6Zx29JHR/GXEj+F/hBw9pltEw1y+tQscb5UxyMvPJI3+EtjHrXiyg/I8lxT/AD/L/k3vJ8NXV+jnPTJBeXyXWpTc8k0vPLLI2Cxz3r3IxUVSqkjDKbu2ZpqeqWcyySzahZzLGVVVwSzKPf0pxSoqhaVJNJkNDe+fO6W6yysSTiHc46Dp86jBxjFOZYouXRPfsDia4njt7LS71w4/GyHH1JrM/N8dW1L2SjgnSs2N4fcDcV2N1eQatevBoF7aSQXNqkvMXLqV2HReted5vnY8sGoq/oXQwyi1OL3ZEx/Z1hWOFYuI70EOeYLbgbZ2wc7HHeql+0st3X8S6WGM9Voz5fDDhrT7Sx+8aVpcQso+Vbm6HPISN+ZzkBjn1rFk83I27nX6/wAi2OJJU3+7+n0/QpavxZwNw/bRx6jrS3bRp8NvbseX6Ku1ZouWSXyRb+5ohi/9Y1+ZgWt+PtjZwNb8K6UiAdDMvKMeuBvWuPi5JP5tHWvc5Gudb8V9W1dyt/cNL8QIjT4IwO4x3q+PiK7/AJhZMcPwLZEpxNdXdv5TXEVpbKSOVNgc1P4UU77ZL4zmts8WutW8Tq1zMZUC4ZWU4b5e9dcG+iLzVsnjf2aXySaBMrcmC0r7EZHvVMYS4vmdlmi2qLafirVdKlls9Gkhh8whnYYJd/5iatWFTXKZTNpuos3L4C3XDk5txeK0mrhmkuWdctI2dj7oPT/tXdRl83SK5qcY0l+v+ezZWvcUa9Z+IU1nE0MmjeXD5SgcpDEZZub+LOenTb8qs/mJSai/w/x1f9TmLxbhyfs2Fpd/Hf2/OhAddnUdjWvBmWWPJGXNieKVMvKuKhQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoCy1l2j0+Qr6gH86z+U6xsv8dXkRp/xDuJI9Yu49QYR6dbJFNGFP97kbkn552rypSfJxPXxpLEsiVt3+hr6fxEFq1ydP062igXaJuQDnOcZxWmOFtIokpN/NIsLrxC1e8u1T74baIJsfKyMiuPDS6JYvHinctkPc"
+ "</image_base64>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>0.1</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>1</shuffleanswers>"
+ "<single>true</single>"
+ "<shuffleanswers>true</shuffleanswers>"
+ "<correctfeedback>"
+ "<text/>"
+ "</correctfeedback>"
+ "<partiallycorrectfeedback>"
+ "<text/>"
+ "</partiallycorrectfeedback>"
+ "<incorrectfeedback>"
+ "<text/>"
+ "</incorrectfeedback>"
+ "<answernumbering>none</answernumbering>"
+ "<answer fraction=\"-100\">"
+ "<text>Une architecture MVC</text>"
+ "<feedback>"
+ "<text>"
+ "Une application non distribuée peut implémentée MVC."
+ "</text>"
+ "</feedback>"
+ "</answer>"
+ "<answer fraction=\"100\">"
+ "<text>Une architecture N tiers ou N vaut 3</text>"
+ "<feedback>"
+ "<text></text>"
+ "</feedback>"
+ "</answer>"
+ "</question>"
//+ "<!-- question: 37092 -->"
+ "<question type=\"multichoice\">"
+ "<name>"
+ "<text>Architectures N tiers</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>Cocher les assertions vraies.</text>"
+ "</questiontext>"
+ "<image>backupdata/446px-Uncle_Sam_pointing_finger_.jpg</image>"
+ "<image_base64>"
//+ "/9j/4AAQSkZJRgABAQEAqwCrAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAJXAb4DAREAAhEBAxEB/8QAHQABAAEFAQEBAAAAAAAAAAAAAAUDBAYHCAIBCf/EAEkQAAIBAwIEBAMFBQUGBQMFAQECAwAEEQUhBhIxQQcTUWEicYEIFDKRoRUjQlKxFjNywdEkYoLh8PEXJTRDopLC0jdEc3Wjsv/EABsBAQADAQEBAQAAAAAAAAAAAAACAwQBBQYH/8QAOBEAAgICAgIABAMHAwUAAgMAAAECEQMhEjEEQRMiUWEycYEFkaGxwdHwFCPhFTNCUvEGYiQ0Q//aAAwDAQACEQMRAD8A6poBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoCnPNFBGZJ5EiQdWdgo/M1xtLsJX0R8vEOjxOUfU7TnG/KsoY/kPnUPjY/qiz4U/oy1k4t0hZHjjnlmkQ/EscDsR+m9ReeFX/Qn/psntH1eI1kTmg0zUpBuR+6C/1NR/1MfodXjSfbSKi6zcHf9l3AGM7ugPy61B+VX/j/ACOrx/rJFQarMVz+z5c+nmL/AK1z/V//AK/yH+n/AP2R5TV5mYBtNnAPfnQ/50j5d9xf8A/H/wD2RXXU1L8rW1yv+8VBH6GrF5Efoc/07q1JFWPUbVyR5jLjb40ZP6gVJeRjfsi8GRK6LiOWOQZjdW+RzVikn0ypxce0e6kcFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgIbUOJtLspGiM/n3C5zFbr5jAjsSNgfmRVUs0I+y6Pjzl6r8yPueIL6dCNPtoYeb8Mk5L/UqCP8A/qsz8z6I0R8SK/E/8/z7EZeftC6TNxrV0iAZ5bfEZPt8IBx9ao/1EpW2y/4MF1H/AD9S1h4d0gyG4ubRri4K8vm3Ll3IPUEtk1TlnzdSJQuNNPovtP0yzhyFto+oIB3x6Uj8ukdlKX1J2IBV+EBc+gq6JnkVTnuc4qTIaPPWos6ADg71ygfMYPTNGdPnNgnJNcO0CcjZiD7V1OxVFnc23mpyrK8Z/mUDNVssUtUebVtStYiFu/vBB2Djt6b1OGfKv/KzkseGT2qPS8TvDIsV3YzCTc8qDdsfy9j+da4eS3qSKZeJ7iyY0nVrTVYnezkJaM8skbqUeM4zhlO4rVGamrRklFxdMvqkRFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAR2qarHZRuEXzZh0QHAz7ntVGXPHHr2XY8Ep/YxLUtWmmiP7SnwMZ8qP4U+o6n6msOTPOXs2Y8UYvS2R1nMt0+bdfg5euMAfIVS46NCdkpbWkxCmUgN2x0qPF9Em16JFLFGUFyzfI4qagymU9lZLaJDslc40znNsrKvL0XAqVbsg3ZVUbjrVi7IMq9qmyB46jvmoVZI+gbHrUqOWfCfntUWztHg4bBO/eo9kuj6B7V1HDwcMDXGiXQwBkUSoWfHVWA5gCBv8ql3sJ0QtzJdadrUN1p8fnC5yJkB/GFHY+tWY5uEg4RyRpujMbO5ivLSG5t25opUDqfUEV6Cdq0YJRcW4v0Vq6RFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQELqWqgRMYHAj3HP/N8vb3rJlz38sTVjw1uXZhGt61AXeIS4YANld8ZrJVuzXBN7RD2ttJe3kPnc8lsq5aRm6nsBXJaL1SVozLT7aK3jHwhQRiocq7INt+yTgAdAQNh0rqplcnRcAHHTpU3ZXYxk1FIH077Y60OFQDpVhE97elT0RPhIxgdq49A8k56dahskeDkj0rm/Z0+qMYGd66Gfe3QUOFNjufWouySGfzojozknG/sa6nYqiNCLZ63bhExHcq7D0VxjOPmKtX0EpWid0SEW8M0aH935hdV/l5tyPzJP1rT498WjLnptMka0FAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAQ3Ed4sUUdt5hQynL4ODyDqB8+nyzWbyJ18i9l+GO+TNd8T6lPcc9vCpCt8IwcAVkVdLpGtJ1yZh+lEvqotj5kgC8rELt16V31pl7utozm0uI0uIuUgq3wIvpiqm9M4ruiftYsYaZh7YFQ7dsNpIlbcqThR0NWRkn0Uzv2XABbNSIdA/5VE4fOuDiunT6oJ+dSVnGVBuvSpdoiz42CD3rjQR4Hrmo6JAdq6AxGR7VwIDvmpL7g8kdf6VE7Z4kYRpkjPyrkqSJRTky2MzP8aAfCcGoJt7iW8VHTKc5B1CCSQ4igieUse3T/KtK02/sUPom9CRxp0ckoKyT5mZT/DzbgfQYFbMUaijJldy0X9WFYoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAYH4qWuoR2CapYc0kNsjfeIlGWC5yHHy3z7b9jWfNDamavG4y+Rvb6NZWF/NdBPvIDhSTzFt8+m1Z5J8tGtL76JaOGzs2T7ojCWTJaTPqelVyb9nU5Se3ov8ASyLe4We6RTP0RAfwj1qposb9IyCGd55vLG75ztUZJ1siqMjs4jHGWc4J7ZqyEeJTN3pF0QMfSpFZ5OQe1cOnpR023rtHGwB1xXUjhUHQ1NETy+Su1cfR1HgYHzqCJA9DQHzah0+jbJJqSB82wdqAt5pFjA6HfFVylRZGLZZK/JLzIMKTnFRhuRbPapnhrU6hrjWz58h41EgHdAckfI7D5GtsI8pGKUqjZmNbDIKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgPjqroyuoZWGCCMgig6NCcU6RFw7rdxaEBIGJkjI25kbJX6jBX/AIfesU48Wz1MeVzinRBaPqMdqxluiWs4ASIi/wAW52NVOMZfmTbfa7ZlegtNcWTX16iJNLIeRSc4XPw/61TOo6s77pGRadfRWyN5MYMzNgvnq3euJr2clb66JuyvjJOFkJyPyrl07IuOiYVgwBG+atspo+9Md6HD1/Cd6kcA2ArqB6B2FdTIh87Y77HNclZ1FPp6YqJIHPYZogfM/Kh0DOMHFLYPLOADk1xyS7OpFlcsp5io3A61TKafRfBNdnu1kWRccoGB6VoxSvTKciadlxoeDq1/j+BIwd+55jWvAtszZukTtaDOKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAYP4qaKdQ0qG+iUGa0JVge8b4B/I8p+WapzxTjbNXi5HCVfU0BdzxcsNlbhZJs5lYbnr39qzXab+ht4/MZBo+uLLG1lZ87NGwWIgZTB6nNUyi2+R1JJ0zLLadJdUigWQCNF2K/iZu/0qCfsPr6mVWLukiAH4eXr61CQ00TlnztynoM+tSgm2VzpIvCMjbPWrCo+k7bdKHD0CMbjc1I5R6DbDFNnKDn4RR6CWzwSB/zqN7JUzyeu9ADuaM6AMAelSBTlHMpquatEoumRl2/Ij8h6DvWe0pJGhLWy6tHDxp8IBxWvGzPNUXfDILSanMejXPIvyVFH9c1s8d2n+Zmz/wDivsTdaDOKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAU7mFLi3khlGY5FKsPY1xq1TOp07OSuNVPCvEd1bLmO5lkZVCIDz4OCfbP8AnWOpU1fR60pKSUvTPGi3Mtpd25gnaN5F5WiI9T1qM43J2jjadL2bP0uOHTI7ZmBn1GQeWMAZAJrLL6HU3JtejJLGVQyKc5O3Marf1s7dE9ZPhwuc71KOnojNaJEncn9KuKKPuTtmutCh6ZoD6Dtt0ocaDNsAaMJHk4NRO7C/EBvvXDr0Ob9DXb0co+lvapCimxO4qMiSITU5CSyv3GwzWO3fzGqEV6KunTLJNbxK6/CnMwzvW7G/lsy5Lt2T/DluYNNJYkvNK8rE+7H/ACxW3x1UEZPIdzr6EpV5SKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKA0P4/actprlnq0SAkx4ckZHXH/4/nWbIqn+Zv8eTeNr6GpNIu54NQF6HTzI3ZcN2yKhOKaeuy3cvRtLSVYW8d1M7S3E5xCDjOG/i9qyTVWixS9L0ZJBewfeGt/M5pYQFIzneq/h/Q4nezIdJuAZGwwb132FcVpoSqtE4sobIGDtjarbKqPMl1BAuZ5URR3JrnNXQ4N9ERecT6dbsP36FQd3LBV/OrY45y6RCU4x1JkFeeK3CNgZFn1aMsvVY1Ln5DA3rRDw80tqJV8eD62fY/Fng6WzjuF1eMhxnyuRvMHsVxmj8PLdUcWeL6TMf1Lxu0eDmFlp1/cYOOdgsYORtjO9Xf9NnW2jnx2/wohpfHMxMhk0VgCeizAkj8qtj+yk26Zx+RKvRRm8d5FB8rQs7nBefG35U/wCktPbOf6mcukfYvGu/kIVtFijOA396WGPnipL9mdKxPyJK6J7TvFW4uuUzaLIFJAHlSgsc+xqqf7Mfp0MfkN9om49dttRuVHM0c2PwTDlNeTk8DNjfJqz0MWeDVdExw+v+2s0rBSUCgHrTFPtMZlrRnOmoUsIFYYIQV6uL8CPNyu5uy5qwrFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAa68cNLS/wCFlkbAMbMnM3RQVJyfqi/nVGfVP7mrxW7aX0OabOZERZ2YYYgZA/CenSqmk0bE3y0Zlaa/b2OlpEyP97EnlROT8KIe5Pr2qiS2/wCIb33+Zcwa9BpAlnvGWCMMDzOSWYAbmroePKe09FWbLHr9xUbxPt1DDQ9Our+RyDzEeXGPmTvWqH7ObpMofktERqnirxBcSrFZ29tZB03IYuffBq5fs+Hve/qV/wCqd+jEbvjPV710Mt+3OGwItwBv7da0R8THB8lH2QlnyO4ybIa71E3NzL96mnZcgjLEjPyrSoQjbqmUKTr6m1fBfg+y4q0TiVdQt4hC4S2t5CmXhlALc4PXbK/OsHmeRLHkXB1Rqww1ctp/xMF4z4Y1DhHWGtL/AOLDZjkUfDKv8w/zrXgzRzK4uvqRy4uDTW0yDs7wGNVblbJJA9frVyfKPZQ4+0tFUy2zsvmxk4JyB/DvUXVSaSOfh0XF3LDFKFicuA2RkYG1TUbd1/EK0rez5BqcaOQOYpk4PoaglTWqOu5aRJ6XrggnDShljRQVLHrRxTit9nVNpEJxZ4kagzfdtLtktvKP/qXJLN8vSs8uUU6dIk4uW2VdI4441ispNTl1+9YRqDEhtgYmbG2TtWaXh4pXyW/3FsZ5klTf7/6HdOmGQ6baGZlaXyU52XoTyjJHtVcapceiuXbLmunBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQGJeKtkL/gfUI3mEKJySsxOAQrAkfXGPrVWb8Nl2B1kRxrqt9bWDPLLIkIWbmCluYkdRgVHHBTSlZry5FjdMsLjj2Bkma1sXe4JBWS5YFUx3CDrW/HhxqD/qYPi5G1vj+RbaDeXmpXlxdatIbh2I5Fl3B+Q6AYrTD5ISqjjTbUm9/Uy+2uv3Y5WMTHPKgOAalOLen9DjaTrsx29uYkUhVcz55eYdFPXBqVKo6ILu5ei0528sxgAhcMSexG+KRUKvfY5NPR7hlkcybBXGwU/wAx6YrspJJ8ZMJJVZ154PaKdG4G0+GZAlzNzXE3uzdP0ArwPJyOeVtuzeoqKpdHzxf4U/tLws7W6c1/ZgywALkuMbp9aePleHJyX6jippxfv/LOVrDTfOv2hnea1SNsSOYuYx74Pw17qtxi41Rin/tyakto9XOjQw6hL511HNaKwKSKOQvn2NcUdaXsOWrX8Spc2Vl5oLMAd/iVseh3qU/kTdHL5IoXEFvhZcg5OcR/1NHKN9+jm29Ijr5v9kPluHY5HTA+Qqal1xaCVtWYlrPmSSNzDlLHPJzbis2WPJUqLI9GwfCy8XiDirQtF1DM1jIV82EtsQqnNZcycoPRZitPTO7tOZWsLcoMJ5a4HoMVnx/hRCf4mXFTIigFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgMB8ctMvNY8O7yx024it7iSaH45c8vKJFJG3sKqzNRjbVl/j3z0cH8YaLc6NrU1re3C3ExVZfMXphhnvVuCakvoSyR3t2Q0RKAHlDMD0rUul0ynp2ZRpV5y3ES8meYd+gqyK7pElSRmUbQLb28nnpJIq4w22Ks07jXSK5xXr2Qd9MYSzc3xIOdgu4PtU9R2+6IOpO0R1zeK7Fn/DgnLA7miSilboKN/hMy4D4S1rXrjFlo89zE7xMZJEKIoyCfiO3Ss2Xy4KPyy2av8ATZI1z+X8/wCx2bAqRlUiXEaDlUHsB0rwltltaKz/AIeuD2NSZw1rxb4XafxLetf2ty2mTyuWn8scyyds4zsdqvxeVPHpdHZRhP8A7iv8jH7nwC06dXc69eLcE7ERAqB6YzVkfOyrtkfhYf8A1dfn/wAEdxB4UcIcJ6XHdazq+rXEpyiRR8oadicgBcH+tWx8/wAjI6h2Vyx41rhf5t/8Glp0dSWMaxIjsAHAJxnYfOvU5Omm9mSWpe6PvDdlFqFzIuoXSwW8f45Cp5FyPX1qGRSjuKLKb2jafh/4KWF0/wC0NQ1S21jTskpGkX48jHxHO2PSvOzeQ1Hi47NcIwW4tlzxBwLYcF8Y8Oa5w5YC2sg/3W5VCTjP8W575xVGDI5XGXsvnFSTk1tfZI6F4Um83Ro1OeaJmjOfYnH6YNTh0Ycq+a/qS9TKxQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQGK+JqueELsxHEilWX5g1m8qSUN/U0+IryUcU+NNmyapZXPlH/wBPySSKhC5ztk+u9S8WW+uy/wAiLWzWyZVlIA963pO1oyfkS2nyxwMkqElo85HrntUopae+xWmjJLiW6lsZUtpETIHKvL27jNaGoO3G7KWm+zL/AA64I4P1+WGHWeMXiuHwGtEi8olvTzG2qjNlywvjv+BNTwJ1xaf36/gdHcL+GHB3Dio+maPDLNy/+ouj57t777fkK8rJ5GWT+Zm2MtfLpP6a/wCTN1ACIiAKowMAYAx7VQ23s5SRUi7nHfaux+pyX0KhOTsAakyNHlUCJyouB7VA7dvZZa1qVvpVjJdXLfCq7L/MfSpwg5tRj2cukay1u4e68rU9RRWnGSqHcR56AV6eGDh8iZnyU/RqvjTSbe4nD2xETOTI6A/i33rVFd9Fem/mITSNLmtrG/t1BkWUhsHAI6Y+ZqzJ8rbrSOwp1RnvA+pzcLTrcGQraleW6QvhcZ/Fv3FZfIxwyx6osU+BtqOFtas3W4EFzYPiW3lQ7+oyK8qXyP7o2wkpK4vTMp4X/ciaDPXEgA/I/wBBVmGVtoo8mOk/0J6tBlFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAYz4jKrcLzK+eUyRg492ArP5MeUK+5o8Z1M0VqfCthqzXVjqSmSGQlFBbBHuB7Vj+Jx2vR6DXKrMJXwP0x7uSOPWb024bGDEoI9if8AlVy8xpJtGaWJLVfxNdca2ejWetjTuF4pGt7NjFJdyyczXEhO/tgV6PjylKClPRnlG3SRd6NY3M9tkKzLGCGAOMY6mt2LJHh+Kt+ymeNt0tleOwWO8haaBry3zzmFiVJAHapufcnv0RVJ0nVGxuC/FGbhq/gtrR7i60fo1lcMGeH/AAN/kazZvHjlvWzsZyVuPf61/wAHRXC3EencTaPBqGlTeZDIMlDsyN3Vh2NeTmwzxSqRrhkUte16J2I5Bx1qpOkTkVWxXWyB5/PPQVx7OmA+IV3JaahZq4YW5yQMbM/ue1bPEUW2vZXlUlHnWv5GD65rttd6Pbw6eGWWIMkmcZ5s9/at2LE1O37M7n9UYHq1wFZTIRzIMYz0PfNXWtaIVfRYDUBG/IgBiZBzDOelclFO6LVOu+yF401ZjoUkD8oM+U3HUZzRpK/R2T3Zs/7MXGz6xbXGhXxC3VoiGMKNnTpn6bV5nlRTSki7HPdezecLz2V0blsLbwPljn8Ubfi/LY/SsUZ8GpGmUVkXFdv+Zlo3GRXonmigIa/4jsLS6a0jc3V6vWCDDMv+I9F+pFUZM8Meu2WRxSlvpHxbu7eJri6dLaJQT5anOB7sf+VUPPKSt6LVjjHvbIrh7jzR9X1H9nx3Si6wzYbbo3L1+dWYc/JfMQyY6ejL61FIoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQEBxwpbQGI5cLNExLdAA4rP5K+T9UX+M6no0wHL65dT/BGPMPKXG4rzmlxZ6jXGrMI8TeNYdFsW0u1m5dQvti4z+6Tu/wA/Stfj4Y5PxdIz58nCVM1vNYR2unWQt0Ek0rH4sYPzNeupttU10ZJIlOELptMs7+WVSwZTC5c5HKeuPQ1PHG0k67srnKqSZ9GoWN5eRRW0DK8ankLdfzq2cYu20VqTSqRVXUbGwMjvYwTh1ML7fEh/m+ddeN70Lb9mxfs8RPLxpfyQXEkltHZFpAGPKWZlxkevX8jWHztRSZbjXuujopCFf515Jq9Ht54lcK8yKxHQsAasUWytyS0yoCMAg8w65FRejq2WWq2EGp2MttdRq8bjqRnlPYj3rkZOL5I6n9Dm/iUNw/rF9p8/MZI38yNmTlMgPQ17uCazQUq2ZMkPhyoxzUszXhnePDSrzAKO4q78PH62VVXssbORjEoZJGl90wBUJP0m+y2K6sxbjyNBDbTSyscOQ2Sd8nqBXZur2c+yNi/ZUtZ7fjO+Etuo8+0MwkLfFEqsNsehz+lef5iUVcmv7F2K3tdE54reN1rLqN9ougYntLcNE9wrYE0vTYj+EHv3qnxfGc6nJHZ5K2mbN8JPFu04j4KjuL2zul1C1P3d4oIzIJWUD8B6bjuxA671PNkhhlxKoY5yVv8Af6Jg6hqfEahtQuW0qxbrZ2rnnYejzDB+iY9MmsWTO5Pj/L+5pjijFcuyRig0rRrVZIlhit48sMYVV9Sf9ayzccbtltuXXZr7ibj6HWWubbTLpGs7c/vGVsc5/lB71ZFt96ISg0rME8N9LfVeLbp5maOGLmnvZP4I4xkpGD6k4z7A1PO1HGt//SUbe2dH8B6zNrfD8dxdRlJVZkBJz5iAkK/1A/MGtfjZHOC5dmbyMahPXRkVaCgUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUBD8YWk99w1fwWnL94KcyBhsSpBx+lU548sbSLvHaWROXRpK3EeoXVyedQIXXzf5R7f5V5quPzI9RtPs598frYw+I1zOoIhureKWEH+XHKQPqpr0fCl8jS1s8/yEuSIXhvWJpTHbSFW8lcr2LD3rcrdvWkUN06MosWVdPcMCss7EsvNkJjvWrFjaSaSOZJcWWfD2BqUrylyq82WHr6Cu8nxXy+zi1r6lxL5MqXsRiPmXDAxgN8Q361yfFq1fZykmb8+zXpZteHNY1MjlS8uhFFzdeSMYJ+XMT+VeZ+0J8snH6GvHFKKaJDxX8VbThKyltNNeK61yVSIYuYFYv9+T0A7DvVHi+O88taS9nMk+OkaNsZ9Tlkh1PiJ7p1v+Z2aWXLE+pX+EZ/SvdxwSShGK0Y5qvmtfoZzofFl/psqfsy/uIliYBYZTzxsPcHtVWXx4zVuP7jinx1Zsjhzxa0+eQ22vRCycYAukPNE59+6/WvPyeFJK49F0c29lp458PJr3Cn9oNOeOebTIzLlCCHg6vg+o6/Q1V4uV+POpaXsuqOWPy1/wA/Q5+i1OOdYmEkbgfCmDvivcUlaV9mJppaK51bT4JXFxOYT/Cucg7YrnyprZ1SRa31rNrkNtcWOl3VzaNJ5aOIiUdgfXt86z5PIxxXBtX9C5YsklyS/U2Nwvwjf6NoPEVjc6zb2N5qsEdoklgDcSRRhgXGRjqoI6968fyfLjnqlrtmjHj1q3/AhtL8BYLW9t5riW4vbXqRKBEvtkZzVc/2hS+WP7zsfHfbaX8TZGiW+i8N6YLTTXt4ogWCpFJ8BPck152XNLJK2zZCCeiN1XxDtdJgkVZzNOOiY+FTiuxhKW1on8OmtGtNR4p1zjjURaTXH3e0YnmiRuQyL3FaVihii5PcvuRcKfymSW1p5cCaNoUSI3IDLMBlYQf4Sf5jvXXOTfOT0UyjF9mS8MXNjZLFwvpDKZpG87UJ85278x9eoFQ+HLI1OfSCkrpeujfPDViLKwXChAyqqoP4UA+Efqfzr0cEGk5P2Ys01J0iXq8pFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFACcDJ6UBi3EHFi2LeRp0MdzcFiuZZPLjXbOc4JP/W9Zn5KbqH7zTHx6XKbpGKz+ID2iGTU9a01BnlKWNu8pB9MnP9Kpl5Duoy/ci2OCMvwxk/4FH/xREqILG11S4J2Ektp5Sn33FVvNmXf9Cx+Kn0l+8+y+I14vKzwXMKkY3iDYP5ZqDz51u/5En40Etr+JWtfFBFVFu3gSUty/vEZM/nVkfKy3WiiXjQXtr9Cz8ReKNa4k8PdRtuB3t49WlCr5q3SqyoW+PkPTmI23Pc98VevIbdTjoqeCKf4kcraPxHxtouuvpRiuZboPiW0uIuY5J6kgdN+ta3ijlSb2RTlCTUX/ABNw+Nfhjd8S8OafqWlRiXiCziCyW0bZE0eMsFz/ABA9B3zj0rzcOb4eRxa0zY4LLCr2uv7fqcw27SW1yrAFXBwexHqDXtwVq67MEl6Zkdpq5NtJHzDm5gwcnJPbHyrVijHqvRXJOy/S+sbfSZboXoa/Nx5P3MgjMZXPMD86inUoq9HE7e+/r6LYa4sdvLdKj+aw+AbYXHpUnkio6Zx29JHR/GXEj+F/hBw9pltEw1y+tQscb5UxyMvPJI3+EtjHrXiyg/I8lxT/AD/L/k3vJ8NXV+jnPTJBeXyXWpTc8k0vPLLI2Cxz3r3IxUVSqkjDKbu2ZpqeqWcyySzahZzLGVVVwSzKPf0pxSoqhaVJNJkNDe+fO6W6yysSTiHc46Dp86jBxjFOZYouXRPfsDia4njt7LS71w4/GyHH1JrM/N8dW1L2SjgnSs2N4fcDcV2N1eQatevBoF7aSQXNqkvMXLqV2HReted5vnY8sGoq/oXQwyi1OL3ZEx/Z1hWOFYuI70EOeYLbgbZ2wc7HHeql+0st3X8S6WGM9Voz5fDDhrT7Sx+8aVpcQso+Vbm6HPISN+ZzkBjn1rFk83I27nX6/wAi2OJJU3+7+n0/QpavxZwNw/bRx6jrS3bRp8NvbseX6Ku1ZouWSXyRb+5ohi/9Y1+ZgWt+PtjZwNb8K6UiAdDMvKMeuBvWuPi5JP5tHWvc5Gudb8V9W1dyt/cNL8QIjT4IwO4x3q+PiK7/AJhZMcPwLZEpxNdXdv5TXEVpbKSOVNgc1P4UU77ZL4zmts8WutW8Tq1zMZUC4ZWU4b5e9dcG+iLzVsnjf2aXySaBMrcmC0r7EZHvVMYS4vmdlmi2qLafirVdKlls9Gkhh8whnYYJd/5iatWFTXKZTNpuos3L4C3XDk5txeK0mrhmkuWdctI2dj7oPT/tXdRl83SK5qcY0l+v+ezZWvcUa9Z+IU1nE0MmjeXD5SgcpDEZZub+LOenTb8qs/mJSai/w/x1f9TmLxbhyfs2Fpd/Hf2/OhAddnUdjWvBmWWPJGXNieKVMvKuKhQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoBQCgFAKAUAoCy1l2j0+Qr6gH86z+U6xsv8dXkRp/xDuJI9Yu49QYR6dbJFNGFP97kbkn552rypSfJxPXxpLEsiVt3+hr6fxEFq1ydP062igXaJuQDnOcZxWmOFtIokpN/NIsLrxC1e8u1T74baIJsfKyMiuPDS6JYvHinctkPc"
+ "</image_base64>"
+ "<generalfeedback>"
+ "<text>"
+ "Rappel N tiers : architectures multi-niveaux pouvant être distribuées sur plusieurs noeuds physique d'un réseau."
+ "</text>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>0.1</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>1</shuffleanswers>"
+ "<single>false</single>"
+ "<shuffleanswers>true</shuffleanswers>"
+ "<correctfeedback>"
+ "<text>OK</text>"
+ "</correctfeedback>"
+ "<partiallycorrectfeedback>"
+ "<text/>"
+ "</partiallycorrectfeedback>"
+ "<incorrectfeedback>"
+ "<text>KO</text>"
+ "</incorrectfeedback>"
+ "<answernumbering>abc</answernumbering>"
+ "<answer fraction=\"0\">"
+ "<text>"
+ "Une architecture N-tiers est uniquement une architecture à base de Web Services"
+ "</text>"
+ "<feedback>"
+ "<text>"
+ "Une architecture distribuée peut reposer par exemple sur RMI"
+ "</text>"
+ "</feedback>"
+ "</answer>"
+ "<answer fraction=\"33.333\">"
+ "<text>"
+ "Une architecture client serveur est une architecture N-tiers"
+ "</text>"
+ "<feedback>"
+ "<text></text>"
+ "</feedback>"
+ "</answer>"
+ "<answer fraction=\"33.333\">"
+ "<text>"
+ "Une architecture N-tiers correspond à une architecture d'application distribuée sur plusieurs noeuds physiques"
+ "</text>"
+ "<feedback>"
+ "<text></text>"
+ "</feedback>"
+ "</answer>"
+ "<answer fraction=\"33.333\">"
+ "<text>"
+ "Une application web est une application reposant sur une architecture N Tiers"
+ "</text>"
+ "<feedback>"
+ "<text></text>"
+ "</feedback>"
+ "</answer>"
+ "</question>"
//+ "<!-- question: 37106 -->"
+ "<question type=\"numerical\">"
+ "<name>"
+ "<text>HTTP 1er protocole de l'Internet</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>"
+ "En quelle année HTTP devient le premier protocole de l'Internet ?"
+ "</text>"
+ "</questiontext>"
+ "<image/>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>0.1</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>0</shuffleanswers>"
+ "<answer fraction=\"100\">"
+ "<text>1996</text>"
+ "<tolerance>0</tolerance>"
+ "<feedback>"
+ "<text/>"
+ "</feedback>"
+ "</answer>"
+ "</question>"
//+ "<!-- question: 37107 -->"
+ "<question type=\"shortanswer\">"
+ "<name>"
+ "<text>MVC</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>Que signifie MVC ?</text>"
+ "</questiontext>"
+ "<image/>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>0.1</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>0</shuffleanswers>"
+ "<usecase>0</usecase>"
+ "<answer fraction=\"100\">"
+ "<text>Model View Controller</text>"
+ "<feedback>"
+ "<text></text>"
+ "</feedback>"
+ "</answer>"
+ "<answer fraction=\"100\">"
+ "<text>Modèle vue contrôleur</text>"
+ "<feedback>"
+ "<text></text>"
+ "</feedback>"
+ "</answer>"
+ "</question>"
//+ "<!-- question: 37105 -->"
+ "<question type=\"shortanswer\">"
+ "<name>"
+ "<text>Premier langage Orienté Objet</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>Quel est le premier langage Orienté Objet ?</text>"
+ "</questiontext>"
+ "<image/>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>0.1</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>0</shuffleanswers>"
+ "<usecase>0</usecase>"
+ "<answer fraction=\"100\">"
+ "<text>Simula 66</text>"
+ "<feedback>"
+ "<text>Parfait !</text>"
+ "</feedback>"
+ "</answer>"
+ "<answer fraction=\"75\">"
+ "<text>Simula</text>"
+ "<feedback>"
+ "<text>Oui, plus précisément Simula 66</text>"
+ "</feedback>"
+ "</answer>"
+ "</question>"
//+ "<!-- question: 37094 -->"
+ "<question type=\"truefalse\">"
+ "<name>"
+ "<text>Tomcat et JEE</text>"
+ "</name>"
+ "<questiontext format=\"moodle_auto_format\">"
+ "<text>"
+ "Tomcat est un conteneur implémentant toutes les spécifications JEE."
+ "</text>"
+ "</questiontext>"
+ "<image/>"
+ "<generalfeedback>"
+ "<text/>"
+ "</generalfeedback>"
+ "<defaultgrade>1</defaultgrade>"
+ "<penalty>1</penalty>"
+ "<hidden>0</hidden>"
+ "<shuffleanswers>0</shuffleanswers>"
+ "<answer fraction=\"0\">"
+ "<text>true</text>"
+ "<feedback>"
+ "<text>Tomcat est un conteneur Web uniquement.</text>"
+ "</feedback>"
+ "</answer>"
+ "<answer fraction=\"100\">"
+ "<text>false</text>"
+ "<feedback>"
+ "<text>Tomcat est un conteneur Web uniquement.</text>"
+ "</feedback>"
+ "</answer>"
+ "</question>"
+ "</quiz>";
}
@Test
public void conversionTest() {
try {
stringJson = new Xml2Json().conversion(stringXML);
} catch(Exception e) {
assertTrue(false);
}
}
@After
public void tearDown() throws Exception {
stringXML = null;
stringJson = null;
}
} |
/**
* @author anusio
*/
package metodos;
public class Metodos {
private Funcao funcao;
private Exibir exibir;
private double tol = .0000001;
private int max_interacao = 100;
public Metodos(Funcao fun) {
funcao = fun;
}
public Metodos(Funcao fun, Exibir e) {
funcao = fun;
exibir = e;
}
public void setFuncao(Funcao funcao) {
this.funcao = funcao;
}
public void setExibir(Exibir exibir) {
this.exibir = exibir;
}
public void setTol(double tol) {
this.tol = tol;
}
public void setMax_interacao(int max_interacao) {
this.max_interacao = max_interacao;
}
private void putInfo(String text) {
if (exibir != null)
exibir.setText(text);
}
private void new_line() {
if (exibir != null)
exibir.newline();
}
public double bissecao(double a, double b) {
double x0,x1,ea;
x1 = a;
putInfo("Metodo Biseco:");
for (int i = 0; i < max_interacao ; i++) {
x0 = x1;
x1 = (a+b)/2;
ea = Math.abs((x1 - x0)/x1)*100;
if(funcao.f(a)*funcao.f(b) < 0){
b = x1;
}else{
a = x1;
}
new_line();
putInfo("interao "+i);
putInfo(" a= "+a);
putInfo(" b= "+b);
putInfo(" x1= "+x1);
putInfo(" ea "+ea);
putInfo(" f(x1)= "+funcao.f(x1));
if(ea < tol){
break;
}
}
return x1;
}
public double falsa_posicao(double a, double b) {
double x0,x1, fl, fu, fx, ea;
ea = 100;
fl = funcao.f(a);
fu = funcao.f(b);
if(fl < fu){
x1 = a;
}else{
x1 = b;
}
putInfo("Falsa posio:");
for (int i = 0; i < max_interacao; i++) {
x0 = x1;
x1 = b + (fu*(a-b))/(fu-fl);
fx = funcao.f(x1);
if(x1 != 0){
ea = Math.abs((x1-x0)/x1)*100;
}
if(fl < fu){
a = x1;
fl = fx;
}else{
b = x1;
fu = fx;
}
new_line();
putInfo("interao "+i);
putInfo(" a= "+a);
putInfo(" b= "+b);
putInfo(" x1= "+x1);
putInfo(" ea "+ea);
putInfo(" f(x1)= "+funcao.f(x1));
if(ea < tol){
break;
}
}
return x1;
}
public void ponto_fixo(double xa) {
double x1, x0, ea;
x1 = xa;
ea = 100;
putInfo("Ponto fixo");
for (int i = 0; i < max_interacao; i++) {
x0 = x1;
x1 = funcao.g(x0);
if(x1 != 0){
ea = Math.abs((x1-x0)/x1)*100;
}
new_line();
putInfo("interao "+i);
putInfo(" a= "+x0);
putInfo(" x1= "+x1);
putInfo(" ea "+ea);
putInfo(" f(x1)= "+funcao.f(x1));
if(ea < tol){
break;
}
}
}
public void nweton_raphson() {
}
public void secante() {
}
} |
package org.commcare.util;
import org.commcare.applogic.CommCareAlertState;
import org.commcare.applogic.CommCareFirstStartState;
import org.commcare.applogic.CommCareHomeState;
import org.commcare.applogic.CommCareLoginState;
import org.commcare.cases.model.Case;
import org.commcare.core.properties.CommCareProperties;
import org.commcare.suite.model.Entry;
import org.commcare.suite.model.Profile;
import org.commcare.suite.model.Suite;
import org.commcare.suite.model.Text;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.instance.ExternalDataInstance;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.PropertyManager;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.core.services.storage.IStorageUtility;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.util.ArrayUtilities;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.form.api.FormEntryModel;
import org.javarosa.formmanager.api.JrFormEntryController;
import org.javarosa.formmanager.api.JrFormEntryModel;
import org.javarosa.formmanager.utility.FormDefFetcher;
import org.javarosa.j2me.view.J2MEDisplay;
import org.javarosa.model.xform.DataModelSerializer;
import org.javarosa.service.transport.securehttp.HttpCredentialProvider;
import org.javarosa.services.transport.TransportService;
import org.javarosa.user.model.User;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.lcdui.StringItem;
import de.enough.polish.ui.Style;
import de.enough.polish.ui.StyleSheet;
import de.enough.polish.ui.UiAccess;
/**
* @author ctsims
*
*/
public class CommCareUtil {
private static final String COMMCARE_RELEASE_PROPERTY = "CommCare-Release";
private final static String PROP_APP_VERSION = "App-Version";
private final static String PROP_CC_APP_VERSION = "CommCare-Version";
private final static String PROP_JR_BUILD_VERSION = "JR-Build-Version";
private final static String PROP_CC_BUILD_VERSION = "CC-Build-Version";
private final static String PROP_CONTENT_VERSION = "CC-Content-Version";
private final static String PROP_POLISH_VERSION = "Polish-Version";
private final static String PROP_POLISH_DEVICE = "Polish-Device";
private final static String PROP_BUILD_DATE = "Built-on";
private final static String PROP_RELEASE_DATE = "Released-on";
private final static String PROP_BUILD_NUM = "Build-Number";
private final static String PROP_PROFILE_REFERENCE = "Profile";
public final static int VERSION_SHORT = 1;
public final static int VERSION_MED = 2;
public final static int VERSION_LONG = 3;
public static int getNumberUnsent() {
return TransportService.getCachedMessagesSize();
}
public static String getProfileReference() {
return getAppProperty(PROP_PROFILE_REFERENCE);
}
public static String getAppProperty (String key) {
return CommCareContext._().getMidlet().getAppProperty(key);
}
public static String getAppProperty (String key, String defaultValue) {
String prop = getAppProperty(key);
return (prop != null ? prop : defaultValue);
}
public static String getVersion () {
return getVersion(VERSION_LONG);
}
public static String getVersion (int type) {
final int hashLength = 6;
String vApp = getAppProperty(PROP_APP_VERSION, "??");
String vHumanApp = getAppProperty(PROP_CC_APP_VERSION, vApp);
String vBuildJR = getAppProperty(PROP_JR_BUILD_VERSION, "??");
String vBuildCC = getAppProperty(PROP_CC_BUILD_VERSION, "??");
String vContent = getAppProperty(PROP_CONTENT_VERSION, "??");
String vPolish = getAppProperty(PROP_POLISH_VERSION, "??");
String vDevice = getAppProperty(PROP_POLISH_DEVICE, "??");
String buildDate = getAppProperty(PROP_BUILD_DATE, "??");
String releaseDate = getAppProperty(PROP_RELEASE_DATE, "
String binaryNum = getAppProperty(PROP_BUILD_NUM, "custom");
boolean released = !isTestingMode();
String profileVersion = null;
Profile p = CommCareContext._().getManager() == null ? null : CommCareContext._().getManager().getCurrentProfile();
if(p != null) {
profileVersion = " App #" + p.getVersion();
}
vBuildJR = PropertyUtils.trim(vBuildJR, hashLength);
vBuildCC = PropertyUtils.trim(vBuildCC, hashLength);
vContent = PropertyUtils.trim(vContent, hashLength);
vPolish = (String)DateUtils.split(vPolish, " ", true).elementAt(0);
buildDate = (String)DateUtils.split(buildDate, " ", true).elementAt(0);
releaseDate = (String)DateUtils.split(releaseDate, " ", true).elementAt(0);
switch (type) {
case VERSION_LONG:
return vHumanApp + " (" + vBuildJR + "-" + vBuildCC + "-" + vContent + "-" + vPolish + "-" + vDevice +
")" + (released ? " build " + binaryNum : "") + (profileVersion == null ? "" : profileVersion) + " b:" + buildDate + " r:" + releaseDate;
case VERSION_MED:
return vHumanApp + " build " + binaryNum + (profileVersion == null ? "" : profileVersion) + (released ? " (" + releaseDate + ")" : "<unreleased>");
case VERSION_SHORT:
return vHumanApp;
default: throw new RuntimeException("unknown version type");
}
}
public static Case getCase (int recordId) {
IStorageUtility cases = StorageManager.getStorage(Case.STORAGE_KEY);
return (Case)cases.read(recordId);
}
public static Case getCase (String caseId) {
IStorageUtilityIndexed cases = (IStorageUtilityIndexed)StorageManager.getStorage(Case.STORAGE_KEY);
return (Case)cases.getRecordForValue("case-id", caseId);
}
public static FormDef getForm (int id) {
IStorageUtility forms = StorageManager.getStorage(FormDef.STORAGE_KEY);
return (FormDef)forms.read(id);
}
public static boolean isTestingMode() {
String mode = PropertyManager._().getSingularProperty(CommCareProperties.DEPLOYMENT_MODE);
if (mode == null || mode.equals(CommCareProperties.DEPLOY_DEFAULT)) {
return !"true".equals(CommCareUtil.getAppProperty(COMMCARE_RELEASE_PROPERTY));
} else {
return mode.equals(CommCareProperties.DEPLOY_TESTING);
}
}
public static void exit () {
Logger.log("app-close", "");
CommCareContext._().getMidlet().notifyDestroyed();
}
public static void launchHomeState() {
J2MEDisplay.startStateWithLoadingScreen(new CommCareHomeState());
}
public static int countEntities(Entry entry, Suite suite) {
final Entry e = entry;
return 0;
// Hashtable<String, String> references = entry.getReferences();
// if(references.size() == 0) {
// throw new RuntimeException("Attempt to count entities for an entry with no references!");
// else {
// //this will be revisited and rewritten
// boolean referral = false;
// int count = 0;
// // Need to do some reference gathering...
// for(Enumeration en = references.keys() ; en.hasMoreElements() ; ) {
// String key = (String)en.nextElement();
// String refType = references.get(key);
// if(refType.toLowerCase().equals("referral")) {
// referral = true;
// if(referral) {
// Entity<PatientReferral> entity = new CommCareEntity<PatientReferral>(suite.getDetail(entry.getShortDetailId()), suite.getDetail(entry.getLongDetailId()), new ReferralInstanceLoader(e.getReferences()));
// EntityFilter<? super PatientReferral> filter = entity.getFilter();
// for(IStorageIterator i = StorageManager.getStorage(PatientReferral.STORAGE_KEY).iterate(); i.hasMore() ;) {
// if(filter.matches((PatientReferral)i.nextRecord())) {
// count++;
// return count;
// } else {
// Entity<Case> entity = new CommCareEntity<Case>(suite.getDetail(entry.getShortDetailId()), suite.getDetail(entry.getLongDetailId()), new CaseInstanceLoader(e.getReferences()));
// EntityFilter<? super Case> filter = entity.getFilter();
// for(IStorageIterator i = StorageManager.getStorage(Case.STORAGE_KEY).iterate(); i.hasMore() ;) {
// if(filter.matches((Case)i.nextRecord())) {
// count++;
// return count;
}
private static int[] getVersions() {
try {
String vApp = getAppProperty(PROP_APP_VERSION, "blank");
if ("blank".equals(vApp)) {
return null;
}
Vector<String> split = DateUtils.split(vApp, ".", false);
if (split.size() < 2) {
return null;
}
int[] version = new int[split.size()];
for (int i = 0; i < version.length; ++i) {
version[i] = Integer.parseInt(split.elementAt(i));
}
return version;
} catch (Exception e) {
return null;
}
}
public static int getMajorVersion() {
int[] versions = getVersions();
if(versions != null) {
return versions[0];
} else {
return -1;
}
}
public static int getMinorVersion() {
int[] versions = getVersions();
if(versions != null) {
return versions[1];
} else {
return -1;
}
}
public static void launchFirstState() {
if(CommCareProperties.PROPERTY_YES.equals(PropertyManager._().getSingularProperty(CommCareProperties.IS_FIRST_RUN)) &&
CommCareContext._().getManager().getCurrentProfile().isFeatureActive("users")) {
J2MEDisplay.startStateWithLoadingScreen(new CommCareFirstStartState());
} else {
J2MEDisplay.startStateWithLoadingScreen(new CommCareLoginState());
}
}
public static void exitMain() {
if(CommCareContext._().getManager().getCurrentProfile().isFeatureActive("users") &&
(!CommCareSense.isAutoLoginEnabled() || !User.STANDARD.equals(CommCareContext._().getUser().getUserType()))) {
J2MEDisplay.startStateWithLoadingScreen(new CommCareLoginState(true));
} else{
exit();
}
}
public static JrFormEntryController createFormEntryController(FormDefFetcher fetcher, boolean supportsNewRepeats) {
return createFormEntryController(new JrFormEntryModel(fetcher.getFormDef(), false, supportsNewRepeats? FormEntryModel.REPEAT_STRUCTURE_NON_LINEAR : FormEntryModel.REPEAT_STRUCTURE_LINEAR));
}
public static JrFormEntryController createFormEntryController(JrFormEntryModel model) {
return new JrFormEntryController(model, CommCareSense.formEntryExtraKey(), true, CommCareSense.formEntryQuick());
}
/**
* Gets the text associated with this entry, while dynamically evaluating
* and resolving any necessary count arguments that might need to be
* included.
*
* @param entry
* @return
*/
public static String getMenuText(Text input, Suite suite, int location) {
String text = input.evaluate();
if(Localizer.getArgs(text).size() == 0) {
return text;
}
else if(Localizer.getArgs(text).size() > 1) {
//We really don't know how to deal with this yet. Shouldn't happen!
return text;
} else {
String arg = Localization.get("commcare.menu.count.wrapper", new String[] {String.valueOf(location + 1)});
//Sweet spot! This argument should be the count of all entities
//which are possible inside of its selection.
return Localizer.processArguments(text, new String[] {arg} );
}
}
public static CommCareAlertState alertFactory (String title, String content) {
return new CommCareAlertState(title, content) {
public void done() {
J2MEDisplay.startStateWithLoadingScreen(new CommCareHomeState());
}
};
}
public static boolean demoEnabled() {
return !CommCareProperties.DEMO_DISABLED.equals(PropertyManager._().getSingularProperty(CommCareProperties.DEMO_MODE));
}
public static boolean loginImagesEnabled(){
boolean sense = CommCareSense.sense();
String loginImages = PropertyManager._().getSingularProperty(CommCareProperties.LOGIN_IMAGES);
if(!sense){
return CommCareProperties.PROPERTY_YES.equals(loginImages);
}
return (!CommCareProperties.PROPERTY_NO.equals(loginImages));
}
public static boolean partialRestoreEnabled() {
return !CommCareProperties.REST_TOL_STRICT.equals(PropertyManager._().getSingularProperty(CommCareProperties.RESTORE_TOLERANCE));
}
public static HttpCredentialProvider wrapCredentialProvider(HttpCredentialProvider credentialProvider) {
String domain = PropertyManager._().getSingularProperty(CommCareProperties.USER_DOMAIN);
if(domain == null || domain == "") {
return credentialProvider;
} else {
return new CommCareUserCredentialProvider(credentialProvider, domain);
}
}
public static void cycleDemoStyles(boolean demo) {
try{
//Below exists to make the style pop into code if it exists.
//#style demotitle?
UiAccess.setStyle(new StringItem("test","test"));
//#style normaltitle?
UiAccess.setStyle(new StringItem("test","test"));
Style title = StyleSheet.getStyle("title");
Style demotitle = StyleSheet.getStyle("demotitle");
Style normaltitle = StyleSheet.getStyle("normaltitle");
if(title == null || demotitle == null || normaltitle ==null) {
return;
}
if(demo) {
title.background = demotitle.background;
} else {
title.background = normaltitle.background;
}
} catch (Exception e) {
//Don't worry about this, this is all gravy anyway
e.printStackTrace();
}
}
public static FormInstance loadFixtureForUser(String refId, String userId) {
IStorageUtilityIndexed storage = (IStorageUtilityIndexed)StorageManager.getStorage("fixture");
FormInstance fixture = null;
Vector<Integer> relevantFixtures = storage.getIDsForValue(FormInstance.META_ID, refId);
///... Nooooot so clean.
if(relevantFixtures.size() == 1) {
//easy case, one fixture, use it
fixture = (FormInstance)storage.read(relevantFixtures.elementAt(0).intValue());
//TODO: Userid check anyway?
} else if(relevantFixtures.size() > 1){
//intersect userid and fixtureid set.
//TODO: Replace context call here with something from the session, need to stop relying on that coupling
Vector<Integer> relevantUserFixtures = storage.getIDsForValue(FormInstance.META_XMLNS, userId);
if(relevantUserFixtures.size() != 0) {
Integer userFixture = ArrayUtilities.intersectSingle(relevantFixtures, relevantUserFixtures);
if(userFixture != null) {
fixture = (FormInstance)storage.read(userFixture.intValue());
}
}
if(fixture == null) {
//Oooookay, so there aren't any fixtures for this user, see if there's a global fixture.
Integer globalFixture = ArrayUtilities.intersectSingle(storage.getIDsForValue(FormInstance.META_XMLNS, ""), relevantFixtures);
if(globalFixture == null) {
//No fixtures?! What is this. Fail somehow. This method should really have an exception contract.
return null;
}
fixture = (FormInstance)storage.read(globalFixture.intValue());
}
} else {
return null;
}
return fixture;
}
public static void printInstance(String instanceRef) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataModelSerializer s = new DataModelSerializer(bos, new CommCareInstanceInitializer(CommCareStatic.appStringCache));
s.serialize(new ExternalDataInstance(instanceRef, "instance"), null);
System.out.println(new String(bos.toByteArray()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean isMagicAdmin(User u) {
return u.isAdminUser() && u.getUsername().equals("admin");
}
} |
package com.exedio.cope;
final class ItemWithoutJavaClass extends Item
{
ItemWithoutJavaClass(final SetValue[] setValues, final Type<? extends Item> type)
{
super(setValues, type);
assert type!=null;
}
ItemWithoutJavaClass(final int pk, final Type<? extends Item> type)
{
super(pk, type);
}
// TODO make serializable and add an empty deserialization constructor
} |
// This file is part of the Ouzel engine.
package org.ouzelengine;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
public class MainActivity extends Activity implements SurfaceHolder.Callback
{
public static final String TAG = "Ouzel";
private View surfaceView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
OuzelLibJNIWrapper.setMainActivity(this);
OuzelLibJNIWrapper.setAssetManager(getAssets());
surfaceView = new View(this);
surfaceView.getHolder().addCallback(this);
setContentView(surfaceView);
}
public void openURL(String url)
{
try
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
catch (Exception e)
{
Log.e(TAG, "Failed to open URL, error " + e.getMessage());
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
OuzelLibJNIWrapper.onSurfaceChanged(holder.getSurface(), width, height);
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
OuzelLibJNIWrapper.setSurface(holder.getSurface());
OuzelLibJNIWrapper.onStart();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
OuzelLibJNIWrapper.setSurface(null);
}
@Override
protected void onStart()
{
super.onStart();
}
@Override
protected void onPause()
{
super.onPause();
OuzelLibJNIWrapper.onPause();
}
@Override
protected void onResume()
{
super.onResume();
OuzelLibJNIWrapper.onResume();
}
} |
package simpleapdu;
import applets.EC_Consts;
import applets.SimpleECCApplet;
import javacard.framework.ISO7816;
import javacard.security.CryptoException;
import javacard.security.KeyPair;
import javax.smartcardio.ResponseAPDU;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
/**
* @author Petr Svenda petr@svenda.com
*/
public class SimpleAPDU {
static CardMngr cardManager = new CardMngr();
private final static byte SELECT_ECTESTERAPPLET[] = {(byte) 0x00, (byte) 0xa4, (byte) 0x04, (byte) 0x00, (byte) 0x0a,
(byte) 0x45, (byte) 0x43, (byte) 0x54, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x72, (byte) 0x30, (byte) 0x31};
static DirtyLogger m_SystemOutLogger = null;
private static final byte TESTECSUPPORTALL_FP[] = {(byte) 0xB0, (byte) 0x5E, (byte) 0x00, (byte) 0x00, (byte) 0x00};
private static final byte TESTECSUPPORTALL_F2M[] = {(byte) 0xB0, (byte) 0x5F, (byte) 0x00, (byte) 0x00, (byte) 0x00};
private static final byte TESTECSUPPORT_GIVENALG[] = {(byte) 0xB0, (byte) 0x71, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00};
private static final short TESTECSUPPORT_ALG_OFFSET = 5;
private static final short TESTECSUPPORT_KEYLENGTH_OFFSET = 6;
private static final byte TESTECSUPPORTALL_LASTUSEDPARAMS[] = {(byte) 0xB0, (byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x00};
private static final byte TESTECSUPPORTALL_FP_KEYGEN_INVALIDCURVEB[] = {(byte) 0xB0, (byte) 0x70, (byte) 0x00, (byte) 0x00, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
private static final short INVALIDCURVEB_NUMREPEATS_OFFSET = 5;
private static final short INVALIDCURVEB_CORRUPTIONTYPE_OFFSET = 7;
private static final short INVALIDCURVEB_REWINDONSUCCESS_OFFSET = 9;
private static final byte TESTECSUPPORT_GENERATEECCKEY[] = {(byte) 0xB0, (byte) 0x5a, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00};
static short getShort(byte[] array, int offset) {
return (short) (((array[offset] & 0xFF) << 8) | (array[offset + 1] & 0xFF));
}
static void setShort(byte[] array, int offset, short value) {
array[offset + 1] = (byte) (value & 0xFF);
array[offset] = (byte) ((value >> 8) & 0xFF);
}
static void testFPkeyGen_setNumRepeats(byte[] apduArray, short numRepeats) {
setShort(apduArray, INVALIDCURVEB_NUMREPEATS_OFFSET, numRepeats);
}
static void testFPkeyGen_setCorruptionType(byte[] apduArray, short corruptionType) {
setShort(apduArray, INVALIDCURVEB_CORRUPTIONTYPE_OFFSET, corruptionType);
}
static void testFPkeyGen_rewindOnSuccess(byte[] apduArray, boolean bRewind) {
apduArray[INVALIDCURVEB_REWINDONSUCCESS_OFFSET] = bRewind ? (byte) 1 : (byte) 0;
}
static CardMngr ReconnnectToCard() throws Exception {
cardManager.DisconnectFromCard();
if (cardManager.ConnectToCard()) {
// Select our application on card
cardManager.sendAPDU(SELECT_ECTESTERAPPLET);
}
return cardManager;
}
static void testSupportECGivenAlg(byte[] apdu, CardMngr cardManager) throws Exception {
ReconnnectToCard();
ResponseAPDU resp = cardManager.sendAPDU(apdu);
PrintECSupport(resp);
}
static void testSupportECAll(CardMngr cardManager) throws Exception {
byte[] testAPDU = Arrays.copyOf(TESTECSUPPORT_GIVENALG, TESTECSUPPORT_GIVENALG.length);
testAPDU[TESTECSUPPORT_ALG_OFFSET] = KeyPair.ALG_EC_FP;
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 128);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 160);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 192);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 224);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 256);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 384);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 521);
testSupportECGivenAlg(testAPDU, cardManager);
testAPDU[TESTECSUPPORT_ALG_OFFSET] = KeyPair.ALG_EC_F2M;
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 113);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 131);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 163);
testSupportECGivenAlg(testAPDU, cardManager);
setShort(testAPDU, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 193);
testSupportECGivenAlg(testAPDU, cardManager);
}
public static void main(String[] args) throws FileNotFoundException, IOException {
boolean genKeys = false;
int genAmount = 0;
boolean testAll = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-g")) {
genKeys = true;
if (args.length >= i + 1) {
try {
genAmount = Integer.parseInt(args[i + 1]);
}catch (NumberFormatException ignored) {
//is another param, genAmount = 0 by default
genAmount = 0;
}
}
} else if (args[i].equals("-a")) {
testAll = true;
}
}
}
//by default do the test
if (!genKeys && !testAll) {
testAll = true;
}
String logFileName = String.format("ECTESTER_log_%d.log", System.currentTimeMillis());
FileOutputStream systemOutLogger = new FileOutputStream(logFileName);
m_SystemOutLogger = new DirtyLogger(systemOutLogger, true);
try {
if (testAll) {
if (cardManager.ConnectToCard()) {
byte[] testAPDU2 = Arrays.copyOf(TESTECSUPPORT_GIVENALG, TESTECSUPPORT_GIVENALG.length);
testAPDU2[TESTECSUPPORT_ALG_OFFSET] = KeyPair.ALG_EC_FP;
setShort(testAPDU2, TESTECSUPPORT_KEYLENGTH_OFFSET, (short) 384);
testSupportECGivenAlg(testAPDU2, cardManager);
testSupportECAll(cardManager);
// Test setting invalid parameter B of curve
byte[] testAPDU = Arrays.copyOf(TESTECSUPPORTALL_FP_KEYGEN_INVALIDCURVEB, TESTECSUPPORTALL_FP_KEYGEN_INVALIDCURVEB.length);
//testFPkeyGen_setCorruptionType(testAPDU, SimpleECCApplet.CORRUPT_B_LASTBYTEINCREMENT);
testFPkeyGen_setCorruptionType(testAPDU, EC_Consts.CORRUPTION_ONEBYTERANDOM);
//testFPkeyGen_setCorruptionType(testAPDU, SimpleECCApplet.CORRUPT_B_FULLRANDOM);
testFPkeyGen_setNumRepeats(testAPDU, (short) 10);
testFPkeyGen_rewindOnSuccess(testAPDU, true);
ReconnnectToCard();
ResponseAPDU resp_fp_keygen = cardManager.sendAPDU(testAPDU);
ResponseAPDU resp_keygen_params = cardManager.sendAPDU(TESTECSUPPORTALL_LASTUSEDPARAMS);
PrintECKeyGenInvalidCurveB(resp_fp_keygen);
PrintECKeyGenInvalidCurveB_lastUserParams(resp_keygen_params);
/*
// Test support for different types of curves
ReconnnectToCard();
ResponseAPDU resp_fp = cardManager.sendAPDU(TESTECSUPPORTALL_FP);
ReconnnectToCard();
ResponseAPDU resp_f2m = cardManager.sendAPDU(TESTECSUPPORTALL_F2M);
PrintECSupport(resp_fp);
PrintECSupport(resp_f2m);
*/
cardManager.DisconnectFromCard();
} else {
m_SystemOutLogger.println("Failed to connect to card");
}
}
if (genKeys) {
// Gather large number of ECC keypairs
if (cardManager.ConnectToCardSelect()) {
cardManager.sendAPDU(SELECT_ECTESTERAPPLET);
String keyFileName = String.format("ECKEYS_%d.log", System.currentTimeMillis());
FileOutputStream keysFile = new FileOutputStream(keyFileName);
String message = "index;time;pubW;privS\n";
keysFile.write(message.getBytes());
byte[] gatherKeyAPDU = Arrays.copyOf(TESTECSUPPORT_GENERATEECCKEY, TESTECSUPPORT_GENERATEECCKEY.length);
// Prepare keypair object
gatherKeyAPDU[ISO7816.OFFSET_P1] = SimpleECCApplet.P1_SETCURVE;
setShort(gatherKeyAPDU, (short) 5, (short) 192); // ecc length
ResponseAPDU respGather = cardManager.sendAPDU(gatherKeyAPDU);
// Generate new keypair
gatherKeyAPDU[ISO7816.OFFSET_P1] = SimpleECCApplet.P1_GENERATEKEYPAIR;
int counter = 0;
while (true) {
counter++;
long elapsed = -System.nanoTime();
respGather = cardManager.sendAPDU(gatherKeyAPDU);
elapsed += System.nanoTime();
byte[] data = respGather.getData();
int offset = 0;
String pubKeyW = "";
String privKeyS = "";
if (data[offset] == EC_Consts.TAG_ECPUBKEY) {
offset++;
short len = getShort(data, offset);
offset += 2;
pubKeyW = CardMngr.bytesToHex(data, offset, len, false);
offset += len;
}
if (data[offset] == EC_Consts.TAG_ECPRIVKEY) {
offset++;
short len = getShort(data, offset);
offset += 2;
privKeyS = CardMngr.bytesToHex(data, offset, len, false);
offset += len;
}
message = String.format("%d;%d;%s;%s\n", counter, elapsed / 1000000, pubKeyW, privKeyS);
keysFile.write(message.getBytes());
m_SystemOutLogger.flush();
keysFile.flush();
//stop when we have enough keys, go on forever with 0
if (counter >= genAmount && genAmount != 0)
break;
}
}
}
} catch (Exception ex) {
m_SystemOutLogger.println("Exception : " + ex);
}
systemOutLogger.close();
}
static String getPrintError(short code) {
if (code == ISO7816.SW_NO_ERROR) {
return "OK\t(0x9000)";
} else {
String codeStr = "unknown";
if (code == CryptoException.ILLEGAL_VALUE) {
codeStr = "ILLEGAL_VALUE";
}
if (code == CryptoException.UNINITIALIZED_KEY) {
codeStr = "UNINITIALIZED_KEY";
}
if (code == CryptoException.NO_SUCH_ALGORITHM) {
codeStr = "NO_SUCH_ALG";
}
if (code == CryptoException.INVALID_INIT) {
codeStr = "INVALID_INIT";
}
if (code == CryptoException.ILLEGAL_USE) {
codeStr = "ILLEGAL_USE";
}
if (code == SimpleECCApplet.SW_SKIPPED) {
codeStr = "skipped";
}
if (code == SimpleECCApplet.SW_KEYPAIR_GENERATED_INVALID) {
codeStr = "SW_KEYPAIR_GENERATED_INVALID";
}
if (code == SimpleECCApplet.SW_INVALID_CORRUPTION_TYPE) {
codeStr = "SW_INVALID_CORRUPTION_TYPE";
}
if (code == SimpleECCApplet.SW_SIG_LENGTH_MISMATCH) {
codeStr = "SW_SIG_LENGTH_MISMATCH";
}
if (code == SimpleECCApplet.SW_SIG_VERIFY_FAIL) {
codeStr = "SW_SIG_VERIFY_FAIL";
}
return String.format("fail\t(%s,\t0x%4x)", codeStr, code);
}
}
enum ExpResult {
SHOULD_SUCCEDD,
MAY_FAIL,
MUST_FAIL
}
static int VerifyPrintResult(String message, byte expectedTag, byte[] buffer, int bufferOffset, ExpResult expRes) {
if (bufferOffset >= buffer.length) {
m_SystemOutLogger.println(" No more data returned");
} else {
if (buffer[bufferOffset] != expectedTag) {
m_SystemOutLogger.println(" ERROR: mismatched tag");
assert (buffer[bufferOffset] == expectedTag);
}
bufferOffset++;
short resCode = getShort(buffer, bufferOffset);
bufferOffset += 2;
boolean bHiglight = false;
if ((expRes == ExpResult.MUST_FAIL) && (resCode == ISO7816.SW_NO_ERROR)) {
bHiglight = true;
}
if ((expRes == ExpResult.SHOULD_SUCCEDD) && (resCode != ISO7816.SW_NO_ERROR)) {
bHiglight = true;
}
if (bHiglight) {
m_SystemOutLogger.println(String.format("!! %-50s%s", message, getPrintError(resCode)));
} else {
m_SystemOutLogger.println(String.format(" %-50s%s", message, getPrintError(resCode)));
}
}
return bufferOffset;
}
static void PrintECSupport(ResponseAPDU resp) {
byte[] buffer = resp.getData();
m_SystemOutLogger.println();
m_SystemOutLogger.println("### Test for support and with valid and invalid EC curves");
int bufferOffset = 0;
while (bufferOffset < buffer.length) {
assert (buffer[bufferOffset] == SimpleECCApplet.ECTEST_SEPARATOR);
bufferOffset++;
String ecType = "unknown";
if (buffer[bufferOffset] == KeyPair.ALG_EC_FP) {
ecType = "ALG_EC_FP";
}
if (buffer[bufferOffset] == KeyPair.ALG_EC_F2M) {
ecType = "ALG_EC_F2M";
}
m_SystemOutLogger.println(String.format("%-53s%s", "EC type:", ecType));
bufferOffset++;
short keyLen = getShort(buffer, bufferOffset);
m_SystemOutLogger.println(String.format("%-53s%d bits", "EC key length (bits):", keyLen));
bufferOffset += 2;
bufferOffset = VerifyPrintResult("KeyPair object allocation:", SimpleECCApplet.ECTEST_ALLOCATE_KEYPAIR, buffer, bufferOffset, ExpResult.SHOULD_SUCCEDD);
bufferOffset = VerifyPrintResult("Generate key with def curve (fails if no def):", SimpleECCApplet.ECTEST_GENERATE_KEYPAIR_DEFCURVE, buffer, bufferOffset, ExpResult.MAY_FAIL);
bufferOffset = VerifyPrintResult("Set valid custom curve:", SimpleECCApplet.ECTEST_SET_VALIDCURVE, buffer, bufferOffset, ExpResult.SHOULD_SUCCEDD);
bufferOffset = VerifyPrintResult("Generate key with valid curve:", SimpleECCApplet.ECTEST_GENERATE_KEYPAIR_CUSTOMCURVE, buffer, bufferOffset, ExpResult.SHOULD_SUCCEDD);
bufferOffset = VerifyPrintResult("ECDH agreement with valid point:", SimpleECCApplet.ECTEST_ECDH_AGREEMENT_VALID_POINT, buffer, bufferOffset, ExpResult.SHOULD_SUCCEDD);
bufferOffset = VerifyPrintResult("ECDH agreement with invalid point (fail is good):", SimpleECCApplet.ECTEST_ECDH_AGREEMENT_INVALID_POINT, buffer, bufferOffset, ExpResult.MUST_FAIL);
bufferOffset = VerifyPrintResult("Set invalid custom curve (may fail):", SimpleECCApplet.ECTEST_SET_INVALIDCURVE, buffer, bufferOffset, ExpResult.MAY_FAIL);
bufferOffset = VerifyPrintResult("Generate key with invalid curve (fail is good):", SimpleECCApplet.ECTEST_GENERATE_KEYPAIR_INVALIDCUSTOMCURVE, buffer, bufferOffset, ExpResult.MUST_FAIL);
m_SystemOutLogger.println();
}
}
static void PrintECKeyGenInvalidCurveB(ResponseAPDU resp) {
byte[] buffer = resp.getData();
m_SystemOutLogger.println();
m_SystemOutLogger.println("### Test for computation with invalid parameter B for EC curve");
int bufferOffset = 0;
while (bufferOffset < buffer.length) {
assert (buffer[bufferOffset] == SimpleECCApplet.ECTEST_SEPARATOR);
bufferOffset++;
String ecType = "unknown";
if (buffer[bufferOffset] == KeyPair.ALG_EC_FP) {
ecType = "ALG_EC_FP";
}
if (buffer[bufferOffset] == KeyPair.ALG_EC_F2M) {
ecType = "ALG_EC_F2M";
}
m_SystemOutLogger.println(String.format("%-53s%s", "EC type:", ecType));
bufferOffset++;
short keyLen = getShort(buffer, bufferOffset);
m_SystemOutLogger.println(String.format("%-53s%d bits", "EC key length (bits):", keyLen));
bufferOffset += 2;
short numRepeats = getShort(buffer, bufferOffset);
bufferOffset += 2;
m_SystemOutLogger.println(String.format("%-53s%d times", "Executed repeats before unexpected error: ", numRepeats));
bufferOffset = VerifyPrintResult("KeyPair object allocation:", SimpleECCApplet.ECTEST_ALLOCATE_KEYPAIR, buffer, bufferOffset, ExpResult.SHOULD_SUCCEDD);
while (bufferOffset < buffer.length) {
bufferOffset = VerifyPrintResult("Set invalid custom curve:", SimpleECCApplet.ECTEST_SET_INVALIDCURVE, buffer, bufferOffset, ExpResult.SHOULD_SUCCEDD);
bufferOffset = VerifyPrintResult("Generate key with invalid curve (fail is good):", SimpleECCApplet.ECTEST_GENERATE_KEYPAIR_INVALIDCUSTOMCURVE, buffer, bufferOffset, ExpResult.MUST_FAIL);
if (buffer[bufferOffset] == SimpleECCApplet.ECTEST_DH_GENERATESECRET) {
bufferOffset = VerifyPrintResult("ECDH agreement with invalid point (fail is good):", SimpleECCApplet.ECTEST_DH_GENERATESECRET, buffer, bufferOffset, ExpResult.MUST_FAIL);
}
bufferOffset = VerifyPrintResult("Set valid custom curve:", SimpleECCApplet.ECTEST_SET_VALIDCURVE, buffer, bufferOffset, ExpResult.SHOULD_SUCCEDD);
bufferOffset = VerifyPrintResult("Generate key with valid curve:", SimpleECCApplet.ECTEST_GENERATE_KEYPAIR_CUSTOMCURVE, buffer, bufferOffset, ExpResult.SHOULD_SUCCEDD);
}
m_SystemOutLogger.println();
}
}
static void PrintECKeyGenInvalidCurveB_lastUserParams(ResponseAPDU resp) {
byte[] buffer = resp.getData();
short offset = 0;
m_SystemOutLogger.print("Last used value of B: ");
while (offset < buffer.length) {
m_SystemOutLogger.print(String.format("%x ", buffer[offset]));
offset++;
}
}
} |
package sockets;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class SocketManager {
public final SocketWriteThread writeThread;
private final Socket socket;
protected final PacketRegistrator packetRegistrator;
private final Object packetListener;
private final Method[] packetListenerMethods;
public SocketManager(Object packetListener, PacketRegistrator packetRegistrator, Socket socket) throws IOException {
this.packetListener = packetListener;
List<Method> methods = new ArrayList<>();
for (Method m : this.packetListener.getClass().getMethods()) {
if (m.isAnnotationPresent(PacketReadHandler.class)) {
Class<?>[] params = m.getParameterTypes();
if (params.length == 1) {
methods.add(m);
}
}
}
this.packetListenerMethods = methods.toArray(new Method[methods.size()]);
methods.clear();
this.socket = socket;
this.packetRegistrator = packetRegistrator;
new SocketReadThread(this, new DataInputStream(socket.getInputStream()));
this.writeThread = new SocketWriteThread(this, new DataOutputStream(socket.getOutputStream()));
}
public boolean isConnected() {
return this.socket.isConnected();
}
public void onReceivePacket(Packet packet) {
for (Method m : this.packetListenerMethods) {
if (m.getParameterTypes()[0].isInstance(packet)) {
try {
m.invoke(packetListener, packet);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
public void disconnect() {
try {
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
package soot;
import soot.jimple.*;
/**
* UnitPrinter implementation for normal (full) Jimple, Grimp, and Baf
*/
public class BriefUnitPrinter extends LabeledUnitPrinter {
public BriefUnitPrinter( Body body ) {
super(body);
}
private boolean baf;
public void startUnit( Unit u ) {
super.startUnit(u);
if( u instanceof Stmt ) {
baf = false;
} else {
baf = true;
}
}
public void methodRef( SootMethodRef m ) {
handleIndent();
if( !baf && m.resolve().isStatic() ){
output.append( m.declaringClass().getName() );
literal(".");
}
output.append( m.name() );
}
public void fieldRef( SootFieldRef f ) {
handleIndent();
if( baf || f.resolve().isStatic() ){
output.append( f.declaringClass().getName() );
literal(".");
}
output.append(f.name());
}
public void identityRef( IdentityRef r ) {
handleIndent();
if( r instanceof ThisRef ) {
literal("@this");
} else if( r instanceof ParameterRef ) {
ParameterRef pr = (ParameterRef) r;
literal("@parameter"+pr.getIndex());
} else if( r instanceof CaughtExceptionRef ) {
literal("@caughtexception");
} else throw new RuntimeException();
}
private boolean eatSpace = false;
public void literal( String s ) {
handleIndent();
if( eatSpace && s.equals(" ") ) {
eatSpace = false;
return;
}
eatSpace = false;
if( !baf ) {
if( false
|| s.equals( Jimple.STATICINVOKE )
|| s.equals( Jimple.VIRTUALINVOKE )
|| s.equals( Jimple.INTERFACEINVOKE )
) {
eatSpace = true;
return;
}
}
output.append(s);
}
public void type( Type t ) {
handleIndent();
output.append( t.toString() );
}
} |
package src.controller;
import java.util.ArrayList;
import src.model.MapEntity_Relation;
/**
*
* @author JohnReedLOL
*/
abstract public class Entity extends DrawableThing {
// Converts an entity's name [which must be unique] into a unique base 35 number
private static final long serialVersionUID = Long.parseLong("Entity", 35);
// map_relationship_ is used in place of a map_referance_
private final MapEntity_Relation map_relationship_;
/**
* Use this to call functions contained within the MapEntity relationship
* @return map_relationship_
* @author Reed, John
*/
@Override
public MapEntity_Relation getMapRelation() {
return map_relationship_;
}
public Entity(String name, char representation,
int x_respawn_point, int y_respawn_point) {
super(name, representation);
map_relationship_ = new MapEntity_Relation( this, x_respawn_point, y_respawn_point );
inventory_ = new ArrayList<Item>();
}
private Occupation occupation_ = null;
ArrayList<Item> inventory_;
// Only 1 equipped item in iteration 1
Item equipped_item_;
//private final int max_level_;
private StatsPack my_stats_after_powerups_;
/**
* Adds default stats to item stats and updates my_stats_after_powerups
* @author Jessan
*/
private void recalculateStats() {
//my_stats_after_powerups_.equals(my_stats_after_powerups_.add(equipped_item_.get_stats_pack_()));
my_stats_after_powerups_ = get_default_stats_pack_().add(equipped_item_.get_default_stats_pack_());
}
/**
* this function levels up an entity
* @author Jessan
*/
public void levelUp() {
if(occupation_ == null){
//levelup normally
StatsPack new_stats = new StatsPack(0,1,1,1,1,1,1,1,1);
set_default_stats_pack(get_default_stats_pack_().add(new_stats));
}
//if occupation is not null/have an occupation
else {
set_default_stats_pack(occupation_.change_stats(get_default_stats_pack_()));
}
}
public void setOccupation(Occupation occupation) {
occupation_ = occupation;
}
public Occupation getOccupation(){
return occupation_;
}
public void addItemToInventory(Item item) {
inventory_.add(item);
}
} |
package cs201.gui.transit;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.Stack;
import javax.swing.JOptionPane;
import cs201.gui.ArtManager;
import cs201.gui.CityPanel;
import cs201.helper.Constants;
import cs201.helper.transit.MovementDirection;
import cs201.helper.transit.Pathfinder;
import cs201.gui.Gui;
import cs201.roles.transit.PassengerRole;
import cs201.structures.Structure;
import cs201.trace.AlertLog;
import cs201.trace.AlertTag;
/**
*
* @author Brandon
*
*/
public class PassengerGui implements Gui
{
private PassengerRole pass;
private Structure destination;
private int destX,destY;
private int x, y;
private boolean fired;
private boolean present;
private CityPanel city;
private MovementDirection currentDirection;
private Stack<MovementDirection> moves;
private boolean pathfinding = false;
/**
* Creates a passenger gui
* @param pass the passenger who holds the gui
* @param city the city which contains the gui
*/
public PassengerGui(PassengerRole pass,CityPanel city)
{
this(pass,city,pass.getCurrentLocation());
}
/**
* Creates a passenger gui
* @param pass the passenger who holds the gui
* @param city the city which contains the gui
* @param x the initial x
* @param y the initial y
*/
public PassengerGui(PassengerRole pass,CityPanel city, int x, int y)
{
this.pass = pass;
this.city = city;
this.x = x;
this.y = y;
destX = x;
destY = y;
fired = true;
present = false;
currentDirection = MovementDirection.None;
moves = new Stack<MovementDirection>();
}
/**
* Creates a passenger gui
* @param pass the passenger who holds the gui
* @param city the city which contains the gui
* @param s the structure to start at
*/
public PassengerGui(PassengerRole pass,CityPanel city, Structure s)
{
this(pass, city, (int) s.getRect().x, (int) s.getRect().y);
}
/**
* Sets whether the gui is present in the scene and should be rendered
* @param present whether it is present
*/
public void setPresent(boolean present)
{
this.present = present;
}
/**
* Signals the GUI to go to a location
* @param structure the structure to go to
*/
public void doGoToLocation(Structure structure)
{
//JOptionPane.showMessageDialog(null,""+pass.getName()+": Being told to go to "+structure.getEntranceLocation().x/CityPanel.GRID_SIZE+" "+structure.getEntranceLocation().y/CityPanel.GRID_SIZE);
destination = structure;
destX = (int)structure.getEntranceLocation().x;
destY = (int)structure.getEntranceLocation().y;
fired = false;
present = true;
findPath();
}
public void doGoToLocation(int x, int y)
{
destX = x;
destY = y;
fired = false;
present = true;
findPath();
}
public void doRoam()
{
Point p = Pathfinder.findRandomWalkingLocation(city.getWalkingMap());
doGoToLocation(p.x*CityPanel.GRID_SIZE,p.y*CityPanel.GRID_SIZE);
}
/*
* Performs BFS to find best path
*/
private void findPath()
{
System.out.println("FINDING PATH");
pathfinding = true;
try
{
moves = Pathfinder.calcTwoWayMove(city.getWalkingMap(), x, y, destX, destY);
}
catch(IllegalArgumentException e)
{
AlertLog.getInstance().logError(AlertTag.TRANSIT, pass.getName(), ""+e.getMessage());
}
pathfinding = false;
}
/**
* Draws the GUI in the given graphcis object
* @param g the graphics object in which to draw
*/
public void draw(Graphics2D g)
{
if (Constants.DEBUG_MODE)
{
g.setColor(Color.RED);
g.fillRect(x,y,CityPanel.GRID_SIZE,CityPanel.GRID_SIZE);
g.setColor(Color.BLACK);
g.drawString(""+destination, x,y);
g.drawString(""+pass.getName(), x,y+CityPanel.GRID_SIZE);
}
else
{
String moveDir = "Person_";
switch(currentDirection)
{
case Right:moveDir+="Right";
break;
case None:moveDir+="Down";
break;
case Up:moveDir+="Up";
break;
case Down:moveDir+="Down";
break;
case Turn:moveDir+="Down";
break;
case Left:moveDir+="Left";
break;
default:moveDir+="Down";
break;
}
g.drawImage (ArtManager.getImage(moveDir),x,y,CityPanel.GRID_SIZE,CityPanel.GRID_SIZE,null);
}
}
/**
* To be extended in subclass
* @param g graphics object to render in
*/
@Override
public void updatePosition()
{
if(!fired && !pathfinding)
{
if(x == destX && y == destY)
{
fired = true;
pass.msgAnimationFinished ();
currentDirection = MovementDirection.None;
return;
}
switch(currentDirection)
{
case Right:
x++;
break;
case Up:
y
break;
case Down:
y++;
break;
case Left:
x
break;
default:
break;
}
if(x % CityPanel.GRID_SIZE == 0 && y % CityPanel.GRID_SIZE == 0 && !moves.isEmpty())
{
currentDirection = moves.pop();
return;
}
}
}
/**
* Gets whether the gui is present and should be rendered
*/
@Override
public boolean isPresent()
{
return present;
}
/**
* Sets the location of the gui
* @param x the new x
* @param y the new y
*/
public void setLocation(int x, int y)
{
System.out.println("Setting location: "+this.pass.getName()+" "+x+" "+y);
this.x = x;
this.y = y;
}
public boolean locationEquals(Structure currentLocation)
{
return currentLocation.getEntranceLocation().x == x && currentLocation.getEntranceLocation().y == y;
}
public void setLocation()
{
Point p = Pathfinder.findRandomWalkingLocation(city.getWalkingMap());
setLocation(p.x*CityPanel.GRID_SIZE,p.y*CityPanel.GRID_SIZE);
setPresent(true);
}
} |
package dataAccessLayer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import businessLogicLayer.Log;
import constants.DalEnum;
import constants.Severity;
import serviceLayer.CtrlLog;
public class DataBaseAccess {
public static Connection getConnection( ) {
CtrlLog ctrlLog = CtrlLog.getInstance( );
Connection cnx = null;
try{
Class.forName("YOUR SQL DRIVER CLASS NAME");
Log driverOk = new Log(Severity.Information, new Date( ), "Driver O.K.");
ctrlLog.writeLog(driverOk, DalEnum.TextFile);
String url = "jdbc:DATABASE://DATABASE_ADDRESS";
String user = "USERNAME";
String passwd = "PASSWORD";
cnx = DriverManager.getConnection(url, user, passwd);
}catch(SQLException e){
Log log = new Log(e, Severity.Critical, new Date( ), "Could not connect to database!");
ctrlLog.writeLog(log, DalEnum.TextFile);
}catch(Exception e){
Log log = new Log(e, Severity.Critical, new Date( ),
"An exception occured while trying to connect to the database!");
ctrlLog.writeLog(log, DalEnum.TextFile);
}
return cnx;
}
} |
package de.lmu.ifi.dbs.algorithm;
import de.lmu.ifi.dbs.data.DoubleVector;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.LocallyWeightedDistanceFunction;
import de.lmu.ifi.dbs.pca.CorrelationPCA;
import de.lmu.ifi.dbs.preprocessing.CorrelationDimensionPreprocessor;
import de.lmu.ifi.dbs.utilities.Description;
import de.lmu.ifi.dbs.utilities.Progress;
import de.lmu.ifi.dbs.utilities.QueryResult;
import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings;
import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.utilities.optionhandling.UnusedParameterException;
import java.util.ArrayList;
import java.util.List;
/**
* Provides the 4C algorithm.
*
* @author Arthur Zimek (<a
* href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>)
*/
public class FourC extends DBSCAN<DoubleVector>
{
/**
* Parameter lambda.
*/
public static final String LAMBDA_P = "lambda";
/**
* Description for parameter lambda.
*/
public static final String LAMBDA_D = "<lambda>(integer) intrinsinc dimensionality of clusters to be found.";
/**
* Keeps lambda.
*/
private int lambda;
/**
* Provides the 4C algorithm.
*
*/
public FourC()
{
super();
parameterToDescription.put(LAMBDA_P + OptionHandler.EXPECTS_VALUE, LAMBDA_D);
optionHandler = new OptionHandler(parameterToDescription, FourC.class.getName());
}
/**
* Replaces the expandCluster function of DBSCAN by the respective 4C method.
*
* @see DBSCAN<DoubleVector>#expandCluster(Database, Integer, Progress)
*/
@Override
protected void expandCluster(Database<DoubleVector> database, Integer startObjectID, Progress progress)
{
List<QueryResult> neighborhoodIDs = database.rangeQuery(startObjectID, epsilon, getDistanceFunction());
if(neighborhoodIDs.size() < minpts)
{
noise.add(startObjectID);
processedIDs.add(startObjectID);
if(isVerbose())
{
progress.setProcessed(processedIDs.size());
System.out.print(status(progress, resultList.size()));
}
}
else
{
List<Integer> currentCluster = new ArrayList<Integer>();
if(((CorrelationPCA) database.getAssociation(CorrelationDimensionPreprocessor.ASSOCIATION_ID_PCA, startObjectID)).getCorrelationDimension() > lambda)
{
noise.add(startObjectID);
processedIDs.add(startObjectID);
if(isVerbose())
{
progress.setProcessed(processedIDs.size());
System.out.print(status(progress, resultList.size()));
}
}
else
{
List<QueryResult> seeds = database.rangeQuery(startObjectID, epsilon, getDistanceFunction());
if(seeds.size() < minpts)
{
noise.add(startObjectID);
processedIDs.add(startObjectID);
if(isVerbose())
{
progress.setProcessed(processedIDs.size());
System.out.print(status(progress, resultList.size()));
}
}
else
{
for(QueryResult nextSeed : seeds)
{
Integer nextID = nextSeed.getID();
if(!processedIDs.contains(nextID))
{
currentCluster.add(nextID);
processedIDs.add(nextID);
}
else if(noise.contains(nextID))
{
currentCluster.add(nextID);
noise.remove(nextID);
}
if(isVerbose())
{
progress.setProcessed(processedIDs.size());
System.out.print(status(progress, resultList.size()));
}
}
seeds.remove(startObjectID);
processedIDs.add(startObjectID);
if(isVerbose())
{
progress.setProcessed(processedIDs.size());
System.out.print(status(progress, resultList.size()));
}
while(seeds.size() > 0)
{
Integer seedID = seeds.remove(0).getID();
List<QueryResult> seedNeighborhoodIDs = database.rangeQuery(seedID, epsilon, getDistanceFunction());
if(seedNeighborhoodIDs.size() >= minpts)
{
if(((CorrelationPCA) database.getAssociation(CorrelationDimensionPreprocessor.ASSOCIATION_ID_PCA, seedID)).getCorrelationDimension() <= lambda)
{
List<QueryResult> reachables = database.rangeQuery(seedID, epsilon, getDistanceFunction());
if(reachables.size() >= minpts)
{
for(int i = 0; i < reachables.size(); i++)
{
QueryResult reachable = reachables.get(i);
boolean inNoise = noise.contains(reachable.getID());
boolean unclassified = !processedIDs.contains(reachable.getID());
if(inNoise || unclassified)
{
if(unclassified)
{
seeds.add(reachable);
}
currentCluster.add(reachable.getID());
processedIDs.add(reachable.getID());
if(inNoise)
{
noise.remove(reachable.getID());
}
if(isVerbose())
{
progress.setProcessed(processedIDs.size());
System.out.print(status(progress, resultList.size()));
}
}
}
}
}
}
}
if(currentCluster.size() >= minpts)
{
resultList.add(currentCluster);
}
else
{
for(Integer id : currentCluster)
{
noise.add(id);
}
noise.add(startObjectID);
processedIDs.add(startObjectID);
}
if(isVerbose())
{
progress.setProcessed(processedIDs.size());
System.out.print(status(progress, resultList.size()));
}
}
}
}
}
/**
*
*
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(java.lang.String[])
*/
@Override
public String[] setParameters(String[] args) throws IllegalArgumentException
{
String[] remainingParameters = super.setParameters(args);
try
{
lambda = Integer.parseInt(optionHandler.getOptionValue(LAMBDA_P));
if(lambda <= 0)
{
throw new IllegalArgumentException("parameter "+LAMBDA_P+" is supposed to be a positive integer - found: "+lambda);
}
}
catch(NumberFormatException e)
{
throw new IllegalArgumentException("parameter "+LAMBDA_P+" is supposed to be a positive integer - found: "+optionHandler.getOptionValue(LAMBDA_P));
}
catch(UnusedParameterException e)
{
throw new IllegalArgumentException("parameter "+LAMBDA_P+" is required");
}
if(!(LocallyWeightedDistanceFunction.class.isAssignableFrom(getDistanceFunction().getClass())))
{
throw new IllegalArgumentException("illegal distance function - must be or extend "+LocallyWeightedDistanceFunction.class.getName());
}
return remainingParameters;
}
/**
*
*
* @see de.lmu.ifi.dbs.algorithm.Algorithm#getAttributeSettings()
*/
@Override
public List<AttributeSettings> getAttributeSettings()
{
List<AttributeSettings> result = new ArrayList<AttributeSettings>();
AttributeSettings attributeSettings = new AttributeSettings(this);
attributeSettings.addSetting(LAMBDA_P, Integer.toString(lambda));
result.add(attributeSettings);
result.addAll(super.getAttributeSettings());
return result;
}
/**
*
* @see de.lmu.ifi.dbs.algorithm.Algorithm#getDescription()
*/
public Description getDescription()
{
return new Description("4C", "Computing Correlation Connected Clusters", "4C identifies local subgroups of data objects sharing a uniform correlation. The algorithm is based on a combination of PCA and density-based clustering (DBSCAN).", "Christian Bhm, Karin Kailing, Peer Krger, Arthur Zimek: Computing Clusters of Correlation Connected Objects, Proc. ACM SIGMOD Int. Conf. on Management of Data, Paris, France, 2004, 455-466");
}
} |
package de.otori.engine;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public abstract class FraktalProgram implements Renderable, KeyListener, MouseListener, MouseMotionListener {
/**
* Indicates zoom level
*/
protected double zoom;
protected Point2F center;
protected int winWidth;
protected int winHeight;
private enum ProgramState {IDLE, ZOOMING, SHIFTING};
private ProgramState state = ProgramState.IDLE; // For sample zooming implementation
public void setWindowSize(int width, int height)
{
winWidth = width;
winHeight = height;
}
@Override
public void preRendering() {
updatePositions();
//System.out.println(String.format("Debug: Center: (%f,%f) zoom: %f", center.x, center.y, zoom));
}
@Override
public void postRendering() {
//Nothing yet...
//Feel free to overide HEHE
}
public void setZoom(double z)
{
zoom = z;
}
public void setCenter(Point2F p)
{
center = new Point2F(p);
}
private long lastClick = 0, lastClickRight = 0;
final static long DOUBLECLICKMAXDIFF = 350;
private Point2F zCenterSrc, zCenterDest;
private double zoomStart;
private double zoomDest;
private long zoomTimeStart;
final long ZOOM_DURATION = 400;
final double ZOOM_FACTOR = 2.; // to da squareee !! :D
/**
* Internal function used for zoom animation.
* @param x
* @param y
* @param zoomIn indicates, whether to zoom in or out.
*/
private void initZoom(int x, int y, boolean zoomIn)
{
if(state != ProgramState.IDLE)
return;
System.out.println(String.format("Debug: Center: (%f,%f) zoom: %f", center.x, center.y, zoom));
System.out.println(String.format("Window size: (%d,%d)", winWidth, winHeight));
System.out.println("Clicked on (" + x + "," + y + ")");
state = ProgramState.ZOOMING;
zCenterSrc = new Point2F(center);
zCenterDest = Misc.calculatePixelRealCoordinates(x, y, winWidth, winHeight, zoom, center);
System.out.println(String.format("Center Dest: (%f,%f)", zCenterDest.x, zCenterDest.y));
zoomStart = zoom;
if(zoomIn)
zoomDest = zoom * ZOOM_FACTOR * ZOOM_FACTOR;
else
zoomDest = zoom / ZOOM_FACTOR / ZOOM_FACTOR;
zoomTimeStart = System.currentTimeMillis();
}
private void updatePositions()
{
switch (state) {
case ZOOMING:
long ticksNow = System.currentTimeMillis() - zoomTimeStart;
if(ticksNow >= ZOOM_DURATION)
{
ticksNow = ZOOM_DURATION;
state = ProgramState.IDLE;
}
double zProgres = ticksNow / (double)ZOOM_DURATION;
zoom = zoomStart + (zoomDest - zoomStart) * zProgres;
center.y = zCenterSrc.y + (zCenterDest.y - zCenterSrc.y) * zProgres;
center.x = zCenterSrc.x + (zCenterDest.x - zCenterSrc.x) * zProgres;
break;
default:
break;
}
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
switch (e.getButton())
{
case MouseEvent.BUTTON1:
if(System.currentTimeMillis() - lastClick < DOUBLECLICKMAXDIFF)
{
initZoom(e.getPoint().x, e.getPoint().y, true);
}
else
{
lastClick = System.currentTimeMillis();
}
break;
case MouseEvent.BUTTON3:
if(System.currentTimeMillis() - lastClickRight < DOUBLECLICKMAXDIFF)
{
initZoom(e.getPoint().x, e.getPoint().y, false);
}
else
{
lastClickRight = System.currentTimeMillis();
}
break;
}
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
private Point2F centerPressed = null, centerStart = null;
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
centerPressed = Misc.calculatePixelRealCoordinates(e.getPoint().x, e.getPoint().y, winWidth, winHeight, zoom, center);
centerStart = new Point2F(center);
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
centerPressed = null;
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
if(centerPressed != null && state == ProgramState.IDLE)
{
Point2F curPos = Misc.calculatePixelRealCoordinates(e.getPoint().x, e.getPoint().y, winWidth, winHeight, zoom, center);
double deltaReal = (curPos.x - centerPressed.x) / 1.25;
double deltaImag = (curPos.y - centerPressed.y) / 1.25;
center.x = centerStart.x - deltaReal;
center.y = centerStart.y - deltaImag;
}
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
} |
package pokerth_test;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.Test;
import pokerth_protocol.*;
import pokerth_protocol.NetGameInfo.EndRaiseModeEnumType;
import pokerth_protocol.NetGameInfo.NetGameTypeEnumType;
import org.junit.Before;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import pokerth_protocol.MyActionRequestMessage.MyActionRequestMessageSequenceType;
import pokerth_protocol.StartEventAckMessage.StartEventAckMessageSequenceType;
public class RunRankingGameTest extends TestBase {
Connection dbConn;
@Before
public void dbInit() throws Exception {
String configFileName = System.getProperty("user.home") + "/.pokerth/config.xml";
File file = new File(configFileName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
Element configNode = (Element)doc.getElementsByTagName("Configuration").item(0);
Element dbAddressNode = (Element)configNode.getElementsByTagName("DBServerAddress").item(0);
String dbAddress = dbAddressNode.getAttribute("value");
Element dbUserNode = (Element)configNode.getElementsByTagName("DBServerUser").item(0);
String dbUser = dbUserNode.getAttribute("value");
Element dbPasswordNode = (Element)configNode.getElementsByTagName("DBServerPassword").item(0);
String dbPassword = dbPasswordNode.getAttribute("value");
Element dbNameNode = (Element)configNode.getElementsByTagName("DBServerDatabaseName").item(0);
String dbName = dbNameNode.getAttribute("value");
final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName;
Class.forName("com.mysql.jdbc.Driver").newInstance ();
dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
}
@Test
public void testRunRankingGame() throws Exception {
Statement dbStatement = dbConn.createStatement();
ResultSet countBeforeResult = dbStatement.executeQuery("SELECT COUNT(idgame) FROM game");
countBeforeResult.first();
long countBefore = countBeforeResult.getLong(1);
long firstPlayerId = userInit();
Collection<Integer> l = new ArrayList<Integer>();
String gameName = AuthUser + " run ranking game";
NetGameInfo gameInfo = createGameInfo(5, EndRaiseModeEnumType.EnumType.doubleBlinds, 0, 50, gameName, l, 10, 0, 11, 10000);
sendMessage(createGameRequestMsg(
gameInfo,
NetGameTypeEnumType.EnumType.rankingGame,
5,
7,
""));
PokerTHMessage msg;
// Game list update (new game)
msg = receiveMessage();
if (!msg.isGameListMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
// Join game ack.
msg = receiveMessage();
if (msg.isJoinGameReplyMessageSelected()) {
if (!msg.getJoinGameReplyMessage().getValue().getJoinGameResult().isJoinGameAckSelected()) {
fail("Could not create game!");
}
}
else {
failOnErrorMessage(msg);
fail("Invalid message.");
}
long gameId = msg.getJoinGameReplyMessage().getValue().getGameId().getValue();
// Game list update (player joined).
msg = receiveMessage();
if (!msg.isGameListMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
// Let 9 additional clients join.
Socket s[] = new Socket[9];
long playerId[] = new long[9];
for (int i = 0; i < 9; i++) {
s[i] = new Socket("::1", 7234);
String username = "test" + (i+1);
String password = username;
playerId[i] = userInit(s[i], username, password);
sendMessage(joinGameRequestMsg(gameId, ""), s[i]);
do {
msg = receiveMessage(s[i]);
failOnErrorMessage(msg);
} while (!msg.isJoinGameReplyMessageSelected());
if (!msg.getJoinGameReplyMessage().getValue().getJoinGameResult().isJoinGameAckSelected()) {
fail("User " + username + " could not join ranking game.");
}
// The player should have joined the game.
msg = receiveMessage();
if (!msg.isPlayerListMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
msg = receiveMessage();
if (!msg.isGamePlayerMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
msg = receiveMessage();
if (!msg.isGameListMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
}
// Server should automatically send start event.
msg = receiveMessage();
if (!msg.isStartEventMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
for (int i = 0; i < 9; i++) {
do {
msg = receiveMessage(s[i]);
failOnErrorMessage(msg);
} while (!msg.isStartEventMessageSelected());
}
// Acknowledge start event.
StartEventAckMessageSequenceType startType = new StartEventAckMessageSequenceType();
startType.setGameId(new NonZeroId(gameId));
StartEventAckMessage startAck = new StartEventAckMessage();
startAck.setValue(startType);
msg = new PokerTHMessage();
msg.selectStartEventAckMessage(startAck);
sendMessage(msg);
for (int i = 0; i < 9; i++) {
sendMessage(msg, s[i]);
}
// Game list update (game now running).
msg = receiveMessage();
if (!msg.isGameListMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
msg = receiveMessage();
if (!msg.isGameStartMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
long handNum = 0;
do {
msg = receiveMessage();
failOnErrorMessage(msg);
if (msg.isHandStartMessageSelected()) {
handNum++;
}
else if (msg.isPlayersTurnMessageSelected()) {
if (msg.getPlayersTurnMessage().getValue().getPlayerId().getValue() == firstPlayerId) {
NetPlayerAction action = new NetPlayerAction();
action.setValue(NetPlayerAction.EnumType.actionAllIn);
MyActionRequestMessageSequenceType myRequest = new MyActionRequestMessageSequenceType();
myRequest.setGameId(new NonZeroId(gameId));
myRequest.setGameState(msg.getPlayersTurnMessage().getValue().getGameState());
myRequest.setHandNum(new NonZeroId(handNum));
myRequest.setMyAction(action);
myRequest.setMyRelativeBet(0);
MyActionRequestMessage myAction = new MyActionRequestMessage();
myAction.setValue(myRequest);
PokerTHMessage outMsg = new PokerTHMessage();
outMsg.selectMyActionRequestMessage(myAction);
sendMessage(outMsg);
}
}
for (int i = 0; i < 9; i++) {
while (s[i].getInputStream().available() > 0) {
PokerTHMessage inMsg = receiveMessage(s[i]);
failOnErrorMessage(inMsg);
if (inMsg.isPlayersTurnMessageSelected()) {
if (inMsg.getPlayersTurnMessage().getValue().getPlayerId().getValue() == playerId[i]) {
NetPlayerAction action = new NetPlayerAction();
action.setValue(NetPlayerAction.EnumType.actionFold);
MyActionRequestMessageSequenceType myRequest = new MyActionRequestMessageSequenceType();
myRequest.setGameId(new NonZeroId(gameId));
myRequest.setGameState(inMsg.getPlayersTurnMessage().getValue().getGameState());
myRequest.setHandNum(new NonZeroId(handNum));
myRequest.setMyAction(action);
myRequest.setMyRelativeBet(0);
MyActionRequestMessage myAction = new MyActionRequestMessage();
myAction.setValue(myRequest);
PokerTHMessage outMsg = new PokerTHMessage();
outMsg.selectMyActionRequestMessage(myAction);
sendMessage(outMsg, s[i]);
}
}
}
}
} while (!msg.isEndOfGameMessageSelected());
Thread.sleep(2000);
// Check database entry for the game.
ResultSet countAfterResult = dbStatement.executeQuery("SELECT COUNT(idgame) FROM game");
countAfterResult.first();
long countAfter = countAfterResult.getLong(1);
assertEquals(countBefore + 1, countAfter);
// Select the latest game.
ResultSet gameResult = dbStatement.executeQuery("SELECT idgame, name, start_time, end_time FROM game WHERE start_time = (SELECT MAX(start_time) from game)");
gameResult.first();
long idgame = gameResult.getLong(1);
String dbGameName = gameResult.getString(2);
assertEquals(gameName, dbGameName);
java.sql.Timestamp gameStart = gameResult.getTimestamp(3);
java.sql.Timestamp gameEnd = gameResult.getTimestamp(4);
assertTrue(gameEnd.after(gameStart));
// Do not consider daylight saving time, just calculate the raw difference.
long gameDurationMsec = gameEnd.getTime() - gameStart.getTime();
assertTrue(gameDurationMsec > 60 * 1000); // game duration should be larger than 1 minute.
assertTrue(gameDurationMsec < 60 * 60 * 1000); // game duration should be smaller than 1 hour.
// Check database entries for the players in the game.
ResultSet gamePlayerResult = dbStatement.executeQuery("SELECT COUNT(DISTINCT player_idplayer) FROM game_has_player WHERE game_idgame = " + idgame);
gamePlayerResult.first();
assertEquals(gamePlayerResult.getLong(1), 10);
// The one who always went all in should have won!
ResultSet winnerResult = dbStatement.executeQuery(
"SELECT place FROM game_has_player LEFT JOIN player_login on (game_has_player.player_idplayer = player_login.id) WHERE game_idgame = " + idgame + " AND username = '" + AuthUser + "'");
winnerResult.first();
assertEquals(winnerResult.getLong(1), 1);
}
} |
package ublu.command;
import ublu.util.ArgArray;
import ublu.util.DataSink;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.RequestNotSupportedException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Set;
import java.util.logging.Level;
/**
* Manage preferences
*
* @author jwoehr
*/
public class CmdProps extends Command {
{
setNameAndDescription("props", "/0 [-to datasink] -set ~@${ name }$ ~@${ value }$ | -get ~@${ name }$ | -list | -read ~@${filepath}$ | -write ~@${filepath}$ ~@${comment}$ : manage properties");
}
/**
* The ops we know
*/
protected enum OPERATIONS {
/**
* Set a prpperty
*/
SET,
/**
* List properties
*/
LIST,
/**
* Get a property
*/
GET,
/**
* Read in a properties file
*/
READ,
/**
* Write out a properties file
*/
WRITE,
/**
* Nada
*/
NOOP
}
/**
* Operate on properties
*
* @param argArray args to the interpreter
* @return what's left of the args
*/
public ArgArray props(ArgArray argArray) {
OPERATIONS operation = OPERATIONS.NOOP;
String propfilepath = null;
String comment = null;
String propname = null;
String value = null;
while (argArray.hasDashCommand()) {
String dashCommand = argArray.parseDashCommand();
switch (dashCommand) {
case "-to":
setDataDestfromArgArray(argArray);
break;
case "-get":
operation = OPERATIONS.GET;
propname = argArray.nextMaybeQuotationTuplePopString();
break;
case "-set":
operation = OPERATIONS.SET;
propname = argArray.nextMaybeQuotationTuplePopString();
value = argArray.nextMaybeQuotationTuplePopString();
break;
case "-list":
operation = OPERATIONS.LIST;
break;
case "-read":
operation = OPERATIONS.READ;
propfilepath = argArray.nextMaybeQuotationTuplePopString();
break;
case "-write":
operation = OPERATIONS.WRITE;
propfilepath = argArray.nextMaybeQuotationTuplePopString();
comment = argArray.nextMaybeQuotationTuplePopString();
break;
default:
unknownDashCommand(dashCommand);
}
}
if (havingUnknownDashCommand()) {
setCommandResult(COMMANDRESULT.FAILURE);
} else {
switch (operation) {
case GET:
try {
put(getInterpreter().getProperty(propname));
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Error putting propery in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case SET:
getInterpreter().setProperty(propname, value);
break;
case LIST:
StringBuilder sb = new StringBuilder();
Set set = getInterpreter().propertyKeys();
for (Object o : set) {
sb.append(o).append('=').append(getInterpreter().getProperty(o.toString())).append('\n');
}
if (sb.length() > 0) { // remove last linefeed
sb.deleteCharAt(sb.length() - 1);
}
try {
put(sb.toString());
} catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
getLogger().log(Level.SEVERE, "Error putting properies list in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case READ:
try {
getInterpreter().readProps(propfilepath);
} catch (FileNotFoundException ex) {
getLogger().log(Level.SEVERE, "Error reading properties file in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Error reading properties file in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
case WRITE:
try {
getInterpreter().writeProps(propfilepath, comment);
} catch (FileNotFoundException ex) {
getLogger().log(Level.SEVERE, "Error writing properties file in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Error writing properties file in " + getNameAndDescription(), ex);
setCommandResult(COMMANDRESULT.FAILURE);
}
break;
default:
getLogger().log(Level.SEVERE, "Unhandled operation {0} in {1}", new Object[]{operation.name(), getNameAndDescription()});
setCommandResult(COMMANDRESULT.FAILURE);
}
}
return argArray;
}
@Override
public ArgArray cmd(ArgArray args) {
reinit();
return props(args);
}
@Override
public COMMANDRESULT getResult() {
return getCommandResult();
}
} |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
public class Txt2SeqConverter
{
public static void main(String[] args)
{
if (args.length != 2)
{
System.out.println("Usage: env HADOOP_CLASSPATH=.:$HADOOP_CLASSPATH hadoop Txt2SeqConverter input output");
System.exit(1);
}
FileSystem fs = null;
String seqFileName = args[1];
Configuration conf = new Configuration();
try {
fs = FileSystem.get(URI.create(seqFileName), conf);
} catch (IOException e)
{
System.out.println("ERROR: " + e.getMessage());
}
Path path = new Path(seqFileName);
IntWritable key = new IntWritable();
Text value = new Text();
SequenceFile.Writer writer = null;
try
{
writer = SequenceFile.createWriter(fs, conf, path, IntWritable.class, Text.class);
BufferedReader br = new BufferedReader(new FileReader(args[0]));
int transactionID = 1;
String transaction = null;
while ((transaction = br.readLine()) != null)
{
key.set(transactionID);
value.set(transaction);
writer.append(key, value);
transactionID++;
}
} catch (IOException e) {
System.out.println("ERROR: " + e.getMessage());
} finally {
IOUtils.closeStream(writer);
}
}
} |
package mondrian.util;
import mondrian.olap.Util;
import java.util.*;
import junit.framework.TestCase;
/**
* Test case for {@link ObjectPool}.
*
* @version $Id$
* @author Richard Emberson
*/
public class ObjectPoolTest extends TestCase {
public ObjectPoolTest() {
super();
}
public ObjectPoolTest(String name) {
super(name);
}
static class KeyValue {
long key;
Object value;
KeyValue(long key, Object value) {
this.key = key;
this.value = value;
}
public int hashCode() {
return (int)(key ^ (key >>> 32));
}
public boolean equals(Object o) {
return (o instanceof KeyValue)
? (((KeyValue) o).key == this.key)
: false;
}
public String toString() {
return value.toString();
}
}
public void testString() throws Exception {
// for reasons unknown this fails with java4
if (Util.PreJdk15) {
return;
}
ObjectPool<String> strings = new ObjectPool<String>();
int nos = 100000;
String[] ss1 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
strings.add(ss1[i]);
}
assertEquals("size not equal", nos, strings.size());
// second array of strings, same as the first but different objects
String[] ss2 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
String s = strings.add(ss2[i]);
assertEquals("string not equal: " +s, s, ss2[i]);
// REVIEW jvs 16-Jan-2008: This failed for me when
// I ran with a 1GB JVM heap size on JDK 1.5, probably
// because of interning (I tried changing genStringsList to add a
// gratuitous String constructor call, but that did not help). If
// there's a reason this test is on strings explicitly, then
// this needs to stay disabled; if the datatype can be changed
// to something which doesn't have any magic interning, then
// it can be re-enabled. This probably explains the
// Util.PreJdk15 "unknown reasons" above.
/*
assertFalse("same object", (s == ss2[i]));
*/
}
strings.clear();
assertEquals("size not equal", 0, strings.size());
nos = 25;
ss1 = genStringsArray(nos);
for (int i = 0; i < nos; i++) {
strings.add(ss1[i]);
}
assertEquals("size not equal", nos, strings.size());
List<String> l = genStringsList(nos);
Iterator<String> it = strings.iterator();
while (it.hasNext()) {
String s = it.next();
l.remove(s);
}
assertTrue("list not empty", l.isEmpty());
}
public void testKeyValue() throws Exception {
ObjectPool<KeyValue> op = new ObjectPool<KeyValue>();
int nos = 100000;
KeyValue[] kv1 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
op.add(kv1[i]);
}
assertEquals("size not equal", nos, op.size());
// second array of KeyValues, same as the first but different objects
KeyValue[] kv2 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
KeyValue kv = op.add(kv2[i]);
assertEquals("KeyValue not equal: " +kv, kv, kv2[i]);
assertFalse("same object", (kv == kv2[i]));
}
op.clear();
assertEquals("size not equal", 0, op.size());
nos = 25;
kv1 = genKeyValueArray(nos);
for (int i = 0; i < nos; i++) {
op.add(kv1[i]);
}
assertEquals("size not equal", nos, op.size());
List<KeyValue> l = genKeyValueList(nos);
Iterator<KeyValue> it = op.iterator();
while (it.hasNext()) {
KeyValue kv = it.next();
l.remove(kv);
}
assertTrue("list not empty", l.isEmpty());
}
/**
* Tests ObjectPools containing large numbers of integer and string keys,
* and makes sure they return the same results as HashSet. Optionally
* measures performance.
*/
public void testLarge() {
// Some typical results (2.4 GHz Intel dual-core).
// Key type: Integer String
// Implementation: ObjectPool HashSet ObjectPool HashSet
// With density=0.01, 298,477 distinct entries, 7,068 hits
// 300,000 adds 221 ms 252 ms 293 ms 1013 ms
// 700,000 gets 164 ms 148 ms 224 ms 746 ms
// With density=0.5, 236,022 distinct entries, 275,117 hits
// 300,000 adds 175 ms 250 ms 116 ms 596 ms
// 700,000 gets 147 ms 176 ms 190 ms 757 ms
// With density=0.999, 189,850 distinct entries, 442,618 hits
// 300,000 adds 128 ms 185 ms 99 ms 614 ms
// 700,000 gets 133 ms 184 ms 130 ms 830 ms
checkLargeMulti(300000, 0.01, 700000, 298477, 7068);
checkLargeMulti(300000, 0.5, 700000, 236022, 275117);
checkLargeMulti(300000, 0.999, 700000, 189850, 442618);
}
private void checkLargeMulti(
int entryCount,
double density,
int retrieveCount,
int expectedDistinct,
int expectedHits)
{
checkLarge(
true, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, true, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
checkLarge(
false, false, entryCount, density, retrieveCount,
expectedDistinct, expectedHits);
}
private void checkLarge(
boolean usePool,
boolean intKey,
int entryCount,
double density,
int retrieveCount,
int expectedDistinct,
int expectedHits)
{
final boolean print = false;
final long t1 = System.currentTimeMillis();
assert density > 0 && density <= 1;
int space = (int) (entryCount / density);
ObjectPool<Object> objectPool = new ObjectPool<Object>();
HashSet<Object> set = new HashSet<Object>();
Random random = new Random(1234);
int distinctCount = 0;
final String longString =
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyy";
for (int i = 0; i < entryCount; i++) {
final Object key = intKey
? random.nextInt(space)
: longString + random.nextInt(space);
if (usePool) {
if (objectPool.add(key) != null) {
++distinctCount;
}
} else {
if (set.add(key)) {
++distinctCount;
}
}
}
final long t2 = System.currentTimeMillis();
int hitCount = 0;
for (int i = 0; i < retrieveCount; i++) {
final Object key = intKey
? random.nextInt(space)
: longString + random.nextInt(space);
if (usePool) {
if (objectPool.contains(key)) {
++hitCount;
}
} else {
if (set.contains(key)) {
++hitCount;
}
}
}
final long t3 = System.currentTimeMillis();
if (usePool) {
// todo: assertEquals(expectedDistinct, objectPool.size());
distinctCount = objectPool.size();
} else {
assertEquals(expectedDistinct, set.size());
}
if (print) {
System.out.println(
"Using " + (usePool ? "ObjectPool" : "HashSet")
+ ", density=" + density
+ ", " + distinctCount + " distinct entries, "
+ hitCount + " hits");
System.out.println(
entryCount + " adds took " + (t2 - t1) + " milliseconds");
System.out.println(
retrieveCount + " gets took " + (t3 - t2) + " milliseconds");
}
assertEquals(expectedDistinct, distinctCount);
assertEquals(expectedHits, hitCount);
}
// helpers
private static String[] genStringsArray(int nos) {
List l = genStringsList(nos);
return (String[]) l.toArray(new String[l.size()]);
}
private static List<String> genStringsList(int nos) {
List<String> l = new ArrayList<String>(nos);
for (int i = 0; i < nos; i++) {
l.add(Integer.valueOf(i).toString());
}
return l;
}
private static KeyValue[] genKeyValueArray(int nos) {
List<KeyValue> l = genKeyValueList(nos);
return (KeyValue[]) l.toArray(new KeyValue[l.size()]);
}
private static List<KeyValue> genKeyValueList(int nos) {
List<KeyValue> l = new ArrayList<KeyValue>(nos);
for (int i = 0; i < nos; i++) {
l.add(new KeyValue((long)i, Integer.valueOf(i)));
}
return l;
}
}
// End ObjectPoolTest.java |
package dr.xml;
import org.w3c.dom.NamedNodeMap;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractXMLObjectParser implements XMLObjectParser {
public final Object parseXMLObject(XMLObject xo, String id, ObjectStore store, boolean strictXML)
throws XMLParseException {
this.store = store;
if (hasSyntaxRules()) {
final XMLSyntaxRule[] rules = getSyntaxRules();
for (XMLSyntaxRule rule : rules) {
if (!rule.isSatisfied(xo)) {
throw new XMLParseException("The '<" + getParserName() +
">' element with id, '" + id +
"', is incorrectly constructed.\nThe following was expected:\n" +
rule.ruleString(xo));
}
}
// Look for undeclared attributes and issue a warning
final NamedNodeMap attributes = xo.getAttributes();
for (int k = 0; k < attributes.getLength(); ++k) {
String name = attributes.item(k).getNodeName();
if (name.equals(XMLObject.ID)) continue;
for (XMLSyntaxRule rule : rules) {
if (rule.containsAttribute(name)) {
name = null;
break;
}
}
if (name != null) {
final String msg = "unhandled attribute (typo?) " + name + " in " + xo;
if (strictXML) {
throw new XMLParseException(msg);
}
System.err.println("WARNING:" + msg);
}
}
// try to catch out of place elements, placed either by mistake or from older incompatible files.
for (int k = 0; k < xo.getChildCount(); ++k) {
final Object child = xo.getChild(k);
String unexpectedName;
if (child instanceof XMLObject) {
final XMLObject ch = (XMLObject) child;
unexpectedName = !isAllowed(ch.getName()) ? ch.getName() : null;
final List<String> unexpected = isUnexpected(ch);
if( unexpected != null ) {
String n = "";
for(int j = 0; j < unexpected.size(); j += 2) {
n = n + ", " + unexpected.get(j) + " in " + unexpected.get(j+1);
}
if( unexpectedName == null ) {
unexpectedName = n.substring(1, n.length()) ;
} else {
unexpectedName = unexpectedName + n;
}
}
} else {
unexpectedName = child.getClass().getName();
for (XMLSyntaxRule rule : rules) {
if (rule.isAllowed(child.getClass())) {
unexpectedName = null;
break;
}
}
}
if( unexpectedName != null ) {
String msg = "unexpected element in " + xo + ": " + unexpectedName;
if (strictXML) {
throw new XMLParseException(msg);
}
System.err.println("WARNING: " + msg);
}
}
}
try {
return parseXMLObject(xo);
} catch (XMLParseException xpe) {
throw new XMLParseException("Error parsing '<" + getParserName() +
">' element with id, '" + id + "':\n" +
xpe.getMessage());
}
}
public String[] getParserNames() {
return new String[]{getParserName()};
}
public final void throwUnrecognizedElement(XMLObject xo) throws XMLParseException {
throw new XMLParseException("Unrecognized element '<" + xo.getName() + ">' in element '<" + getParserName() + ">'");
}
public abstract Object parseXMLObject(XMLObject xo) throws XMLParseException;
/**
* @return an array of syntax rules required by this element.
* Order is not important.
*/
public abstract XMLSyntaxRule[] getSyntaxRules();
/**
* Allowed if any of the rules allows that element
* @param elementName
* @return
*/
public final boolean isAllowed(String elementName) {
final XMLSyntaxRule[] rules = getSyntaxRules();
if (rules != null && rules.length > 0) {
for (XMLSyntaxRule rule : rules) {
if (rule.isAllowed(elementName)) {
return true;
}
}
}
return false;
}
public final List<String> isUnexpected(XMLObject element) {
List<String> un = null;
final XMLSyntaxRule[] rules = getSyntaxRules();
if (rules != null && rules.length > 0) {
for (XMLSyntaxRule rule : rules) {
if (rule.isAllowed(element.getName())) {
for(int nc = 0; nc < element.getChildCount(); ++nc) {
final Object child = element.getChild(nc);
if( child instanceof XMLObject ) {
final String name = ((XMLObject) child).getName();
if( ! rule.isAllowed(name) ) {
if( un == null ) {
un = new ArrayList<String>();
}
un.add(name);
un.add(element.getName());
}
}
}
}
}
}
return un;
}
public abstract String getParserDescription();
public abstract Class getReturnType();
public final boolean hasExample() {
return getExample() != null;
}
public String getExample() {
return null;
}
public final ObjectStore getStore() {
return store;
}
/**
* @return a description of this parser as a string.
*/
public final String toHTML(XMLDocumentationHandler handler) {
StringBuffer buffer = new StringBuffer();
buffer.append("<div id=\"").append(getParserName()).append("\" class=\"element\">\n");
buffer.append(" <div class=\"elementheader\">\n");
buffer.append(" <span class=\"elementname\">").append(getParserName()).append("</span> element\n");
buffer.append(" <div class=\"description\">\n");
buffer.append(" ").append(getParserDescription()).append("\n");
buffer.append(" </div>\n");
buffer.append(" </div>\n");
if (hasSyntaxRules()) {
XMLSyntaxRule[] rules = getSyntaxRules();
buffer.append(" <div class=\"rules\">\n");
for (XMLSyntaxRule rule : rules) {
buffer.append(rule.htmlRuleString(handler));
}
buffer.append(" </div>\n");
}
buffer.append("<div class=\"example\">");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
handler.outputExampleXML(pw, this);
pw.flush();
pw.close();
buffer.append(sw.toString());
buffer.append("</div>\n");
buffer.append("</div>\n");
return buffer.toString();
}
/**
* @return a description of this parser as a string.
*/
public final String toWiki(XMLDocumentationHandler handler) {
StringBuffer buffer = new StringBuffer();
buffer.append("===<code><").append(getParserName()).append("></code> element===\n\n");
buffer.append(getParserDescription()).append("\n\n");
if (hasSyntaxRules()) {
XMLSyntaxRule[] rules = getSyntaxRules();
List<XMLSyntaxRule> attributes = new ArrayList<XMLSyntaxRule>();
List<XMLSyntaxRule> contents = new ArrayList<XMLSyntaxRule>();
for (XMLSyntaxRule rule : rules) {
if (rule instanceof AttributeRule) {
attributes.add(rule);
} else {
contents.add(rule);
}
}
if (attributes.size() > 0) {
buffer.append("\nThe element takes following attributes:\n");
for (XMLSyntaxRule rule : attributes) {
buffer.append(rule.wikiRuleString(handler, "*"));
}
buffer.append("\n");
}
if (contents.size() > 0) {
buffer.append("\nThe element has the following contents:\n");
for (XMLSyntaxRule rule : contents) {
buffer.append(rule.wikiRuleString(handler, "*"));
}
buffer.append("\n");
}
}
buffer.append("\nExample:\n");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
handler.outputExampleXML(pw, this);
pw.flush();
pw.close();
buffer.append(sw.toString());
buffer.append("\n");
return buffer.toString();
}
/**
* @return a description of this parser as a string.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("\nELEMENT ").append(getParserName()).append("\n");
if (hasSyntaxRules()) {
XMLSyntaxRule[] rules = getSyntaxRules();
for (XMLSyntaxRule rule : rules) {
buffer.append(" ").append(rule.ruleString()).append("\n");
}
}
return buffer.toString();
} |
package view;
import java.util.ArrayList;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import controller.CellSocietyController;
public class SimulationScreen {
private CellSocietyController myController;
private int myWidth;
private int myHeight;
private HBox myTop;
private GridPane myGridPane;
private boolean myStart;
private BorderPane root;
private ArrayList<Button> myButtons;
/**
* This function begins setting up the general simulation scene. This
* includes things like adding the four buttons at the top that load, step
* through, speed up, and stop/start the simulation. Note: all strings used
* to create buttons must be retrieved from a .properties file. Right now I
* have them hard coded into the program.
*
* @returns a scene
*/
public void initSimScreen(int width, int height, CellSocietyController controller){
myController = controller;
root = new BorderPane();
myWidth = width;
myHeight = height;
myGridPane = new GridPane();
myStart = true;
myButtons = new ArrayList<>();
//myController = new CellSocietyController(width, height);
root.setTop(addButtons());
root.setCenter(myGridPane);
}
public BorderPane getNode(){
return root;
}
private HBox addButtons() {
myTop = new HBox();
myTop.setPrefHeight(myHeight/20);
myTop.setPrefWidth(myWidth);
myTop.getChildren().addAll(addLoadButton(), addStopStartButton(), addStepButton(),
addSpeedUpButton(), addSlowDownButton());
for(Button button: myButtons){
button.setPrefWidth(myWidth / (myButtons.size()));
button.setPrefHeight(myTop.getPrefHeight());
}
double length = myTop.getChildren().size();
double buttonWidth = myButtons.get(0).getPrefWidth();
myTop.setSpacing((myWidth - length * buttonWidth) / (length));
return myTop;
}
/**
* This function adds the load button to the scene and creates the
* eventListener.
*
* @return Button that loads new file
*/
private Button addLoadButton() {
Button loadButton = new Button("Load");
myButtons.add(loadButton);
loadButton.setOnAction(e -> {
myController.transitionToFileLoaderScreen();
});
return loadButton;
}
private Button addSlowDownButton(){
Button slowDownButton = new Button("Slow Down");
myButtons.add(slowDownButton);
slowDownButton.setOnAction(e -> {
myController.slowDownSimulation();
});
return slowDownButton;
}
/**
* This function adds the step button to the scene and creates the
* eventListener.
*/
private Button addStepButton() {
Button stepButton = new Button("Step");
myButtons.add(stepButton);
stepButton.setOnAction(e -> {
myController.stepThroughSimulation();
});
return stepButton;
}
/**
* Adds speed up button
*/
private Button addSpeedUpButton() {
Button speedUpButton = new Button("Speed Up");
myButtons.add(speedUpButton);
speedUpButton.setOnAction(e -> {
myController.speedUpSimulation();
});
return speedUpButton;
}
/**
* adds stop.start button
*
* @return
*/
private Button addStopStartButton() {
Button stopStartButton = new Button("Stop/Start");
myButtons.add(stopStartButton);
stopStartButton.setOnAction(e -> {
//if false it is stopped
myStart = !myStart;
myController.stopOrStart(myStart);
});
return stopStartButton;
}
/**
* must be passed a grid of some type so that it can determine the colors of
* each square It will then go through each square and set its appropriate
* color
*
* @param colorGrid
*/
public void updateScreen(Color[][] colorGrid) {
for (int j = 0; j < colorGrid.length; j++) {
for (int i = 0; i < colorGrid[0].length; i++) {
// get color and update square with that color
getChild(j, i).setFill(colorGrid[j][i]);
}
}
}
/**
* goes through myGridPane and creates a new rectangle object at each spot
* in the grid
* @param gridHeight
* @param gridWidth
*/
public void initSimView(int gridHeight, int gridWidth) {
for (int j = 0; j < gridHeight; j++) {
for (int i = 0; i < gridWidth; i++) {
Rectangle rect = new Rectangle();
rect.setFill(Color.BLACK);
rect.setStroke(Color.BLACK);
rect.setWidth(myWidth / gridWidth - rect.getStrokeWidth());
rect.setHeight((myHeight - myTop.getPrefHeight()) / gridHeight);
myGridPane.add(rect, i, j);
}
}
}
private Shape getChild(int row, int column) {
for (Node child : myGridPane.getChildren()) {
if (GridPane.getRowIndex(child) == row
&& GridPane.getColumnIndex(child) == column) {
return (Shape) child;
}
}
System.out.println("error, getChild() method not working");
return null;
}
} |
package pokemon.launcher;
import java.util.Vector;
import pokemon.annotations.Tps;
import pokemon.controle.Cinematique;
import pokemon.controle.JoueurController;
import pokemon.controle.MenuListener;
import pokemon.modele.ChangeMapException;
import pokemon.modele.Combat;
import pokemon.modele.Direction;
import pokemon.modele.Dresseur;
import pokemon.modele.Joueur;
import pokemon.modele.NPC;
import pokemon.vue.CombatV;
import pokemon.vue.DialogBox;
import pokemon.vue.GameScreen;
import pokemon.vue.JoueurVue;
import pokemon.vue.NPCVue;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.FitViewport;
@Tps(nbhours=10)
public class MapScreen extends GameScreen{
private MyGdxGame game;
//Attributs joueur
private Joueur j=MyGdxGame.Jtest;
private JoueurVue joueur= new JoueurVue(j);
private JoueurController controller;
//Attributs NPCs
private Vector<NPCVue> npcs = new Vector<NPCVue>();
//Attributs affichage
private int width=640;//Gdx.graphics.getWidth();
private int height=360;//Gdx.graphics.getHeight();
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera cam;
//Attributs cinematiques
private Cinematique cinematique = null;
private Stage stage;
private DialogBox box = null;
//Attribut sonore
private Music music;
//Constructeurs
public MapScreen(MyGdxGame game) {
this.game = game;
this.controller = new JoueurController(this, joueur);
updateMusic();
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.position.set(j.getPos().x,j.getPos().y,0);
cam.update();
update(delta);
renderer.setView(cam);
renderer.render();
renderer.getBatch().begin();
//Rendu des NPCs
for(NPCVue npc : npcs) {
npc.render(renderer.getBatch(), delta);
}
//Rendu du joueur
joueur.render(delta, renderer.getBatch());
renderer.getBatch().end();
stage.draw();
super.drawUI(delta);
}
@Override
public void resize(int arg0, int arg1) {
//cam.viewportWidth=arg0/2f;
//cam.viewportHeight=arg1/2f;
stage.getViewport().update(arg0, arg1, true);
stage.getBatch().getProjectionMatrix().setToOrtho2D(0, 0, this.width,this.height);
}
@Override
public void show() {
//Affichage de la TiledMap
renderer=new OrthogonalTiledMapRenderer(j.getCurrentMap().getTiledMap());
cam=new OrthographicCamera();
cam.zoom-=0.32;
//Affichage des NPC
updateNPCs();
//Generation du Stage
stage = new Stage(new FitViewport(width,height,cam));
//Definition de l'input
if(cinematique == null) {
Gdx.input.setInputProcessor(controller);
}
else {
Gdx.input.setInputProcessor(cinematique.getController());
}
}
public void update(float delta)
{
//On met a jour la position du joueur.
try {
joueur.updatePosition(renderer);
} catch (ChangeMapException e) {
npcs.clear();
updateNPCs();
updateMusic();
}
//On met a jour la position des NPC
for(NPC npc : j.getCurrentMap().getNpcs()) {
npc.updatePosition();
}
//On met a jour la cinematique en cas de mouvement de personnage.
if(cinematique != null) {
//On update la cinematique...
if(!cinematique.update()) {
//... et si elle est finie, on l'enlve.
cinematique = null;
if(game.getScreen()==this){
Gdx.input.setInputProcessor(controller);
}
}
}
//On vrifie si le joueur est aggro par un PNJ
detectBattle();
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
public void dispose() {
music.dispose();
}
@Override
public void hide() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
//Autres fonctions
public void updateCutscene(Joueur j) {
// //Si aucune cinematique est en train d'etre jouee ...
// if(talkingNPC == null) {
// //... on recupere le NPC cible.
// talkingNPC = j.getCurrentMap().getNPC(j);
// if(talkingNPC != null)
// switch(j.getOrientation()) {
// case East:
// talkingNPC.setOrientation(Direction.West);
// break;
// case North:
// talkingNPC.setOrientation(Direction.South);
// break;
// case South:
// talkingNPC.setOrientation(Direction.North);
// break;
// case West:
// talkingNPC.setOrientation(Direction.East);
// break;
// default:
// break;
// if(talkingNPC != null && talkingNPC.getMoveDistance() <= 0) {
// String textToDisplay = null;
// boolean isCutsceneEnded = false;
// //Tant qu'on a pas de texte ...
// while(textToDisplay == null) {
// try {
// //... on exectue le dialogue du NPC.
// textToDisplay = j.interact(talkingNPC, MyGdxGame.npcList);
// } catch (NoMoreInstructionException e) {
// //Si le dialogue est fini, on quitte la boucle.
// isCutsceneEnded = true;
// break;
// } catch (MovementException e) {
// //Si un personnage doit bouger, on detruit la boite de dialogue (si il y en a une).
// if(box != null) {
// stage.clear();
// box.remove();
// box = null;
// //Enfin, on sort de la boucle.
// break;
// } catch (CombatException e) {
// //Si le dresseur a une equipe...
// if(e.getDresseur()!= null) {
// //... on lance un combat
// music.stop();
// Combat c = new Combat(j, e.getDresseur());
// c.start();
// game.setScreen(new CombatV(c,game));
// //Si on a un texte a afficher ...
// if(textToDisplay != null) {
// //... alors si il n'y a pas de boite ...
// if(box == null) {
// //... alors on cree une nouvelle boite, et on met le joueur en mode cinematique.
// j.setMove(false);
// box = new DialogBox(textToDisplay);
// stage.addActor(box);
// //... sinon ...
// else {
// //... on met a jour la boite existante.
// box.setMessage(textToDisplay);
// //... sinon, si aucun texte n'est a afficher ...
// else if(box != null && isCutsceneEnded) {
// //... on detruit la boite.
// j.setMove(true);
// stage.clear();
// box.remove();
// box = null;
// talkingNPC = null;
NPC talkingNPC = j.getCurrentMap().getNPC(j);
if(talkingNPC != null) {
//On change l'orientation du NPC
switch(j.getOrientation()) {
case East:
talkingNPC.setOrientation(Direction.West);
break;
case North:
talkingNPC.setOrientation(Direction.South);
break;
case South:
talkingNPC.setOrientation(Direction.North);
break;
case West:
talkingNPC.setOrientation(Direction.East);
break;
default:
break;
}
cinematique = new Cinematique(this, talkingNPC);
Gdx.input.setInputProcessor(cinematique.getController());
}
}
public void popMenu() {
new MenuListener(game, this);
}
public void updateMusic() {
if(music != null) {
music.stop();
}
music = Gdx.audio.newMusic(Gdx.files.internal(j.getCurrentMap().getMusique().getPath()));
music.setVolume(0.3f);
music.setLooping(true);
music.play();
}
public void addBox(String text) {
//Si il n'y a pas dja de boite de dialogue...
if(box == null) {
//... on en cre une avec le texte fourni
box = new DialogBox(text);
stage.addActor(box);
}
else {
box.setMessage(text);
}
}
public void removeBox() {
//Si une boite de dialogue existe ...
if(box != null) {
//... on l'enlve
System.out.println("Remove()");
stage.clear();
box.remove();
box = null;
}
}
public void startBattle(Dresseur dress) {
music.stop();
Combat c = new Combat(j, dress);
c.start();
game.setScreen(new CombatV(c,game));
}
public NPC getNPCById(int i) {
return j.getCurrentMap().getNPCById(i);
}
//Fonctions privees
private void updateNPCs() {
for(NPC npc : j.getCurrentMap().getNpcs()) {
NPCVue npcvue = new NPCVue(npc);
npcs.add(npcvue);
}
}
private void detectBattle() {
//Pour chaque NPC de la map, on cherche si le joueur est dans la porte
for(NPC npc : j.getCurrentMap().getNpcs()) {
Direction dir = npc.getOrientation();
Vector2 pos = npc.getPos();
Vector2 dim = npc.getDimensions();
//On construit la zone d'intraction du personnage
Rectangle interactRegion = getInteractRegion(pos, dim, dir);
//On vrifie si le joueur est dans cette zone
Rectangle playerHitbox = new Rectangle(j.getPos().x, j.getPos().y-16, j.getDimensions().x, j.getDimensions().y - 5);
if(interactRegion.overlaps(playerHitbox))
{
// System.out.println("NPC : " + pos);
// System.out.println("Region : " + interactRegion);
//On dclenche la cinmatique de combat
}
}
}
private Rectangle getInteractRegion(Vector2 pos, Vector2 dim, Direction dir){
float dist = 50; // valeur a modifier
float thickness = 6;
Rectangle interactRegion = new Rectangle();
switch(dir)
{
case East:
interactRegion.x = pos.x + dim.y;
interactRegion.y = pos.y + (dim.y / 2) - (thickness / 2);
interactRegion.width = dist;
interactRegion.height = thickness;
break;
case North:
interactRegion.x = pos.x + (dim.x / 2) - (thickness / 2);
interactRegion.y = pos.y + dim.x;
interactRegion.width = thickness;
interactRegion.height = dist;
break;
case South:
interactRegion.x = pos.x + (dim.x / 2) - (thickness / 2);
interactRegion.y = pos.y - dist;
interactRegion.width = thickness;
interactRegion.height = dist;
break;
case West:
interactRegion.x = pos.x - dist;
interactRegion.y = pos.y + (dim.x / 2) - (thickness / 2);
interactRegion.width = dist;
interactRegion.height = thickness;
break;
default:
interactRegion.x = pos.x + (dim.x / 2) - (thickness / 2);
interactRegion.y = pos.y - dist;
interactRegion.width = thickness;
interactRegion.height = dist;
break;
}
return interactRegion;
}
} |
package dronemis.openCV;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
public class ImageProcessor {
public BufferedImage toBufferedImage(Mat matrix){
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( matrix.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = matrix.channels()*matrix.cols()*matrix.rows();
byte [] buffer = new byte[bufferSize];
matrix.get(0,0,buffer); // get all the pixels
BufferedImage image = new BufferedImage(matrix.cols(),matrix.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(buffer, 0, targetPixels, 0, buffer.length);
return image;
}
public Mat toMatImage(BufferedImage image) {
// Convert to byte array
byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
// Create a Matrix
Mat imageMat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
// Fill Matrix
imageMat.put(0, 0, pixels);
return imageMat;
}
} |
/* ConfigFile.java */
package droplauncher.config;
import droplauncher.debugging.Debugging;
import droplauncher.tools.MainTools;
import droplauncher.tools.MemoryFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* Class for handling configuration files.
*
* @author Adakite Systems
* @author adakitesystems@gmail.com
*/
public class ConfigFile {
private static final Logger LOGGER = LogManager.getRootLogger();
public static final String FILE_EXTENSION = ".cfg";
public static final String VARIABLE_DELIMITER = "=";
public static final String COMMENT_DELIMITER = ";";
private String filename;
private MemoryFile memoryFile;
private ArrayList<ConfigVariable> variables;
/**
* Initialize class variables.
*/
public ConfigFile() {
this.filename = null;
this.memoryFile = new MemoryFile();
this.variables = new ArrayList<>();
}
/**
* Create a file if it does not already exist.
*
* @param filename path to file
* @return
* true if file was created successfully or already exists,
* otherwise false
*/
public boolean create(String filename) {
if (MainTools.isEmpty(filename)) {
LOGGER.warn(Debugging.EMPTY_STRING);
return false;
} else if (MainTools.doesFileExist(filename)) {
LOGGER.warn("file already exists: " + filename);
return true;
}
File file = new File(filename);
String parentDir = file.getParent();
if (parentDir != null && !MainTools.doesDirectoryExist(parentDir)) {
file.mkdirs();
}
try {
this.filename = filename;
boolean status = file.createNewFile() && open(filename);
return status;
} catch (IOException ex) {
LOGGER.error(ex.getMessage(), ex);
return false;
}
}
/**
* Opens the configuration file and read in its variables.
*
* @param filename specified configuration file to read
* @return
* true if file has been opened successfully,
* otherwise false
*/
public boolean open(String filename) {
this.filename = filename;
if (MainTools.isEmpty(filename)) {
LOGGER.warn(Debugging.EMPTY_STRING);
}
if (!this.memoryFile.readIntoMemory(filename)) {
LOGGER.warn("open failed: " + filename);
return false;
}
this.variables.clear();
ArrayList<String> lines = this.memoryFile.getLines();
int len = lines.size();
/* Read was successful but file is empty. */
if (len < 1) {
return true;
}
String line;
String varName;
String varValue;
int index;
/* Read lines as variables and values. */
for (int i = 0; i < len; i++) {
line = lines.get(i).trim();
/* Ignore comments. */
if (line.startsWith(COMMENT_DELIMITER)) {
continue;
}
index = line.indexOf(COMMENT_DELIMITER);
if (index >= 0) {
line = line.substring(0, index);
}
/* Parse variable. */
index = line.indexOf(VARIABLE_DELIMITER);
if (index < 0) {
continue;
}
varName = line.substring(0, index).trim();
varValue = line.substring(index + 1, line.length()).trim();
this.variables.add(new ConfigVariable(varName, varValue));
LOGGER.info(
"Read variable: " + filename + ": "
+ varName + " " + VARIABLE_DELIMITER + " " + varValue
);
}
return true;
}
public boolean refresh() {
return open(this.filename);
}
/**
* Returns the index of the specified variable name.
*
* @param name specified variable name
* @return
* the index of the specified variable name if found,
* otherwise -1
*/
public int indexOfName(String name) {
if (MainTools.isEmpty(name)) {
LOGGER.warn(Debugging.EMPTY_STRING);
return -1;
}
int len = this.variables.size();
ConfigVariable tmpVar;
for (int i = 0; i < len ; i++) {
tmpVar = this.variables.get(i);
if (tmpVar.getName().equalsIgnoreCase(name)) {
return i;
}
}
return -1;
}
/**
* Returns the index of the specified value.
*
* @param value specified value
* @return
* the index of the specified value name if found,
* otherwise -1
*/
public int indexOfValue(String value) {
if (MainTools.isEmpty(value)) {
LOGGER.warn(Debugging.EMPTY_STRING);
return -1;
}
int len = this.variables.size();
ConfigVariable tmpVar;
for (int i = 0; i < len ; i++) {
tmpVar = this.variables.get(i);
if (tmpVar.getValue().equalsIgnoreCase(value)) {
return i;
}
}
return -1;
}
/**
* Returns the name corresponding to the specified variable value.
*
* @param value specified variable value
* @return the name corresponding to the specified variable value
*/
public String getName(String value) {
int index = indexOfValue(value);
if (index < 0) {
return null;
}
return this.variables.get(index).getName();
}
/**
* Returns the value corresponding to the specified variable name.
*
* @param name specified variable name
* @return the value corresponding to the specified variable name
*/
public String getValue(String name) {
int index = indexOfName(name);
if (index < 0) {
return null;
}
return this.variables.get(index).getValue();
}
/**
* Create a new variable in the config file.
*
* @param name variable name
* @param value variable value
* @return
* true if variable did not exist before and does now,
* otherwise false
*/
public boolean createVariable(String name, String value) {
if (MainTools.isEmpty(name)) {
LOGGER.warn(Debugging.EMPTY_STRING);
return false;
}
if (MainTools.isEmpty(value)) {
value = "";
}
/* Test if variable already exists. */
if (indexOfName(name) >= 0) {
return setVariable(name, value);
}
/* Add complete variable string to memory file. */
this.memoryFile.getLines().add(
name
+ " " + ConfigFile.VARIABLE_DELIMITER + " "
+ value
);
/* Update changes in file. */
return this.memoryFile.writeToDisk() && refresh();
}
/**
* Sets the specified variable's value and writes changes to disk.
*
* @param name specified variable name
* @param value specified value of variable
* @return
* true if variable exists, its value has been set, and written to disk,
* otherwise false
*/
public boolean setVariable(String name, String value) {
int varIndex = indexOfName(name);
if (varIndex < 0) {
return false;
}
ArrayList<String> lines = this.memoryFile.getLines();
String line;
String comment;
boolean writeToFile = false;
int len = lines.size();
int index;
/* Find variable and set its value. */
for (int i = 0; i < len; i++) {
line = lines.get(i);
comment = "";
index = line.indexOf(COMMENT_DELIMITER);
if (index >= 0) {
comment = line.substring(index, line.length());
}
if (line.trim().toLowerCase().startsWith(name) && line.contains(VARIABLE_DELIMITER)) {
line = name + " " + VARIABLE_DELIMITER + " " + value + " " + comment;
this.memoryFile.getLines().set(i, line);
writeToFile = true;
}
}
/* Update changes in file. */
if (writeToFile) {
if (!this.memoryFile.writeToDisk()) {
return false;
}
this.variables.set(varIndex, new ConfigVariable(name, value));
return refresh();
}
/* If this line is reached, something went wrong. */
return false;
}
/**
* Enables the specifiedd variable in the config file by
* uncommenting the line.
*
* @param name specified variable to enable
* @return
* true if variable is enabled,
* otherwise false
*/
public boolean enableVariable(String name) {
if (indexOfName(name) >= 0) {
/* Variable is already enabled. */
return true;
}
ArrayList<String> lines = this.memoryFile.getLines();
String line;
String currentLine = null;
int currentIndex = -1;
int len = lines.size();
int index;
/* Find the most current line matching variable name. */
for (int i = 0; i < len; i++) {
line = lines.get(i);
if (line.trim().toLowerCase().startsWith(COMMENT_DELIMITER)
&& line.contains(name + " ")
&& line.contains(VARIABLE_DELIMITER)) {
currentLine = line;
currentIndex = i;
}
}
if (currentLine == null) {
/* Unable to find variable. */
return false;
}
index = currentLine.indexOf(COMMENT_DELIMITER);
currentLine = currentLine.substring(index + 1, currentLine.length()).trim();
this.memoryFile.getLines().set(currentIndex, currentLine);
return (this.memoryFile.writeToDisk() && refresh());
}
/**
* Disables the specified variable in the config file by
* commenting the line.
*
* @param name specified variable to disable
* @return
* true if variable is now disabled,
* otherwise false
*/
public boolean disableVariable(String name) {
if (indexOfName(name) < 0) {
/* Variable is already disabled. */
return true;
}
String line;
ArrayList<String> lines = this.memoryFile.getLines();
int len = lines.size();
for (int i = 0; i < len; i++) {
line = lines.get(i);
if (line.trim().toLowerCase().startsWith(name)
&& line.contains(VARIABLE_DELIMITER)) {
line = COMMENT_DELIMITER + " " + line;
this.memoryFile.getLines().set(i, line);
return (this.memoryFile.writeToDisk() && refresh());
}
}
/* If this line is reached, variable was not found in the config. */
return false;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.stuy.commands.Autonomous;
import edu.stuy.commands.DriveManualJoystickControl;
import edu.stuy.util.VictorRobotDrive;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SendablePIDController;
/**
*
* @author Kevin Wang
*/
public class Drivetrain extends Subsystem {
public RobotDrive drive;
public Solenoid gearShift;
Solenoid gearShiftLow;
Solenoid gearShiftHigh;
AnalogChannel sonar;
AnalogChannel vcc;
public Encoder encoderLeft;
public Encoder encoderRight;
Gyro gyro;
SendablePIDController controller;
final int WHEEL_RADIUS = 3;
final double CIRCUMFERENCE = 2 * Math.PI * WHEEL_RADIUS;
final int ENCODER_CODES_PER_REV = 360;
final double DISTANCE_PER_PULSE = CIRCUMFERENCE / ENCODER_CODES_PER_REV;
double Kp = 0.035;
double Ki = 0.0005;
double Kd = 1.0;
private double previousReading = -1.0;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public Drivetrain() {
drive = new VictorRobotDrive(RobotMap.FRONT_LEFT_MOTOR, RobotMap.REAR_LEFT_MOTOR, RobotMap.FRONT_RIGHT_MOTOR, RobotMap.REAR_RIGHT_MOTOR);
drive.setSafetyEnabled(false);
encoderLeft = new Encoder(RobotMap.LEFT_ENCODER_CHANNEL_A, RobotMap.LEFT_ENCODER_CHANNEL_B, true);
encoderRight = new Encoder(RobotMap.RIGHT_ENCODER_CHANNEL_A, RobotMap.RIGHT_ENCODER_CHANNEL_B, true);
encoderLeft.setDistancePerPulse(DISTANCE_PER_PULSE);
encoderRight.setDistancePerPulse(DISTANCE_PER_PULSE);
encoderLeft.start();
encoderRight.start();
gyro = new Gyro(RobotMap.GYRO_CHANNEL);
gyro.setSensitivity(0.007);
controller = new SendablePIDController(Kp, Ki, Kd, gyro, new PIDOutput() {
public void pidWrite(double output) {
drive.arcadeDrive(SpeedRamp.profileSpeed_Bravo(Autonomous.INCHES_TO_FENDER - getAvgDistance(), Autonomous.INCHES_TO_FENDER, 1), -output);
}
}, 0.005);
gearShiftLow = new Solenoid(RobotMap.GEAR_SHIFT_LOW);
gearShiftHigh = new Solenoid(RobotMap.GEAR_SHIFT_LOW);
sonar = new AnalogChannel(RobotMap.SONAR_CHANNEL);
vcc = new AnalogChannel(RobotMap.VCC_CHANNEL);
}
/**
* Gets the analog voltage of the MaxBotics ultrasonic sensor, and debounces the input
* @return Analog voltage reading from 0 to 5
*/
public double getSonarVoltage() {
double newReading = sonar.getVoltage();
double goodReading = previousReading;
if (previousReading - (-1) < .001 || (newReading - previousReading) < .5) {
goodReading = newReading;
previousReading = newReading;
} else {
previousReading = newReading;
}
return goodReading;
}
/**
* Get value of maximum analog input in volts.
* @return value of maximum analog input in volts.
*/
public double getVcc() {
return vcc.getVoltage();
}
/**
* Scales sonar voltage reading to inches
* @return distance from alliance wall in inches, as measured by sonar sensor
*/
public double getSonarDistance_in() {
double cm = getSonarVoltage() * 1024 / getVcc(); // MaxSonar EZ4 input units are in (Vcc/1024) / cm; multiply by (1024/Vcc) to get centimeters
return cm / 2.54; // 1 cm is 1/2.54 inch
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
setDefaultCommand(new DriveManualJoystickControl());
}
public Command getDefaultCommand() {
return super.getDefaultCommand();
}
public void tankDrive(double leftValue, double rightValue) {
drive.tankDrive(leftValue, rightValue);
}
public void setGear(boolean high) {
gearShiftHigh.set(high);
gearShiftLow.set(!high);
}
public boolean getGear() {
return gearShift.get();
}
public void initController() {
resetEncoders();
controller.setSetpoint(0);
controller.enable();
}
public void endController() {
controller.disable();
}
/**
* Sets the ramping distance and direction by constructing a new PID controller.
* @param distance inches to travel
*/
public void setDriveStraightDistanceAndDirection(final double distance, final int direction) {
if (controller != null) {
controller.disable();
controller.free();
}
controller = new SendablePIDController(Kp, Ki, Kd, gyro, new PIDOutput() {
public void pidWrite(double output) {
drive.arcadeDrive(SpeedRamp.profileSpeed_Bravo(distance - getAvgDistance(), distance, direction), -output);
}
}, 0.005);
}
public void driveStraight() {
controller.setSetpoint(0); // Go straight
}
/**
* Calculate average distance of the two encoders.
* @return Average of the distances (inches) read by each encoder since they were last reset.
*/
public double getAvgDistance() {
return (getLeftEncoderDistance() + getRightEncoderDistance()) / 2.0;
}
public double getLeftEncoderDistance() {
return encoderLeft.getDistance();
}
public double getRightEncoderDistance() {
return encoderRight.getDistance();
}
/**
* Reset both encoders's tick, distance, etc. count to zero
*/
public void resetEncoders() {
encoderLeft.reset();
encoderRight.reset();
}
public double getGyroAngle() {
return gyro.getAngle();
}
public static class SpeedRamp {
public static double profileSpeed_Bravo(double distToFinish, double totalDistToTravel, int direction) {
double outputSpeed = 0;
double thirdOfDistToTravel = totalDistToTravel / 3.0;
double difference = totalDistToTravel - distToFinish;
double stage = Math.abs(difference / totalDistToTravel);
// If we are in the first third of travel, ramp up speed proportionally to distance from first third
if (stage < 1.0/3.0) {
outputSpeed = 0.5 + (1-0.5)/(1.0/3.0) * stage; // Scales from 0.5->1, approaching 1 as the distance traveled
//approaches the first third
}
else if (stage < 2.0/3.0) {
outputSpeed = 1.0;
}
else if (stage < 1) {
outputSpeed = distToFinish / (thirdOfDistToTravel); // Scales from 1->0 during the final third of distance travel.
}
if (outputSpeed < 0.3) {
outputSpeed = 0.3;
}
return outputSpeed * direction;
}
}
} |
import java.util.*;
public class Verifier
{
public static final String EXAMPLE_DATA = "example.txt";
public static final long EXAMPLE_ADDRESS_1 = 7;
public static final long EXAMPLE_VALUE_1 = 0;
public static final long EXAMPLE_ADDRESS_2 = 8;
public static final long EXAMPLE_VALUE_2 = 64;
public Verifier (boolean debug)
{
_debug = debug;
}
public boolean verify ()
{
Vector<Command> cmds = Util.loadCommands(EXAMPLE_DATA, _debug);
Memory mem = new Memory();
for (int i = 0; i < cmds.size(); i++)
{
System.out.println("Loaded:\n"+cmds.elementAt(i));
cmds.elementAt(i).execute(mem);
}
if (mem.getValue(EXAMPLE_ADDRESS_1) == EXAMPLE_VALUE_1)
{
if (mem.getValue(EXAMPLE_ADDRESS_2) == EXAMPLE_VALUE_2)
return true;
else
System.out.println("Wrong value at memory address "+EXAMPLE_ADDRESS_2+": "+EXAMPLE_VALUE_2);
}
else
System.out.println("Wrong value at memory address "+EXAMPLE_ADDRESS_1+": "+EXAMPLE_VALUE_1);
return false;
}
private boolean _debug;
} |
package bresenham;
/**
* @author Mario
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.util.Random;
public class Bresenham extends JPanel {
public static JPanel panel ;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
Dimension size = getSize();
Insets insets = getInsets();
int w = size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;
}
public static void Bresenham(x1, y1, x2, y2) {
int dx = x1 - x2;
int dy = y1 - y2;
int p = 2*dy -dx;
if( dx > dy ) {
const1 = 2*dy;
const2 = 2 * (dy -dx);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bresenham");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showInputDialog("");
frame.setVisible(true);
}
} |
package tla2sany.modanalyzer;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import tla2sany.semantic.AbortException;
import tla2sany.semantic.Errors;
import tla2sany.semantic.ExternalModuleTable;
import tla2sany.st.TreeNode;
import tla2sany.utilities.Vector;
import util.ToolIO;
public class SpecObj
{
String primaryFileName;
// The raw file name for the root (top) module, unprocessed by adding
// ".tla" or by prepending the full file system path to it)
ExternalModuleTable externalModuleTable = new ExternalModuleTable();
// This is the one ExternalModuleTable for the entire specification;
// it includes ModuleNode's for the root module, and for all modules
// that it depends on directly or indirectly by EXTENDS or INSTANCE
public Vector semanticAnalysisVector = new Vector();
// Stack of units parsed, in the order in which semantic analysis
// must be done, i.e. if MODULE A references B, A is lower
// on the stack. The same module name can occur multiple times.
public Hashtable parseUnitContext = new Hashtable();
// Holds all known ParseUnit objects, i.e external, top-level
// modules that have so far been encountered, keyed by module
// (parseUnit) string name
private ModuleRelationships moduleRelationshipsSpec = new ModuleRelationships();
// Maps ModulePointers to ModuleRelatives objects for all modules
// in the specification, including all inner modules and all top-level
// external modules.
private StringToNamedInputStream ntfis = null;
ParseUnit rootParseUnit = null;
// The ParseUnit object for the first (i.e. "root") file, roughly
// the file that is named in the command line; null until the root
// file is parsed
ModulePointer rootModule = null;
// The top level module of the rootParseUnit;
// null until rootParseUnit is parsed
String rootModuleName;
// The String name of rootModule, unknown until rootParseUnit is parsed,
// although it is supposed to be closely related to the file name
public Errors initErrors = new Errors();
// The Errors object for reporting errors that happen at initialization
// time.
public Errors parseErrors = new Errors();
// The Errors object for reporting errors that occur during parsing,
// including the retrieval of files (ParseUnits) for extention and
// instantiation or the root and their extentions and instantiations, etc.
Errors globalContextErrors = new Errors();
// The Errors object for reporting errors in creating the global
// context from the file that stores it.
public Errors semanticErrors = new Errors();
// The Errors object for reporting errors discovered during semantic
// analysis, including level checking.
public int errorLevel = 0;
/**
* Default constructor of the SpecObj with a given primary filename and the default
* NameToFileIStream for its resolution
* @param pfn primary filename of the specification
* @deprecated please use the {@link SpecObj#SpecObj(String, StringToNamedInputStream)}
* with <code>null</code> as a second argument
*/
public SpecObj(String pfn)
{
this(pfn, null);
}
/**
* Constructs a SpecObj for the given filename using a specified filename resolver
* @param pfn primary filename of the specification
* @param ntfis string to named input stream resolver, if <code>null</code>,
* the {@link NameToFileIStream} is used
*/
public SpecObj(String pfn, StringToNamedInputStream ntfis)
{
if (ntfis == null)
{
ntfis = new NameToFileIStream();
}
this.primaryFileName = pfn;
this.ntfis = ntfis;
}
/**
* Any integer other than 0 returned from this method indicates a
* fatal error while processing the TLA+ spec. No further use
* should be made of this object except by the maintainer.
*/
public final int getErrorLevel()
{
return errorLevel;
}
/**
* Returns the name of the top-level module as passed to the method
* Specification.frontEndMain().
*/
public final String getName()
{
return rootModuleName;
}
public final void setName(String name)
{
rootModuleName = name;
}
/**
* Returns the raw file name of the top-level module as passed to
* the method Specification.frontEndMain().
*/
public final String getFileName()
{
return primaryFileName;
}
/**
* Returns the ExternalModuleTable object that contains all of the
* definitions for this Specification. May be null or incomplete if
* getErrorLevel() returns a nonzero number.
*/
public final ExternalModuleTable getExternalModuleTable()
{
return externalModuleTable;
}
/**
* Returns Errors object produced during initialization of the FrontEnd.
* Should never be interesting.
*/
public final Errors getInitErrors()
{
return initErrors;
}
/**
* Returns Errors object containing errors found during parsing.
*/
public final Errors getParseErrors()
{
return parseErrors;
}
/**
* Returns Errors object containing errors found while parsing the
* built-in operator and synonym tables. Should never be interesting.
*/
public final Errors getGlobalContextErrors()
{
return globalContextErrors;
}
/**
* Returns Errors object containing errors found during semantic
* processing and level checking.
*/
public final Errors getSemanticErrors()
{
return semanticErrors;
}
// Returns enumeration of the modules so far included in the spec
public final Enumeration getModules()
{
return moduleRelationshipsSpec.getKeys();
}
// Returns the moduleRelationshipsSpec object
final ModuleRelationships getModuleRelationships()
{
return moduleRelationshipsSpec;
}
// Prints the context of one ParseUnit
public final void printParseUnitContext()
{
Enumeration enumerate = parseUnitContext.keys();
ToolIO.out.println("parseUnitContext =");
while (enumerate.hasMoreElements())
{
String key = (String) enumerate.nextElement();
ToolIO.out.println(" " + key + "-->" + ((ParseUnit) parseUnitContext.get(key)).getName());
}
}
// This method looks up a ParseUnit "name" in the parseUnitContext
// table. If it is not found, then the corresponding file is looked
// up in the file system and parsed, and a new ParseUnit is created
// for it and an entry for it added to the parseUnitContext table.
// The argument firstCall should be true iff this is the first call
// to this method; it is used to determine that the name of the
// module in the ParseUnit created is the name of the entire
// SpecObj. Returns the ParseUnit found or created. Aborts if
// neither happens.
private final ParseUnit findOrCreateParsedUnit(String name, Errors errors, boolean firstCall) throws AbortException
{
ParseUnit parseUnit;
// See if ParseUnit "name" is already in parseUnitContext table
parseUnit = (ParseUnit) parseUnitContext.get(name);
// if not, then we have to get it from the file system
if (parseUnit == null)
{
// if module "name" is not already in parseUnitContext table
// find a file derived from the name and create a
// NamedInputStream for it if possible
NamedInputStream nis = this.ntfis.toIStream(name);
if (nis != null)
{
// if a non-null NamedInputStream exists, create ParseUnit
// from "nis", but don't parse it yet
parseUnit = new ParseUnit(this, nis);
// put "parseUnit" and its name in "parseUnitContext" table
parseUnitContext.put(parseUnit.getName(), parseUnit);
} else
{
errors.addAbort("Cannot find source file for module " + name + " imported in module "
+ nextExtenderOrInstancerModule.getName() + ".");
}
}
// Actually parse the file named in "parseUnit" (or no-op if it
// has already been parsed)
parseUnit.parseFile(errors, firstCall);
return parseUnit;
// return a non-null "parseUnit" iff named module has been found,
// either already parsed or in the file system
}
// Fill the Vector used to drive the semantic analysis of external
// modules. The basic requirement is that if ParseUnit A extends or
// instances ParseUnit B, then A must have a higher index in the
// Vector than B.
private void calculateDependencies(ParseUnit currentParseUnit)
{
Vector extendees = currentParseUnit.getExtendees();
Vector instancees = currentParseUnit.getInstancees();
// Make sure all extendees of currentModule are in the semanticAnalysisVector
for (int i = 0; i < extendees.size(); i++)
{
calculateDependencies((ParseUnit) extendees.elementAt(i));
}
// And then make sure all instancees of currentModule are in the
// semanticAnalysisVector
for (int i = 0; i < instancees.size(); i++)
{
calculateDependencies((ParseUnit) instancees.elementAt(i));
}
// Then put self in the Vector, if not already there
if (!semanticAnalysisVector.contains(currentParseUnit.getName()))
{
semanticAnalysisVector.addElement(currentParseUnit.getName());
}
return;
}
// Converts a Vector of ParseUnits to a string representing a
// circular chain of references, for purposes of the error message
// in nonCircularityBody method below.
private String pathToString(Vector path)
{
String ret = "";
for (int i = 0; i < path.size(); i++)
{
ret += ((ParseUnit) path.elementAt(i)).getFileName() + "
}
return ret + ((ParseUnit) path.elementAt(0)).getFileName();
}
// This method determines whether the there is any circularity
// detectable this far among ParseUnits that involves the one named
// parseUnitName. If there is, cause an abort; otherwise return.
private void nonCircularityTest(ParseUnit parseUnit, Errors errors) throws AbortException
{
HashSet alreadyVisited = new HashSet();
Vector circularPath = new Vector();
circularPath.addElement(parseUnit);
nonCircularityBody(parseUnit, parseUnit, errors, alreadyVisited, circularPath);
}
// Recursive depth-first search method to see if there is a circular
// dependence from 'parseUnit' to 'parseUnit' through another
// ParseUnit, candidate. If so, an abort message is posted on
// errors, and the method aborts. The set alreadyVisited is
// used to prevent searching paths through the same candidate
// multiple times.
private void nonCircularityBody(ParseUnit parseUnit, ParseUnit candidate, Errors errors, HashSet alreadyVisited,
Vector circularPath) throws AbortException
{
// If we have already checked for circularities through this
// parseUnit, just return
if (alreadyVisited.contains(candidate))
return;
alreadyVisited.add(candidate);
// Vector referencees holds ParseUnits either extended by or
// instanced by "candidate"
Vector referencees = candidate.getExtendees();
referencees.appendNoRepeats(candidate.getInstancees());
for (int i = 0; i < referencees.size(); i++)
{
ParseUnit referencee = (ParseUnit) referencees.elementAt(i);
// See if our search has reached "parseUnit";
// if so, we have a circularity
if (referencee == parseUnit)
{
// Circularity detected
errors.addAbort("Circular dependency among .tla files; " + "dependency cycle is:\n\n "
+ pathToString(circularPath));
} else
{
circularPath.addElement(referencee);
// See if there is a circular path continuing through this referencee
nonCircularityBody(parseUnit, referencee, errors, alreadyVisited, circularPath);
circularPath.removeElementAt(circularPath.size() - 1);
} // end if
} // end for
return;
}
// The next two methods and the variables declared before them
// traverse the tree of module relationships recursively, starting
// at "currentModule", to find a name in an EXTENDS decl that is as
// yet unresolved, if any, and set "nextParseUnit" to its name.
// Return false iff there are no more unresolved EXTENDS names in
// the entire specification.
String nextParseUnitName = "";
// The place where name of the next unresolved extention
// or instance module is stored by the next methods
ModulePointer nextExtenderOrInstancerModule = null;
// The place where a reference to the module that extends
// or instances the next parse unit is stored by the next method
boolean extentionFound;
boolean instantiationFound;
// A wrapper for the next method, which empties the alreadyVisited
// table calling the recursive method below
private boolean findNextUnresolvedExtention(ModulePointer currentModule)
{
HashSet alreadyVisited = new HashSet();
return findNextUnresolvedExtentionBody(currentModule, alreadyVisited);
}
// Traverse the tree of module relationships recursively, starting
// at "currentModule", to find a name in an EXTENDS decl that is as
// yet unresolved, if any, and set "nextParseUnit" to its name.
// Return false iff there are no more unresolved EXTENDS names in
// the entire specification.
private boolean findNextUnresolvedExtentionBody(ModulePointer currentModule, HashSet alreadyVisited)
{
if (alreadyVisited.contains(currentModule))
{
extentionFound = false;
return false;
}
alreadyVisited.add(currentModule);
ModuleContext currentContext = currentModule.getContext();
Vector extendees = currentModule.getNamesOfModulesExtended();
Vector instancees = currentModule.getNamesOfModulesInstantiated();
// for all of the modules named as extendees of the current
// module, but which may or not be resolved yet
for (int i = 0; i < extendees.size(); i++)
{
// if one of them is unresolved
if (currentContext.resolve((String) extendees.elementAt(i)) == null)
{
// then it is the next unresolved extention; return it
nextParseUnitName = (String) extendees.elementAt(i);
nextExtenderOrInstancerModule = currentModule;
extentionFound = true;
return true;
}
} // end for
// See if one of the already-resolved extendees has any unresolved
// extentions
for (int i = 0; i < extendees.size(); i++)
{
// by recursive invocation of this method on the extendees
if (findNextUnresolvedExtentionBody(currentContext.resolve((String) extendees.elementAt(i)), alreadyVisited))
{
extentionFound = true;
return true;
}
} // end for
// See if one of the already-resolved instancees of currentModule
// has any unresolved extentions
for (int i = 0; i < instancees.size(); i++)
{
// if this instancee has been resolved
if (currentContext.resolve((String) instancees.elementAt(i)) != null)
{
// check by recursive invocation of this method on the instancees
if (findNextUnresolvedExtentionBody(currentContext.resolve((String) instancees.elementAt(i)),
alreadyVisited))
{
extentionFound = true;
return true;
} // end if
} // end if
} // end for
// Finally, see if any of "currentModule"'s inner modules (or any
// they extend or instance) have any unresolved extentions by
// invoking this method recursively on them.
Vector innerModules = currentModule.getDirectInnerModules();
for (int i = 0; i < innerModules.size(); i++)
{
if (findNextUnresolvedExtentionBody((ModulePointer) innerModules.elementAt(i), alreadyVisited))
{
extentionFound = true;
return true;
}
} // end for
// Iff there are no unresolved extention module names, we return false
extentionFound = false;
return false;
} // end findNextUnresolvedExtentionBody()
// A wrapper for the next method, which empties the alreadyVisited
// table calling the recursive method below
private boolean findNextUnresolvedInstantiation(ModulePointer currentModule)
{
HashSet alreadyVisited = new HashSet();
return findNextUnresolvedInstantiationBody(currentModule, alreadyVisited);
}
// Determines whether an INSTANCE statement for the module named
// "instancee" refers to an earlier-defined internal module within
// the same module "module". This is accomplished essentially by a
// linear search of the declaration in the syntactic tree of
// "module". Note: this does NOT scale when there are large numbers
// of INSTANCE decls in a long module.
private boolean instanceResolvesToInternalModule(ModulePointer currentModule, String instanceeName)
{
// Find the body part of module tree
TreeNode body = currentModule.getBody();
// We will be accumulating the set of names of internal modules
// defined before the INSTANCE declaration.
HashSet internalModulesSeen = new HashSet();
// loop through the top level definitions in the body of the
// module looking for embedded modules instantiations, and module
// definitions
for (int i = 0; i < body.heirs().length; i++)
{
TreeNode def = body.heirs()[i];
// if we encounter an new (inner) module
if (def.getImage().equals("N_Module"))
{
// Pick off name of inner module
String innerModuleName = def.heirs()[0].heirs()[1].getImage();
// Add to the set of names of inner modules seen so far
internalModulesSeen.add(innerModuleName);
}
// if we encounter an INSTANCE decl
else if (def.getImage().equals("N_Instance"))
{
TreeNode[] instanceHeirs = def.heirs();
int nonLocalInstanceNodeIX;
// The modifier "LOCAL" may or may not appear in the syntax tree;
// if so, offset by 1
if (instanceHeirs[0].getImage().equals("LOCAL"))
{
nonLocalInstanceNodeIX = 1;
} else
{
nonLocalInstanceNodeIX = 0;
}
// Find the name of the module being instantiated
String instanceModuleName = instanceHeirs[nonLocalInstanceNodeIX].heirs()[1].getImage();
// if this is the module name we are searching for, then if it
// corresponds to an inner module defined earlier, then return
// true; else return false.
if (instanceModuleName.equals(instanceeName))
{
return internalModulesSeen.contains(instanceeName);
} // end if
} // end if
// if we encounter a module definition (i.e. D(x,y) == INSTANCE
// Modname WITH ...) that counts as an instance also
else if (def.getImage().equals("N_ModuleDefinition"))
{
TreeNode[] instanceHeirs = def.heirs();
int nonLocalInstanceNodeIX;
// The modifier "LOCAL" may or may not appear in the syntax tree;
// if so, offset by 1
if (instanceHeirs[0].getImage().equals("LOCAL"))
{
nonLocalInstanceNodeIX = 3;
} else
{
nonLocalInstanceNodeIX = 2;
}
// Find the name of the module being instantiated
String instanceModuleName = instanceHeirs[nonLocalInstanceNodeIX].heirs()[1].getImage();
// if this is the module name we are searching for, then if it
// corresponds to an inner module defined earlier, then return
// true; else return false.
if (instanceModuleName.equals(instanceeName))
{
return internalModulesSeen.contains(instanceeName);
} // end if
} // end else
} // end for
return false;
} // end instanceResolvesToInternalModule()
// Traverse the tree of module relationships recursively to find a
// name in an INSTANCE decl that is as yet unresolved, if any, and
// set "nextParseUnit" to its name. Return false iff there are no
// more unresolved INSTANCES names in the entire specification.
private boolean findNextUnresolvedInstantiationBody(ModulePointer currentModule, HashSet alreadyVisited)
{
if (alreadyVisited.contains(currentModule))
{
instantiationFound = false;
return false;
}
alreadyVisited.add(currentModule);
ModuleContext currentContext = currentModule.getContext();
Vector extendees = currentModule.getNamesOfModulesExtended();
Vector instancees = currentModule.getNamesOfModulesInstantiated();
// for all of the modules named as instancees of the current
// module, but which may or not be resolved yet.
for (int i = 0; i < instancees.size(); i++)
{
// if one of them is unresolved
if (currentContext.resolve((String) instancees.elementAt(i)) == null)
{
// See if it can be resolved WITHIN the module in which the
// INSTANCE stmt occurs, i.e. does it resolve to an inner
// module declared above this INSTANCE stmt? Nothing in the
// logic so far covers this (most common) case, so we have to
// insert logic here to check now.
if (!instanceResolvesToInternalModule(currentModule, (String) instancees.elementAt(i)))
{
// then it is the next unresolved instantiation; return it
nextParseUnitName = (String) instancees.elementAt(i);
nextExtenderOrInstancerModule = currentModule;
instantiationFound = true;
return true;
}
}
}
// See if one of the already-resolved extendees has any
// unresolved instantiations
for (int i = 0; i < extendees.size(); i++)
{
// by recursive invocation of this method on the extendees
if (findNextUnresolvedInstantiationBody(currentContext.resolve((String) extendees.elementAt(i)),
alreadyVisited))
{
instantiationFound = true;
return true;
}
}
// See if one of the already-resolved instancees of currentModule
// has any unresolved extentions.
for (int i = 0; i < instancees.size(); i++)
{
// if this instancee has been resolved
if (currentContext.resolve((String) instancees.elementAt(i)) != null)
{
if (findNextUnresolvedInstantiationBody(currentContext.resolve((String) instancees.elementAt(i)),
alreadyVisited))
{
instantiationFound = true;
return true;
}
}
}
// Finally, see if any of "currentModule"'s inner modules (or any
// they extend) have any unresolved instantiations by invoking
// this method recursively on them.
Vector innerModules = currentModule.getDirectInnerModules();
for (int i = 0; i < innerModules.size(); i++)
{
if (findNextUnresolvedInstantiationBody((ModulePointer) innerModules.elementAt(i), alreadyVisited))
{
instantiationFound = true;
return true;
}
}
// Iff there are no unresolved Instantiation module names,
// we return false
instantiationFound = false;
return false;
}
// Returns true iff mod1 is known to directly extend mod2
private boolean directlyExtends(ModulePointer mod1, ModulePointer mod2)
{
ModuleRelatives mod1Rels = mod1.getRelatives();
Vector extendees = mod1Rels.directlyExtendedModuleNames;
ModuleContext mod1Context = mod1Rels.context;
for (int i = 0; i < extendees.size(); i++)
{
if (mod1Context.resolve((String) extendees.elementAt(i)) == mod2)
return true;
}
;
return false;
}
// Returns a Vector of all modules and submodules in the spec so far
// that directly or indirectly extend "module", including "module"
// itself. This method is horribly inefficient when there are a
// large number of modules, looping as it does through ALL modules;
// it must be rewritten recursively!!
private Vector getModulesIndirectlyExtending(ModulePointer module)
{
// The Vector of Modules that equals, or directly or indirectly
// extends, "module"
Vector extenders = new Vector();
extenders.addElement(module);
// initializations for the following nested loop
boolean additions = true;
int lastAdditionsStart = 0;
int lastAdditionsEnd = extenders.size();
// while there were more additions to the Vector of modules
// indirectly extending "module"
while (additions)
{
additions = false;
// for all newly added modules, see if there are any others that
// extend them
for (int i = lastAdditionsStart; i < lastAdditionsEnd; i++)
{
// Check ALL modules in the entire specification (!) to see if
// they extend the i'th element of the vector
Enumeration enumModules = getModules();
while (enumModules.hasMoreElements())
{
ModulePointer modPointer = (ModulePointer) enumModules.nextElement();
if (directlyExtends(modPointer, (ModulePointer) extenders.elementAt(i)))
{
if (!additions)
lastAdditionsStart = lastAdditionsEnd;
extenders.addElement(modPointer);
additions = true;
}
}
lastAdditionsStart = lastAdditionsEnd;
lastAdditionsEnd = extenders.size();
}
}
return extenders;
}
// This modules binds the name used in an INSTANCE definition in
// module "instancer" to the top-level module in ParseUnit instancee
private void resolveNamesBetweenSpecAndInstantiation(ModulePointer instancer, ParseUnit instancee)
{
// Bind the name of the instancee in the instancer's context
ModuleContext instancerContext = instancer.getRelatives().context;
instancerContext.bindIfNotBound(instancee.getName(), instancee.getRootModule());
}
// This method adds names to various module contexts (the context of
// "extender" and any modules that extend it) that come from the
// top-level inner modules in a ParseUnit (extendee) which is
// extended by "extender". For any module "extender", and any
// module xx that extends "extender", directly or indirectly, we
// must resolve module names in xx to top level internal modules in
// extendeeParseUnit
private void resolveNamesBetweenSpecAndExtention(ModulePointer extender, ParseUnit extendee)
{
// First, bind the name of the extendee in the extender's context
ModuleContext extenderContext = extender.getRelatives().context;
extenderContext.bindIfNotBound(extendee.getName(), extendee.getRootModule());
// Vextor of ModulePointers for modules that either are
// "extender", or extend "extender" directly, of extend it
// indirectly.
Vector modulesIndirectlyExtending = getModulesIndirectlyExtending(extender);
for (int i = 0; i < modulesIndirectlyExtending.size(); i++)
{
resolveNamesBetweenModuleAndExtention((ModulePointer) modulesIndirectlyExtending.elementAt(i), extendee);
}
}
// Add all of the top level inner modules of extendeeParseUnit to
// the contexts of extenderModule by doing appropriate bindings, and
// do the same for all of extenderModule's submodules
private void resolveNamesBetweenModuleAndExtention(ModulePointer extenderModule, ParseUnit extendeeParseUnit)
{
ModuleRelatives extenderRelatives = extenderModule.getRelatives();
ModuleContext extenderContext = extenderRelatives.context;
Vector instantiatedNames = extenderRelatives.directlyInstantiatedModuleNames;
Vector extendedNames = extenderRelatives.directlyExtendedModuleNames;
// find all unresolved names in extenderModule and its submodules
// and see if they can be resolved in extendeeParseUnit
// for each module name extended by extenderModule, try to resolve
// it in the module it extends
for (int i = 0; i < extendedNames.size(); i++)
{
String extendedName = (String) extendedNames.elementAt(i);
// Pick up vector of top level inner modules of extendeeParseUnit
Vector extendeeInnerModules = extendeeParseUnit.getRootModule().getDirectInnerModules();
// See if the name occurs among the direct inner modules of extendee
for (int j = 0; j < extendeeInnerModules.size(); j++)
{
ModulePointer extendeeInnerModule = ((ModulePointer) extendeeInnerModules.elementAt(j));
String extendeeInnerName = extendeeInnerModule.getName();
// if we have a match...
if (extendedName.equals(extendeeInnerName))
{
// bind the name to the inner module of extendee in the
// context of the extender iff it is unbound before this
extenderContext.bindIfNotBound(extendedName, extendeeInnerModule);
// and move on to the next instanceName
break;
} // end if
} // end for j
} // end for i
// for each module name instantiated at the top level of
// extenderModule, try to resolve it in the module it extends
for (int i = 0; i < instantiatedNames.size(); i++)
{
String instanceName = (String) instantiatedNames.elementAt(i);
// Pick up vector of top level inner modules of extendeeParseUnit
Vector extendeeInnerModules = extendeeParseUnit.getRootModule().getDirectInnerModules();
// See if the name occurs among the direct inner modules of extendee
for (int j = 0; j < extendeeInnerModules.size(); j++)
{
ModulePointer extendeeInnerModule = ((ModulePointer) extendeeInnerModules.elementAt(j));
String extendeeInnerName = extendeeInnerModule.getName();
// if we have a match...
if (instanceName.equals(extendeeInnerName))
{
// bind the name to the inner module of extendee in the
// context of the extender iff it is unbound before this
extenderContext.bindIfNotBound(instanceName, extendeeInnerModule);
// and move on to the next instanceName
break;
} // end if
} // end for j
} // end for i
// Now, for each inner module (recursively) of the extender
// modules, try to resolve ITS unresolved module names in the same
// extendee ParseUnit.
Vector extenderInnerModules = extenderRelatives.directInnerModules;
for (int i = 0; i < extenderInnerModules.size(); i++)
{
ModulePointer nextInner = (ModulePointer) extenderInnerModules.elementAt(i);
resolveNamesBetweenModuleAndExtention(nextInner, extendeeParseUnit);
}
}
/**
* This method "loads" an entire specification, starting with the
* top-level rootExternalModule and followed by all of the external
* modules it references via EXTENDS and INSTANCE statements.
*/
public boolean loadSpec(String rootExternalModuleName, Errors errors) throws AbortException
{
// If rootExternalModuleName" has *not* already been parsed, then
// go to the file system and find the file containing it, create a
// ParseUnit for it, and parse it. Parsing includes determining
// module relationships. Aborts if not found in file system
rootParseUnit = findOrCreateParsedUnit(rootExternalModuleName, errors, true /* first call */);
rootModule = rootParseUnit.getRootModule();
// Retrieve and parse all module extentions: As long as there is
// another unresolved module name...
// 0. Find the ParseUnit in corresponding to the name; go to the
// file system to find it and parse it if necessary. Not its
// relationship with other ParseUnits
// 1. Verify that next unresolved module is not a circular
// dependency among ParseUnits.
// 2. Read, parse, and analyze module relationships for next
// unresolved module name, and create a ParseUnit for it.
// 3. Integrate the ModuleRelationships information from the new
// ParseUnit into that for this entire SpecObj
// 4. Select the next unresolved module name for processing.
ParseUnit nextExtentionOrInstantiationParseUnit = null;
while (findNextUnresolvedExtention(rootModule) || findNextUnresolvedInstantiation(rootModule))
{
// nextParseUnitName has not already been processed through some
// other path,
if (parseUnitContext.get(nextParseUnitName) == null)
{
// find it in the file system (if there) and parse and analyze it.
nextExtentionOrInstantiationParseUnit = findOrCreateParsedUnit(nextParseUnitName, errors, false /* not first call */);
} else
{
// or find it in the known parseUnitContext
nextExtentionOrInstantiationParseUnit = (ParseUnit) parseUnitContext.get(nextParseUnitName);
}
// Record that extenderOrInstancerParseUnit EXTENDs or INSTANCEs
// nextExtentionOrInstantiationParseUnit, and that
// nextExtentionOrInstantiationParseUnit is extended or
// instanced by extenderOrInstancerParseUnit.
ParseUnit extenderOrInstancerParseUnit = nextExtenderOrInstancerModule.getParseUnit();
if (extentionFound)
{
extenderOrInstancerParseUnit.addExtendee(nextExtentionOrInstantiationParseUnit);
nextExtentionOrInstantiationParseUnit.addExtendedBy(extenderOrInstancerParseUnit);
}
if (instantiationFound)
{
extenderOrInstancerParseUnit.addInstancee(nextExtentionOrInstantiationParseUnit);
nextExtentionOrInstantiationParseUnit.addInstancedBy(extenderOrInstancerParseUnit);
}
// Check for circular references among parseUnits; abort if found
nonCircularityTest(nextExtentionOrInstantiationParseUnit, errors);
// If this ParseUnit is loaded because of an EXTENDS decl, then
// it may have inner modules that are the resolvants for
// unresolved module names in the nextExtenderOrInstancerModule;
// resolve the ones that are possible
if (extentionFound)
{
resolveNamesBetweenSpecAndExtention(nextExtenderOrInstancerModule,
nextExtentionOrInstantiationParseUnit);
}
// If this ParseUnit is loaded because of an INSTANCE stmt, then
// the outer module of the ParseUnit is the resolution of the
// previously unresolved instantiation.
if (instantiationFound)
{
resolveNamesBetweenSpecAndInstantiation(nextExtenderOrInstancerModule,
nextExtentionOrInstantiationParseUnit);
}
} // end while
// Walk the moduleRelationshipsSpec graph to set up
// semanticAnalysisVector; this vector determines the order in
// which semantic analysis is done on parseUnits
calculateDependencies(rootParseUnit);
return true;
// loadUnresolvedRelatives(moduleRelationshipsSpec, rootModule, errors);
}
} |
package tlc2.tool.distributed;
import java.io.File;
import java.io.IOException;
import tlc2.TLCGlobals;
import tlc2.tool.Action;
import tlc2.tool.StateVec;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateInfo;
import tlc2.tool.Tool;
import tlc2.tool.WorkerException;
import tlc2.util.FP64;
import tlc2.value.Value;
import util.FileUtil;
import util.FilenameToStream;
import util.ToolIO;
import util.UniqueString;
/**
* @version $Id$
*/
public class TLCApp extends DistApp {
private String config;
/* Constructors */
public TLCApp(String specFile, String configFile, boolean deadlock,
String fromChkpt, int fpBits) throws IOException {
this(specFile, configFile, deadlock, true, null, fpBits);
this.fromChkpt = fromChkpt;
this.metadir = FileUtil.makeMetaDir(this.tool.specDir, fromChkpt);
}
// TODO too many constructors redefinitions, replace with this(..) calls
public TLCApp(String specFile, String configFile,
Boolean deadlock, Boolean preprocess, FilenameToStream fts, int fpBits) throws IOException {
// get the spec dir from the spec file
int lastSep = specFile.lastIndexOf(File.separatorChar);
String specDir = (lastSep == -1) ? "" : specFile.substring(0,
lastSep + 1);
specFile = specFile.substring(lastSep + 1);
this.config = configFile;
// TODO NameResolver
this.tool = new Tool(specDir, specFile, configFile, fts);
// SZ Feb 24, 2009: setup the user directory
ToolIO.setUserDir(specDir);
this.checkDeadlock = deadlock.booleanValue();
this.preprocess = preprocess.booleanValue();
// SZ Feb 20, 2009: added null reference to SpecObj
this.tool.init(this.preprocess, null);
this.impliedInits = this.tool.getImpliedInits();
this.invariants = this.tool.getInvariants();
this.impliedActions = this.tool.getImpliedActions();
this.actions = this.tool.getActions();
this.fpBits = fpBits;
}
/* Fields */
public Tool tool;
public Action[] invariants; // the invariants to be checked
public Action[] impliedInits; // the implied-inits to be checked
public Action[] impliedActions; // the implied-actions to be checked
public Action[] actions; // the subactions
private boolean checkDeadlock; // check deadlock?
private boolean preprocess; // preprocess?
private String fromChkpt = null; // recover from this checkpoint
private String metadir = null; // the directory pathname for metadata
private int fpBits = -1;
/**
* Statistics how many states this app computed
*/
private long statesComputed = 0L;
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getCheckDeadlock()
*/
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getCheckDeadlock()
*/
public final Boolean getCheckDeadlock() {
return new Boolean(this.checkDeadlock);
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getPreprocess()
*/
public final Boolean getPreprocess() {
return new Boolean(this.preprocess);
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getFileName()
*/
public final String getFileName() {
return this.tool.rootFile;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getSpecDir()
*/
public String getSpecDir() {
return this.tool.specDir;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getConfigName()
*/
public String getConfigName() {
return this.config;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getMetadir()
*/
public final String getMetadir() {
return this.metadir;
}
public final int getFPBits() {
return fpBits;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#canRecover()
*/
public final boolean canRecover() {
return this.fromChkpt != null;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getInitStates()
*/
public final TLCState[] getInitStates() throws WorkerException {
StateVec theInitStates = this.tool.getInitStates();
TLCState[] res = new TLCState[theInitStates.size()];
for (int i = 0; i < theInitStates.size(); i++) {
TLCState curState = theInitStates.elementAt(i);
if (!this.tool.isGoodState(curState)) {
String msg = "Error: Initial state is not completely specified by the"
+ " initial predicate.";
throw new WorkerException(msg, curState, null, false);
}
res[i] = (TLCState) curState;
}
statesComputed += res.length;
return res;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getNextStates(tlc2.tool.TLCState)
*/
public final TLCState[] getNextStates(TLCState curState)
throws WorkerException {
StateVec nextStates = new StateVec(10);
for (int i = 0; i < this.actions.length; i++) {
Action curAction = this.actions[i];
StateVec nstates = this.tool.getNextStates(curAction,
(TLCState) curState);
nextStates = nextStates.addElements(nstates);
}
int len = nextStates.size();
if (len == 0 && this.checkDeadlock) {
throw new WorkerException("Error: deadlock reached.", curState,
null, false);
}
TLCState[] res = new TLCState[nextStates.size()];
for (int i = 0; i < nextStates.size(); i++) {
TLCState succState = nextStates.elementAt(i);
if (!this.tool.isGoodState(succState)) {
String msg = "Error: Successor state is not completely specified by"
+ " the next-state action.";
throw new WorkerException(msg, curState, succState, false);
}
res[i] = succState;
}
statesComputed += res.length;
return res;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#checkState(tlc2.tool.TLCState, tlc2.tool.TLCState)
*/
public final void checkState(TLCState s1, TLCState s2)
throws WorkerException {
TLCState ts2 = (TLCState) s2;
for (int i = 0; i < this.invariants.length; i++) {
if (!tool.isValid(this.invariants[i], ts2)) {
// We get here because of invariant violation:
String msg = "Error: Invariant " + this.tool.getInvNames()[i]
+ " is violated.";
throw new WorkerException(msg, s1, s2, false);
}
}
if (s1 == null) {
for (int i = 0; i < this.impliedInits.length; i++) {
if (!this.tool.isValid(this.impliedInits[i], ts2)) {
// We get here because of implied-inits violation:
String msg = "Error: Implied-init "
+ this.tool.getImpliedInitNames()[i]
+ " is violated.";
throw new WorkerException(msg, s1, s2, false);
}
}
} else {
TLCState ts1 = (TLCState) s1;
for (int i = 0; i < this.impliedActions.length; i++) {
if (!tool.isValid(this.impliedActions[i], ts1, ts2)) {
// We get here because of implied-action violation:
String msg = "Error: Implied-action "
+ this.tool.getImpliedActNames()[i]
+ " is violated.";
throw new WorkerException(msg, s1, s2, false);
}
}
}
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#isInModel(tlc2.tool.TLCState)
*/
public final boolean isInModel(TLCState s) {
return this.tool.isInModel((TLCState) s);
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#isInActions(tlc2.tool.TLCState, tlc2.tool.TLCState)
*/
public final boolean isInActions(TLCState s1, TLCState s2) {
return this.tool.isInActions((TLCState) s1, (TLCState) s2);
}
/* Reconstruct the initial state whose fingerprint is fp. */
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getState(long)
*/
public final TLCStateInfo getState(long fp) {
return this.tool.getState(fp);
}
/* Reconstruct the next state of state s whose fingerprint is fp. */
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getState(long, tlc2.tool.TLCState)
*/
public final TLCStateInfo getState(long fp, TLCState s) {
return this.tool.getState(fp, s);
}
/* Reconstruct the info for the transition from s to s1. */
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getState(tlc2.tool.TLCState, tlc2.tool.TLCState)
*/
public TLCStateInfo getState(TLCState s1, TLCState s) {
return this.tool.getState(s1, s);
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getStatesComputed()
*/
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#getStatesComputed()
*/
public long getStatesComputed() {
return statesComputed;
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#setCallStack()
*/
public final void setCallStack() {
this.tool.setCallStack();
}
/* (non-Javadoc)
* @see tlc2.tool.distributed.DistApp#printCallStack()
*/
public final String printCallStack() {
// SZ Jul 10, 2009: check if this is ok
// changed the method signature
return this.tool.getCallStack().toString();
}
public static TLCApp create(String args[]) throws IOException {
String specFile = null;
String configFile = null;
boolean deadlock = true;
int fpIndex = 0;
int fpBits = 0;
String fromChkpt = null;
int index = 0;
while (index < args.length) {
if (args[index].equals("-config")) {
index++;
if (index < args.length) {
configFile = args[index];
int len = configFile.length();
if (configFile.startsWith(".cfg", len - 4)) {
configFile = configFile.substring(0, len - 4);
}
index++;
} else {
printErrorMsg("Error: configuration file required.");
return null;
}
} else if (args[index].equals("-tool")) {
index++;
TLCGlobals.tool = true;
} else if (args[index].equals("-deadlock")) {
index++;
deadlock = false;
} else if (args[index].equals("-recover")) {
index++;
if (index < args.length) {
fromChkpt = args[index++] + FileUtil.separator;
} else {
printErrorMsg("Error: need to specify the metadata directory for recovery.");
return null;
}
} else if (args[index].equals("-checkpoint")) {
index++;
if (index < args.length) {
try {
TLCGlobals.chkptDuration = Integer.parseInt(args[index]) * 1000 * 60;
if (TLCGlobals.chkptDuration < 0) {
printErrorMsg("Error: expect a nonnegative integer for -checkpoint option.");
}
index++;
} catch (Exception e) {
printErrorMsg("Error: An integer for checkpoint interval is required. But encountered "
+ args[index]);
}
} else {
printErrorMsg("Error: checkpoint interval required.");
}
} else if (args[index].equals("-coverage")) {
index++;
if (index < args.length) {
try {
TLCGlobals.coverageInterval = Integer
.parseInt(args[index]) * 1000;
if (TLCGlobals.coverageInterval < 0) {
printErrorMsg("Error: expect a nonnegative integer for -coverage option.");
return null;
}
index++;
} catch (Exception e) {
printErrorMsg("Error: An integer for coverage report interval required."
+ " But encountered " + args[index]);
return null;
}
} else {
printErrorMsg("Error: coverage report interval required.");
return null;
}
} else if (args[index].equals("-terse")) {
index++;
Value.expand = false;
} else if (args[index].equals("-nowarning")) {
index++;
TLCGlobals.warn = false;
} else if (args[index].equals("-fp")) {
index++;
if (index < args.length) {
try {
fpIndex = Integer.parseInt(args[index]);
if (fpIndex < 0 || fpIndex >= FP64.Polys.length) {
printErrorMsg("Error: The number for -fp must be between 0 and "
+ (FP64.Polys.length - 1) + " (inclusive).");
return null;
}
index++;
} catch (Exception e) {
printErrorMsg("Error: A number for -fp is required. But encountered "
+ args[index]);
return null;
}
} else {
printErrorMsg("Error: expect an integer for -workers option.");
return null;
}
} else if (args[index].equals("-fpbits")) {
index++;
if (index < args.length) {
try {
fpBits = Integer.parseInt(args[index]);
index++;
} catch (Exception e) {
printErrorMsg("Error: A number for -fpbits is required. But encountered "
+ args[index]);
return null;
}
} else {
printErrorMsg("Error: expect an integer for -workers option.");
return null;
}
} else if (args[index].equals("-metadir")) {
index++;
if (index < args.length)
{
TLCGlobals.metaDir = args[index++] + FileUtil.separator;
} else {
printErrorMsg("Error: need to specify the metadata directory.");
return null;
}
} else {
if (args[index].charAt(0) == '-') {
printErrorMsg("Error: unrecognized option: " + args[index]);
return null;
}
if (specFile != null) {
printErrorMsg("Error: more than one input files: "
+ specFile + " and " + args[index]);
return null;
}
specFile = args[index++];
int len = specFile.length();
if (specFile.startsWith(".tla", len - 4)) {
specFile = specFile.substring(0, len - 4);
}
}
}
if (specFile == null) {
printErrorMsg("Error: Missing input TLA+ module.");
return null;
}
if (configFile == null)
configFile = specFile;
if (fromChkpt != null) {
// We must recover the intern table as early as possible
UniqueString.internTbl.recover(fromChkpt);
}
FP64.Init(fpIndex);
return new TLCApp(specFile, configFile, deadlock, fromChkpt, fpBits);
}
private static void printErrorMsg(String msg) {
ToolIO.out.println(msg);
ToolIO.out
.println("Usage: java tlc2.tool.TLCServer [-option] inputfile");
}
} |
package algorithms.imageProcessing;
import algorithms.MultiArrayMergeSort;
import algorithms.compGeometry.clustering.KMeansPlusPlus;
import algorithms.imageProcessing.util.MatrixUtil;
import algorithms.misc.Histogram;
import algorithms.misc.HistogramHolder;
import algorithms.misc.MiscMath;
import algorithms.util.PairIntArray;
import algorithms.util.PolygonAndPointPlotter;
import algorithms.util.Errors;
import algorithms.util.PairInt;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ejml.simple.SimpleMatrix;
/**
*
* @author nichole
*/
public class ImageProcesser {
protected Logger log = Logger.getLogger(this.getClass().getName());
public void applySobelKernel(Image input) {
IKernel kernel = new SobelX();
Kernel kernelX = kernel.getKernel();
float normX = kernel.getNormalizationFactor();
kernel = new SobelY();
Kernel kernelY = kernel.getKernel();
float normY = kernel.getNormalizationFactor();
applyKernels(input, kernelX, kernelY, normX, normY);
}
public void applySobelKernel(GreyscaleImage input) {
IKernel kernel = new SobelX();
Kernel kernelX = kernel.getKernel();
float normX = kernel.getNormalizationFactor();
kernel = new SobelY();
Kernel kernelY = kernel.getKernel();
float normY = kernel.getNormalizationFactor();
applyKernels(input, kernelX, kernelY, normX, normY);
}
protected void applyKernels(Image input, Kernel kernelX, Kernel kernelY,
float normFactorX, float normFactorY) {
/*
assumes that kernelX is applied to a copy of the img
and kernelY is applied to a separate copy of the img and
then they are added in quadrature for the final result.
*/
Image imgX = input.copyImage();
Image imgY = input.copyImage();
applyKernel(imgX, kernelX, normFactorX);
applyKernel(imgY, kernelY, normFactorY);
Image img2 = combineConvolvedImages(imgX, imgY);
input.resetTo(img2);
}
protected void applyKernels(GreyscaleImage input, Kernel kernelX, Kernel kernelY,
float normFactorX, float normFactorY) {
/*
assumes that kernelX is applied to a copy of the img
and kernelY is applied to a separate copy of the img and
then they are added in quadrature for the final result.
*/
GreyscaleImage imgX = input.copyImage();
GreyscaleImage imgY = input.copyImage();
applyKernel(imgX, kernelX, normFactorX);
applyKernel(imgY, kernelY, normFactorY);
GreyscaleImage img2 = combineConvolvedImages(imgX, imgY);
input.resetTo(img2);
}
public Image combineConvolvedImages(Image imageX, Image imageY) {
Image img2 = new Image(imageX.getWidth(), imageX.getHeight());
for (int i = 0; i < imageX.getWidth(); i++) {
for (int j = 0; j < imageX.getHeight(); j++) {
int rX = imageX.getR(i, j);
int gX = imageX.getG(i, j);
int bX = imageX.getB(i, j);
int rY = imageY.getR(i, j);
int gY = imageY.getG(i, j);
int bY = imageY.getB(i, j);
double r = Math.sqrt(rX*rX + rY*rY);
double g = Math.sqrt(gX*gX + gY*gY);
double b = Math.sqrt(bX*bX + bY*bY);
r = (r > 255) ? 255 : r;
g = (g > 255) ? 255 : g;
b = (b > 255) ? 255 : b;
//int rgb = (int)(((rSum & 0x0ff) << 16)
// | ((gSum & 0x0ff) << 8) | (bSum & 0x0ff));
img2.setRGB(i, j, (int)r, (int)g, (int)b);
}
}
return img2;
}
/**
* process only the green channel and set red and blue to zero
* @param imageX
* @param imageY
* @return
*/
public GreyscaleImage combineConvolvedImages(final GreyscaleImage imageX,
final GreyscaleImage imageY) {
GreyscaleImage img2 = imageX.createWithDimensions();
for (int i = 0; i < imageX.getWidth(); i++) {
for (int j = 0; j < imageX.getHeight(); j++) {
int gX = imageX.getValue(i, j);
int gY = imageY.getValue(i, j);
//double g = Math.sqrt(0.5*(gX*gX + gY*gY));
//g = (g > 255) ? 255 : g;
double g = Math.sqrt(gX*gX + gY*gY);
if (g > 255) {
g = 255;
}
//int rgb = (int)(((rSum & 0x0ff) << 16)
// | ((gSum & 0x0ff) << 8) | (bSum & 0x0ff));
img2.setValue(i, j, (int)g);
}
}
return img2;
}
/**
* apply kernel to input. NOTE, that because the image is composed of
* vectors that should have values between 0 and 255, inclusive, if the
* kernel application results in a value outside of that range, the value
* is reset to 0 or 255.
* @param input
* @param kernel
* @param normFactor
*/
protected void applyKernel(Image input, Kernel kernel, float normFactor) {
int h = (kernel.getWidth() - 1) >> 1;
Image output = new Image(input.getWidth(), input.getHeight());
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
long rValue = 0;
long gValue = 0;
long bValue = 0;
// apply the kernel to pixels centered in (i, j)
for (int col = 0; col < kernel.getWidth(); col++) {
int x = col - h;
int imgX = i + x;
// edge corrections. use replication
if (imgX < 0) {
imgX = -1 * imgX - 1;
} else if (imgX >= input.getWidth()) {
int diff = imgX - input.getWidth();
imgX = input.getWidth() - diff - 1;
}
for (int row = 0; row < kernel.getHeight(); row++) {
int y = row - h;
int imgY = j + y;
// edge corrections. use replication
if (imgY < 0) {
imgY = -1 * imgY - 1;
} else if (imgY >= input.getHeight()) {
int diff = imgY - input.getHeight();
imgY = input.getHeight() - diff - 1;
}
int rPixel = input.getR(imgX, imgY);
int gPixel = input.getG(imgX, imgY);
int bPixel = input.getB(imgX, imgY);
int k = kernel.getValue(col, row);
rValue += k * rPixel;
gValue += k * gPixel;
bValue += k * bPixel;
}
}
rValue *= normFactor;
gValue *= normFactor;
bValue *= normFactor;
if (rValue < 0) {
rValue = 0;
}
if (rValue > 255) {
rValue = 255;
}
if (gValue < 0) {
gValue = 0;
}
if (gValue > 255) {
gValue = 255;
}
if (bValue < 0) {
bValue = 0;
}
if (bValue > 255) {
bValue = 255;
}
output.setRGB(i, j, (int)rValue, (int)gValue, (int)bValue);
}
}
input.resetTo(output);
}
/**
* apply kernel to input. NOTE, that because the image is composed of vectors
* that should have values between 0 and 255, inclusive, if the kernel application
* results in a value outside of that range, the value is reset to 0 or
* 255.
* @param input
* @param kernel
* @param normFactor
*/
protected void applyKernel(GreyscaleImage input, Kernel kernel, float normFactor) {
int h = (kernel.getWidth() - 1) >> 1;
GreyscaleImage output = input.createWithDimensions();
//TODO: consider changing normalization to be similar to Kernel1DHelper
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
long value = 0;
// apply the kernel to pixels centered in (i, j)
for (int col = 0; col < kernel.getWidth(); col++) {
int x = col - h;
int imgX = i + x;
// edge corrections. use replication
if (imgX < 0) {
imgX = -1 * imgX - 1;
} else if (imgX >= input.getWidth()) {
int diff = imgX - input.getWidth();
imgX = input.getWidth() - diff - 1;
}
for (int row = 0; row < kernel.getHeight(); row++) {
int y = row - h;
int imgY = j + y;
// edge corrections. use replication
if (imgY < 0) {
imgY = -1 * imgY - 1;
} else if (imgY >= input.getHeight()) {
int diff = imgY - input.getHeight();
imgY = input.getHeight() - diff - 1;
}
int pixel = input.getValue(imgX, imgY);
int k = kernel.getValue(col, row);
value += k * pixel;
}
}
value *= normFactor;
if (value < 0) {
value = 0;
}
if (value > 255) {
value = 255;
}
output.setValue(i, j, (int)value);
}
}
input.resetTo(output);
}
public Image computeTheta(Image convolvedX, Image convolvedY) {
Image output = new Image(convolvedX.getWidth(), convolvedX.getHeight());
for (int i = 0; i < convolvedX.getWidth(); i++) {
for (int j = 0; j < convolvedX.getHeight(); j++) {
double rX = convolvedX.getR(i, j);
double gX = convolvedX.getG(i, j);
double bX = convolvedX.getB(i, j);
double rY = convolvedY.getR(i, j);
double gY = convolvedY.getG(i, j);
double bY = convolvedY.getB(i, j);
int thetaR = calculateTheta(rX, rY);
int thetaG = calculateTheta(gX, gY);
int thetaB = calculateTheta(bX, bY);
output.setRGB(i, j, thetaR, thetaG, thetaB);
}
}
return output;
}
public GreyscaleImage computeTheta(final GreyscaleImage convolvedX,
final GreyscaleImage convolvedY) {
GreyscaleImage output = convolvedX.createWithDimensions();
for (int i = 0; i < convolvedX.getWidth(); i++) {
for (int j = 0; j < convolvedX.getHeight(); j++) {
double gX = convolvedX.getValue(i, j);
double gY = convolvedY.getValue(i, j);
int thetaG = calculateTheta(gX, gY);
output.setValue(i, j, thetaG);
}
}
return output;
}
public GreyscaleImage subtractImages(final GreyscaleImage image,
final GreyscaleImage subtrImage) {
if (image.getWidth() != subtrImage.getWidth()) {
throw new IllegalArgumentException("image widths must be the same");
}
if (image.getHeight() != subtrImage.getHeight()) {
throw new IllegalArgumentException("image heights must be the same");
}
GreyscaleImage output = image.createWithDimensions();
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int diff = image.getValue(i, j) - subtrImage.getValue(i, j);
output.setValue(i, j, diff);
}
}
return output;
}
protected int calculateTheta(double gradientX, double gradientY) {
if (gradientX == 0 && (gradientY != 0)) {
return 90;
}
if (gradientY == 0) {
return 0;
}
double div = gradientY/gradientX;
double theta = Math.atan(div)*180./Math.PI;
int angle = (int)theta;
// +x, +y -> +
// -x, +y -> -
// -x, -y -> +
// +x, -y -> -
if (!(gradientX < 0) && !(gradientY < 0)) {
if (angle < 0) {
// make it positive if negative
angle *= -1;
}
} else if ((gradientX < 0) && !(gradientY < 0)) {
if (!(angle < 0)) {
// make it negative if it's not
angle *= -1;
}
} else if ((gradientX < 0) && (gradientY < 0)) {
if (angle < 0) {
// make it positive if negative
angle *= -1;
}
} else if (!(gradientX < 0) && (gradientY < 0)) {
if (!(angle < 0)) {
// make it negative if it's not
angle *= -1;
}
}
return angle;
}
/**
* images bounded by zero's have to be shrunk to the columns and rows
* of the first non-zeroes in order to keep the lines that should be
* attached to the image edges from eroding completely.
*
* @param input
* @return
*/
public int[] shrinkImageToFirstNonZeros(final GreyscaleImage input) {
int xNZFirst = -1;
int xNZLast = -1;
int yNZFirst = -1;
int yNZLast = -1;
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
xNZFirst = i;
break;
}
}
if (xNZFirst > -1) {
break;
}
}
for (int j = 0; j < input.getHeight(); j++) {
for (int i = 0; i < input.getWidth(); i++) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
yNZFirst = j;
break;
}
}
if (yNZFirst > -1) {
break;
}
}
for (int i = (input.getWidth() - 1); i > -1; i
for (int j = (input.getHeight() - 1); j > -1; j
if (input.getValue(i, j) > 0) {
xNZLast = i;
break;
}
}
if (xNZLast > -1) {
break;
}
}
for (int j = (input.getHeight() - 1); j > -1; j
for (int i = (input.getWidth() - 1); i > -1; i
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
yNZLast = j;
break;
}
}
if (yNZLast > -1) {
break;
}
}
if ((xNZFirst > 0) || (xNZLast < (input.getWidth() - 1))
|| (yNZFirst > 0) || (yNZLast < (input.getHeight() - 1))) {
//add a 2 pix border
xNZFirst -= 2;
yNZFirst -= 2;
if (xNZFirst < 0) {
xNZFirst = 0;
}
if (yNZFirst < 0) {
yNZFirst = 0;
}
if (xNZLast == -1) {
xNZLast = input.getWidth() - 1;
} else if (xNZLast < (input.getWidth() - 2)) {
// add a 1 pix border
xNZLast += 2;
} else if (xNZLast < (input.getWidth() - 1)) {
// add a 1 pix border
xNZLast++;
}
if (yNZLast == -1) {
yNZLast = input.getHeight() - 1;
} else if (yNZLast < (input.getHeight() - 2)) {
// add a 1 pix border
yNZLast += 2;
} else if (yNZLast < (input.getHeight() - 1)) {
// add a 1 pix border
yNZLast++;
}
int xLen = xNZLast - xNZFirst + 1;
int yLen = yNZLast - yNZFirst + 1;
GreyscaleImage output = new GreyscaleImage(xLen, yLen);
output.setXRelativeOffset(xNZFirst);
output.setYRelativeOffset(yNZFirst);
for (int i = xNZFirst; i <= xNZLast; i++) {
int iIdx = i - xNZFirst;
for (int j = yNZFirst; j <= yNZLast; j++) {
int jIdx = j - yNZFirst;
output.setValue(iIdx, jIdx, input.getValue(i, j));
}
}
input.resetTo(output);
return new int[]{xNZFirst, yNZFirst};
}
return new int[]{0, 0};
}
public void shrinkImage(final GreyscaleImage input,
int[] offsetsAndDimensions) {
//xOffset, yOffset, width, height
GreyscaleImage output = new GreyscaleImage(offsetsAndDimensions[2],
offsetsAndDimensions[3]);
output.setXRelativeOffset(offsetsAndDimensions[0]);
output.setYRelativeOffset(offsetsAndDimensions[1]);
int x = 0;
for (int col = offsetsAndDimensions[0]; col < offsetsAndDimensions[2];
col++) {
int y = 0;
for (int row = offsetsAndDimensions[1]; row < offsetsAndDimensions[3];
row++) {
int v = input.getValue(col, row);
output.setValue(x, y, v);
y++;
}
x++;
}
}
public void applyImageSegmentation(GreyscaleImage input, int kBands)
throws IOException, NoSuchAlgorithmException {
KMeansPlusPlus instance = new KMeansPlusPlus();
instance.computeMeans(kBands, input);
int[] binCenters = instance.getCenters();
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
for (int i = 0; i < binCenters.length; i++) {
int vc = binCenters[i];
int bisectorBelow = ((i - 1) > -1) ?
((binCenters[i - 1] + vc) / 2) : 0;
int bisectorAbove = ((i + 1) > (binCenters.length - 1)) ?
255 : ((binCenters[i + 1] + vc) / 2);
if ((v >= bisectorBelow) && (v <= bisectorAbove)) {
input.setValue(col, row, vc);
break;
}
}
}
}
}
public void convertToBinaryImage(GreyscaleImage input) {
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
if (v != 0) {
input.setValue(col, row, 1);
}
}
}
}
/**
* using the gradient's theta image, find the sky as the largest set of
* contiguous 0 values and apply the edge filter to it to reduce the
* boundary to a single pixel curve.
*
* NOTE that the theta image has a boundary that has been increased by
* the original image blur and then the difference of gaussians to make
* the gradient, so the distance of the skyline from the real image horizon
* is several pixels.
* For example, the canny edge filter used in "outdoorMode" results in
* gaussian kernels applied twice to give an effective sigma of
* sqrt(2*2 + 0.5*0.5) = 2.1. The FWHM of such a spread is then
* 2.355*2.1 = 6 pixels. The theta image skyline is probably blurred to a
* width larger than the combined FWHM, however, making it 7 or 8 pixels.
* Therefore, it's recommended that the image returned from this be followed
* with: edge extraction; then fit the edges to the intermediate canny edge
* filter product (the output of the 2 layer filter) by making a translation
* of the extracted skyline edge until the correlation with the filter2
* image is highest (should be within 10 pixel shift). Because this
* method does not assume orientation of the image, the invoker needs
* to also retrieve the centroid of the sky, so that is also returned
* in an output variable given in the arguments.
*
* @param theta
* @param originalImage
* @param outputSkyCentroid container to hold the output centroid of
* the sky.
* @param edgeSettings
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public GreyscaleImage createSkyline(GreyscaleImage theta,
Image originalImage,
CannyEdgeFilterSettings edgeSettings, PairIntArray outputSkyCentroid)
throws IOException, NoSuchAlgorithmException {
GreyscaleImage mask = createBestSkyMask(theta, originalImage,
edgeSettings, outputSkyCentroid);
if (mask != null) {
multiply(mask, 255);
CannyEdgeFilter filter = new CannyEdgeFilter();
filter.setFilterImageTrim(theta.getXRelativeOffset(),
theta.getYRelativeOffset(), theta.getWidth(),
theta.getHeight());
filter.applyFilter(mask);
return mask;
}
return null;
}
/**
* NOT READY FOR USE YET.
*
* @param theta
* @return
*/
public GreyscaleImage createRoughSkyMask(GreyscaleImage theta) throws
IOException, NoSuchAlgorithmException {
if (theta == null) {
throw new IllegalArgumentException("theta cannot be null");
}
theta = theta.copyImage();
applyImageSegmentation(theta, 2);
subtractMinimum(theta);
convertToBinaryImage(theta);
removeSpurs(theta);
throw new UnsupportedOperationException("not ready for use yet");
//return theta;
}
protected int determineBinFactorForSkyMask(int numberOfThetaPixels) {
//TODO: this can be adjusted by the jvm settings for stack size
int defaultLimit = 87000;
if (numberOfThetaPixels <= defaultLimit) {
return 1;
}
double a = (double)numberOfThetaPixels/87000.;
// rounds down
int f2 = (int)a/2;
int binFactor = f2 * 2;
if ((a - binFactor) > 0) {
binFactor += 2;
}
return binFactor;
}
/**
* NOT READY FOR USE
*
* create a mask for what is interpreted as sky in the image and return
* a mask with 0's for sky and 1's for non-sky.
*
* Internally, the method looks at contiguous regions of zero value pixels
* in the theta image and it looks at color in the original image.
* The camera image plane can have a rotation such that the
* horizon might not be along rows in the image, that is the method
* looks for sky that is not necessarily at the top of the image, but
* should be on the boundary of the image
* (note that reflection of sky can be found the same way, but this
* method does not try to find sky that is not on the boundary of the
* image).
* (the "boundary" logic may change, in progress...)
*
* Note that if the image contains a silhouette of featureless
* foreground and a sky full of clouds, the method will interpret the
* foreground as sky so it is up to the invoker to invert the mask.
*
* NOTE: the cloud finding logic will currently fail if originalColorImage
* is black and white.
*
* @param theta
* @param originalColorImage
* @param edgeSettings
* @param outputSkyCentroid container to hold the output centroid of
* the sky.
* @return
* @throws java.io.IOException
* @throws java.security.NoSuchAlgorithmException
*/
public GreyscaleImage createBestSkyMask(final GreyscaleImage theta,
Image originalColorImage, CannyEdgeFilterSettings edgeSettings,
PairIntArray outputSkyCentroid) throws
IOException, NoSuchAlgorithmException {
if (theta == null) {
throw new IllegalArgumentException("theta cannot be null");
}
GreyscaleImage thetaImg = theta;
int binFactor = determineBinFactorForSkyMask(theta.getNPixels());
if (binFactor > 1) {
thetaImg = binImage(theta, binFactor);
}
List<PairIntArray> zeroPointLists = getSortedContiguousZeros(thetaImg);
if (zeroPointLists.isEmpty()) {
GreyscaleImage mask = thetaImg.createWithDimensions();
// return an image of all 1's
mask.fill(1);
return mask;
}
if (binFactor > 1) {
thetaImg = theta;
zeroPointLists = unbinZeroPointLists(zeroPointLists, binFactor);
}
//TODO: this needs to be improved as soon as the rest of the
// algorithm is finished.
// currently not a robust way to determine that sky is horizontal
// or vertical and might not be correct for an angle not 90 degrees.
// probably needs equiv tranform for deconvolution of the image...
int xMin = MiscMath.findMin(zeroPointLists.get(0).getX());
int xMax = MiscMath.findMax(zeroPointLists.get(0).getX());
int yMin = MiscMath.findMin(zeroPointLists.get(0).getY());
int yMax = MiscMath.findMax(zeroPointLists.get(0).getY());
double xLen = (double)(xMax - xMin)/(double)theta.getWidth();
double yLen = (double)(yMax - yMin)/(double)theta.getHeight();
boolean makeCorrectionsAlongX = (xLen < yLen) ? true : false;
int convDispl = 6;
// now the coordinates in zeroPointLists are w.r.t. thetaImg
removeSetsThatAreDark(zeroPointLists, originalColorImage, thetaImg,
makeCorrectionsAlongX, convDispl);
reduceToLargest(zeroPointLists);
removeHighContrastPoints(zeroPointLists, originalColorImage,
thetaImg,
makeCorrectionsAlongX, convDispl);
if (binFactor > 1) {
Image img1 = theta.createWithDimensions().copyImageToGreen();
ImageIOHelper.addAlternatingColorCurvesToImage(zeroPointLists, img1);
ImageDisplayer.displayImage("before oversampling corrections", img1);
int topToCorrect = zeroPointLists.size();
//make corrections for resolution:
addBackMissingZeros(zeroPointLists, theta, binFactor, topToCorrect);
/*
img1 = theta.createWithDimensions().copyImageToGreen();
ImageIOHelper.addAlternatingColorCurvesToImage(zeroPointLists, img1);
ImageDisplayer.displayImage("added missing zeros", img1);
*/
}
int[] rgb = getAvgMinMaxColor(zeroPointLists.get(0), thetaImg,
originalColorImage, makeCorrectionsAlongX, convDispl);
Set<PairInt> points = combine(zeroPointLists);
GreyscaleImage mask = growPointsToSkyline(points, originalColorImage,
theta, rgb, makeCorrectionsAlongX, convDispl);
log.info("SKY avg: " + rgb[0] + " min=" + rgb[1] + " max=" + rgb[2]);
ImageProcesser imageProcesser = new ImageProcesser();
imageProcesser.printImageColorContrastStats(originalColorImage, 161, 501);
MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper();
double[] xycen = curveHelper.calculateXYCentroids(points);
outputSkyCentroid.add((int)Math.round(xycen[0]), (int)Math.round(xycen[1]));
if (mask != null) {
removeSpurs(mask);
}
return mask;
}
public Set<PairInt> combine(List<PairIntArray> points) {
Set<PairInt> set = new HashSet<PairInt>();
for (PairIntArray p : points) {
for (int i = 0; i < p.getN(); i++) {
int x = p.getX(i);
int y = p.getY(i);
PairInt pi = new PairInt(x, y);
set.add(pi);
}
}
return set;
}
public List<PairIntArray> getLargestSortedContiguousZeros(GreyscaleImage theta) {
return getSortedContiguousValues(theta, 0, false, true);
}
public List<PairIntArray> getSortedContiguousZeros(GreyscaleImage theta) {
return getSortedContiguousValues(theta, 0, false, false);
}
public List<PairIntArray> getLargestSortedContiguousNonZeros(GreyscaleImage theta) {
return getSortedContiguousValues(theta, 0, true, true);
}
private List<PairIntArray> getSortedContiguousValues(GreyscaleImage theta,
int value, boolean excludeValue, boolean limitToLargest) {
DFSContiguousValueFinder zerosFinder = new DFSContiguousValueFinder(theta);
if (excludeValue) {
zerosFinder.findGroupsNotThisValue(value);
} else {
zerosFinder.findGroups(value);
}
int nGroups = zerosFinder.getNumberOfGroups();
if (nGroups == 0) {
return new ArrayList<PairIntArray>();
}
int[] groupIndexes = new int[nGroups];
int[] groupN = new int[nGroups];
for (int gId = 0; gId < nGroups; gId++) {
int n = zerosFinder.getNumberofGroupMembers(gId);
groupIndexes[gId] = gId;
groupN[gId] = n;
}
MultiArrayMergeSort.sortByDecr(groupN, groupIndexes);
List<Integer> groupIds = new ArrayList<Integer>();
groupIds.add(Integer.valueOf(groupIndexes[0]));
if (nGroups > 1) {
float n0 = (float)groupN[0];
for (int i = 1; i < groupN.length; i++) {
if (limitToLargest) {
float number = groupN[i];
float frac = number/n0;
System.out.println(number);
//TODO: this should be adjusted by some metric.
// a histogram?
// since most images should have been binned to <= 300 x 300 pix,
// making an assumption about a group >= 100 pixels
if ((1 - frac) < 0.4) {
//if (number > 100) {
groupIds.add(Integer.valueOf(groupIndexes[i]));
} else {
break;
}
} else {
groupIds.add(Integer.valueOf(groupIndexes[i]));
}
}
}
List<PairIntArray> list = new ArrayList<PairIntArray>();
for (Integer gIndex : groupIds) {
int gIdx = gIndex.intValue();
PairIntArray points = zerosFinder.getXY(gIdx);
list.add(points);
}
return list;
}
public void multiply(GreyscaleImage input, float m) {
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
int f = (int)(m * v);
input.setValue(col, row, f);
}
}
}
public void subtractMinimum(GreyscaleImage input) {
int min = MiscMath.findMin(input.getValues());
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
int f = v - min;
input.setValue(col, row, f);
}
}
}
/**
* multiply these images, that is pixel by pixel multiplication.
* No corrections are made for integer overflow.
* @param input1
* @param input2
* @return
*/
public GreyscaleImage multiply(GreyscaleImage input1, GreyscaleImage input2) {
if (input1 == null) {
throw new IllegalArgumentException("input1 cannot be null");
}
if (input2 == null) {
throw new IllegalArgumentException("input2 cannot be null");
}
if (input1.getWidth() != input2.getWidth()) {
throw new IllegalArgumentException(
"input1 and input2 must have same widths");
}
if (input1.getHeight()!= input2.getHeight()) {
throw new IllegalArgumentException(
"input1 and input2 must have same heights");
}
GreyscaleImage output = input1.createWithDimensions();
for (int col = 0; col < input1.getWidth(); col++) {
for (int row = 0; row < input1.getHeight(); row++) {
int v = input1.getValue(col, row) * input2.getValue(col, row);
output.setValue(col, row, v);
}
}
return output;
}
/**
* compare each pixel and set output to 0 if both inputs are 0, else set
* output to 1.
* @param input1
* @param input2
* @return
*/
public GreyscaleImage binaryOr(GreyscaleImage input1, GreyscaleImage input2) {
if (input1 == null) {
throw new IllegalArgumentException("input1 cannot be null");
}
if (input2 == null) {
throw new IllegalArgumentException("input2 cannot be null");
}
if (input1.getWidth() != input2.getWidth()) {
throw new IllegalArgumentException(
"input1 and input2 must have same widths");
}
if (input1.getHeight()!= input2.getHeight()) {
throw new IllegalArgumentException(
"input1 and input2 must have same heights");
}
GreyscaleImage output = input1.createWithDimensions();
for (int col = 0; col < input1.getWidth(); col++) {
for (int row = 0; row < input1.getHeight(); row++) {
int v1 = input1.getValue(col, row);
int v2 = input2.getValue(col, row);
if ((v1 != 0) || (v2 != 0)) {
output.setValue(col, row, 1);
}
}
}
return output;
}
public void blur(GreyscaleImage input, float sigma) {
float[] kernel = Gaussian1D.getKernel(sigma);
Kernel1DHelper kernel1DHelper = new Kernel1DHelper();
GreyscaleImage output = input.createWithDimensions();
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
double conv = kernel1DHelper.convolvePointWithKernel(
input, i, j, kernel, true);
int g = (int) conv;
output.setValue(i, j, g);
}
}
input.resetTo(output);
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
double conv = kernel1DHelper.convolvePointWithKernel(
input, i, j, kernel, false);
int g = (int) conv;
output.setValue(i, j, g);
}
}
input.resetTo(output);
}
public void divideByBlurredSelf(GreyscaleImage input, float sigma) {
GreyscaleImage input2 = input.copyImage();
blur(input, sigma);
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
int v = input.getValue(i, j);
int vorig = input2.getValue(i, j);
if (v != 0) {
float r = (float)vorig/(float)v;
if ((i==250) && (j >= 50) && (j <= 150)) {
log.info(Float.toString(r));
}
input.setValue(i, j, (int)(100*r));
}
}
}
}
/**
* make a binary mask with the given zeroCoords as a group of starter points
* for the mask and also set to '0' any points within zeroCoords' bounds.
*
* @param theta
* @param zeroCoords
* @return
*/
public GreyscaleImage createMask(GreyscaleImage theta, PairIntArray zeroCoords) {
GreyscaleImage out = theta.createWithDimensions();
out.fill(1);
for (int pIdx = 0; pIdx < zeroCoords.getN(); pIdx++) {
int x = zeroCoords.getX(pIdx);
int y = zeroCoords.getY(pIdx);
out.setValue(x, y, 0);
}
return out;
}
/**
* make a binary mask with the given zeroCoords as a group of starter points
* for the mask and also set to '0' any points within zeroCoords' bounds.
*
* @param theta
* @param nonzeroCoords
* @return
*/
public GreyscaleImage createInvMask(GreyscaleImage theta,
PairIntArray nonzeroCoords) {
GreyscaleImage out = theta.createWithDimensions();
for (int pIdx = 0; pIdx < nonzeroCoords.getN(); pIdx++) {
int x = nonzeroCoords.getX(pIdx);
int y = nonzeroCoords.getY(pIdx);
out.setValue(x, y, 1);
}
return out;
}
/**
* this is meant to operate on an image with only 0's and 1's
* @param input
*/
public void removeSpurs(GreyscaleImage input) {
int width = input.getWidth();
int height = input.getHeight();
int nIterMax = 1000;
int nIter = 0;
int numRemoved = 1;
while ((nIter < nIterMax) && (numRemoved > 0)) {
numRemoved = 0;
for (int col = 0; col < input.getWidth(); col++) {
if ((col < 2) || (col > (width - 3))) {
continue;
}
for (int row = 0; row < input.getHeight(); row++) {
if ((row < 2) || (row > (height - 3))) {
continue;
}
int v = input.getValue(col, row);
if (v == 0) {
continue;
}
// looking for pixels having only one neighbor who subsequently
// has only 1 or 2 neighbors
// as long as neither are connected to image boundaries
int neighborIdx = getIndexIfOnlyOneNeighbor(input, col, row);
if (neighborIdx > -1) {
int neighborX = input.getCol(neighborIdx);
int neighborY = input.getRow(neighborIdx);
int nn = count8RegionNeighbors(input, neighborX, neighborY);
if (nn <= 2) {
input.setValue(col, row, 0);
numRemoved++;
}
} else {
int n = count8RegionNeighbors(input, col, row);
if (n == 0) {
input.setValue(col, row, 0);
numRemoved++;
}
}
}
}
log.info("numRemoved=" + numRemoved + " nIter=" + nIter);
nIter++;
}
if (nIter > 30) {
try {
multiply(input, 255);
ImageDisplayer.displayImage("segmented for sky", input);
int z = 1;
} catch (IOException ex) {
Logger.getLogger(ImageProcesser.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
protected int count8RegionNeighbors(GreyscaleImage input, int x, int y) {
int width = input.getWidth();
int height = input.getHeight();
int count = 0;
for (int c = (x - 1); c <= (x + 1); c++) {
if ((c < 0) || (c > (width - 1))) {
continue;
}
for (int r = (y - 1); r <= (y + 1); r++) {
if ((r < 0) || (r > (height - 1))) {
continue;
}
if ((c == x) && (r == y)) {
continue;
}
int v = input.getValue(c, r);
if (v > 0) {
count++;
}
}
}
return count;
}
protected int getIndexIfOnlyOneNeighbor(GreyscaleImage input, int x, int y) {
int width = input.getWidth();
int height = input.getHeight();
int count = 0;
int xNeighbor = -1;
int yNeighbor = -1;
for (int c = (x - 1); c <= (x + 1); c++) {
if ((c < 0) || (c > (width - 1))) {
continue;
}
for (int r = (y - 1); r <= (y + 1); r++) {
if ((r < 0) || (r > (height - 1))) {
continue;
}
if ((c == x) && (r == y)) {
continue;
}
int v = input.getValue(c, r);
if (v > 0) {
if (count > 0) {
return -1;
}
xNeighbor = c;
yNeighbor = r;
count++;
}
}
}
if (count == 0) {
return -1;
}
int index = input.getIndex(xNeighbor, yNeighbor);
return index;
}
private int[] getAvgMinMaxColor(PairIntArray points, GreyscaleImage theta,
Image originalImage, boolean addAlongX, int addAmount) {
int xOffset = theta.getXRelativeOffset();
int yOffset = theta.getYRelativeOffset();
double rSum = 0;
double gSum = 0;
double bSum = 0;
double rgbMinSum = Double.MAX_VALUE;
double rgbMaxSum = Double.MIN_VALUE;
int count = 0;
for (int pIdx = 0; pIdx < points.getN(); pIdx++) {
int x = points.getX(pIdx);
int y = points.getY(pIdx);
int ox = x + xOffset;
int oy = y + yOffset;
//TODO: this may need corrections for other orientations
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalImage.getHeight() - 1))) {
continue;
}
int rgb = originalImage.getRGB(ox, oy);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
rSum += r;
gSum += g;
bSum += b;
if (rgb < rgbMinSum) {
rgbMinSum = rgb;
}
if (rgb > rgbMaxSum) {
rgbMaxSum = rgb;
}
count++;
}
if (count == 0) {
return new int[]{0, 0, 0};
}
rSum /= (double)count;
gSum /= (double)count;
bSum /= (double)count;
rgbMinSum /= (double)count;
rgbMaxSum /= (double)count;
double rgbSum = (rSum + gSum + bSum)/3.;
return new int[]{(int)Math.round(rgbSum), (int)Math.round(rgbMinSum),
(int)Math.round(rgbMaxSum)};
}
/**
* look for gaps in zeroValuePoints and if the color of the points within
* the originalImage appears to be whiter than sky, consider the points
* to be clouds. cloud points are then added to zeroValuePoints because
* it's known that zeroValuePoints is subsequently used to mask out pixels
* that should not be used for a skyline edge (and hence corners).
*
* NOTE: this makes a correction for gaussian blurring, that is subtracting
* the 6 pixels from convolving w/ gaussian of sigma=2, then sigma=0.5
* which is what happens when "outdoorMode" is used to create the theta
* image.
*
* Note, this method won't find the clouds which are touching the horizon.
* The Brown & Lowe 2003 panoramic images of a snowy mountain shows
* 2 examples of complications with cloud removal.
* To the far left on the mountain horizon, one can see that clouds do
* obscure the mountain, and in the middle of the horizon of image,
* one can see that clouds and the mountain peak are surrounded by
* sky to left and right, though not completely below.
* In those cases where the clouds are touching the horizon, one probably
* wants to wait until have registered more than one image to understand
* motion and hence how to identify the clouds.
*
* @param points
* @param theta
* @param originalImage
* @return
*/
private void removeClouds(PairIntArray zeroValuePoints, GreyscaleImage theta,
Image originalImage, boolean addAlongX, int addAmount,
int rgbSkyAvg, int rgbSkyMin, int rgbSkyMax) {
/*
find the gaps in the set zeroValuePoints and determine if their
color is whiteish compared to the background sky or looks like the
background sky too.
easiest way, though maybe not fastest:
-- determine min and max of x and y of zeroValuePoints.
-- scan along each row to find the start column of the row and the
end column of the row.
-- repeat the scan of the row only within column boundaries and
search for each point in zeroValuePoints
-- if it is not present in zeroValuePoints,
check the originalImage value. if it is white with respect
to rgbSky, add it to zeroValuePoints
Can see that snowy mountain tops may be removed, so need to add to
the block within the row scan, a scan above and below the possible
cloud pixel to make sure that it is enclosed by sky pixels above
and below too.
would like to make a fast search of zeroValuePoints so using pixel index
as main data and putting all into a hash set
*/
if (zeroValuePoints.getN() == 0) {
return;
}
Set<Integer> zpSet = new HashSet<Integer>();
for (int pIdx = 0; pIdx < zeroValuePoints.getN(); pIdx++) {
int x = zeroValuePoints.getX(pIdx);
int y = zeroValuePoints.getY(pIdx);
int idx = theta.getIndex(x, y);
zpSet.add(Integer.valueOf(idx));
}
int xOffset = theta.getXRelativeOffset();
int yOffset = theta.getYRelativeOffset();
int rSky = (rgbSkyAvg >> 16) & 0xFF;
int gSky = (rgbSkyAvg >> 8) & 0xFF;
int bSky = rgbSkyAvg & 0xFF;
int rMinSky = (rgbSkyMin >> 16) & 0xFF;
int gMinSky = (rgbSkyMin >> 8) & 0xFF;
int bMinSky = rgbSkyMin & 0xFF;
int rMaxSky = (rgbSkyMax >> 16) & 0xFF;
int gMaxSky = (rgbSkyMax >> 8) & 0xFF;
int bMaxSky = rgbSkyMax & 0xFF;
/*
blue sky: 143, 243, 253
white clouds on blue sky: 192, 242, 248 (increased red, roughly same blue)
red sky:
white clouds on red sky: (increased blue and green, roughly same red)
*/
boolean skyIsBlue = (bSky > rSky);
int xMin = MiscMath.findMin(zeroValuePoints.getX());
int xMax = MiscMath.findMax(zeroValuePoints.getX());
int yMin = MiscMath.findMin(zeroValuePoints.getY());
int yMax = MiscMath.findMax(zeroValuePoints.getY());
for (int row = yMin; row <= yMax; row++) {
int start = -1;
int stop = 0;
for (int col = xMin; col <= xMax; col++) {
int idx = theta.getIndex(col, row);
if (zpSet.contains(Integer.valueOf(idx))) {
stop = col;
if (start == -1) {
start = col;
}
}
}
if (start == -1) {
continue;
}
// any pixels not in set are potentially cloud pixels
for (int col = start; col <= stop; col++) {
int idx = theta.getIndex(col, row);
if (!zpSet.contains(Integer.valueOf(idx))) {
int x = theta.getCol(idx);
int y = theta.getRow(idx);
int ox = x + xOffset;
int oy = y + yOffset;
//TODO: this may need corrections for other orientations
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalImage.getHeight() - 1))) {
continue;
}
int red = originalImage.getR(ox, oy);
int green = originalImage.getG(ox, oy);
int blue = originalImage.getB(ox, oy);
// is it white or near the color?
boolean looksLikeACloudPixel = false;
boolean looksLikeASkyPixel = false;
looksLikeACloudPixel = ((blue >= bSky) && (red >= rSky)
&& (green >= gSky) &&
((skyIsBlue && (blue > bSky) && (green > gSky))
||
(!skyIsBlue && (red > rSky))));
if (skyIsBlue && !looksLikeACloudPixel) {
// expect blue ~ b, but red > r
int db = Math.abs(blue - bSky);
int dr = red - rSky;
// if dr is < 0, it's 'bluer', hence similar to sky
if ((db < 10) && (dr > 25)) {
// could be dark part of cloud, but could also be
// a rock formation for example
/*if ((((double)blue/(double)green) < 0.1) &&
(((double)blue/(double)red) > 2.)) {
looksLikeACloudPixel = true;
}*/
} else if ((dr < 0) && (db >= 0)) {
if ((green - gSky) > 0) {
looksLikeASkyPixel = true;
}
}
} else if (!looksLikeACloudPixel) {
// expect red ~ r, but blue > b and green > g
int dr = Math.abs(red - rSky);
int db = blue - bSky;
int dg = green - gSky;
if ((dr < 10) && (db > 25) && (dg > 25)) {
looksLikeACloudPixel = true;
} else if ((db < 0) && (dr >= 0)) {
if ((green - gSky) < 0) {
looksLikeASkyPixel = true;
}
}
}
if (looksLikeASkyPixel) {
zeroValuePoints.add(col, row);
zpSet.add(Integer.valueOf(idx));
if (col < xMin) {
xMin = col;
}
if (col > xMax) {
xMax = col;
}
if (row < yMin) {
yMin = row;
}
if (row > yMax) {
yMax = row;
}
continue;
}
if (looksLikeACloudPixel) {
//further scan up and down to make sure enclosed by sky
boolean foundSkyPixel = false;
// search for sky pixel above current (that is, lower y)
if ((row - 1) == -1) {
foundSkyPixel = true;
}
if (!foundSkyPixel) {
for (int rowI = (row - 1); rowI >= yMin; rowI
int idxI = theta.getIndex(col, rowI);
if (zpSet.contains(Integer.valueOf(idxI))) {
foundSkyPixel = true;
break;
}
}
}
if (!foundSkyPixel) {
continue;
}
// search below for sky pixels, that is search higher y
foundSkyPixel = false;
if ((row + 1) == theta.getHeight()) {
foundSkyPixel = true;
}
if (!foundSkyPixel) {
for (int rowI = (row + 1); rowI <= yMax; rowI++) {
int idxI = theta.getIndex(col, rowI);
if (zpSet.contains(Integer.valueOf(idxI))) {
foundSkyPixel = true;
break;
}
}
}
if (!foundSkyPixel) {
// might be the peak of a snowy mountain
continue;
}
// this looks like a cloud pixel, so region should be
// considered 'sky'
zeroValuePoints.add(col, row);
}
}
}
}
}
public GreyscaleImage binImageToKeepZeros(GreyscaleImage img,
int binFactor) {
if (img == null) {
throw new IllegalArgumentException("img cannot be null");
}
int w0 = img.getWidth();
int h0 = img.getHeight();
int w1 = w0/binFactor;
int h1 = h0/binFactor;
GreyscaleImage out = new GreyscaleImage(w1, h1);
out.setXRelativeOffset(Math.round(img.getXRelativeOffset()/2.f));
out.setYRelativeOffset(Math.round(img.getYRelativeOffset()/2.f));
for (int i = 0; i < w1; i++) {
for (int j = 0; j < h1; j++) {
int vSum = 0;
int count = 0;
boolean isZero = false;
// if there's a zero in the binFactor x binFactor block,
// v is set to 0
for (int ii = (i*binFactor); ii < ((i + 1)*binFactor); ii++) {
for (int jj = (j*binFactor); jj < ((j + 1)*binFactor); jj++) {
if ((ii < 0) || (ii > (w0 - 1))) {
continue;
}
if ((jj < 0) || (jj > (h0 - 1))) {
continue;
}
int v = img.getValue(ii, jj);
if (v == 0) {
isZero = true;
vSum = 0;
break;
}
vSum += v;
count++;
}
if (isZero) {
break;
}
}
if (vSum > 0) {
float v = (float)vSum/(float)count;
vSum = Math.round(v);
}
out.setValue(i, j, vSum);
}
}
return out;
}
public GreyscaleImage binImage(GreyscaleImage img,
int binFactor) {
if (img == null) {
throw new IllegalArgumentException("img cannot be null");
}
int w0 = img.getWidth();
int h0 = img.getHeight();
int w1 = w0/binFactor;
int h1 = h0/binFactor;
GreyscaleImage out = new GreyscaleImage(w1, h1);
out.setXRelativeOffset(Math.round(img.getXRelativeOffset()/2.f));
out.setYRelativeOffset(Math.round(img.getYRelativeOffset()/2.f));
for (int i = 0; i < w1; i++) {
for (int j = 0; j < h1; j++) {
int vSum = 0;
int count = 0;
for (int ii = (i*binFactor); ii < ((i + 1)*binFactor); ii++) {
for (int jj = (j*binFactor); jj < ((j + 1)*binFactor); jj++) {
if ((ii < 0) || (ii > (w0 - 1))) {
continue;
}
if ((jj < 0) || (jj > (h0 - 1))) {
continue;
}
int v = img.getValue(ii, jj);
vSum += v;
count++;
}
}
if (count > 0) {
float v = (float)vSum/(float)count;
vSum = Math.round(v);
}
out.setValue(i, j, vSum);
}
}
return out;
}
public Image binImage(Image img, int binFactor) {
if (img == null) {
throw new IllegalArgumentException("img cannot be null");
}
int w0 = img.getWidth();
int h0 = img.getHeight();
int w1 = w0/binFactor;
int h1 = h0/binFactor;
Image out = new Image(w1, h1);
for (int i = 0; i < w1; i++) {
for (int j = 0; j < h1; j++) {
long rSum = 0;
long gSum = 0;
long bSum = 0;
int count = 0;
for (int ii = (i*binFactor); ii < ((i + 1)*binFactor); ii++) {
for (int jj = (j*binFactor); jj < ((j + 1)*binFactor); jj++) {
if ((ii < 0) || (ii > (w0 - 1))) {
continue;
}
if ((jj < 0) || (jj > (h0 - 1))) {
continue;
}
int rgb = img.getRGB(ii, jj);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
rSum += r;
gSum += g;
bSum += b;
count++;
}
}
if (count > 0) {
rSum = Math.round((float)rSum/(float)count);
gSum = Math.round((float)gSum/(float)count);
bSum = Math.round((float)bSum/(float)count);
}
out.setRGB(i, j, (int)rSum, (int)gSum, (int)bSum);
}
}
return out;
}
public GreyscaleImage unbinMask(GreyscaleImage mask, int binFactor,
GreyscaleImage originalTheta) {
if (mask == null) {
throw new IllegalArgumentException("mask cannot be null");
}
if (originalTheta == null) {
throw new IllegalArgumentException("originalTheta cannot be null");
}
GreyscaleImage out = originalTheta.createWithDimensions();
int w0 = mask.getWidth();
int h0 = mask.getHeight();
int w1 = out.getWidth();
int h1 = out.getHeight();
for (int i = 0; i < w0; i++) {
for (int j = 0; j < h0; j++) {
int v = mask.getValue(i, j);
for (int ii = (i*binFactor); ii < ((i + 1)*binFactor); ii++) {
for (int jj = (j*binFactor); jj < ((j + 1)*binFactor); jj++) {
out.setValue(ii, jj, v);
}
}
}
}
if ((originalTheta.getWidth() & 1) == 1) {
// copy next to last column into last column
int i = originalTheta.getWidth() - 2;
for (int j = 0; j < h1; j++) {
int v = out.getValue(i, j);
out.setValue(i + 1, j, v);
}
}
if ((originalTheta.getHeight() & 1) == 1) {
// copy next to last row into last row
int j = originalTheta.getHeight() - 2;
for (int i = 0; i < w1; i++) {
int v = out.getValue(i, j);
out.setValue(i, j + 1, v);
}
}
// TODO: consider correction for oversampling at location of skyline
// using originalTheta
return out;
}
private List<PairIntArray> unbinZeroPointLists(List<PairIntArray> zeroPointLists,
int binFactor) {
if (zeroPointLists == null) {
throw new IllegalArgumentException("mask cannot be null");
}
List<PairIntArray> output = new ArrayList<PairIntArray>();
for (PairIntArray zeroPointList : zeroPointLists) {
PairIntArray transformed = new PairIntArray(zeroPointList.getN() *
binFactor);
for (int i = 0; i < zeroPointList.getN(); i++) {
int x = zeroPointList.getX(i);
int y = zeroPointList.getY(i);
for (int ii = (x*binFactor); ii < ((x + 1)*binFactor); ii++) {
for (int jj = (y*binFactor); jj < ((y + 1)*binFactor); jj++) {
transformed.add(ii, jj);
}
}
}
output.add(transformed);
}
return output;
}
/**
* iterate over each point in zeroPointLists and visit its 8 neighbors
* looking for those not in it's list. if not in list and is in the
* image as a zero value pixel, place it in the list. note that this is a method to use
* for correcting the zero points lists after down sampling to make the
* list and then up sampling to use it.
*
* @param zeroPointLists
* @param theta
*/
private void addBackMissingZeros(List<PairIntArray> zeroPointLists,
GreyscaleImage theta, int binFactor, int topNumberToCorrect) {
int width = theta.getWidth();
int height = theta.getHeight();
int end = topNumberToCorrect;
if (zeroPointLists.size() < end) {
end = zeroPointLists.size();
}
List<Set<Integer> > sets = new ArrayList<Set<Integer> >();
for (int ii = 0; ii < end; ii++) {
PairIntArray zeroValuePoints = zeroPointLists.get(ii);
Set<Integer> zpSet = new HashSet<Integer>();
for (int pIdx = 0; pIdx < zeroValuePoints.getN(); pIdx++) {
int x = zeroValuePoints.getX(pIdx);
int y = zeroValuePoints.getY(pIdx);
int idx = theta.getIndex(x, y);
zpSet.add(Integer.valueOf(idx));
}
sets.add(zpSet);
}
for (int ii = 0; ii < end; ii++) {
PairIntArray zeroValuePoints = zeroPointLists.get(ii);
Set<Integer> zpSet = sets.get(ii);
Set<Integer> add = new HashSet<Integer>();
for (int pIdx = 0; pIdx < zeroValuePoints.getN(); pIdx++) {
int x = zeroValuePoints.getX(pIdx);
int y = zeroValuePoints.getY(pIdx);
for (int c = (x - binFactor); c <= (x + binFactor); c++) {
if ((c < 0) || (c > (width - 1))) {
continue;
}
for (int r = (y - binFactor); r <= (y + binFactor); r++) {
if ((r < 0) || (r > (height - 1))) {
continue;
}
if ((c == x) && (r == y)) {
continue;
}
int neighborIdx = theta.getIndex(c, r);
Integer index = Integer.valueOf(neighborIdx);
if (zpSet.contains(index)) {
continue;
}
int v = theta.getValue(c, r);
if (v == 0) {
add.add(index);
}
}
}
}
if (!add.isEmpty()) {
for (Integer a : add) {
int c = theta.getCol(a.intValue());
int r = theta.getRow(a.intValue());
zeroValuePoints.add(c, r);
zpSet.add(a);
}
}
}
}
/**
* remove points in zeropoint lists where there is a non-zero pixel in the
* theta image.
*
* @param zeroPointLists
* @param theta
*/
private void removeOverSampledZeros(List<PairIntArray> zeroPointLists,
GreyscaleImage theta) {
for (PairIntArray zeroValuePoints : zeroPointLists) {
List<Integer> remove = new ArrayList<Integer>();
for (int pIdx = 0; pIdx < zeroValuePoints.getN(); pIdx++) {
int x = zeroValuePoints.getX(pIdx);
int y = zeroValuePoints.getY(pIdx);
int v = theta.getValue(x, y);
if (v > 0) {
remove.add(Integer.valueOf(pIdx));
}
}
if (!remove.isEmpty()) {
for (int i = (remove.size() - 1); i > -1; i
int idx = remove.get(i).intValue();
zeroValuePoints.removeRange(idx, idx);
}
}
}
}
public void printImageColorContrastStats(Image image, List<PairIntArray>
zeroPoints) {
}
public void printImageColorContrastStats(Image image, int rgbSkyAvg,
int plotNumber) throws IOException {
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
int rSky = (rgbSkyAvg >> 16) & 0xFF;
int gSky = (rgbSkyAvg >> 8) & 0xFF;
int bSky = rgbSkyAvg & 0xFF;
double[] yuvSky = MatrixUtil.multiply(m, new double[]{rSky, gSky, bSky});
double t313 = Math.pow(3, (1./3.));
int w = image.getWidth();
int h = image.getHeight();
int slice = 1;
PolygonAndPointPlotter plotter = new PolygonAndPointPlotter();
for (int i = 0; i < 6; i++) {
int startCol = -1;
int stopCol = -1;
int startRow = -1;
int stopRow = -1;
boolean plotAlongRows = true;
String labelSuffix = null;
switch(i) {
case 0:
//horizontal at low y
startCol = 0;
stopCol = w - 1;
startRow = slice;
stopRow = startRow + slice;
plotAlongRows = false;
labelSuffix = "horizontal stripe at low y";
break;
case 1:
//horizontal at mid y
startCol = 0;
stopCol = w - 1;
startRow = (h - slice)/2 ;
stopRow = startRow + slice;
plotAlongRows = false;
labelSuffix = "horizontal stripe at mid y";
break;
case 2:
//horizontal at high y
startCol = 0;
stopCol = w - 1;
startRow = (h - 2*slice) - 1;
stopRow = startRow + slice;
plotAlongRows = false;
labelSuffix = "horizontal stripe at high y";
break;
case 3:
//vertical at low x
startCol = slice;
stopCol = startCol + slice;
startRow = 0;
stopRow = h - 1;
plotAlongRows = true;
labelSuffix = "vertical stripe at low x";
break;
case 4:
//vertical at mid x
startCol = (w - slice)/2;
stopCol = startCol + slice;
startRow = 0;
stopRow = h - 1;
plotAlongRows = true;
labelSuffix = "vertical stripe at mid x";
break;
default:
//vertical at high x
startCol = (w - 2*slice) - 1;
stopCol = startCol + slice;
startRow = 0;
stopRow = h - 1;
plotAlongRows = true;
labelSuffix = "vertical stripe at high x";
break;
}
// contrast as y
// hue
// blue
// red
float[] contrast = null;
float[] hue = null;
float[] red = null;
float[] blue = null;
float[] white = null;
float[] axis = null;
if (!plotAlongRows) {
// plot along columns
contrast = new float[w];
hue = new float[w];
red = new float[w];
blue = new float[w];
white = new float[w];
axis = new float[w];
for (int col = startCol; col <= stopCol; col++) {
int row = startRow;
int r = image.getR(col, row);
int g = image.getG(col, row);
int b = image.getB(col, row);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
double hueValue = Math.atan2(t313 * (g - b), ((2 * r) - g - b));
double contrastValue = (yuvSky[0] - yuv[0])/yuv[0];
double whiteValue = (r + g + b)/3.;
contrast[col] = (float)contrastValue;
hue[col] = (float)hueValue;
blue[col] = (float)b;
red[col] = (float)r;
white[col] = (float)whiteValue;
axis[col] = col;
}
} else {
// plot along rows
contrast = new float[h];
hue = new float[h];
red = new float[h];
blue = new float[h];
white = new float[h];
axis = new float[h];
for (int row = startRow; row <= stopRow; row++) {
int col = startCol;
int r = image.getR(col, row);
int g = image.getG(col, row);
int b = image.getB(col, row);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
double hueValue = Math.atan2(t313 * (g - b), ((2 * r) - g - b));
double contrastValue = (yuvSky[0] - yuv[0])/yuv[0];
double whiteValue = (r + g + b)/3.;
contrast[row] = (float)contrastValue;
hue[row] = (float)hueValue;
blue[row] = (float)b;
red[row] = (float)r;
white[row] = (float)whiteValue;
axis[row] = row;
}
}
float xmn = MiscMath.findMin(axis);
float xmx = MiscMath.findMax(axis);
float ymn = MiscMath.findMin(contrast);
float ymx = 1.1f * MiscMath.findMax(contrast);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, contrast, null, null, null, null,
"contrast " + labelSuffix);
ymn = MiscMath.findMin(hue);
ymx = 1.1f * MiscMath.findMax(hue);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, hue, null, null, null, null, "hue " + labelSuffix);
ymn = MiscMath.findMin(blue);
ymx = 1.1f * MiscMath.findMax(blue);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, blue, null, null, null, null, "blue " + labelSuffix);
ymn = MiscMath.findMin(red);
ymx = 1.1f * MiscMath.findMax(red);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, red, null, null, null, null, "red " + labelSuffix);
ymn = MiscMath.findMin(white);
ymx = 1.1f * MiscMath.findMax(white);
plotter.addPlot(xmn, xmx, ymn, ymx,
axis, white, null, null, null, null, "white " + labelSuffix);
plotter.writeFile(plotNumber);
}
}
private void removeSetsThatAreDark(List<PairIntArray>
zeroPointLists, Image originalColorImage, GreyscaleImage theta,
boolean addAlongX, int addAmount) {
int colorLimit = 100;
List<Integer> remove = new ArrayList<Integer>();
int xOffset = theta.getXRelativeOffset();
int yOffset = theta.getYRelativeOffset();
for (int gId = 0; gId < zeroPointLists.size(); gId++) {
PairIntArray points = zeroPointLists.get(gId);
int nBelowLimit = 0;
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
int ox = x + xOffset;
int oy = y + yOffset;
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
if ((r < colorLimit) && (b < colorLimit) && (g < colorLimit)) {
nBelowLimit++;
}
}
log.fine(gId + ") nBelowLimit=" + nBelowLimit
+ " (" + ((double)nBelowLimit/(double)points.getN()) + ")");
if (((double)nBelowLimit/(double)points.getN()) > 0.5) {
remove.add(Integer.valueOf(gId));
}
}
if (!remove.isEmpty()) {
for (int i = (remove.size() - 1); i > -1; i
zeroPointLists.remove(remove.get(i).intValue());
}
}
}
private void reduceToLargest(List<PairIntArray> zeroPointLists) {
int rmIdx = -1;
if (zeroPointLists.size() > 1) {
float n0 = (float)zeroPointLists.get(0).getN();
for (int i = 1; i < zeroPointLists.size(); i++) {
float number = zeroPointLists.get(i).getN();
float frac = number/n0;
System.out.println(number + " n0=" + n0);
//TODO: this should be adjusted by some metric.
// a histogram?
// since most images should have been binned to <= 300 x 300 pix,
// making an assumption about a group >= 100 pixels
if (frac < 0.1) {
rmIdx = i;
break;
}
}
}
if (rmIdx > -1) {
List<PairIntArray> out = new ArrayList<PairIntArray>();
for (int i = 0; i < rmIdx; i++) {
out.add(zeroPointLists.get(i));
}
zeroPointLists.clear();
zeroPointLists.addAll(out);
}
}
private void removeHighContrastPoints(List<PairIntArray>
zeroPointLists, Image originalColorImage, GreyscaleImage theta,
boolean addAlongX, int addAmount) {
int xOffset = theta.getXRelativeOffset();
int yOffset = theta.getYRelativeOffset();
double avgY = calculateY(zeroPointLists.get(0), originalColorImage,
xOffset, yOffset, addAlongX, addAmount);
// remove points that have contrast larger than tail of histogram
HistogramHolder h = createContrastHistogram(avgY, zeroPointLists,
originalColorImage, xOffset, yOffset, addAlongX,
addAmount);
if (h == null) {
return;
}
/*
try {
h.plotHistogram("contrast", 1);
} catch (IOException e) {
log.severe(e.getMessage());
}
*/
int yPeakIdx = MiscMath.findYMaxIndex(h.getYHist());
int tailXIdx = h.getXHist().length - 1;
if (tailXIdx > yPeakIdx) {
float yPeak = h.getYHist()[yPeakIdx];
float crit = 0.03f;
float dy = Float.MIN_VALUE;
for (int i = (yPeakIdx + 1); i < h.getYHist().length; i++) {
float f = (float)h.getYHist()[i]/yPeak;
dy = Math.abs(h.getYHist()[i] - h.getYHist()[i - 1]);
System.out.println("x=" + h.getXHist()[i] + " f=" + f + " dy=" + dy);
if (f < crit) {
tailXIdx = i;
break;
}
}
}
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
//remove points w/ contrast higher than the tail of the histogram
double critContrast = h.getXHist()[tailXIdx];
for (int gId = 0; gId < zeroPointLists.size(); gId++) {
PairIntArray points = zeroPointLists.get(gId);
Set<PairInt> pointsSet = new HashSet<PairInt>();
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
PairInt pi = new PairInt(x, y);
pointsSet.add(pi);
}
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
int ox = x + xOffset;
int oy = y + yOffset;
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
float contrast = (float)((avgY - yuv[0]) / yuv[0]);
if (contrast > critContrast) {
PairInt pi0 = new PairInt(x, y);
pointsSet.remove(pi0);
for (int xx = (x - 1); xx <= (x + 1); xx++) {
if ((xx < 0) || (xx > (theta.getWidth() - 1))) {
continue;
}
for (int yy = (y - 1); yy <= (y + 1); yy++) {
if ((yy < 0) || (yy > (theta.getHeight() - 1))) {
continue;
}
if ((xx == x) && (yy == y)) {
continue;
}
PairInt pi1 = new PairInt(xx, yy);
if (pointsSet.contains(pi1)) {
pointsSet.remove(pi1);
}
}
}
}
}
if (pointsSet.size() != points.getN()) {
PairIntArray points2 = new PairIntArray();
for (PairInt pi : pointsSet) {
points2.add(pi.getX(), pi.getY());
}
points.swapContents(points2);
}
}
}
public double calculateY(PairIntArray points, Image originalColorImage,
int xOffset, int yOffset, boolean addAlongX, int addAmount) {
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
double avgY = 0;
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
int ox = x + xOffset;
int oy = y + yOffset;
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
avgY += yuv[0];
}
avgY /= (double)points.getN();
return avgY;
}
private HistogramHolder createContrastHistogram(List<PairIntArray>
zeroPointLists, Image originalColorImage, int xRelativeOffset,
int yRelativeOffset, boolean addAlongX, int addAmount) {
if (zeroPointLists.isEmpty()) {
return null;
}
double avgY = calculateY(zeroPointLists.get(0), originalColorImage,
xRelativeOffset, yRelativeOffset, addAlongX, addAmount);
return createContrastHistogram(avgY, zeroPointLists,
originalColorImage, xRelativeOffset, yRelativeOffset,
addAlongX, addAmount);
}
private HistogramHolder createContrastHistogram(double avgY,
List<PairIntArray> zeroPointLists, Image originalColorImage,
int xOffset, int yOffset, boolean addAlongX, int addAmount) {
if (zeroPointLists.isEmpty()) {
return null;
}
double[][] m = new double[3][];
m[0] = new double[]{0.256, 0.504, 0.098};
m[1] = new double[]{-0.148, -0.291, 0.439};
m[2] = new double[]{0.439, -0.368, -0.072};
int nPoints = 0;
for (int gId = 0; gId < zeroPointLists.size(); gId++) {
nPoints += zeroPointLists.get(gId).getN();
}
float[] yValues = new float[nPoints];
int count = 0;
for (int gId = 0; gId < zeroPointLists.size(); gId++) {
PairIntArray points = zeroPointLists.get(gId);
for (int i = 0; i < points.getN(); i++) {
int x = points.getX(i);
int y = points.getY(i);
int ox = x + xOffset;
int oy = y + yOffset;
if (addAlongX) {
ox += addAmount;
} else {
oy += addAmount;
}
if ((ox < 0) || (ox > (originalColorImage.getWidth() - 1))) {
continue;
}
if ((oy < 0) || (oy > (originalColorImage.getHeight() - 1))) {
continue;
}
int r = originalColorImage.getR(x, y);
int g = originalColorImage.getG(x, y);
int b = originalColorImage.getB(x, y);
double[] rgb = new double[]{r, g, b};
double[] yuv = MatrixUtil.multiply(m, rgb);
yuv = MatrixUtil.add(yuv, new double[]{16, 128, 128});
float contrastValue = (float)((avgY - yuv[0]) / yuv[0]);
yValues[count] = contrastValue;
count++;
}
}
HistogramHolder h = Histogram.calculateSturgesHistogramRemoveZeroTail(
yValues, Errors.populateYErrorsBySqrt(yValues));
return h;
}
private void transformPointsToOriginalReferenceFrame(Set<PairInt> points,
GreyscaleImage theta, boolean makeCorrectionsAlongX, int addAmount) {
// transform points to original color image frame
int totalXOffset = theta.getXRelativeOffset();
int totalYOffset = theta.getYRelativeOffset();
if (makeCorrectionsAlongX) {
totalXOffset += addAmount;
} else {
totalYOffset += addAmount;
}
for (PairInt p : points) {
int x = p.getX();
int y = p.getY();
x += totalXOffset;
y += totalYOffset;
p.setX(x);
p.setY(y);
}
}
private GreyscaleImage growPointsToSkyline(Set<PairInt> points,
Image originalColorImage, GreyscaleImage theta, int[] rgb,
boolean makeCorrectionsAlongX, int addAmount) {
transformPointsToOriginalReferenceFrame(points, theta,
makeCorrectionsAlongX, addAmount);
// dfs w/ boundary found by contrast and color
throw new UnsupportedOperationException("Not supported yet.");
}
} |
package rabbit;
public class CommandCreator {
public String createCommand(String userCommand) {
String[] tokens = userCommand.split("\\s+");
switch(tokens[0]) {
case "security":
switch (tokens[1]) {
case "tls":
return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
case "ecrypt2lvl":
return "nmap --script ssl-enum-ciphers -p 443" + tokens[2];
case "open_ports":
return "nmap " + tokens[2];
default :
return null;
}
default :
return null;
}
}
} |
package battleships.gui.panels;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JPanel;
import translator.CoordinateTranslator;
import translator.TranslatorAdapter;
import battleships.backend.Settings;
import battleships.gui.BattleShipsInputUnit;
import battleships.gui.listeners.BattleshipsDeployListeners;
import battleships.gui.panels.logic.BattleshipsDeployLogic;
import game.api.GameState;
import generics.GameBoardPanel;
public class BattleshipDeployPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JPanel gameBoardPanel;
private GameState gameState;
private JPanel deployPanel;
private BattleshipsDeployListeners deployListener;
private BattleshipsDeployLogic deployLogic;
private BattleshipGamePanels gamePanels;
public BattleshipDeployPanel(GameState gameState,BattleShipsInputUnit inputUnit) {
this.gameState = gameState;
createDeployPanel(inputUnit);
}
public void createDeployPanel(BattleShipsInputUnit inputUnit) {
this.setLayout(new BorderLayout());
TranslatorAdapter ta = new TranslatorAdapter(new CoordinateTranslator());
createGameBoardPanel(ta);
createBattleshipsUtilityPanel(inputUnit);
deployListener = new BattleshipsDeployListeners(gameState,inputUnit);
deployLogic = new BattleshipsDeployLogic(gameState);
gamePanels = new BattleshipGamePanels(gameState, ta);
}
private void createGameBoardPanel(TranslatorAdapter ta) {
this.gameBoardPanel = new GameBoardPanel(gameState, ta, new Color(34, 177, 76, 255));
}
private void createBattleshipsUtilityPanel(BattleShipsInputUnit inputUnit){
}
} |
package org.parser.marpa;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
/**
* Test Application
*/
public class AppParse {
/**
* @param args arguments, unused
*/
public static void main(String[] args) {
AppLogger eslifLogger1 = new AppLogger();
AppLogger eslifLogger2 = new AppLogger();
AppLogger eslifLogger = eslifLogger2;
int nbthread = 1;
int ithread;
ArrayList<Thread> threadlist = new ArrayList<Thread>();
int nbalive;
/*
eslifLogger.info(" ATTACH ME");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
System.err.println(e);
}
*/
eslifLogger.info("Running over " + nbthread + " threads, using two loggers");
for (ithread = 0; ithread < nbthread; ithread++) {
eslifLogger = (eslifLogger == eslifLogger2) ? eslifLogger1 : eslifLogger2;
eslifLogger.info("Starting thread No " + ithread + " with logger " + eslifLogger);
Thread t = new Thread(new AppThread(eslifLogger));
t.start();
threadlist.add(t);
}
nbalive = nbthread;
while (nbalive > 0) {
nbalive = 0;
for (int i = 0; i < threadlist.size(); i++) {
Thread t = threadlist.get(i);
if (t != null) {
if (t.isAlive()) {
eslifLogger.info("Thread No " + i + " is still alive");
nbalive++;
} else {
threadlist.set(i, null);
}
}
}
if (nbalive > 0) {
eslifLogger.info(nbalive + " threads alive - sleeping one second");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.err.println(e);
}
} else {
eslifLogger.info("All " + threadlist.size() + " threads finished");
}
}
// Import/export test
new AppImportExport(eslifLogger).run();
}
} |
package ca.eandb.jmist.framework.job;
import ca.eandb.jdcp.job.AbstractParallelizableJob;
import ca.eandb.jdcp.job.TaskWorker;
import ca.eandb.jmist.framework.Display;
import ca.eandb.jmist.framework.Emitter;
import ca.eandb.jmist.framework.Intersection;
import ca.eandb.jmist.framework.Lens;
import ca.eandb.jmist.framework.Light;
import ca.eandb.jmist.framework.Material;
import ca.eandb.jmist.framework.NearestIntersectionRecorder;
import ca.eandb.jmist.framework.Photon;
import ca.eandb.jmist.framework.Random;
import ca.eandb.jmist.framework.Raster;
import ca.eandb.jmist.framework.ScatteredRay;
import ca.eandb.jmist.framework.ScatteredRays;
import ca.eandb.jmist.framework.Scene;
import ca.eandb.jmist.framework.SceneElement;
import ca.eandb.jmist.framework.ShadingContext;
import ca.eandb.jmist.framework.color.Color;
import ca.eandb.jmist.framework.color.ColorModel;
import ca.eandb.jmist.framework.color.WavelengthPacket;
import ca.eandb.jmist.framework.shader.MinimalShadingContext;
import ca.eandb.jmist.math.Point2;
import ca.eandb.jmist.math.Point3;
import ca.eandb.jmist.math.Ray3;
import ca.eandb.jmist.math.Sphere;
import ca.eandb.jmist.math.Vector3;
import ca.eandb.util.progress.ProgressMonitor;
/**
* @author brad
*
*/
public final class LightTracingJob extends AbstractParallelizableJob {
/**
* Serialization version ID.
*/
private static final long serialVersionUID = 159143623050840832L;
private final Scene scene;
private final ColorModel colorModel;
private final Random random;
private transient Raster raster;
private final Display display;
private final int photons;
private final int tasks;
private final int minPhotonsPerTask;
private final int extraPhotons;
private final int width;
private final int height;
private final boolean displayPartialResults;
private transient int tasksProvided = 0;
private transient int tasksSubmitted = 0;
private transient int photonsSubmitted = 0;
public LightTracingJob(Scene scene, Display display, int width, int height, ColorModel colorModel, Random random, int photons, int tasks, boolean displayPartialResults) {
this.scene = scene;
this.display = display;
this.colorModel = colorModel;
this.random = random;
this.photons = photons;
this.tasks = tasks;
this.minPhotonsPerTask = photons / tasks;
this.extraPhotons = photons - minPhotonsPerTask;
this.width = width;
this.height = height;
this.displayPartialResults = displayPartialResults;
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.ParallelizableJob#getNextTask()
*/
public synchronized Object getNextTask() throws Exception {
if (tasksProvided < tasks) {
return tasksProvided++ < extraPhotons ? minPhotonsPerTask + 1
: minPhotonsPerTask;
} else {
return null;
}
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.ParallelizableJob#isComplete()
*/
public boolean isComplete() throws Exception {
return tasksSubmitted == tasks;
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.ParallelizableJob#submitTaskResults(java.lang.Object, java.lang.Object, ca.eandb.util.progress.ProgressMonitor)
*/
public synchronized void submitTaskResults(Object task, Object results,
ProgressMonitor monitor) throws Exception {
int taskPhotons = (Integer) task;
Raster taskRaster = (Raster) results;
monitor.notifyStatusChanged("Accumulating partial results...");
photonsSubmitted += taskPhotons;
if (displayPartialResults) {
double alpha = (double) taskPhotons / (double) photonsSubmitted;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
raster.setPixel(x, y, raster.getPixel(x, y).times(
1.0 - alpha).plus(
taskRaster.getPixel(x, y).times(alpha)));
}
}
display.setPixels(0, 0, raster);
} else {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
raster.setPixel(x, y, raster.getPixel(x, y).plus(taskRaster.getPixel(x, y)));
}
}
}
monitor.notifyProgress(++tasksSubmitted, tasks);
if (tasksSubmitted == tasks) {
monitor.notifyStatusChanged("Ready to write results");
} else {
monitor.notifyStatusChanged("Waiting for partial results");
}
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.AbstractParallelizableJob#initialize()
*/
@Override
public void initialize() throws Exception {
raster = colorModel.createRaster(width, height);
if (displayPartialResults) {
display.initialize(width, height, colorModel);
}
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.AbstractParallelizableJob#finish()
*/
@Override
public void finish() throws Exception {
if (!displayPartialResults) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
raster.setPixel(x, y, raster.getPixel(x, y).divide(photons));
}
}
display.initialize(width, height, colorModel);
display.setPixels(0, 0, raster);
}
display.finish();
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.ParallelizableJob#worker()
*/
public TaskWorker worker() throws Exception {
return new Worker();
}
private final class Worker implements TaskWorker {
/** Serialization version ID. */
private static final long serialVersionUID = -7848301189373426210L;
private transient Light light;
private transient Sphere target;
private transient SceneElement root;
private transient Lens lens;
private synchronized void ensureInitialized() {
if (root == null) {
light = scene.getLight();
target = scene.boundingSphere();
root = scene.getRoot();
lens = scene.getLens();
}
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.TaskWorker#performTask(java.lang.Object, ca.eandb.util.progress.ProgressMonitor)
*/
public Object performTask(Object task, ProgressMonitor monitor) {
int photons = (Integer) task;
Raster raster = colorModel.createRaster(width, height);
ensureInitialized();
for (int i = 0; i < photons; i++) {
if (i % 10000 == 0) {
if (!monitor.notifyProgress(i, photons)) {
monitor.notifyCancelled();
return null;
}
}
Color sample = colorModel.sample(random);
WavelengthPacket lambda = sample.getWavelengthPacket();
Emitter emitter = light.sample(random);
Photon photon = emitter.emit(target, lambda, random);
Ray3 ray = photon.ray();
sample = sample.times(photon.power());
{
Point3 p = photon.position();
Lens.Projection proj = lens.project(p);
if (proj != null) {
Point3 q = proj.pointOnLens();
if (root.visibility(p, q)) {
Vector3 out = p.unitVectorTo(q);
Point2 ndc = proj.pointOnImagePlane();
Color color = emitter.getEmittedRadiance(out, lambda);
double atten = proj.importance();
Color result = color.times(sample).times(atten*0.5);
int rx = (int) Math.floor(ndc.x() * raster.getWidth());
int ry = (int) Math.floor(ndc.y() * raster.getHeight());
raster.setPixel(rx, ry, raster.getPixel(rx, ry).plus(result));
}
}
}
sample = sample.times(0.5);
while (true) {
Vector3 v = ray.direction();
Intersection x = NearestIntersectionRecorder.computeNearestIntersection(ray, root);
if (x == null) {
break;
}
ShadingContext context = new MinimalShadingContext(random);
x.prepareShadingContext(context);
context.getModifier().modify(context);
Material material = context.getMaterial();
/* trace to camera. */
Point3 p = context.getPosition();
Lens.Projection proj = lens.project(p);
if (proj != null) {
Point3 q = proj.pointOnLens();
if (root.visibility(p, q)) {
Vector3 out = p.unitVectorTo(q);
Point2 ndc = proj.pointOnImagePlane();
Color bsdf = material.scattering(context, v, out, lambda);
double atten = proj.importance() * Math.abs(out.dot(context.getShadingNormal()));
Color result = bsdf.times(sample).times(atten*0.5);
int rx = (int) Math.floor(ndc.x() * raster.getWidth());
int ry = (int) Math.floor(ndc.y() * raster.getHeight());
raster.setPixel(rx, ry, raster.getPixel(rx, ry).plus(result));
}
}
/* trace scattered ray. */
ScatteredRays scat = new ScatteredRays(context, v, lambda, random, material);
ScatteredRay sr = scat.getRandomScatteredRay(true);
if (sr == null) {
break;
}
ray = sr.getRay();
sample = sample.times(sr.getColor()).times(0.5);
}
}
monitor.notifyProgress(photons, photons);
monitor.notifyComplete();
return raster;
}
}
} |
package ca.eandb.jmist.framework.job;
import ca.eandb.jdcp.job.AbstractParallelizableJob;
import ca.eandb.jdcp.job.TaskWorker;
import ca.eandb.jmist.framework.Display;
import ca.eandb.jmist.framework.Emitter;
import ca.eandb.jmist.framework.Intersection;
import ca.eandb.jmist.framework.Lens;
import ca.eandb.jmist.framework.Light;
import ca.eandb.jmist.framework.Material;
import ca.eandb.jmist.framework.NearestIntersectionRecorder;
import ca.eandb.jmist.framework.Photon;
import ca.eandb.jmist.framework.Random;
import ca.eandb.jmist.framework.Raster;
import ca.eandb.jmist.framework.ScatteredRay;
import ca.eandb.jmist.framework.ScatteredRays;
import ca.eandb.jmist.framework.Scene;
import ca.eandb.jmist.framework.SceneElement;
import ca.eandb.jmist.framework.ShadingContext;
import ca.eandb.jmist.framework.color.Color;
import ca.eandb.jmist.framework.color.ColorModel;
import ca.eandb.jmist.framework.color.WavelengthPacket;
import ca.eandb.jmist.framework.shader.MinimalShadingContext;
import ca.eandb.jmist.math.Point2;
import ca.eandb.jmist.math.Point3;
import ca.eandb.jmist.math.Ray3;
import ca.eandb.jmist.math.Sphere;
import ca.eandb.jmist.math.Vector3;
import ca.eandb.util.progress.ProgressMonitor;
/**
* @author brad
*
*/
public final class LightTracingJob extends AbstractParallelizableJob {
/**
* Serialization version ID.
*/
private static final long serialVersionUID = 159143623050840832L;
private final Scene scene;
private final ColorModel colorModel;
private final Random random;
private transient Raster raster;
private final Display display;
private final int photons;
private final int tasks;
private final int minPhotonsPerTask;
private final int extraPhotons;
private final int width;
private final int height;
private transient int tasksProvided = 0;
private transient int tasksSubmitted = 0;
public LightTracingJob(Scene scene, Display display, int width, int height, ColorModel colorModel, Random random, int photons, int tasks) {
this.scene = scene;
this.display = display;
this.colorModel = colorModel;
this.random = random;
this.photons = photons;
this.tasks = tasks;
this.minPhotonsPerTask = photons / tasks;
this.extraPhotons = photons - minPhotonsPerTask;
this.width = width;
this.height = height;
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.ParallelizableJob#getNextTask()
*/
public Object getNextTask() throws Exception {
if (tasksProvided < tasks) {
return tasksProvided++ < extraPhotons ? minPhotonsPerTask + 1
: minPhotonsPerTask;
} else {
return null;
}
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.ParallelizableJob#isComplete()
*/
public boolean isComplete() throws Exception {
return tasksSubmitted == tasks;
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.AbstractParallelizableJob#initialize()
*/
@Override
public void initialize() throws Exception {
raster = colorModel.createRaster(width, height);
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.ParallelizableJob#submitTaskResults(java.lang.Object, java.lang.Object, ca.eandb.util.progress.ProgressMonitor)
*/
public void submitTaskResults(Object task, Object results,
ProgressMonitor monitor) throws Exception {
Raster taskRaster = (Raster) results;
monitor.notifyStatusChanged("Accumulating partial results...");
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
raster.setPixel(x, y, raster.getPixel(x, y).plus(taskRaster.getPixel(x, y)));
}
}
monitor.notifyProgress(++tasksSubmitted, tasks);
if (tasksSubmitted == tasks) {
monitor.notifyStatusChanged("Ready to write results");
} else {
monitor.notifyStatusChanged("Waiting for partial results");
}
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.AbstractParallelizableJob#finish()
*/
@Override
public void finish() throws Exception {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
raster.setPixel(x, y, raster.getPixel(x, y).divide(photons));
}
}
display.initialize(width, height, colorModel);
display.setPixels(0, 0, raster);
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.ParallelizableJob#worker()
*/
public TaskWorker worker() throws Exception {
return new Worker();
}
private final class Worker implements TaskWorker {
private static final long serialVersionUID = -7848301189373426210L;
private transient Light light;
private transient Sphere target;
private transient SceneElement root;
private transient Lens lens;
private synchronized void ensureInitialized() {
if (root == null) {
light = scene.getLight();
target = scene.boundingSphere();
root = scene.getRoot();
lens = scene.getLens();
}
}
/* (non-Javadoc)
* @see ca.eandb.jdcp.job.TaskWorker#performTask(java.lang.Object, ca.eandb.util.progress.ProgressMonitor)
*/
public Object performTask(Object task, ProgressMonitor monitor) {
int photons = (Integer) task;
Raster raster = colorModel.createRaster(width, height);
ensureInitialized();
for (int i = 0; i < photons; i++) {
if (i % 10000 == 0) {
if (!monitor.notifyProgress(i, photons)) {
monitor.notifyCancelled();
return null;
}
}
Color sample = colorModel.sample(random);
WavelengthPacket lambda = sample.getWavelengthPacket();
Emitter emitter = light.sample(random);
Photon photon = emitter.emit(target, lambda, random);
Ray3 ray = photon.ray();
sample = sample.times(photon.power());
{
Point3 p = photon.position();
Lens.Projection proj = lens.project(p);
if (proj != null) {
Point3 q = proj.pointOnLens();
if (root.visibility(p, q)) {
Vector3 out = p.unitVectorTo(q);
Point2 ndc = proj.pointOnImagePlane();
Color color = emitter.getEmittedRadiance(out, lambda);
double atten = proj.importance();
Color result = color.times(sample).times(atten*0.5);
int rx = (int) Math.floor(ndc.x() * raster.getWidth());
int ry = (int) Math.floor(ndc.y() * raster.getHeight());
raster.setPixel(rx, ry, raster.getPixel(rx, ry).plus(result));
}
}
}
sample = sample.times(0.5);
while (true) {
Vector3 v = ray.direction();
Intersection x = NearestIntersectionRecorder.computeNearestIntersection(ray, root);
if (x == null) {
break;
}
ShadingContext context = new MinimalShadingContext(random);
x.prepareShadingContext(context);
context.getModifier().modify(context);
Material material = context.getMaterial();
/* trace to camera. */
Point3 p = context.getPosition();
Lens.Projection proj = lens.project(p);
if (proj != null) {
Point3 q = proj.pointOnLens();
if (root.visibility(p, q)) {
Vector3 out = p.unitVectorTo(q);
Point2 ndc = proj.pointOnImagePlane();
Color bsdf = material.scattering(context, v, out, lambda);
double atten = proj.importance() * Math.abs(out.dot(context.getShadingNormal()));
Color result = bsdf.times(sample).times(atten*0.5);
int rx = (int) Math.floor(ndc.x() * raster.getWidth());
int ry = (int) Math.floor(ndc.y() * raster.getHeight());
raster.setPixel(rx, ry, raster.getPixel(rx, ry).plus(result));
}
}
/* trace scattered ray. */
ScatteredRays scat = new ScatteredRays(context, v, lambda, random, material);
ScatteredRay sr = scat.getRandomScatteredRay(true);
if (sr == null) {
break;
}
ray = sr.getRay();
sample = sample.times(sr.getColor()).times(0.5);
}
}
monitor.notifyProgress(photons, photons);
monitor.notifyComplete();
return raster;
}
}
} |
package com.axelby.podax;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
// catch all of our Bluetooth events
public class BluetoothConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// If we're not stopping when headphones disconnect, don't worry about it
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (!prefs.getBoolean("stopOnBluetoothPref", true))
return;
// Figure out what kind of device it is
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// pause if it's headphones
if (btDevice.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.AUDIO_VIDEO)
if (PlayerStatus.isPlaying())
PlayerService.stop(context);
}
} |
package com.codeup.auth.filters;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class AuthenticationFilter implements Filter {
private String redirectTo;
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws ServletException, IOException {
HttpSession session = ((HttpServletRequest) request).getSession(false);
if (session == null || session.getAttribute("user") == null) {
((HttpServletResponse) response).sendRedirect(redirectTo);
} else {
chain.doFilter(request, response);
}
}
public void destroy() {
}
public void init(FilterConfig config) throws ServletException {
redirectTo = config.getInitParameter("redirectTo");
}
} |
package com.beetle.voip;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import com.beetle.im.IMService;
import com.beetle.im.RTMessage;
import com.beetle.im.RTMessageObserver;
import com.beetle.im.Timer;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
import io.gobelieve.voip_demo.R;
import static android.os.SystemClock.uptimeMillis;
public class VOIPActivity extends WebRTCActivity implements RTMessageObserver {
protected static final String TAG = "face";
public static final long APPID = 7;
public static long activityCount = 0;
protected String channelID;
protected long currentUID;
protected long peerUID;
protected MediaPlayer player;
protected boolean isConnected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "voip activity on create");
activityCount++;
IMService.getInstance().addRTObserver(this);
if (isCaller) {
playOutgoingCall();
} else {
playIncomingCall();
}
}
@Override
protected void onDestroy () {
Log.i(TAG, "voip activity on destroy");
IMService.getInstance().removeRTObserver(this);
activityCount
if (this.player != null) {
this.player.stop();
this.player = null;
}
close();
super.onDestroy();
}
protected void dismiss() {
setResult(RESULT_OK);
finish();
}
private boolean getHeadphoneStatus() {
AudioManager audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
boolean headphone = audioManager.isWiredHeadsetOn() || audioManager.isBluetoothA2dpOn();
return headphone;
}
protected void playResource(int resID) {
try {
AssetFileDescriptor afd = getResources().openRawResourceFd(resID);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
player.setLooping(true);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true);
am.setMode(AudioManager.STREAM_MUSIC);
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void playOutgoingCall() {
playResource(R.raw.call);
}
protected void playIncomingCall() {
playResource(R.raw.start);
}
protected void startStream() {
super.startStream();
}
protected void stopStream() {
super.stopStream();
}
public static int getNow() {
Date date = new Date();
long t = date.getTime();
return (int)(t/1000);
}
public void onRefuse() {
this.player.stop();
this.player = null;
dismiss();
}
public void onHangUp() {
if (this.isConnected) {
stopStream();
dismiss();
} else {
this.player.stop();
this.player = null;
dismiss();
}
}
public void onTalking() {
this.player.stop();
this.player = null;
dismiss();
}
public void onDialTimeout() {
this.player.stop();
this.player = null;
dismiss();
}
public void onAcceptTimeout() {
dismiss();
}
public void onConnected() {
if (this.player != null) {
this.player.stop();
this.player = null;
}
Log.i(TAG, "voip connected");
startStream();
this.isConnected = true;
}
public void onDisconnect() {
stopStream();
dismiss();
}
@Override
protected void sendP2PMessage(JSONObject json) {
RTMessage rt = new RTMessage();
rt.sender = this.currentUID;
rt.receiver = this.peerUID;
try {
JSONObject obj = new JSONObject();
obj.put("p2p", json);
rt.content = obj.toString();
Log.i(TAG, "send rt message:" + rt.content);
IMService.getInstance().sendRTMessage(rt);
} catch (JSONException e ) {
e.printStackTrace();
}
}
@Override
public void onRTMessage(RTMessage rt) {
if (rt.sender != peerUID) {
return;
}
try {
JSONObject json = new JSONObject(rt.content);
if (json.has("p2p")) {
JSONObject obj = json.getJSONObject("p2p");
Log.i(TAG, "recv p2p message:" + rt.content);
processP2PMessage(obj);
} else if (json.has("voip")) {
JSONObject obj = json.getJSONObject("voip");
Log.i(TAG, "recv voip message:" + rt.content);
processVOIPMessage(rt.sender, obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private static final int VOIP_DIALING = 1;
private static final int VOIP_CONNECTED = 2;
private static final int VOIP_ACCEPTING = 3;
private static final int VOIP_ACCEPTED = 4;
private static final int VOIP_REFUSED = 6;
private static final int VOIP_HANGED_UP = 7;
private static final int VOIP_SHUTDOWN = 8;
//session mode
private static final int SESSION_VOICE = 0;
private static final int SESSION_VIDEO = 1;
private int dialBeginTimestamp;
private Timer dialTimer;
private Timer acceptTimer;
private Timer pingTimer;
//ping
private int lastPingTimestamp;
private int state;
private int mode;
public void close() {
if (this.dialTimer != null) {
this.dialTimer.suspend();
this.dialTimer = null;
}
if (this.acceptTimer != null) {
this.acceptTimer.suspend();
this.acceptTimer = null;
}
if (this.pingTimer != null) {
this.pingTimer.suspend();
this.pingTimer = null;
}
}
public void ping() {
lastPingTimestamp = getNow();
this.pingTimer = new Timer() {
@Override
protected void fire() {
VOIPActivity.this.sendPing();
//ping
int now = getNow();
if (now - lastPingTimestamp > 10) {
VOIPActivity.this.onDisconnect();
}
}
};
this.pingTimer.setTimer(uptimeMillis()+100, 1000);
this.pingTimer.resume();
}
public void dialVoice() {
state = VOIP_DIALING;
mode = SESSION_VOICE;
this.dialBeginTimestamp = getNow();
sendDial();
this.dialTimer = new Timer() {
@Override
protected void fire() {
VOIPActivity.this.sendDial();
}
};
this.dialTimer.setTimer(uptimeMillis()+1000, 1000);
this.dialTimer.resume();
}
public void dialVideo() {
state = VOIP_DIALING;
mode = SESSION_VIDEO;
this.dialBeginTimestamp = getNow();
sendDial();
this.dialTimer = new Timer() {
@Override
protected void fire() {
VOIPActivity.this.sendDial();
}
};
this.dialTimer.setTimer(uptimeMillis()+1000, 1000);
this.dialTimer.resume();
}
public void accept() {
Log.i(TAG, "accepting...");
state = VOIP_ACCEPTED;
this.acceptTimer = new Timer() {
@Override
protected void fire() {
VOIPActivity.this.onAcceptTimeout();
}
};
this.acceptTimer.setTimer(uptimeMillis()+1000*10);
this.acceptTimer.resume();
sendDialAccept();
}
public void refuse() {
Log.i(TAG, "refusing...");
state = VOIP_REFUSED;
sendDialRefuse();
}
public void hangup() {
Log.i(TAG, "hangup...");
if (state == VOIP_DIALING) {
this.dialTimer.suspend();
this.dialTimer = null;
sendHangUp();
state = VOIP_HANGED_UP;
} else if (state == VOIP_CONNECTED) {
sendHangUp();
state = VOIP_HANGED_UP;
} else {
Log.i(TAG, "invalid voip state:" + state);
}
}
public void processVOIPMessage(long sender, JSONObject obj) {
if (sender != peerUID) {
sendTalking(sender);
return;
}
VOIPCommand command = new VOIPCommand(obj);
Log.i(TAG, "state:" + state + " command:" + command.cmd);
if (state == VOIP_DIALING) {
if (command.cmd == VOIPCommand.VOIP_COMMAND_ACCEPT) {
sendConnected();
state = VOIP_CONNECTED;
this.dialTimer.suspend();
this.dialTimer = null;
Log.i(TAG, "voip connected");
onConnected();
this.ping();
} else if (command.cmd == VOIPCommand.VOIP_COMMAND_REFUSE) {
state = VOIP_REFUSED;
sendRefused();
this.dialTimer.suspend();
this.dialTimer = null;
this.onRefuse();
} else if (command.cmd == VOIPCommand.VOIP_COMMAND_TALKING) {
state = VOIP_SHUTDOWN;
this.dialTimer.suspend();
this.dialTimer = null;
this.onTalking();
}
} else if (state == VOIP_ACCEPTING) {
if (command.cmd == VOIPCommand.VOIP_COMMAND_HANG_UP) {
state = VOIP_HANGED_UP;
onHangUp();
}
} else if (state == VOIP_ACCEPTED) {
if (command.cmd == VOIPCommand.VOIP_COMMAND_CONNECTED) {
this.acceptTimer.suspend();
this.acceptTimer = null;
state = VOIP_CONNECTED;
onConnected();
this.ping();
} else if (command.cmd == VOIPCommand.VOIP_COMMAND_HANG_UP) {
this.acceptTimer.suspend();
this.acceptTimer = null;
state = VOIP_HANGED_UP;
onHangUp();
} else if (command.cmd == VOIPCommand.VOIP_COMMAND_DIAL ||
command.cmd == VOIPCommand.VOIP_COMMAND_DIAL_VIDEO) {
this.sendDialAccept();
}
} else if (state == VOIP_CONNECTED) {
if (command.cmd == VOIPCommand.VOIP_COMMAND_HANG_UP) {
state = VOIP_HANGED_UP;
onHangUp();
} else if (command.cmd == VOIPCommand.VOIP_COMMAND_ACCEPT) {
sendConnected();
} else if (command.cmd == VOIPCommand.VOIP_COMMAND_PING) {
lastPingTimestamp = getNow();
}
}
}
private void sendControlCommand(int cmd) {
RTMessage rt = new RTMessage();
rt.sender = currentUID;
rt.receiver = peerUID;
try {
VOIPCommand command = new VOIPCommand();
command.cmd = cmd;
command.channelID = this.channelID;
JSONObject obj = command.getContent();
if (obj == null) {
return;
}
JSONObject json = new JSONObject();
json.put("voip", obj);
rt.content = json.toString();
IMService.getInstance().sendRTMessage(rt);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void sendDial() {
if (mode == SESSION_VOICE) {
sendControlCommand(VOIPCommand.VOIP_COMMAND_DIAL);
} else if (mode == SESSION_VIDEO) {
sendControlCommand(VOIPCommand.VOIP_COMMAND_DIAL_VIDEO);
} else {
assert(false);
}
long now = getNow();
if (now - this.dialBeginTimestamp >= 60) {
Log.i(TAG, "dial timeout");
this.dialTimer.suspend();
this.dialTimer = null;
this.onDialTimeout();
}
}
private void sendRefused() {
sendControlCommand(VOIPCommand.VOIP_COMMAND_REFUSED);
}
private void sendConnected() {
sendControlCommand(VOIPCommand.VOIP_COMMAND_CONNECTED);
}
private void sendTalking(long receiver) {
RTMessage rt = new RTMessage();
rt.sender = currentUID;
rt.receiver = receiver;
try {
VOIPCommand command = new VOIPCommand();
command.cmd = VOIPCommand.VOIP_COMMAND_TALKING;
command.channelID = this.channelID;
JSONObject obj = command.getContent();
if (obj == null) {
return;
}
JSONObject json = new JSONObject();
json.put("voip", obj);
rt.content = json.toString();
IMService.getInstance().sendRTMessage(rt);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void sendPing() {
sendControlCommand(VOIPCommand.VOIP_COMMAND_PING);
}
private void sendDialAccept() {
sendControlCommand(VOIPCommand.VOIP_COMMAND_ACCEPT);
}
private void sendDialRefuse() {
sendControlCommand(VOIPCommand.VOIP_COMMAND_REFUSE);
}
private void sendHangUp() {
sendControlCommand(VOIPCommand.VOIP_COMMAND_HANG_UP);
}
} |
package com.kickstarter.libs;
import android.content.pm.PackageInfo;
import android.support.annotation.NonNull;
import com.kickstarter.BuildConfig;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.util.Locale;
public final class Release {
private final PackageInfo packageInfo;
public Release(final @NonNull PackageInfo packageInfo) {
this.packageInfo = packageInfo;
}
public @NonNull String applicationId() {
return packageInfo.packageName;
}
public DateTime dateTime() {
return new DateTime(BuildConfig.BUILD_DATE, DateTimeZone.UTC).withZone(DateTimeZone.getDefault());
}
public String sha() {
return BuildConfig.GIT_SHA;
}
public Integer versionCode() {
return packageInfo.versionCode;
}
public String versionName() {
return packageInfo.versionName;
}
public String variant() {
// e.g. internalDebug, externalRelease
return new StringBuilder().append(BuildConfig.FLAVOR_AUDIENCE)
.append(BuildConfig.BUILD_TYPE.substring(0, 1).toUpperCase(Locale.US))
.append(BuildConfig.BUILD_TYPE.substring(1))
.toString();
}
} |
package beast.evolution.likelihood;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import beast.core.Description;
import beast.core.Input;
import beast.core.State;
import beast.core.util.Log;
import beast.evolution.alignment.Alignment;
import beast.evolution.branchratemodel.BranchRateModel;
import beast.evolution.branchratemodel.StrictClockModel;
import beast.evolution.sitemodel.SiteModel;
import beast.evolution.substitutionmodel.SubstitutionModel;
import beast.evolution.tree.Node;
import beast.evolution.tree.Tree;
import beast.evolution.tree.TreeInterface;
@Description("Calculates the probability of sequence data on a beast.tree given a site and substitution model using " +
"a variant of the 'peeling algorithm'. For details, see" +
"Felsenstein, Joseph (1981). Evolutionary trees from DNA sequences: a maximum likelihood approach. J Mol Evol 17 (6): 368-376.")
public class TreeLikelihood extends GenericTreeLikelihood {
final public Input<Boolean> m_useAmbiguities = new Input<>("useAmbiguities", "flag to indicate that sites containing ambiguous states should be handled instead of ignored (the default)", false);
final public Input<Boolean> m_useTipLikelihoods = new Input<>("useTipLikelihoods", "flag to indicate that partial likelihoods are provided at the tips", false);
public static enum Scaling {none, always, _default};
final public Input<Scaling> scaling = new Input<>("scaling", "type of scaling to use, one of " + Arrays.toString(Scaling.values()) + ". If not specified, the -beagle_scaling flag is used.", Scaling._default, Scaling.values());
/**
* calculation engine *
*/
protected LikelihoodCore likelihoodCore;
protected BeagleTreeLikelihood beagle;
/**
* BEASTObject associated with inputs. Since none of the inputs are StateNodes, it
* is safe to link to them only once, during initAndValidate.
*/
SubstitutionModel substitutionModel;
protected SiteModel.Base m_siteModel;
protected BranchRateModel.Base branchRateModel;
/**
* flag to indicate the
* // when CLEAN=0, nothing needs to be recalculated for the node
* // when DIRTY=1 indicates a node partial needs to be recalculated
* // when FILTHY=2 indicates the indices for the node need to be recalculated
* // (often not necessary while node partial recalculation is required)
*/
protected int hasDirt;
/**
* Lengths of the branches in the tree associated with each of the nodes
* in the tree through their node numbers. By comparing whether the
* current branch length differs from stored branch lengths, it is tested
* whether a node is dirty and needs to be recomputed (there may be other
* reasons as well...).
* These lengths take branch rate models in account.
*/
protected double[] m_branchLengths;
protected double[] storedBranchLengths;
/**
* memory allocation for likelihoods for each of the patterns *
*/
protected double[] patternLogLikelihoods;
/**
* memory allocation for the root partials *
*/
protected double[] m_fRootPartials;
/**
* memory allocation for probability tables obtained from the SiteModel *
*/
double[] probabilities;
int matrixSize;
/**
* flag to indicate ascertainment correction should be applied *
*/
boolean useAscertainedSitePatterns = false;
/**
* dealing with proportion of site being invariant *
*/
double proportionInvariant = 0;
List<Integer> constantPattern = null;
@Override
public void initAndValidate() {
// sanity check: alignment should have same #taxa as tree
if (dataInput.get().getTaxonCount() != treeInput.get().getLeafNodeCount()) {
throw new IllegalArgumentException("The number of nodes in the tree does not match the number of sequences");
}
beagle = null;
beagle = new BeagleTreeLikelihood();
try {
beagle.initByName(
"data", dataInput.get(), "tree", treeInput.get(), "siteModel", siteModelInput.get(),
"branchRateModel", branchRateModelInput.get(), "useAmbiguities", m_useAmbiguities.get(),
"useTipLikelihoods", m_useTipLikelihoods.get(),"scaling", scaling.get().toString());
if (beagle.beagle != null) {
//a Beagle instance was found, so we use it
return;
}
} catch (Exception e) {
// ignore
}
// No Beagle instance was found, so we use the good old java likelihood core
beagle = null;
int nodeCount = treeInput.get().getNodeCount();
if (!(siteModelInput.get() instanceof SiteModel.Base)) {
throw new IllegalArgumentException("siteModel input should be of type SiteModel.Base");
}
m_siteModel = (SiteModel.Base) siteModelInput.get();
m_siteModel.setDataType(dataInput.get().getDataType());
substitutionModel = m_siteModel.substModelInput.get();
if (branchRateModelInput.get() != null) {
branchRateModel = branchRateModelInput.get();
} else {
branchRateModel = new StrictClockModel();
}
m_branchLengths = new double[nodeCount];
storedBranchLengths = new double[nodeCount];
int stateCount = dataInput.get().getMaxStateCount();
int patterns = dataInput.get().getPatternCount();
if (stateCount == 4) {
likelihoodCore = new BeerLikelihoodCore4();
} else {
likelihoodCore = new BeerLikelihoodCore(stateCount);
}
String className = getClass().getSimpleName();
Alignment alignment = dataInput.get();
Log.info.println(className + "(" + getID() + ") uses " + likelihoodCore.getClass().getSimpleName());
Log.info.println(" " + alignment.toString(true));
// print startup messages via Log.print*
proportionInvariant = m_siteModel.getProportionInvariant();
m_siteModel.setPropInvariantIsCategory(false);
if (proportionInvariant > 0) {
calcConstantPatternIndices(patterns, stateCount);
}
initCore();
patternLogLikelihoods = new double[patterns];
m_fRootPartials = new double[patterns * stateCount];
matrixSize = (stateCount + 1) * (stateCount + 1);
probabilities = new double[(stateCount + 1) * (stateCount + 1)];
Arrays.fill(probabilities, 1.0);
if (dataInput.get().isAscertained) {
useAscertainedSitePatterns = true;
}
}
/**
* Determine indices of m_fRootProbabilities that need to be updates
* // due to sites being invariant. If none of the sites are invariant,
* // the 'site invariant' category does not contribute anything to the
* // root probability. If the site IS invariant for a certain character,
* // taking ambiguities in account, there is a contribution of 1 from
* // the 'site invariant' category.
*/
void calcConstantPatternIndices(final int patterns, final int stateCount) {
constantPattern = new ArrayList<>();
for (int i = 0; i < patterns; i++) {
final int[] pattern = dataInput.get().getPattern(i);
final boolean[] isInvariant = new boolean[stateCount];
Arrays.fill(isInvariant, true);
for (final int state : pattern) {
final boolean[] isStateSet = dataInput.get().getStateSet(state);
if (m_useAmbiguities.get() || !dataInput.get().getDataType().isAmbiguousState(state)) {
for (int k = 0; k < stateCount; k++) {
isInvariant[k] &= isStateSet[k];
}
}
}
for (int k = 0; k < stateCount; k++) {
if (isInvariant[k]) {
constantPattern.add(i * stateCount + k);
}
}
}
}
protected void initCore() {
final int nodeCount = treeInput.get().getNodeCount();
likelihoodCore.initialize(
nodeCount,
dataInput.get().getPatternCount(),
m_siteModel.getCategoryCount(),
true, m_useAmbiguities.get()
);
final int extNodeCount = nodeCount / 2 + 1;
final int intNodeCount = nodeCount / 2;
if (m_useAmbiguities.get() || m_useTipLikelihoods.get()) {
setPartials(treeInput.get().getRoot(), dataInput.get().getPatternCount());
} else {
setStates(treeInput.get().getRoot(), dataInput.get().getPatternCount());
}
hasDirt = Tree.IS_FILTHY;
for (int i = 0; i < intNodeCount; i++) {
likelihoodCore.createNodePartials(extNodeCount + i);
}
}
/**
* This method samples the sequences based on the tree and site model.
*/
@Override
public void sample(State state, Random random) {
throw new UnsupportedOperationException("Can't sample a fixed alignment!");
}
/**
* set leaf states in likelihood core *
*/
protected void setStates(Node node, int patternCount) {
if (node.isLeaf()) {
Alignment data = dataInput.get();
int i;
int[] states = new int[patternCount];
int taxonIndex = getTaxonIndex(node.getID(), data);
for (i = 0; i < patternCount; i++) {
int code = data.getPattern(taxonIndex, i);
int[] statesForCode = data.getDataType().getStatesForCode(code);
if (statesForCode.length==1)
states[i] = statesForCode[0];
else
states[i] = code; // Causes ambiguous states to be ignored.
}
likelihoodCore.setNodeStates(node.getNr(), states);
} else {
setStates(node.getLeft(), patternCount);
setStates(node.getRight(), patternCount);
}
}
/**
*
* @param taxon the taxon name as a string
* @param data the alignment
* @return the taxon index of the given taxon name for accessing its sequence data in the given alignment,
* or -1 if the taxon is not in the alignment.
*/
private int getTaxonIndex(String taxon, Alignment data) {
int taxonIndex = data.getTaxonIndex(taxon);
if (taxonIndex == -1) {
if (taxon.startsWith("'") || taxon.startsWith("\"")) {
taxonIndex = data.getTaxonIndex(taxon.substring(1, taxon.length() - 1));
}
if (taxonIndex == -1) {
throw new RuntimeException("Could not find sequence " + taxon + " in the alignment");
}
}
return taxonIndex;
}
/**
* set leaf partials in likelihood core *
*/
protected void setPartials(Node node, int patternCount) {
if (node.isLeaf()) {
Alignment data = dataInput.get();
int states = data.getDataType().getStateCount();
double[] partials = new double[patternCount * states];
int k = 0;
int taxonIndex = getTaxonIndex(node.getID(), data);
for (int patternIndex_ = 0; patternIndex_ < patternCount; patternIndex_++) {
double[] tipLikelihoods = data.getTipLikelihoods(taxonIndex,patternIndex_);
if (tipLikelihoods != null) {
for (int state = 0; state < states; state++) {
partials[k++] = tipLikelihoods[state];
}
}
else {
int stateCount = data.getPattern(taxonIndex, patternIndex_);
boolean[] stateSet = data.getStateSet(stateCount);
for (int state = 0; state < states; state++) {
partials[k++] = (stateSet[state] ? 1.0 : 0.0);
}
}
}
likelihoodCore.setNodePartials(node.getNr(), partials);
} else {
setPartials(node.getLeft(), patternCount);
setPartials(node.getRight(), patternCount);
}
}
/**
* Calculate the log likelihood of the current state.
*
* @return the log likelihood.
*/
double m_fScale = 1.01;
int m_nScale = 0;
int X = 100;
@Override
public double calculateLogP() {
if (beagle != null) {
logP = beagle.calculateLogP();
return logP;
}
final TreeInterface tree = treeInput.get();
try {
if (traverse(tree.getRoot()) != Tree.IS_CLEAN)
calcLogP();
}
catch (ArithmeticException e) {
return Double.NEGATIVE_INFINITY;
}
m_nScale++;
if (logP > 0 || (likelihoodCore.getUseScaling() && m_nScale > X)) {
// System.err.println("Switch off scaling");
// m_likelihoodCore.setUseScaling(1.0);
// m_likelihoodCore.unstore();
// m_nHasDirt = Tree.IS_FILTHY;
// X *= 2;
// traverse(tree.getRoot());
// calcLogP();
// return logP;
} else if (logP == Double.NEGATIVE_INFINITY && m_fScale < 10 && !scaling.get().equals(Scaling.none)) { // && !m_likelihoodCore.getUseScaling()) {
m_nScale = 0;
m_fScale *= 1.01;
Log.warning.println("Turning on scaling to prevent numeric instability " + m_fScale);
likelihoodCore.setUseScaling(m_fScale);
likelihoodCore.unstore();
hasDirt = Tree.IS_FILTHY;
traverse(tree.getRoot());
calcLogP();
return logP;
}
return logP;
}
void calcLogP() {
logP = 0.0;
if (useAscertainedSitePatterns) {
final double ascertainmentCorrection = dataInput.get().getAscertainmentCorrection(patternLogLikelihoods);
for (int i = 0; i < dataInput.get().getPatternCount(); i++) {
logP += (patternLogLikelihoods[i] - ascertainmentCorrection) * dataInput.get().getPatternWeight(i);
}
} else {
for (int i = 0; i < dataInput.get().getPatternCount(); i++) {
logP += patternLogLikelihoods[i] * dataInput.get().getPatternWeight(i);
}
}
}
/* Assumes there IS a branch rate model as opposed to traverse() */
int traverse(final Node node) {
int update = (node.isDirty() | hasDirt);
final int nodeIndex = node.getNr();
final double branchRate = branchRateModel.getRateForBranch(node);
final double branchTime = node.getLength() * branchRate;
// First update the transition probability matrix(ices) for this branch
//if (!node.isRoot() && (update != Tree.IS_CLEAN || branchTime != m_StoredBranchLengths[nodeIndex])) {
if (!node.isRoot() && (update != Tree.IS_CLEAN || branchTime != m_branchLengths[nodeIndex])) {
m_branchLengths[nodeIndex] = branchTime;
final Node parent = node.getParent();
likelihoodCore.setNodeMatrixForUpdate(nodeIndex);
for (int i = 0; i < m_siteModel.getCategoryCount(); i++) {
final double jointBranchRate = m_siteModel.getRateForCategory(i, node) * branchRate;
substitutionModel.getTransitionProbabilities(node, parent.getHeight(), node.getHeight(), jointBranchRate, probabilities);
//System.out.println(node.getNr() + " " + Arrays.toString(m_fProbabilities));
likelihoodCore.setNodeMatrix(nodeIndex, i, probabilities);
}
update |= Tree.IS_DIRTY;
}
// If the node is internal, update the partial likelihoods.
if (!node.isLeaf()) {
// Traverse down the two child nodes
final Node child1 = node.getLeft(); //Two children
final int update1 = traverse(child1);
final Node child2 = node.getRight();
final int update2 = traverse(child2);
// If either child node was updated then update this node too
if (update1 != Tree.IS_CLEAN || update2 != Tree.IS_CLEAN) {
final int childNum1 = child1.getNr();
final int childNum2 = child2.getNr();
likelihoodCore.setNodePartialsForUpdate(nodeIndex);
update |= (update1 | update2);
if (update >= Tree.IS_FILTHY) {
likelihoodCore.setNodeStatesForUpdate(nodeIndex);
}
if (m_siteModel.integrateAcrossCategories()) {
likelihoodCore.calculatePartials(childNum1, childNum2, nodeIndex);
} else {
throw new RuntimeException("Error TreeLikelihood 201: Site categories not supported");
//m_pLikelihoodCore->calculatePartials(childNum1, childNum2, nodeNum, siteCategories);
}
if (node.isRoot()) {
// No parent this is the root of the beast.tree -
// calculate the pattern likelihoods
final double[] frequencies = //m_pFreqs.get().
substitutionModel.getFrequencies();
final double[] proportions = m_siteModel.getCategoryProportions(node);
likelihoodCore.integratePartials(node.getNr(), proportions, m_fRootPartials);
if (constantPattern != null) { // && !SiteModel.g_bUseOriginal) {
proportionInvariant = m_siteModel.getProportionInvariant();
// some portion of sites is invariant, so adjust root partials for this
for (final int i : constantPattern) {
m_fRootPartials[i] += proportionInvariant;
}
}
likelihoodCore.calculateLogLikelihoods(m_fRootPartials, frequencies, patternLogLikelihoods);
}
}
}
return update;
} // traverseWithBRM
/** CalculationNode methods **/
/**
* check state for changed variables and update temp results if necessary *
*/
@Override
protected boolean requiresRecalculation() {
if (beagle != null) {
return beagle.requiresRecalculation();
}
hasDirt = Tree.IS_CLEAN;
if (dataInput.get().isDirtyCalculation()) {
hasDirt = Tree.IS_FILTHY;
return true;
}
if (m_siteModel.isDirtyCalculation()) {
hasDirt = Tree.IS_DIRTY;
return true;
}
if (branchRateModel != null && branchRateModel.isDirtyCalculation()) {
//m_nHasDirt = Tree.IS_DIRTY;
return true;
}
return treeInput.get().somethingIsDirty();
}
@Override
public void store() {
if (beagle != null) {
beagle.store();
super.store();
return;
}
if (likelihoodCore != null) {
likelihoodCore.store();
}
super.store();
System.arraycopy(m_branchLengths, 0, storedBranchLengths, 0, m_branchLengths.length);
}
@Override
public void restore() {
if (beagle != null) {
beagle.restore();
super.restore();
return;
}
if (likelihoodCore != null) {
likelihoodCore.restore();
}
super.restore();
double[] tmp = m_branchLengths;
m_branchLengths = storedBranchLengths;
storedBranchLengths = tmp;
}
/**
* @return a list of unique ids for the state nodes that form the argument
*/
@Override
public List<String> getArguments() {
return Collections.singletonList(dataInput.get().getID());
}
/**
* @return a list of unique ids for the state nodes that make up the conditions
*/
@Override
public List<String> getConditions() {
return m_siteModel.getConditions();
}
} // class TreeLikelihood |
package com.pae14_1;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
public class HomePageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
ConnectBT connectBT = new ConnectBT();
connectBT.execute();
}
public void navigate(View v) {
Intent intent;
switch (v.getId()) {
case R.id.ultra_sonic:
intent = new Intent(HomePageActivity.this, UltraSonicActivity.class);
startActivity(intent);
break;
case R.id.infrared:
intent = new Intent(HomePageActivity.this, InfraRedActivity.class);
startActivity(intent);
break;
case R.id.rc:
intent = new Intent(HomePageActivity.this, RemoteControlActivity.class);
startActivity(intent);
break;
case R.id.self_balance:
intent = new Intent(HomePageActivity.this, SelfBalanceActivity.class);
startActivity(intent);
break;
}
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private boolean ConnectSuccess = true; //if it's here, it's almost connected
@Override
protected void onPreExecute() {
progress = ProgressDialog.show(HomePageActivity.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
@Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(Globals.address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
} catch (IOException e) {
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
@Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(HomePageActivity.this, HomePageActivity.this.getString(R.string.cnt_failed), Toast.LENGTH_LONG).show();
HomePageActivity.this.finish();
} else {
Toast.makeText(HomePageActivity.this, HomePageActivity.this.getString(R.string.connected), Toast.LENGTH_LONG).show();
isBtConnected = true;
}
progress.dismiss();
}
}
} |
package com.hp.hpl.jena.graph.test;
import com.hp.hpl.jena.util.HashUtils;
import com.hp.hpl.jena.util.iterator.*;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.graph.query.*;
import com.hp.hpl.jena.mem.GraphMem;
import com.hp.hpl.jena.shared.*;
import java.util.*;
/**
AbstractTestGraph provides a bunch of basic tests for something that
purports to be a Graph. The abstract method getGraph must be overridden
in subclasses to deliver a Graph of interest.
@author kers
*/
public /* abstract */ class AbstractTestGraph extends GraphTestBase
{
public AbstractTestGraph( String name )
{ super( name ); }
/**
Returns a Graph to take part in the test. Must be overridden in
a subclass.
*/
// public abstract Graph getGraph();
public Graph getGraph() { return new GraphMem(); }
public Graph getGraphWith( String facts )
{
Graph g = getGraph();
graphAdd( g, facts );
return g;
}
/**
This test case was generated by Ian and was caused by GraphMem
not keeping up with changes to the find interface.
*/
public void testFindAndContains()
{
Graph g = getGraph();
Node r = Node.create( "r" ), s = Node.create( "s" ), p = Node.create( "P" );
g.add( Triple.create( r, p, s ) );
assertTrue( g.contains( r, p, Node.ANY ) );
assertTrue( g.find( r, p, Node.ANY ).hasNext() );
}
public void testFindByFluidTriple()
{
Graph g = getGraph();
g.add( triple( "x y z ") );
assertTrue( g.find( triple( "?? y z" ) ).hasNext() );
assertTrue( g.find( triple( "x ?? z" ) ).hasNext() );
assertTrue( g.find( triple( "x y ??" ) ).hasNext() );
}
public void testContainsConcrete()
{
Graph g = getGraph();
graphAdd( g, "s P o; _x _R _y; x S 0" );
assertTrue( g.contains( triple( "s P o" ) ) );
assertTrue( g.contains( triple( "_x _R _y" ) ) );
assertTrue( g.contains( triple( "x S 0" ) ) );
assertFalse( g.contains( triple( "s P Oh" ) ) );
assertFalse( g.contains( triple( "S P O" ) ) );
assertFalse( g.contains( triple( "s p o" ) ) );
assertFalse( g.contains( triple( "_x _r _y" ) ) );
assertFalse( g.contains( triple( "x S 1" ) ) );
}
public void testContainsFluid()
{
Graph g = getGraph();
graphAdd( g, "x R y; a P b" );
assertTrue( g.contains( triple( "?? R y" ) ) );
assertTrue( g.contains( triple( "x ?? y" ) ) );
assertTrue( g.contains( triple( "x R ??" ) ) );
assertTrue( g.contains( triple( "?? P b" ) ) );
assertTrue( g.contains( triple( "a ?? b" ) ) );
assertTrue( g.contains( triple( "a P ??" ) ) );
assertTrue( g.contains( triple( "?? R y" ) ) );
assertFalse( g.contains( triple( "?? R b" ) ) );
assertFalse( g.contains( triple( "a ?? y" ) ) );
assertFalse( g.contains( triple( "x P ??" ) ) );
assertFalse( g.contains( triple( "?? R x" ) ) );
assertFalse( g.contains( triple( "x ?? R" ) ) );
assertFalse( g.contains( triple( "a S ??" ) ) );
}
/**
test isEmpty - moved from the QueryHandler code.
*/
public void testIsEmpty()
{
Graph g = getGraph();
if (canBeEmpty( g ))
{
assertTrue( g.isEmpty() );
g.add( Triple.create( "S P O" ) );
assertFalse( g.isEmpty() );
g.add( Triple.create( "A B C" ) );
assertFalse( g.isEmpty() );
g.add( Triple.create( "S P O" ) );
assertFalse( g.isEmpty() );
g.delete( Triple.create( "S P O" ) );
assertFalse( g.isEmpty() );
g.delete( Triple.create( "A B C" ) );
assertTrue( g.isEmpty() );
}
}
public void testAGraph()
{
String title = this.getClass().getName();
Graph g = getGraph();
int baseSize = g.size();
graphAdd( g, "x R y; p S q; a T b" );
assertContainsAll( title + ": simple graph", g, "x R y; p S q; a T b" );
assertEquals( title + ": size", baseSize + 3, g.size() );
graphAdd( g, "spindizzies lift cities; Diracs communicate instantaneously" );
assertEquals( title + ": size after adding", baseSize + 5, g.size() );
g.delete( triple( "x R y" ) );
g.delete( triple( "a T b" ) );
assertEquals( title + ": size after deleting", baseSize + 3, g.size() );
assertContainsAll( title + ": modified simple graph", g, "p S q; spindizzies lift cities; Diracs communicate instantaneously" );
assertOmitsAll( title + ": modified simple graph", g, "x R y; a T b" );
ClosableIterator it = g.find( null, node("lift"), null );
assertTrue( title + ": finds some triple(s)", it.hasNext() );
assertEquals( title + ": finds a 'lift' triple", triple("spindizzies lift cities"), it.next() );
assertFalse( title + ": finds exactly one triple", it.hasNext() );
}
// public void testStuff()
//// testAGraph( "StoreMem", new GraphMem() );
//// testAGraph( "StoreMemBySubject", new GraphMem() );
//// String [] empty = new String [] {};
//// Graph g = graphWith( "x R y; p S q; a T b" );
////
//// assertContainsAll( "simple graph", g, "x R y; p S q; a T b" );
//// graphAdd( g, "spindizzies lift cities; Diracs communicate instantaneously" );
//// g.delete( triple( "x R y" ) );
//// g.delete( triple( "a T b" ) );
//// assertContainsAll( "modified simple graph", g, "p S q; spindizzies lift cities; Diracs communicate instantaneously" );
//// assertOmitsAll( "modified simple graph", g, "x R y; a T b" );
/**
Test that Graphs have transaction support methods, and that if they fail
on some g they fail because they do not support the operation.
*/
public void testHasTransactions()
{
Graph g = getGraph();
TransactionHandler th = g.getTransactionHandler();
th.transactionsSupported();
try { th.begin(); } catch (UnsupportedOperationException x) {}
try { th.abort(); } catch (UnsupportedOperationException x) {}
try { th.commit(); } catch (UnsupportedOperationException x) {}
Command cmd = new Command()
{ public Object execute() { return null; } };
try { th.executeInTransaction( cmd ); }
catch (UnsupportedOperationException x) {}
}
static final Triple [] tripleArray = tripleArray( "S P O; A R B; X Q Y" );
static final List tripleList = Arrays.asList( tripleArray( "i lt j; p equals q" ) );
static final Triple [] setTriples = tripleArray
( "scissors cut paper; paper wraps stone; stone breaks scissors" );
static final Set tripleSet = HashUtils.createSet( Arrays.asList( setTriples ) );
public void testBulkUpdate()
{
Graph g = getGraph();
BulkUpdateHandler bu = g.getBulkUpdateHandler();
Graph items = graphWith( "pigs might fly; dead can dance" );
int initialSize = g.size();
bu.add( tripleArray );
testContains( g, tripleArray );
testOmits( g, tripleList );
bu.add( tripleList );
testContains( g, tripleList );
testContains( g, tripleArray );
bu.add( tripleSet.iterator() );
testContains( g, tripleSet.iterator() );
testContains( g, tripleList );
testContains( g, tripleArray );
bu.add( items );
testContains( g, items );
testContains( g, tripleSet.iterator() );
testContains( g, tripleArray );
testContains( g, tripleList );
bu.delete( tripleArray );
testOmits( g, tripleArray );
testContains( g, tripleList );
testContains( g, tripleSet.iterator() );
testContains( g, items );
bu.delete( tripleSet.iterator() );
testOmits( g, tripleSet.iterator() );
testOmits( g, tripleArray );
testContains( g, tripleList );
testContains( g, items );
bu.delete( items );
testOmits( g, tripleSet.iterator() );
testOmits( g, tripleArray );
testContains( g, tripleList );
testOmits( g, items );
bu.delete( tripleList );
assertEquals( "graph has original size", initialSize, g.size() );
}
public void testBulkAddWithReification()
{
testBulkAddWithReification( false );
testBulkAddWithReification( true );
}
public void testBulkAddWithReificationPreamble()
{
Graph g = getGraph();
xSPO( g.getReifier() );
assertFalse( g.getReifier().getReificationTriples().isEmpty() );
}
public void testBulkAddWithReification( boolean withReifications )
{
Graph graphToUpdate = getGraph();
BulkUpdateHandler bu = graphToUpdate.getBulkUpdateHandler();
Graph graphToAdd = graphWith( "pigs might fly; dead can dance" );
Reifier updatedReifier = graphToUpdate.getReifier();
Reifier addedReifier = graphToAdd.getReifier();
xSPOyXYZ( addedReifier );
bu.add( graphToAdd, withReifications );
assertIsomorphic
(
withReifications ? addedReifier.getReificationTriples() : graphWith( "" ),
updatedReifier.getReificationTriples()
);
}
protected void xSPOyXYZ( Reifier r )
{
xSPO( r );
r.reifyAs( Node.create( "y" ), Triple.create( "X Y Z" ) );
}
protected void aABC( Reifier r )
{ r.reifyAs( Node.create( "a" ), Triple.create( "A B C" ) ); }
protected void xSPO( Reifier r )
{ r.reifyAs( Node.create( "x" ), Triple.create( "S P O" ) ); }
public void testRemove()
{
testRemove( "S ?? ??", "S ?? ??" );
testRemove( "S ?? ??", "?? P ??" );
testRemove( "S ?? ??", "?? ?? O" );
testRemove( "?? P ??", "S ?? ??" );
testRemove( "?? P ??", "?? P ??" );
testRemove( "?? P ??", "?? ?? O" );
testRemove( "?? ?? O", "S ?? ??" );
testRemove( "?? ?? O", "?? P ??" );
testRemove( "?? ?? O", "?? ?? O" );
}
public void testRemove( String findRemove, String findCheck )
{
Graph g = getGraphWith( "S P O" );
ExtendedIterator it = g.find( Triple.create( findRemove ) );
try
{
it.next(); it.remove(); it.close();
assertFalse( g.contains( Triple.create( findCheck ) ) );
}
catch (UnsupportedOperationException e)
{ assertFalse( g.getCapabilities().iteratorRemoveAllowed() ); }
}
public void testBulkRemoveWithReification()
{
testBulkUpdateRemoveWithReification( true );
testBulkUpdateRemoveWithReification( false );
}
public void testBulkUpdateRemoveWithReification( boolean withReifications )
{
Graph g = getGraph();
BulkUpdateHandler bu = g.getBulkUpdateHandler();
Graph items = graphWith( "pigs might fly; dead can dance" );
Reifier gr = g.getReifier(), ir = items.getReifier();
xSPOyXYZ( ir );
xSPO( gr ); aABC( gr );
bu.delete( items, withReifications );
Graph answer = graphWith( "" );
Reifier ar = answer.getReifier();
if (withReifications)
aABC( ar );
else
{
xSPO( ar );
aABC( ar );
}
assertIsomorphic( ar.getReificationTriples(), gr.getReificationTriples() );
}
public void testHasCapabilities()
{
Graph g = getGraph();
Capabilities c = g.getCapabilities();
boolean sa = c.sizeAccurate();
boolean aaSome = c.addAllowed();
boolean aaAll = c.addAllowed( true );
boolean daSome = c.deleteAllowed();
boolean daAll = c.deleteAllowed( true );
boolean cbe = c.canBeEmpty();
}
public void testFind()
{
Graph g = getGraph();
graphAdd( g, "S P O" );
assertTrue( g.find( Node.ANY, null, null ).hasNext() );
assertTrue( g.find( null, Node.ANY, null ).hasNext() );
}
public void testFind2()
{
Graph g = getGraphWith( "S P O" );
TripleIterator waitingForABigRefactoringHere = null;
ExtendedIterator it = g.find( Node.ANY, Node.ANY, Node.ANY );
}
protected boolean canBeEmpty( Graph g )
{ return g.isEmpty(); }
public void testEventRegister()
{
Graph g = getGraph();
GraphEventManager gem = g.getEventManager();
assertSame( gem, gem.register( new RecordingListener() ) );
}
/**
Test that we can safely unregister a listener that isn't registered.
*/
public void testEventUnregister()
{
getGraph().getEventManager().unregister( L );
}
/**
Handy triple for test purposes.
*/
protected Triple SPO = Triple.create( "S P O" );
protected RecordingListener L = new RecordingListener();
/**
Utility: get a graph, register L with its manager, return the graph.
*/
protected Graph getAndRegister( GraphListener gl )
{
Graph g = getGraph();
g.getEventManager().register( gl );
return g;
}
public void testAddTriple()
{
Graph g = getAndRegister( L );
g.add( SPO );
L.assertHas( new Object[] {"add", g, SPO} );
}
public void testDeleteTriple()
{
Graph g = getAndRegister( L );
g.delete( SPO );
L.assertHas( new Object[] { "delete", g, SPO} );
}
public void testTwoListeners()
{
RecordingListener L1 = new RecordingListener();
RecordingListener L2 = new RecordingListener();
Graph g = getGraph();
GraphEventManager gem = g.getEventManager();
gem.register( L1 ).register( L2 );
g.add( SPO );
L2.assertHas( new Object[] {"add", g, SPO} );
L1.assertHas( new Object[] {"add", g, SPO} );
}
public void testUnregisterWorks()
{
Graph g = getGraph();
GraphEventManager gem = g.getEventManager();
gem.register( L ).unregister( L );
g.add( SPO );
L.assertHas( new Object[] {} );
}
public void testRegisterTwice()
{
Graph g = getAndRegister( L );
g.getEventManager().register( L );
g.add( SPO );
L.assertHas( new Object[] {"add", g, SPO, "add", g, SPO} );
}
public void testUnregisterOnce()
{
Graph g = getAndRegister( L );
g.getEventManager().register( L ).unregister( L );
g.delete( SPO );
L.assertHas( new Object[] {"delete", g, SPO} );
}
public void testBulkAddArrayEvent()
{
Graph g = getAndRegister( L );
Triple [] triples = tripleArray( "x R y; a P b" );
g.getBulkUpdateHandler().add( triples );
L.assertHas( new Object[] {"add[]", g, triples} );
}
public void testBulkAddList()
{
Graph g = getAndRegister( L );
List elems = Arrays.asList( tripleArray( "bells ring loudly; pigs might fly" ) );
g.getBulkUpdateHandler().add( elems );
L.assertHas( new Object[] {"addList", g, elems} );
}
public void testBulkDeleteArray()
{
Graph g = getAndRegister( L );
Triple [] triples = tripleArray( "x R y; a P b" );
g.getBulkUpdateHandler().delete( triples );
L.assertHas( new Object[] {"delete[]", g, triples} );
}
public void testBulkDeleteList()
{
Graph g = getAndRegister( L );
List elems = Arrays.asList( tripleArray( "bells ring loudly; pigs might fly" ) );
g.getBulkUpdateHandler().delete( elems );
L.assertHas( new Object[] {"deleteList", g, elems} );
}
public void testBulkAddIterator()
{
Graph g = getAndRegister( L );
Triple [] triples = tripleArray( "I wrote this; you read that; I wrote this" );
g.getBulkUpdateHandler().add( asIterator( triples ) );
L.assertHas( new Object[] {"addIterator", g, Arrays.asList( triples )} );
}
public void testBulkDeleteIterator()
{
Graph g = getAndRegister( L );
Triple [] triples = tripleArray( "I wrote this; you read that; I wrote this" );
g.getBulkUpdateHandler().delete( asIterator( triples ) );
L.assertHas( new Object[] {"deleteIterator", g, Arrays.asList( triples )} );
}
public Iterator asIterator( Triple [] triples )
{ return Arrays.asList( triples ).iterator(); }
public void testBulkAddGraph()
{
Graph g = getAndRegister( L );
Graph triples = graphWith( "this type graph; I type slowly" );
g.getBulkUpdateHandler().add( triples );
L.assertHas( new Object[] {"addGraph", g, triples} );
}
public void testBulkDeleteGraph()
{
Graph g = getAndRegister( L );
Graph triples = graphWith( "this type graph; I type slowly" );
g.getBulkUpdateHandler().delete( triples );
L.assertHas( new Object[] {"deleteGraph", g, triples} );
}
public void testGeneralEvent()
{
Graph g = getAndRegister( L );
Object value = new int[]{};
g.getEventManager().notifyEvent( g, value );
L.assertHas( new Object[] { "someEvent", g, value } );
}
public void testRemoveAllEvent()
{
Graph g = getAndRegister( L );
g.getBulkUpdateHandler().removeAll();
L.assertHas( new Object[] { "someEvent", g, GraphEvents.removeAll } );
}
public void testRemoveSomeEvent()
{
Graph g = getAndRegister( L );
Node S = node( "S" ), P = node( "?P" ), O = node( "??" );
g.getBulkUpdateHandler().remove( S, P, O );
Object event = GraphEvents.remove( S, P, O );
L.assertHas( new Object[] { "someEvent", g, event } );
}
/**
* Test that nodes can be found in all triple positions.
* However, testing for literals in subject positions is suppressed
* at present to avoid problems with InfGraphs which try to prevent
* such constructs leaking out to the RDF layer.
*/
public void testContainsNode()
{
Graph g = getGraph();
graphAdd( g, "a P b; _c _Q _d; a 11 12" );
QueryHandler qh = g.queryHandler();
assertTrue( qh.containsNode( node( "a" ) ) );
assertTrue( qh.containsNode( node( "P" ) ) );
assertTrue( qh.containsNode( node( "b" ) ) );
assertTrue( qh.containsNode( node( "_c" ) ) );
assertTrue( qh.containsNode( node( "_Q" ) ) );
assertTrue( qh.containsNode( node( "_d" ) ) );
// assertTrue( qh.containsNode( node( "10" ) ) );
assertTrue( qh.containsNode( node( "11" ) ) );
assertTrue( qh.containsNode( node( "12" ) ) );
assertFalse( qh.containsNode( node( "x" ) ) );
assertFalse( qh.containsNode( node( "_y" ) ) );
assertFalse( qh.containsNode( node( "99" ) ) );
}
public void testRemoveAll()
{
testRemoveAll( "" );
testRemoveAll( "a R b" );
testRemoveAll( "c S d; e:ff GGG hhhh; _i J 27; Ell Em 'en'" );
}
public void testRemoveAll( String triples )
{
Graph g = getGraph();
graphAdd( g, triples );
g.getBulkUpdateHandler().removeAll();
assertTrue( g.isEmpty() );
}
/**
Test cases for RemoveSPO(); each entry is a triple (add, remove, result).
<ul>
<li>add - the triples to add to the graph to start with
<li>remove - the pattern to use in the removal
<li>result - the triples that should remain in the graph
</ul>
*/
protected String[][] cases =
{
{ "x R y", "x R y", "" },
{ "x R y; a P b", "x R y", "a P b" },
{ "x R y; a P b", "?? R y", "a P b" },
{ "x R y; a P b", "x R ??", "a P b" },
{ "x R y; a P b", "x ?? y", "a P b" },
{ "x R y; a P b", "?? ?? ??", "" },
{ "x R y; a P b; c P d", "?? P ??", "x R y" },
{ "x R y; a P b; x S y", "x ?? ??", "a P b" },
};
/**
Test that remove(s, p, o) works, in the presence of inferencing graphs that
mean emptyness isn't available. This is why we go round the houses and
test that expected ~= initialContent + addedStuff - removed - initialContent.
*/
public void testRemoveSPO()
{
for (int i = 0; i < cases.length; i += 1)
for (int j = 0; j < 3; j += 1)
{
Graph content = getGraph();
Graph baseContent = copy( content );
graphAdd( content, cases[i][0] );
Triple remove = triple( cases[i][1] );
Graph expected = graphWith( cases[i][2] );
content.getBulkUpdateHandler().remove( remove.getSubject(), remove.getPredicate(), remove.getObject() );
Graph finalContent = remove( copy( content ), baseContent );
assertIsomorphic( cases[i][1], expected, finalContent );
}
}
protected void add( Graph toUpdate, Graph toAdd )
{
toUpdate.getBulkUpdateHandler().add( toAdd );
}
protected Graph remove( Graph toUpdate, Graph toRemove )
{
toUpdate.getBulkUpdateHandler().delete( toRemove );
return toUpdate;
}
protected Graph copy( Graph g )
{
Graph result = Factory.createDefaultGraph();
result.getBulkUpdateHandler().add( g );
return result;
}
protected Graph getClosed()
{
Graph result = getGraph();
result.close();
return result;
}
// public void testClosedDelete()
// try { getClosed().delete( triple( "x R y" ) ); fail( "delete when closed" ); }
// catch (ClosedException c) { /* as required */ }
// public void testClosedAdd()
// try { getClosed().add( triple( "x R y" ) ); fail( "add when closed" ); }
// catch (ClosedException c) { /* as required */ }
// public void testClosedContainsTriple()
// try { getClosed().contains( triple( "x R y" ) ); fail( "contains[triple] when closed" ); }
// catch (ClosedException c) { /* as required */ }
// public void testClosedContainsSPO()
// Node a = Node.ANY;
// try { getClosed().contains( a, a, a ); fail( "contains[SPO] when closed" ); }
// catch (ClosedException c) { /* as required */ }
// public void testClosedFindTriple()
// try { getClosed().find( triple( "x R y" ) ); fail( "find [triple] when closed" ); }
// catch (ClosedException c) { /* as required */ }
// public void testClosedFindSPO()
// Node a = Node.ANY;
// try { getClosed().find( a, a, a ); fail( "find[SPO] when closed" ); }
// catch (ClosedException c) { /* as required */ }
// public void testClosedSize()
// try { getClosed().size(); fail( "size when closed (" + this.getClass() + ")" ); }
// catch (ClosedException c) { /* as required */ }
} |
package com.jaselogic.adamsonelearn;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.jsoup.select.Elements;
import com.jaselogic.adamsonelearn.DocumentManager.DocumentCookie;
import com.jaselogic.adamsonelearn.DocumentManager.ResponseReceiver;
import com.jaselogic.adamsonelearn.SubjectListAdapter.SubjectListItem;
import com.jaselogic.adamsonelearn.TodayListAdapter.TodayListItem;
import com.jaselogic.adamsonelearn.UpdatesListAdapter.UpdatesListItem;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
class HomePageFragment {
//Page fragment class
public static class UpdatesFragment extends ListFragment implements ResponseReceiver {
private final static String SELECTOR_UPDATES_PAGE = "tr";
private final static String SELECTOR_SUBJECT = "div > div:nth-of-type(1) span";
private final static String SELECTOR_TITLE = "div > div:nth-of-type(2) span";
private final static String SELECTOR_BODY = "div > div:nth-of-type(3) span";
private final static String SELECTOR_DATE = "div > div:nth-of-type(4)";
private final static String SELECTOR_AVATAR = "img[alt=Avatar]";
private final static String SELECTOR_TEACHER = "span.teachername";
private String cookie;
private UpdatesListAdapter adapter;
private ArrayList<UpdatesListItem> updateArrayList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View pageRootView = inflater.inflate(R.layout.fragment_listview,
container, false);
updateArrayList = new ArrayList<UpdatesListItem>();
adapter = new UpdatesListAdapter(getActivity(), updateArrayList);
setListAdapter(adapter);
//get original cookie
cookie = ((Dashboard)getActivity()).cookie;
return pageRootView;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
new DocumentManager.DownloadDocumentTask(UpdatesFragment.this,
DocumentManager.PAGE_UPDATES, cookie).execute();
}
};
//listen to subject list ready event
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(mMessageReceiver, new IntentFilter("subject-list-ready"));
}
@Override
public void onPause() {
LocalBroadcastManager.getInstance(getActivity())
.unregisterReceiver(mMessageReceiver);
super.onPause();
}
@Override
public void onResourceReceived(DocumentCookie res) throws IOException {
//open database
SQLiteDatabase eLearnDb = getActivity().openOrCreateDatabase("AdUELearn", Context.MODE_PRIVATE, null);
//drop table if it exists
eLearnDb.execSQL("DROP TABLE IF EXISTS UpdatesTable;");
//create the table
eLearnDb.execSQL("CREATE TABLE UpdatesTable " +
"(SectionId INTEGER, Title TEXT, " +
"Body TEXT, DateAdded INTEGER);");
//Root node for updates page.
Elements updates = res.document.select(SELECTOR_UPDATES_PAGE);
Elements teacher = updates.select(SELECTOR_TEACHER);
Elements subject = updates.select(SELECTOR_SUBJECT);
Elements title = updates.select(SELECTOR_TITLE);
Elements body = updates.select(SELECTOR_BODY);
Elements dateAdded = updates.select(SELECTOR_DATE);
Elements avatarSrc = updates.select(SELECTOR_AVATAR);
//SQL Statement
String sqlUpdates = "INSERT INTO UpdatesTable VALUES (?,?,?,?);";
SQLiteStatement stUpdates = eLearnDb.compileStatement(sqlUpdates);
//begin SQL transaction
eLearnDb.beginTransaction();
for(int i = 0; i < subject.size(); i++) {
UpdatesListItem updateItem = new UpdatesListItem();
updateItem.name = teacher.get(i).text().trim();
updateItem.subject = subject.get(i).text().trim();
updateItem.title = title.get(i).text().trim();
updateItem.body = body.get(i).text().trim();
updateItem.dateAdded = dateAdded.get(i).text().trim();
int subjCode = Integer.parseInt(
updateItem.subject.substring(0, updateItem.subject.indexOf(' '))
);
DateFormat formatter = new SimpleDateFormat(
"'Date Added : 'MMM dd, yyyy 'at' hh:mm:ss aa");
Date date = null;
try {
date = (Date) formatter.parse(updateItem.dateAdded);
} catch (ParseException e) {
e.printStackTrace();
}
Log.d("STAHP",
date.toString()
);
String src = avatarSrc.get(i).attr("src");
updateItem.avatarSrc = "http://learn.adamson.edu.ph/" + src.substring(3,
(src.indexOf('#') > 0 ? src.indexOf('#') : src.length()));
//add item to database
stUpdates.clearBindings();
stUpdates.bindLong(1, subjCode);
stUpdates.bindString(2, updateItem.title);
stUpdates.bindString(3, updateItem.body);
stUpdates.bindLong(4, date.getTime());
stUpdates.execute();
updateArrayList.add(updateItem);
}
//set transaction success, then end transaction
eLearnDb.setTransactionSuccessful();
eLearnDb.endTransaction();
Cursor c = eLearnDb.rawQuery(
"SELECT SubjTable.ProfName, UpdatesTable.SectionId, " +
"SubjTable.SubjName, UpdatesTable.Title, " +
"UpdatesTable.Body, UpdatesTable.DateAdded " +
"FROM UpdatesTable LEFT JOIN SubjTable ON " +
"UpdatesTable.SectionId=SubjTable.SectionId", null);
adapter.notifyDataSetChanged();
//close database
eLearnDb.close();
}
}
public static class SubjectsFragment extends ListFragment implements ResponseReceiver {
private final static String SELECTOR_SUBJECTS_PAGE = "td";
private final static String SELECTOR_AVATAR = "img[alt=Avatar]";
private final static String SELECTOR_TEACHER = "div.teachername";
private final static String SELECTOR_SUBJECTNAME = "div.lectitle";
private final static String SELECTOR_SCHEDULE = "div.addeddate";
private String cookie;
private SubjectListAdapter adapter;
private ArrayList<SubjectListItem> subjectArrayList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View pageRootView = inflater.inflate(R.layout.fragment_listview,
container, false);
subjectArrayList = new ArrayList<SubjectListItem>();
adapter = new SubjectListAdapter(getActivity(), subjectArrayList);
setListAdapter(adapter);
//get original cookie
cookie = ((Dashboard)getActivity()).cookie;
new DocumentManager.DownloadDocumentTask(SubjectsFragment.this,
DocumentManager.PAGE_SUBJECTS, cookie).execute();
return pageRootView;
}
@Override
public void onResourceReceived(DocumentCookie res)
throws IOException {
//open or create elearn database
SQLiteDatabase eLearnDb = getActivity().openOrCreateDatabase("AdUELearn", Context.MODE_PRIVATE, null);
//add subjects to database
addSubjectsToDatabase(res, eLearnDb);
//Broadcast subject-list-ready event
broadcastListReady();
//display subjects in subject list view
displaySubjects(eLearnDb);
//close database
eLearnDb.close();
}
public void broadcastListReady() {
Intent intent = new Intent("subject-list-ready");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}
public void addSubjectsToDatabase(DocumentCookie res, SQLiteDatabase eLearnDb) {
//Root node for updates page.
Elements updates = res.document.select(SELECTOR_SUBJECTS_PAGE);
Elements teacher = updates.select(SELECTOR_TEACHER);
Elements subject = updates.select(SELECTOR_SUBJECTNAME);
Elements schedule = updates.select(SELECTOR_SCHEDULE);
Elements avatarSrc = updates.select(SELECTOR_AVATAR);
//drop subject table if it exists
eLearnDb.execSQL("DROP TABLE IF EXISTS SubjTable");
//create subj table
/*
* DaySlots can be implemented as boolean type for each day
* (hasMonday, hasTuesday etc..) but since there is no boolean
* primitive type for SQLite and type affinity of boolean is an
* 8-bit integer, it would consume more space than having a single
* column for day slots.
* Days are represented as a 6-bit integer
* 0 bit when subject has no slot, otherwise 1
* Monday starts at the least significant bit, up to 6th bit which is saturday
* example:
* for MWF subjects: 010101b = 21
* for Sat subjects: 100000b = 32
* for subjects with Tuesday: xxxx1x or (dayslot | (1 << 1));
*
* TimeStart is the time slot start per day with 0 = 7:00am
* and increments for every 30mins. (e.g. 1 = 7:30, 2 = 8:00)
*
* TimeEnd is the time slot end per day with 0 = 7:00am
* and increments for every 30mins.
*/
eLearnDb.execSQL("CREATE TABLE SubjTable " +
"(SectionId INTEGER, SubjName TEXT, " +
"ProfName TEXT, DaySlot INTEGER, " +
"TimeStart INTEGER, TimeEnd INTEGER, Room TEXT, " +
"AvatarSrc TEXT);");
//SQL Statement
String sqlSubj = "INSERT INTO SubjTable VALUES (?,?,?,?,?,?,?,?);";
SQLiteStatement stSubj = eLearnDb.compileStatement(sqlSubj);
//create a transaction to minimize database insertion times
eLearnDb.beginTransaction();
for(int i = 0; i < subject.size(); i++) {
SubjectListItem subjectItem = new SubjectListItem();
subjectItem.teacher = teacher.get(i).text().trim();
subjectItem.subject = subject.get(i).text().trim();
subjectItem.schedule = schedule.get(i).text().trim();
//get the index of ':' separator of subject and section id
int sepIndex = subjectItem.subject.indexOf(':');
//extract the section id from the subject
int sectionId = Integer.parseInt(subjectItem.subject
.substring(0, sepIndex - 1)
);
//extract the subject name
String subjName = subjectItem.subject.substring(sepIndex + 2);
//extract the day slots
//get the index of the first space
int firstSpaceIndex = subjectItem.schedule.indexOf(' ');
String daySlotString = subjectItem.schedule
.substring(0, firstSpaceIndex);
int daySlot = ScheduleHelper.convertStringToIntDaySlot(daySlotString);
//extract timeslots
String timeSlotString = subjectItem.schedule = subjectItem.schedule
.substring(firstSpaceIndex).trim();
//get next space index
int nextSpaceIndex = timeSlotString.indexOf(' ');
timeSlotString = timeSlotString.substring(0, nextSpaceIndex);
//01:34-67:90
//convert to integer timeslot
String startString = timeSlotString.substring(0, 5);
String endString = timeSlotString.substring(6, 11);
int startSlot = ScheduleHelper.convertStringToIntSlot(startString);
int endSlot = ScheduleHelper.convertStringToIntSlot(endString);
//extract room
String room = subjectItem.schedule.substring(nextSpaceIndex).trim();
String src = avatarSrc.get(i).attr("src");
subjectItem.avatarSrc = "http://learn.adamson.edu.ph/" + src.substring(3,
(src.indexOf('#') > 0 ? src.indexOf('#') : src.length()));
//add item to database.
stSubj.clearBindings();
stSubj.bindLong(1, sectionId);
stSubj.bindString(2, subjName);
stSubj.bindString(3, subjectItem.teacher);
stSubj.bindLong(4, daySlot);
stSubj.bindLong(5, startSlot);
stSubj.bindLong(6, endSlot);
stSubj.bindString(7, room);
stSubj.bindString(8, subjectItem.avatarSrc);
stSubj.execute();
//subjectArrayList.add(subjectItem);
}
//set transaction successful, then end transaction
eLearnDb.setTransactionSuccessful();
eLearnDb.endTransaction();
}
public void displaySubjects(SQLiteDatabase eLearnDb) {
//issue select
Cursor c = eLearnDb.rawQuery("SELECT * FROM SubjTable", null);
while(c.moveToNext()) {
SubjectListItem subjectItem = new SubjectListItem();
StringBuilder sbSubject = new StringBuilder(
String.format("%05d", c.getInt(c.getColumnIndex("SectionId")))
);
sbSubject.append(" : ");
sbSubject.append(c.getString(c.getColumnIndex("SubjName")));
subjectItem.subject = sbSubject.toString();
subjectItem.teacher = c.getString(c.getColumnIndex("ProfName"));
StringBuilder sbSchedule = new StringBuilder(
ScheduleHelper.convertIntToStringDaySlot(c.getInt(c.getColumnIndex("DaySlot")))
);
sbSchedule.append(" ");
sbSchedule.append(
ScheduleHelper.convertIntToStringSlot(
c.getInt(c.getColumnIndex("TimeStart")),
c.getInt(c.getColumnIndex("TimeEnd")) )
);
sbSchedule.append(" ");
sbSchedule.append(c.getString(c.getColumnIndex("Room")));
subjectItem.schedule = sbSchedule.toString();
subjectItem.avatarSrc = c.getString(c.getColumnIndex("AvatarSrc"));
subjectArrayList.add(subjectItem);
}
adapter.notifyDataSetChanged();
}
}
public static class TodayFragment extends ListFragment {
private TodayListAdapter adapter;
private ArrayList<TodayListItem> todayArrayList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup pageRootView = (ViewGroup) inflater.inflate(
R.layout.fragment_listview, container, false);
todayArrayList = new ArrayList<TodayListItem>();
adapter = new TodayListAdapter(getActivity(), todayArrayList);
setListAdapter(adapter);
return pageRootView;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//get current time
Time timeNow = new Time();
timeNow.setToNow();
//open database
SQLiteDatabase eLearnDb = getActivity().openOrCreateDatabase("AdUELearn", Context.MODE_PRIVATE, null);
populateTodayListView(timeNow, eLearnDb);
//close database
eLearnDb.close();
}
};
//listen to subject list ready event
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(mMessageReceiver, new IntentFilter("subject-list-ready"));
}
@Override
public void onPause() {
LocalBroadcastManager.getInstance(getActivity())
.unregisterReceiver(mMessageReceiver);
super.onPause();
}
public void populateTodayListView(Time timeNow, SQLiteDatabase eLearnDb) {
Cursor c = eLearnDb.rawQuery(
"SELECT * FROM SubjTable WHERE DaySlot & ? > 1 " +
"ORDER BY TimeStart",
new String[] { String.valueOf(1 << (timeNow.weekDay - 1)) }
);
int timeSlotNow = ScheduleHelper.convertTimeToIntSlot(timeNow);
short indicator = 0; // 1 = NOW, 2 = NEXT
while(c.moveToNext()) {
int curTimeStart = c.getInt(c.getColumnIndex("TimeStart"));
int curTimeEnd = c.getInt(c.getColumnIndex("TimeEnd"));
TodayListItem tempItem = new TodayListItem();
TodayListItem tempTitle = new TodayListItem();
tempTitle.viewType = TodayListAdapter.ItemType.ITEM_TITLE;
if( timeSlotNow < curTimeStart && (indicator & 2) == 0 ) { //WALANG PANG NOW at NEXT
tempItem.viewType = TodayListAdapter.ItemType.ITEM_NEXT;
tempTitle.mainText = "NEXT:";
todayArrayList.add(tempTitle);
indicator |= 2;
} else if ( timeSlotNow >= curTimeStart && timeSlotNow < curTimeEnd ) { //Now
tempItem.viewType = TodayListAdapter.ItemType.ITEM_NOW;
tempTitle.mainText = "NOW:";
todayArrayList.add(tempTitle);
indicator |= 1;
} else if ( timeSlotNow < curTimeStart ) {
tempTitle.mainText = "LATER:";
tempItem.viewType = TodayListAdapter.ItemType.ITEM_LATER;
if ( indicator < 4 )
todayArrayList.add(tempTitle);
indicator |= 4;
}
//if now bit is unset after first pass, set it
if( (indicator & 1) == 0 && (indicator & 2) == 2 ) {
tempItem.viewType = TodayListAdapter.ItemType.ITEM_NOW;
indicator |= 1;
}
//add to list here.
if(indicator > 0) {
tempItem.mainText = c.getString(c.getColumnIndex("SubjName"));
tempItem.timeText = ScheduleHelper
.convertIntToStringSlot(curTimeStart, curTimeEnd);
tempItem.roomText = c.getString(c.getColumnIndex("Room"));
todayArrayList.add(tempItem);
}
}
adapter.notifyDataSetChanged();
}
}
} |
package com.quirkygaming.propertylib;
import java.io.Serializable;
import com.quirkygaming.propertylib.PropertyObserver.EventType;
/**
* An extension of Property<T> with the addition of a set method.
*
* @author Chandler Griscom
* @version 1.0
*/
public class MutableProperty<T> extends BoundProperty<T> implements Serializable {
private static final long serialVersionUID = -6764130456697090580L;
/**
* Constructs a new MutableProperty with type T as specified by initialValue.
*
* @param initialValue Provides the initial value of the MutableProperty as well as its type.
* @return The newly constructed MutableProperty
*/
public static <T> MutableProperty<T> newProperty(T initialValue) {
return new MutableProperty<T>(new PropertyImpl<T>(initialValue));
}
/**
* Constructs a new clone-on-get MutableProperty with type T as specified by initialValue.
*
* @param initialValue Provides the initial value of the MutableProperty as well as its type.
* @return The newly constructed MutableProperty
*/
public static <T extends Cloneable> MutableProperty<T> newClonableProperty(T initialValue) {
return new MutableProperty<T>(new CloningProperty<T>(initialValue));
}
MutableProperty(Property<T> property) {
super(property);
}
/**
* Sets the value of this MutableProperty
*/
public void set(T v) {
signal(EventType.SET);
super.setInternal(v);
}
/**
* Returns an immutable (Property) version of this MutableProperty.
*
* @return The immutable version
*/
public Property<T> getImmutable() {
return super.getInternalProperty();
}
/**
* Construct (if necessary) and return a mutator for this Property
* @return The Mutator
*/
public Mutator getMutator() {
if (mutator == null) {
mutator = new Mutator();
}
return mutator;
}
} |
package com.speedment.codegen.java.models;
import com.speedment.codegen.base.CodeModel;
import com.speedment.codegen.java.interfaces.Annotable;
import com.speedment.codegen.java.interfaces.Dependable;
import com.speedment.codegen.java.interfaces.Documentable;
import com.speedment.codegen.java.interfaces.Fieldable;
import com.speedment.codegen.java.interfaces.Modifiable;
import com.speedment.codegen.java.interfaces.Nameable;
import com.speedment.codegen.java.models.modifiers.Modifier;
import com.speedment.util.Copier;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
*
* @author Emil Forslund
*/
public class Annotation implements CodeModel<Annotation>,
Nameable<Annotation>,
Documentable<Annotation>,
Fieldable<Annotation>,
Dependable<Annotation>,
Modifiable<Annotation>,
Annotable<Annotation> {
private String name;
private Optional<Javadoc> javadoc;
private final List<AnnotationUsage> annotations;
private final List<Field> fields;
private final List<Import> dependencies;
private final Set<Modifier> modifiers;
public Annotation(String name) {
this.name = name;
this.javadoc = Optional.empty();
this.annotations = new ArrayList<>();
this.fields = new ArrayList<>();
this.dependencies = new ArrayList<>();
this.modifiers = EnumSet.noneOf(Modifier.class);
}
public Annotation(Annotation prototype) {
name = prototype.name;
javadoc = Copier.copy(prototype.javadoc);
annotations = Copier.copy(prototype.annotations);
fields = Copier.copy(prototype.fields);
dependencies = Copier.copy(prototype.dependencies);
modifiers = Copier.copy(prototype.modifiers, c -> c.copy(), EnumSet.noneOf(Modifier.class));
}
public Type toType() {
return new Type(name);
}
@Override
public Annotation setName(String name) {
this.name = name;
return this;
}
@Override
public String getName() {
return name;
}
@Override
public Annotation add(Field field) {
fields.add(field);
return this;
}
@Override
public List<Field> getFields() {
return fields;
}
@Override
public Annotation setJavadoc(Javadoc doc) {
this.javadoc = Optional.of(doc);
return this;
}
@Override
public Optional<Javadoc> getJavadoc() {
return javadoc;
}
@Override
public Annotation add(Import dep) {
dependencies.add(dep);
return this;
}
@Override
public List<Import> getDependencies() {
return dependencies;
}
@Override
public Set<Modifier> getModifiers() {
return modifiers;
}
@Override
public Annotation copy() {
return new Annotation(this);
}
@Override
public Annotation add(AnnotationUsage annotation) {
annotations.add(annotation);
return this;
}
@Override
public List<AnnotationUsage> getAnnotations() {
return annotations;
}
} |
package com.valkryst.VTerminal.builder;
import com.valkryst.VJSON.VJSONParser;
import com.valkryst.VTerminal.component.Button;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.json.simple.JSONObject;
@Data
@NoArgsConstructor
public class ButtonBuilder extends ComponentBuilder<Button> implements VJSONParser {
/** The text to display on the button. */
private String text;
/** The function to run when the button is clicked. */
private Runnable onClickFunction;
@Override
public Button build() {
checkState();
super.setDimensions(text.length(), 1);
return new Button(this);
}
@Override
protected void checkState() {
super.checkState();
if (text == null) {
text = "";
}
if (onClickFunction == null) {
onClickFunction = () -> {};
}
}
@Override
public void reset() {
super.reset();
text = "";
onClickFunction = () -> {};
}
@Override
public void parse(final JSONObject jsonObject) {
if (jsonObject == null) {
return;
}
super.parse(jsonObject);
final String text = getString(jsonObject, "text");
if (text == null) {
throw new NullPointerException("The 'text' value was not found.");
} else {
this.text = text;
}
}
/**
* Sets the text for the button to display.
*
* @param text
* The text.
*/
public void setText(final String text) {
this.text = text;
if (text != null && text.isEmpty() == false) {
super.setWidth(text.length());
}
}
} |
package com.wolfesoftware.mipsos.assembler;
import java.io.*;
import java.util.*;
import com.wolfesoftware.mipsos.common.*;
public class Assembler
{
private static final String blankBinAddr = " ";
private static final String blankBinWord = " ";
/**
* calls assemble() with options gathered from the command-line arguments.
* See printUsage().
*/
public static void main(String[] args)
{
// get options from args
LinkedList<String> argList = Util.arrayToLinkedList(args);
AssemblerOptions options = new AssemblerOptions();
options.parse(argList);
if (argList.size() != 1)
throw new RuntimeException();
String inputPath = argList.getFirst();
// call the assemble function
try {
assemble(inputPath, options);
} catch (AssemblingException e) {
System.out.print(e.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] assembleToBytes(String inputPath, AssemblerOptions options) throws AssemblingException, IOException
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
options.outStream = outStream;
assemble(inputPath, options);
return outStream.toByteArray();
}
public static void assemble(String inputPath, AssemblerOptions options) throws AssemblingException, IOException
{
InputStream inStream = new FileInputStream(inputPath);
// read input stream
Scanner inScanner = new Scanner(inStream);
StringBuilder fullSourceBuilder = new StringBuilder();
ArrayList<Integer> lineIndecies = new ArrayList<Integer>();
// convert all newlines to '\n'
if (inScanner.hasNextLine()) { // do the first one specially with no "\n" at the beginning
lineIndecies.add(fullSourceBuilder.length());
fullSourceBuilder.append(inScanner.nextLine());
}
while (inScanner.hasNextLine()) {
fullSourceBuilder.append('\n');
lineIndecies.add(fullSourceBuilder.length());
fullSourceBuilder.append(inScanner.nextLine());
}
String fullSource = fullSourceBuilder.toString();
// tokenize
Token.TokenBase[] tokens;
try {
tokens = Tokenizer.tokenize(fullSource);
} catch (TokenizingException e) {
int srcLocation = e.srcLocation;
int line = Util.findInList(lineIndecies, srcLocation);
int col = srcLocation - lineIndecies.get(line);
throw new CompilingException(srcLocation, line + 1, col + 1, 1, e.message);
}
// parse
Parser.Binarization binarization;
try {
binarization = Parser.parse(tokens, options.dataAddress, options.textAddress);
} catch (ParsingException e) {
Token.TokenBase token = tokens[e.tokenIndex];
int startLine = Util.findInList(lineIndecies, token.srcStart);
throw new CompilingException(token.srcStart, startLine + 1, token.srcStart - lineIndecies.get(startLine), token.srcEnd - token.srcStart, e.message);
}
// collect all the required labels
BinTreeSet<String> requiredLabels = new BinTreeSet<String>();
requiredLabels.add("main");
for (Bin.BinBase binElem : binarization.dataElems)
for (String s : binElem.getLabelDependencies())
requiredLabels.add(s);
for (Bin.BinBase binElem : binarization.textElems)
for (String s : binElem.getLabelDependencies())
requiredLabels.add(s);
// collect all defined labels
BinTreeSet<String> definedLabels = new BinTreeSet<String>();
definedLabels.addAll(binarization.labels.keySet());
// determine missing ones
ArrayList<String> missingLabels = requiredLabels.complement(definedLabels);
// check that all labels are defined
if (!(missingLabels.isEmpty()))
throw new UndefinedLabelsException(missingLabels); // report missing labels
// output
if (options.readable) {
// header
PrintStream printStream = new PrintStream(options.outStream);
printStream.println("; header");
byte[] bytes = binarization.header.getBinary(binarization.labels, -1);
int wordCounter = 0;
printStream.println(blankBinAddr + bytesWordToString(bytes, 4 * wordCounter++) + " ; .data Offset");
printStream.println(blankBinAddr + bytesWordToString(bytes, 4 * wordCounter++) + " ; .data Address");
printStream.println(blankBinAddr + bytesWordToString(bytes, 4 * wordCounter++) + " ; .data Length");
printStream.println(blankBinAddr + bytesWordToString(bytes, 4 * wordCounter++) + " ; .text Offset");
printStream.println(blankBinAddr + bytesWordToString(bytes, 4 * wordCounter++) + " ; .text Address");
printStream.println(blankBinAddr + bytesWordToString(bytes, 4 * wordCounter++) + " ; .text Length");
printStream.println(blankBinAddr + bytesWordToString(bytes, 4 * wordCounter++) + " ; executable entry point");
// .data section
verboseOutput(binarization.dataElems, printStream, ".data", options.dataAddress, binarization.labels, true, tokens, fullSource);
// .text section
verboseOutput(binarization.textElems, printStream, ".text", options.textAddress, binarization.labels, true, tokens, fullSource);
} else {
ArrayList<Segment> segments = new ArrayList<Segment>();
DebugInfo debugInfo = options.debugInfo ? new DebugInfo(inputPath, binarization.labels) : null;
// .data section
ByteArrayOutputStream dataSection = new ByteArrayOutputStream();
nonverboseOutput(options.dataAddress, binarization.dataElems, binarization.labels, dataSection);
segments.add(makeMemorySegment(binarization.header.dataAddr, dataSection.toByteArray()));
if (debugInfo != null)
debugInfo.write(options.dataAddress, binarization.dataElems, binarization.labels, lineIndecies, tokens);
// .text section
ByteArrayOutputStream textSection = new ByteArrayOutputStream();
nonverboseOutput(options.textAddress, binarization.textElems, binarization.labels, textSection);
segments.add(makeMemorySegment(binarization.header.textAddr, textSection.toByteArray()));
if (debugInfo != null)
debugInfo.write(options.textAddress, binarization.textElems, binarization.labels, lineIndecies, tokens);
// debug info segment
if (debugInfo != null)
segments.add(debugInfo.toSegment());
// entrypoint segment
int entryPoint = binarization.labels.get("main").intValue();
segments.add(makeEntrypointSegment(entryPoint));
Segment[] segmentsArray = segments.toArray(new Segment[segments.size()]);
ExecutableBinary binary = new ExecutableBinary(segmentsArray);
binary.encode(options.outStream);
}
}
private static Segment makeEntrypointSegment(int entryPoint)
{
HashMap<String, byte[]> attributes = new HashMap<String, byte[]>();
attributes.put(Segment.ATTRIBUTE_TYPE, Segment.TYPE_ENTRYPOINT);
attributes.put(Segment.ATTRIBUTE_ADDRESS, ByteUtils.convertInt(entryPoint));
return new Segment(attributes, new byte[0]);
}
private static Segment makeMemorySegment(int address, byte[] bytes)
{
HashMap<String, byte[]> attributes = new HashMap<String, byte[]>();
attributes.put(Segment.ATTRIBUTE_TYPE, Segment.TYPE_MEMORY);
attributes.put(Segment.ATTRIBUTE_ADDRESS, ByteUtils.convertInt(address));
return new Segment(attributes, bytes);
}
private static void verboseOutput(Bin.BinBase[] elems, PrintStream printStream, String sectionTitle, long baseAddress, HashMap<String, Long> labels, boolean useAddress,
Token.TokenBase[] tokens, String fullSrc)
{
if (elems.length > 0) {
printStream.println();
printStream.println(sectionTitle);
}
long addr = baseAddress;
for (Bin.BinBase binElem : elems) {
byte[] bytes = binElem.getBinary(labels, addr);
String[] strBinWords = new String[bytes.length >> 2];
for (int j = 0; j < bytes.length / 4; j++) {
strBinWords[j] = (useAddress ? addrToString(addr) + ": " : blankBinAddr) + bytesWordToString(bytes, j * 4);
addr += 4;
}
String comment = fullSrc.substring(tokens[binElem.tokenStart].srcStart, tokens[binElem.tokenEnd - 1].srcEnd);
String[] commentLines = comment.split("\n");
int maxLen = Math.max(strBinWords.length, commentLines.length);
for (int j = 0; j < maxLen; j++) {
printStream.println((j < strBinWords.length ? strBinWords[j] : blankBinWord) + (j < commentLines.length ? " ; " + commentLines[j] : ""));
}
}
}
private static void nonverboseOutput(long baseAddress, Bin.BinBase[] binElems, HashMap<String, Long> labels, OutputStream outStream) throws IOException
{
long addr = baseAddress;
for (Bin.BinBase binElem : binElems) {
byte[] data = binElem.getBinary(labels, addr);
outStream.write(data);
addr += data.length;
}
}
// validates the address into the 32-bit unsigned range and returns a String
// of the hex value in the form "HHHHHHHH"
private static String addrToString(long addr)
{
// validate range
if (!(0 <= addr && addr <= 0xFFFFFFFFL))
throw new RuntimeException(); // todo
String rtnStr = "";
for (int i = 0; i < 8; i++) // eight nibbles in a word
{
rtnStr = Long.toHexString(addr & 0xF).toUpperCase() + rtnStr;
addr >>= 4;
}
return rtnStr;
}
// returns a String of the hex value of one word starting at i in the byte
// array in the form "HHHHHHHH"
private static String bytesWordToString(byte[] bytes, int i)
{
String rtnStr = "";
for (int j = i; j < i + 4; j++) // four bytes in a word
{
// big endian
rtnStr += Integer.toHexString((bytes[j] & 0xF0) >> 4).toUpperCase();
rtnStr += Integer.toHexString((bytes[j] & 0x0F) >> 0).toUpperCase();
}
return rtnStr;
}
public static ExecutableBinary assembleToBinary(String inputPath, AssemblerOptions assemblerOptions) throws AssemblingException, IOException
{
byte[] binaryBytes = Assembler.assembleToBytes(inputPath, assemblerOptions);
InputStream binaryInputStream = new ByteArrayInputStream(binaryBytes);
return ExecutableBinary.decode(binaryInputStream);
}
} |
package com.SamB440.AdvancementGUI;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.advancement.Advancement;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
/**
* @author charliej - the very API
* @author DiscowZombie - adopting for Builder-Pattern
* @author 2008Choco - NamespacedKey support
* @author GiansCode - small but useful changes
* @author Ste3et_C0st - add/take advancement logic
* @author PROgrammer_JARvis - rework and combining
* @author ysl3000 - useful advice and bug-tracking at PullRequests/ JUnit-Tests, full Builder-Pattern support, Lombok
*/
public class AdvancementAPI {
private static final Gson gson = new Gson();
private NamespacedKey id;
private String parent, icon, background;
private TextComponent title, description;
private FrameType frame;
private boolean announce = true, toast = true, hidden = true;
private int counter = 1;
private Set<Trigger.TriggerBuilder> triggers;
private AdvancementAPI(NamespacedKey id, String parent, String icon, String background, TextComponent title, TextComponent description, FrameType frame, boolean announce, boolean toast, boolean hidden, int counter, Set<Trigger.TriggerBuilder> triggers) {
this.id = id;
this.parent = parent;
this.icon = icon;
this.background = background;
this.title = title;
this.description = description;
this.frame = frame;
this.announce = announce;
this.toast = toast;
this.hidden = hidden;
this.counter = counter;
this.triggers = triggers;
}
public static AdvancementAPIBuilder builder(NamespacedKey id) {
return new AdvancementAPIBuilder().id(id);
}
@Deprecated
public void save(String world) {
this.save(Bukkit.getWorld(world));
}
@Deprecated
public void save(World world) {
File file = new File(world.getWorldFolder(), "data" + File.separator + "advancements"
+ File.separator + id.getNamespace() + File.separator + id.getKey() + ".json");
File dir = file.getParentFile();
if (dir.mkdirs() || dir.exists()) {
try (FileWriter writer = new FileWriter(file)) {
writer.write(getJSON());
Bukkit.getLogger().info("[AdvancementAPI] Created " + id.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getJSON() {
JsonObject json = new JsonObject();
JsonObject icon = new JsonObject();
icon.addProperty("item", getIcon());
JsonObject display = new JsonObject();
display.add("icon", icon);
display.add("title", getJsonFromComponent(getTitle()));
display.add("description", getJsonFromComponent(getDescription()));
display.addProperty("background", getBackground());
display.addProperty("frame", getFrame().toString());
display.addProperty("announce_to_chat", announce);
display.addProperty("show_toast", toast);
display.addProperty("hidden", hidden);
json.addProperty("parent", getParent());
JsonObject criteria = new JsonObject();
//Changed to normal comment as JavaDocs are not displayed here @PROgrm_JARvis
/*
* Define each criteria, for each criteria in list,
* add items, trigger and conditions
*/
for (Trigger.TriggerBuilder triggerBuilder : getTriggers()) {
Trigger trigger = triggerBuilder.build();
criteria.add(trigger.name, trigger.toJsonObject());
}
json.add("criteria", criteria);
json.add("display", display);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
}
public String getIcon() {
return this.icon;
}
public static JsonElement getJsonFromComponent(TextComponent textComponent) {
return gson.fromJson(ComponentSerializer.toString(textComponent), JsonElement.class);
}
public TextComponent getTitle() {
return this.title;
}
public TextComponent getDescription() {
return this.description;
}
public String getBackground() {
return this.background;
}
public FrameType getFrame() {
return this.frame;
}
public String getParent() {
return this.parent;
}
public Set<Trigger.TriggerBuilder> getTriggers() {
return this.triggers;
}
public AdvancementAPI show(JavaPlugin plugin, Player... players) {
add();
grant(players);
Bukkit.getScheduler().runTaskLater(plugin, () -> {
revoke(players);
remove();
}, 20L);
return this;
}
@SuppressWarnings("deprecation")
public AdvancementAPI add() {
try {
Bukkit.getUnsafe().loadAdvancement(id, getJSON());
Bukkit.getLogger().info("Successfully registered advancement.");
} catch (IllegalArgumentException e) {
Bukkit.getLogger().info("Error registering advancement. It seems to already exist!");
}
return this;
}
public AdvancementAPI grant(Player... players) {
Advancement advancement = getAdvancement();
for (Player player : players) {
if (!player.getAdvancementProgress(advancement).isDone()) {
Collection<String> remainingCriteria = player.getAdvancementProgress(advancement).getRemainingCriteria();
Bukkit.getLogger().info(remainingCriteria.toString());
for (String remainingCriterion : remainingCriteria)
player.getAdvancementProgress(getAdvancement())
.awardCriteria(remainingCriterion);
}
}
return this;
}
public AdvancementAPI revoke(Player... players) {
Advancement advancement = getAdvancement();
for (Player player : players) {
if (player.getAdvancementProgress(advancement).isDone()) {
Collection<String> awardedCriteria = player.getAdvancementProgress(advancement).getAwardedCriteria();
Bukkit.getLogger().info(awardedCriteria.toString());
for (String awardedCriterion : awardedCriteria)
player.getAdvancementProgress(getAdvancement())
.revokeCriteria(awardedCriterion);
}
}
return this;
}
@SuppressWarnings("deprecation")
public AdvancementAPI remove() {
Bukkit.getUnsafe().removeAdvancement(id);
return this;
}
public Advancement getAdvancement() {
return Bukkit.getAdvancement(id);
}
public boolean counterUp(Player player) {
String criteriaString = null;
for (String criteria : getAdvancement().getCriteria()) {
if (player.getAdvancementProgress(getAdvancement()).getDateAwarded(criteria) != null) {
criteriaString = criteria;
} else {
break;
}
}
if (criteriaString == null) return false;
player.getAdvancementProgress(getAdvancement()).awardCriteria(criteriaString);
return true;
}
public boolean counterDown(Player player) {
String criteriaString = null;
for (String criteria : getAdvancement().getCriteria()) {
if (player.getAdvancementProgress(getAdvancement()).getDateAwarded(criteria) != null) {
criteriaString = criteria;
} else {
break;
}
}
if (criteriaString == null) return false;
player.getAdvancementProgress(getAdvancement()).revokeCriteria(criteriaString);
return true;
}
public void counterReset(Player player) {
for (String criteria : getAdvancement().getCriteria()) {
if (player.getAdvancementProgress(getAdvancement()).getDateAwarded(criteria) != null) {
player.getAdvancementProgress(getAdvancement()).revokeCriteria(criteria);
}
}
}
public NamespacedKey getId() {
return this.id;
}
public boolean isAnnounce() {
return this.announce;
}
public boolean isToast() {
return this.toast;
}
public boolean isHidden() {
return this.hidden;
}
public int getCounter() {
return this.counter;
}
public static class AdvancementAPIBuilder {
private NamespacedKey id;
private String parent;
private String icon;
private String background;
private TextComponent title;
private TextComponent description;
private FrameType frame;
private boolean announce;
private boolean toast;
private boolean hidden;
private int counter;
private ArrayList<Trigger.TriggerBuilder> triggers;
AdvancementAPIBuilder() {
}
public AdvancementAPIBuilder title(String title) {
this.title = new TextComponent(title);
return this;
}
public AdvancementAPIBuilder title(TextComponent title) {
this.title = title;
return this;
}
public AdvancementAPIBuilder description(String description) {
this.description = new TextComponent(description);
return this;
}
public AdvancementAPIBuilder description(TextComponent description) {
this.description = description;
return this;
}
public AdvancementAPIBuilder id(NamespacedKey id) {
this.id = id;
return this;
}
public AdvancementAPIBuilder parent(String parent) {
this.parent = parent;
return this;
}
public AdvancementAPIBuilder icon(String icon) {
this.icon = icon;
return this;
}
public AdvancementAPIBuilder background(String background) {
this.background = background;
return this;
}
public AdvancementAPIBuilder frame(FrameType frame) {
this.frame = frame;
return this;
}
public AdvancementAPIBuilder announce(boolean announce) {
this.announce = announce;
return this;
}
public AdvancementAPIBuilder toast(boolean toast) {
this.toast = toast;
return this;
}
public AdvancementAPIBuilder hidden(boolean hidden) {
this.hidden = hidden;
return this;
}
public AdvancementAPIBuilder counter(int counter) {
this.counter = counter;
return this;
}
public AdvancementAPIBuilder trigger(Trigger.TriggerBuilder trigger) {
if (this.triggers == null)
this.triggers = new ArrayList<Trigger.TriggerBuilder>();
this.triggers.add(trigger);
return this;
}
public AdvancementAPIBuilder triggers(Collection<? extends Trigger.TriggerBuilder> triggers) {
if (this.triggers == null)
this.triggers = new ArrayList<Trigger.TriggerBuilder>();
this.triggers.addAll(triggers);
return this;
}
public AdvancementAPIBuilder clearTriggers() {
if (this.triggers != null)
this.triggers.clear();
return this;
}
public AdvancementAPI build() {
Set<Trigger.TriggerBuilder> triggers;
switch (this.triggers == null ? 0 : this.triggers.size()) {
case 0:
triggers = java.util.Collections.singleton(Trigger.builder(Trigger.TriggerType.IMPOSSIBLE, "default"));
break;
case 1:
triggers = java.util.Collections.singleton(this.triggers.get(0));
break;
default:
triggers = new java.util.LinkedHashSet<Trigger.TriggerBuilder>(this.triggers.size() < 1073741824 ? 1 + this.triggers.size() + (this.triggers.size() - 3) / 3 : Integer.MAX_VALUE);
triggers.addAll(this.triggers);
triggers = java.util.Collections.unmodifiableSet(triggers);
}
return new AdvancementAPI(id, parent, icon, background, title, description, frame, announce, toast, hidden, counter, triggers);
}
public String toString() {
return "io.chazza.advancementapi.AdvancementAPI.AdvancementAPIBuilder(id=" + this.id + ", parent=" + this.parent + ", icon=" + this.icon + ", background=" + this.background + ", title=" + this.title + ", description=" + this.description + ", frame=" + this.frame + ", announce=" + this.announce + ", toast=" + this.toast + ", hidden=" + this.hidden + ", counter=" + this.counter + ", triggers=" + this.triggers + ")";
}
}
} |
package snake;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
/**
* @author Aaron
* @author Ryan
*
*/
@SuppressWarnings("serial")
public class GamePanel extends JPanel implements Runnable, KeyListener {
//Dimensions
public static final int WIDTH = 640;
public static final int HEIGHT = 512;
//Properties
public static final String TITLE = "Snake";
public static final double VERSION = 1.0;
private boolean debug = false;
//Image
private BufferedImage image;
private Graphics2D g2d;
//Thread
private Thread thread;
private boolean running;
private int TargetFPS = 60;
private int FPS;
private long targetTime = 1000 / TargetFPS;
private Grid grid = new Grid();
public GamePanel() {
//Sets JPanel size
this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
this.setFocusable(true);
this.requestFocus();
}
/**
* Initializes double buffering and grid
*/
public void init(){
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) image.getGraphics();
running = true;
//Initialize grid
grid.init();
}
public void update(){
//Update the grid
grid.update();
}
/**
* This method renders to the double buffered image
*/
public void render(){
//Render the grid
grid.render(g2d);
//Render the debug menu
if(debug){
g2d.setColor(Color.WHITE);
g2d.drawString("Debug Menu", 5, 15);
g2d.drawString("fps:" + FPS, 5, 35);
}
}
/**
* Method to render the double buffered frame
*/
public void renderToScreen(){
Graphics g = this.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
}
@Override
public void run() {
long start;
long elapsed;
long delay;
init();
//Game loop
while(running){
start = System.nanoTime();
update();
render();
renderToScreen();
elapsed = System.nanoTime() - start;
delay = targetTime - elapsed / 1000000;
FPS = (int) (1000000000 / elapsed);
if(delay < 0){
delay = 0;
}
try{
Thread.sleep(delay);
} catch(Exception e){
e.printStackTrace();
}
}
}
//Initializes thread and listeners
@Override
public void addNotify(){
super.addNotify();
if(thread == null){
thread = new Thread(this);
this.addKeyListener(this);
//this.addMouseListener(this);
//this.addMouseMotionListener(this);
//this.addMouseWheelListener(this);
thread.start();
}
}
@Override
public void keyPressed(KeyEvent e) {
//Debugging Menu
if(e.getKeyCode() == KeyEvent.VK_BACK_QUOTE){
if(debug){
debug = false;
} else{
debug = true;
}
}
//Quit
if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
System.exit(0);
}
if(e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_W){
grid.getSnake().setHeadDirectionRequest(0);
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D){
grid.getSnake().setHeadDirectionRequest(1);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_S){
grid.getSnake().setHeadDirectionRequest(2);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A){
grid.getSnake().setHeadDirectionRequest(3);
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
} |
package team353;
import battlecode.common.*;
import java.util.*;
public class RobotPlayer {
public static class smuConstants {
public static int roundToLaunchAttack = 1600;
public static int roundToDefendTowers = 500;
public static int roundToFormSupplyConvoy = 400; // roundToBuildSOLDIERS;
public static int RADIUS_FOR_SUPPLY_CONVOY = 2;
public static int numTowersRemainingToAttackHQ = 1;
public static double weightExponentMagic = 0.3;
public static double weightScaleMagic = 0.8;
public static int currentOreGoal = 100;
public static double percentBeaversToGoToSecondBase = 0.4;
// Defence
public static int NUM_TOWER_PROTECTORS = 4;
public static int NUM_HOLE_PROTECTORS = 3;
public static int PROTECT_OTHERS_RANGE = 10;
public static int DISTANCE_TO_START_PROTECTING_SQUARED = 200;
// Idle States
public static MapLocation defenseRallyPoint;
public static int PROTECT_HOLE = 1;
public static int PROTECT_TOWER = 2;
// Supply
public static int NUM_ROUNDS_TO_KEEP_SUPPLIED = 20;
// Contain
public static int CLOCKWISE = 0;
public static int COUNTERCLOCKWISE = 1;
public static int CURRENTLY_BEING_CONTAINED = 1;
public static int NOT_CURRENTLY_BEING_CONTAINED = 2;
}
public static class smuIndices {
public static int RALLY_POINT_X = 0;
public static int RALLY_POINT_Y = 1;
//Economy
public static int freqQueue = 11;
public static int HQ_BEING_CONTAINED = 20;
public static final int freqRoundToBuild = 100;
public static final int freqRoundToFinish = 200;
public static final int freqDesiredNumOf = 400;
public static final int freqNumAEROSPACELAB = 301;
public static final int freqNumBARRACKS = 302;
public static final int freqNumBASHER = 303;
public static final int freqNumBEAVER = 304;
public static final int freqNumCOMMANDER = 305;
public static final int freqNumCOMPUTER = 306;
public static final int freqNumDRONE = 307;
public static final int freqNumHANDWASHSTATION = 308;
public static final int freqNumHELIPAD = 309;
public static final int freqNumHQ = 310;
public static final int freqNumLAUNCHER = 311;
public static final int freqNumMINER = 312;
public static final int freqNumMINERFACTORY = 313;
public static final int freqNumMISSILE = 314;
public static final int freqNumSOLDIER = 315;
public static final int freqNumSUPPLYDEPOT = 316;
public static final int freqNumTANK = 317;
public static final int freqNumTANKFACTORY = 318;
public static final int freqNumTECHNOLOGYINSTITUTE = 319;
public static final int freqNumTOWER = 320;
public static final int freqNumTRAININGFIELD = 321;
public static final int[] freqNum = new int[] {0, freqNumAEROSPACELAB, freqNumBARRACKS, freqNumBASHER, freqNumBEAVER, freqNumCOMMANDER,
freqNumCOMPUTER, freqNumDRONE, freqNumHANDWASHSTATION, freqNumHELIPAD, freqNumHQ, freqNumLAUNCHER, freqNumMINER,
freqNumMINERFACTORY, freqNumMISSILE, freqNumSOLDIER, freqNumSUPPLYDEPOT, freqNumTANK, freqNumTANKFACTORY,
freqNumTECHNOLOGYINSTITUTE, freqNumTOWER, freqNumTRAININGFIELD};
public static int TOWER_HOLES_BEGIN = 2000;
}
public static void run(RobotController rc) throws GameActionException {
BaseBot myself;
if (rc.getType() == RobotType.HQ) {
myself = new HQ(rc);
} else if (rc.getType() == RobotType.MINER) {
myself = new Miner(rc);
} else if (rc.getType() == RobotType.MINERFACTORY) {
myself = new Minerfactory(rc);
} else if (rc.getType() == RobotType.BEAVER) {
myself = new Beaver(rc);
} else if (rc.getType() == RobotType.BARRACKS) {
myself = new Barracks(rc);
} else if (rc.getType() == RobotType.SOLDIER) {
myself = new Soldier(rc);
} else if (rc.getType() == RobotType.BASHER) {
myself = new Basher(rc);
} else if (rc.getType() == RobotType.HELIPAD) {
myself = new Helipad(rc);
} else if (rc.getType() == RobotType.DRONE) {
myself = new Drone(rc);
} else if (rc.getType() == RobotType.TOWER) {
myself = new Tower(rc);
} else if (rc.getType() == RobotType.SUPPLYDEPOT) {
myself = new Supplydepot(rc);
} else if (rc.getType() == RobotType.HANDWASHSTATION) {
myself = new Handwashstation(rc);
} else if (rc.getType() == RobotType.TANKFACTORY) {
myself = new Tankfactory(rc);
} else if (rc.getType() == RobotType.TANK) {
myself = new Tank(rc);
} else if (rc.getType() == RobotType.AEROSPACELAB) {
myself = new Aerospacelab(rc);
} else if (rc.getType() == RobotType.LAUNCHER) {
myself = new Launcher(rc);
} else if (rc.getType() == RobotType.MISSILE) {
myself = new Missile(rc);
} else {
myself = new BaseBot(rc);
}
while (true) {
try {
myself.go();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static class BaseBot {
protected RobotController rc;
protected MapLocation myHQ, theirHQ;
protected Team myTeam, theirTeam;
protected int myRange;
protected RobotType myType;
static Random rand;
public BaseBot(RobotController rc) {
this.rc = rc;
this.myHQ = rc.senseHQLocation();
this.theirHQ = rc.senseEnemyHQLocation();
this.myTeam = rc.getTeam();
this.theirTeam = this.myTeam.opponent();
this.myType = rc.getType();
this.myRange = myType.attackRadiusSquared;
rand = new Random(rc.getID());
}
public int getDistanceSquared(MapLocation A, MapLocation B){
return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
}
public int getDistanceSquared(MapLocation A){
MapLocation B = rc.getLocation();
return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
}
public Direction[] getDirectionsToward(MapLocation dest) {
Direction toDest = rc.getLocation().directionTo(dest);
Direction[] dirs = {toDest,
toDest.rotateLeft(), toDest.rotateRight(),
toDest.rotateLeft().rotateLeft(), toDest.rotateRight().rotateRight()};
return dirs;
}
public Direction[] getDirectionsAway(MapLocation dest) {
Direction toDest = rc.getLocation().directionTo(dest).opposite();
Direction[] dirs = {toDest,
toDest.rotateLeft(), toDest.rotateRight(),
toDest.rotateLeft().rotateLeft(), toDest.rotateRight().rotateRight()};
return dirs;
}
public Direction getMoveDir(MapLocation dest) {
Direction[] dirs = getDirectionsToward(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
public Direction getMoveDirAway(MapLocation dest) {
Direction[] dirs = getDirectionsAway(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
public Direction getMoveDirRand(MapLocation dest) {
//TODO return a random direction
Direction[] dirs = getDirectionsToward(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
public Direction getMoveDirAwayRand(MapLocation dest) {
//TODO return a random direction
Direction[] dirs = getDirectionsAway(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
//Will return a single direction for spawning. (Uses getDirectionsToward())
public Direction getSpawnDir(RobotType type) {
Direction[] dirs = getDirectionsToward(this.theirHQ);
for (Direction d : dirs) {
if (rc.canSpawn(d, type)) {
return d;
}
}
dirs = getDirectionsToward(this.myHQ);
for (Direction d : dirs) {
if (rc.canSpawn(d, type)) {
return d;
} else {
//System.out.println("Could not find valid spawn location!");
}
}
return null;
}
//Will return a single direction for building. (Uses getDirectionsToward())
public Direction getBuildDir(RobotType type) {
Direction[] dirs = getDirectionsToward(this.theirHQ);
for (Direction d : dirs) {
if (rc.canBuild(d, type)) {
return d;
}
}
dirs = getDirectionsToward(this.myHQ);
for (Direction d : dirs) {
if (rc.canBuild(d, type)) {
return d;
} else {
//System.out.println("Could not find valid build location!");
}
}
return null;
}
public RobotInfo[] getAllies() {
RobotInfo[] allies = rc.senseNearbyRobots(Integer.MAX_VALUE, myTeam);
return allies;
}
public RobotInfo[] getEnemiesInAttackingRange() {
RobotInfo[] enemies = rc.senseNearbyRobots(myRange, theirTeam);
return enemies;
}
public void attackLeastHealthEnemy(RobotInfo[] enemies) throws GameActionException {
if (enemies.length == 0) {
return;
}
double minEnergon = Double.MAX_VALUE;
MapLocation toAttack = null;
for (RobotInfo info : enemies) {
if (info.health < minEnergon) {
toAttack = info.location;
minEnergon = info.health;
}
}
if (toAttack != null) {
rc.attackLocation(toAttack);
}
}
public void attackLeastHealthEnemyInRange() throws GameActionException {
RobotInfo[] enemies = getEnemiesInAttackingRange();
if (enemies.length > 0) {
if (rc.isWeaponReady()) {
attackLeastHealthEnemy(enemies);
}
}
}
public void moveToRallyPoint() throws GameActionException {
if (rc.isCoreReady()) {
int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X);
int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y);
MapLocation rallyPoint = new MapLocation(rallyX, rallyY);
RobotInfo[] robots = rc.senseNearbyRobots(rallyPoint, 10, myTeam);
if (Clock.getRoundNum() > smuConstants.roundToLaunchAttack
|| rc.getLocation().distanceSquaredTo(rallyPoint) > 8 + Clock.getRoundNum() / 100) {
Direction newDir = getMoveDir(rallyPoint);
if (newDir != null) {
rc.move(newDir);
}
}
}
}
//Returns the current rally point MapLocation
public MapLocation getRallyPoint() throws GameActionException {
int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X);
int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y);
MapLocation rallyPoint = new MapLocation(rallyX, rallyY);
return rallyPoint;
}
//Moves a random safe direction from input array
public void moveOptimally(Direction[] optimalDirections) throws GameActionException {
//TODO check safety
if (optimalDirections != null) {
boolean lookingForDirection = true;
while(lookingForDirection){
MapLocation[] enemyTowers = rc.senseEnemyTowerLocations();
Direction randomDirection = optimalDirections[(int) (rand.nextDouble()*optimalDirections.length)];
MapLocation tileInFront = rc.getLocation().add(randomDirection);
//check that the direction in front is not a tile that can be attacked by the enemy towers
boolean tileInFrontSafe = true;
for(MapLocation m: enemyTowers){
if(m.distanceSquaredTo(tileInFront)<=RobotType.TOWER.attackRadiusSquared){
tileInFrontSafe = false;
break;
}
}
//check that we are not facing off the edge of the map
TerrainTile terrainTileInFront = rc.senseTerrainTile(tileInFront);
if(!tileInFrontSafe || terrainTileInFront == TerrainTile.OFF_MAP
|| (myType != RobotType.DRONE && terrainTileInFront!=TerrainTile.NORMAL)){
randomDirection = randomDirection.rotateLeft();
}else{
//try to move in the randomDirection direction
if(rc.isCoreReady()&&rc.canMove(randomDirection)){
rc.move(randomDirection);
lookingForDirection = false;
return;
}
}
}
//System.out.println("No suitable direction found!");
}
}
//Gets optimal directions and then calls moveOptimally() with those directions.
public void moveOptimally() throws GameActionException {
Direction[] optimalDirections = getOptimalDirections();
if (optimalDirections != null) {
moveOptimally(optimalDirections);
}
}
//TODO Finish
public Direction[] getOptimalDirections() throws GameActionException {
// The switch statement should result in an array of directions that make sense
//for the RobotType. Safety is considered in moveOptimally()
RobotType currentRobotType = rc.getType();
Direction[] optimalDirections = null;
switch(currentRobotType){
case BASHER:
break;
case BEAVER:
if (getDistanceSquared(this.myHQ) < 50){
optimalDirections = getDirectionsAway(this.myHQ);
}
optimalDirections = Direction.values();
break;
case COMMANDER:
break;
case COMPUTER:
break;
case DRONE:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case LAUNCHER:
break;
case MINER:
if (getDistanceSquared(this.myHQ) < 50){
optimalDirections = getDirectionsToward(this.myHQ);
}
optimalDirections = Direction.values();
break;
case MISSILE:
break;
case SOLDIER:
break;
case TANK:
break;
default:
//error
} //Done RobotType specific actions.
return optimalDirections;
}
//Spawns or Queues the unit if it is needed
public boolean tryToSpawn(RobotType spawnType) throws GameActionException{
int round = Clock.getRoundNum();
double ore = rc.getTeamOre();
int spawnTypeInt = RobotTypeToInt(spawnType);
int spawnQueue = rc.readBroadcast(smuIndices.freqQueue);
//Check if we actually need anymore spawnType units
if (round > rc.readBroadcast(smuIndices.freqRoundToBuild + spawnTypeInt) && rc.readBroadcast(smuIndices.freqNum[spawnTypeInt]) < rc.readBroadcast(smuIndices.freqDesiredNumOf + spawnTypeInt)){
if(ore > myType.oreCost){
if (spawnUnit(spawnType)) return true;
} else {
//Add spawnType to queue
if (spawnQueue == 0){
rc.broadcast(smuIndices.freqQueue, spawnTypeInt);
}
return false;
}
}
return false;
}
//Spawns unit based on calling type. Performs all checks.
public boolean spawnOptimally() throws GameActionException {
if (rc.isCoreReady()){
int spawnQueue = rc.readBroadcast(smuIndices.freqQueue);
switch(myType){
case BARRACKS:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.SOLDIER)){
if (tryToSpawn(RobotType.SOLDIER)) return true;
}
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BASHER)){
if (tryToSpawn(RobotType.BASHER)) return true;
}
break;
case HQ:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BEAVER)){
if (tryToSpawn(RobotType.BEAVER)) return true;
}
break;
case HELIPAD:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.DRONE)){
if (tryToSpawn(RobotType.DRONE)) return true;
}
break;
case AEROSPACELAB:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.LAUNCHER)){
if (tryToSpawn(RobotType.LAUNCHER)) return true;
}
break;
case MINERFACTORY:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.MINER)){
if (tryToSpawn(RobotType.MINER)) return true;
}
break;
case TANKFACTORY:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.TANK)){
if (tryToSpawn(RobotType.TANK)) return true;
}
break;
case TECHNOLOGYINSTITUTE:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMPUTER)){
if (tryToSpawn(RobotType.COMPUTER)) return true;
}
break;
case TRAININGFIELD:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMMANDER)){
if (tryToSpawn(RobotType.COMMANDER)) return true;
}
break;
default:
System.out.println("ERROR: No building type match found in spawnOptimally()!");
return false;
}
}//isCoreReady
return false;
}
//Gets direction, checks delays, and spawns unit
public boolean spawnUnit(RobotType spawnType) {
//Get a direction and then actually spawn the unit.
Direction randomDir = getSpawnDir(spawnType);
if(rc.isCoreReady() && randomDir != null){
try {
if (rc.canSpawn(randomDir, spawnType)) {
rc.spawn(randomDir, spawnType);
if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == spawnType) {
rc.broadcast(smuIndices.freqQueue, 0);
}
incrementCount(spawnType);
return true;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
return false;
}
//Spawns unit based on calling type. Performs all checks.
public void buildOptimally() throws GameActionException {
if (rc.isCoreReady()){
int round = Clock.getRoundNum();
double ore = rc.getTeamOre();
boolean buildingsOutrankUnits = true;
int queue = rc.readBroadcast(smuIndices.freqQueue);
//If there is something in the queue and we can not replace it, then return
if (queue != 0 && !buildingsOutrankUnits){
System.out.println("Queue full, can't outrank");
return;
}
Integer[] buildingInts = new Integer[] {RobotTypeToInt(RobotType.AEROSPACELAB),
RobotTypeToInt(RobotType.BARRACKS), RobotTypeToInt(RobotType.HANDWASHSTATION), RobotTypeToInt(RobotType.HELIPAD),
RobotTypeToInt(RobotType.MINERFACTORY), RobotTypeToInt(RobotType.SUPPLYDEPOT), RobotTypeToInt(RobotType.TANKFACTORY),
RobotTypeToInt(RobotType.TECHNOLOGYINSTITUTE), RobotTypeToInt(RobotType.TRAININGFIELD)};
//Check if there is a building in queue
if (Arrays.asList(buildingInts).contains(queue)) {
//Build it if we can afford it
if (ore > IntToRobotType(queue).oreCost) {
System.out.println("Satisfying queue.");
buildUnit(IntToRobotType(queue));
}
//Return either way, we can't replace buildings in the queue
return;
}
//we should sort the array based on need
Arrays.sort(buildingInts, new Comparator<Integer>() {
public int compare(Integer type1, Integer type2) {
double wType1 = 0;
double wType2 = 0;
try {
wType1 = getWeightOfRobotType(IntToRobotType(type1));
wType2 = getWeightOfRobotType(IntToRobotType(type2));
} catch (GameActionException e) {
e.printStackTrace();
}
return Double.compare(wType1, wType2);
}
});
//for i in array of structures
for (int buildTypeInt : buildingInts) {
int currentBuildNum = rc.readBroadcast(smuIndices.freqNum[buildTypeInt]);
if (round > rc.readBroadcast(smuIndices.freqRoundToBuild + buildTypeInt) &&
rc.readBroadcast(smuIndices.freqDesiredNumOf + buildTypeInt) > 0 &&
rc.readBroadcast(smuIndices.freqRoundToBuild + buildTypeInt) < rc.readBroadcast(smuIndices.freqRoundToFinish + buildTypeInt) &&
currentBuildNum < rc.readBroadcast(smuIndices.freqDesiredNumOf + buildTypeInt)){
//We don't have as many buildings as we want...
if (ore > IntToRobotType(buildTypeInt).oreCost){
buildUnit(IntToRobotType(buildTypeInt));
//System.out.println("Tried to build "+ IntToRobotType(buildTypeInt));
} else {
double weightToBeat = getWeightOfRobotType(IntToRobotType(buildTypeInt));
double rolled = rand.nextDouble();
//System.out.println("Rolled "+ rolled + "for a " + buildTypeInt + " against " + weightToBeat);
if (rolled < weightToBeat){
rc.broadcast(smuIndices.freqQueue, buildTypeInt);
System.out.println("Scheduled a " + IntToRobotType(buildTypeInt).name() +
". Need " + IntToRobotType(buildTypeInt).oreCost + " ore.");
}
return;
}
}
}
}
}
//Gets direction, checks delays, and builds unit
public boolean buildUnit(RobotType buildType) {
//Get a direction and then actually build the unit.
Direction randomDir = getBuildDir(buildType);
if(rc.isCoreReady() && randomDir != null){
try {
if (rc.canBuild(randomDir, buildType)) {
rc.build(randomDir, buildType);
if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == buildType) {
rc.broadcast(smuIndices.freqQueue, 0);
}
incrementCount(buildType);
return true;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
return false;
}
//TODO find a way to deal with deaths.
public void incrementCount(RobotType type) throws GameActionException {
switch(type){
case AEROSPACELAB:
rc.broadcast(smuIndices.freqNumAEROSPACELAB, rc.readBroadcast(smuIndices.freqNumAEROSPACELAB)+1);
break;
case BARRACKS:
rc.broadcast(smuIndices.freqNumBARRACKS, rc.readBroadcast(smuIndices.freqNumBARRACKS)+1);
break;
case BASHER:
rc.broadcast(smuIndices.freqNumBASHER, rc.readBroadcast(smuIndices.freqNumBASHER)+1);
break;
case BEAVER:
rc.broadcast(smuIndices.freqNumBEAVER, rc.readBroadcast(smuIndices.freqNumBEAVER)+1);
break;
case COMMANDER:
rc.broadcast(smuIndices.freqNumCOMMANDER, rc.readBroadcast(smuIndices.freqNumCOMMANDER)+1);
break;
case COMPUTER:
rc.broadcast(smuIndices.freqNumCOMPUTER, rc.readBroadcast(smuIndices.freqNumCOMPUTER)+1);
break;
case DRONE:
rc.broadcast(smuIndices.freqNumDRONE, rc.readBroadcast(smuIndices.freqNumDRONE)+1);
break;
case HANDWASHSTATION:
rc.broadcast(smuIndices.freqNumHANDWASHSTATION, rc.readBroadcast(smuIndices.freqNumHANDWASHSTATION)+1);
break;
case HELIPAD:
rc.broadcast(smuIndices.freqNumHELIPAD, rc.readBroadcast(smuIndices.freqNumHELIPAD)+1);
break;
case LAUNCHER:
rc.broadcast(smuIndices.freqNumLAUNCHER, rc.readBroadcast(smuIndices.freqNumLAUNCHER)+1);
break;
case MINER:
rc.broadcast(smuIndices.freqNumMINER, rc.readBroadcast(smuIndices.freqNumMINER)+1);
break;
case MINERFACTORY:
rc.broadcast(smuIndices.freqNumMINERFACTORY, rc.readBroadcast(smuIndices.freqNumMINERFACTORY)+1);
break;
case MISSILE:
rc.broadcast(smuIndices.freqNumMISSILE, rc.readBroadcast(smuIndices.freqNumMISSILE)+1);
break;
case SOLDIER:
rc.broadcast(smuIndices.freqNumSOLDIER, rc.readBroadcast(smuIndices.freqNumSOLDIER)+1);
break;
case SUPPLYDEPOT:
rc.broadcast(smuIndices.freqNumSUPPLYDEPOT, rc.readBroadcast(smuIndices.freqNumSUPPLYDEPOT)+1);
break;
case TANK:
rc.broadcast(smuIndices.freqNumTANK, rc.readBroadcast(smuIndices.freqNumTANK)+1);
break;
case TANKFACTORY:
rc.broadcast(smuIndices.freqNumTANKFACTORY, rc.readBroadcast(smuIndices.freqNumTANKFACTORY)+1);
break;
case TECHNOLOGYINSTITUTE:
rc.broadcast(smuIndices.freqNumTECHNOLOGYINSTITUTE, rc.readBroadcast(smuIndices.freqNumTECHNOLOGYINSTITUTE)+1);
break;
case TRAININGFIELD:
rc.broadcast(smuIndices.freqNumTRAININGFIELD, rc.readBroadcast(smuIndices.freqNumTRAININGFIELD)+1);
break;
default:
//System.out.println("ERRROR!");
return;
}
}
public void transferSupplies() throws GameActionException {
double lowestSupply = rc.getSupplyLevel();
if (lowestSupply == 0) {
return;
}
int roundStart = Clock.getRoundNum();
final MapLocation myLocation = rc.getLocation();
RobotInfo[] nearbyAllies = rc.senseNearbyRobots(myLocation,GameConstants.SUPPLY_TRANSFER_RADIUS_SQUARED,rc.getTeam());
double transferAmount = 0;
MapLocation suppliesToThisLocation = null;
for(RobotInfo ri:nearbyAllies){
if (!ri.type.isBuilding && ri.supplyLevel < lowestSupply) {
lowestSupply = ri.supplyLevel;
transferAmount = (rc.getSupplyLevel()-ri.supplyLevel)/2;
suppliesToThisLocation = ri.location;
}
}
if(suppliesToThisLocation!=null){
if (roundStart == Clock.getRoundNum() && transferAmount > 0) {
try {
rc.transferSupplies((int)transferAmount, suppliesToThisLocation);
} catch(GameActionException gax) {
gax.printStackTrace();
}
}
}
}
// true, I'm in the convoy or going to be
// false, no place in the convoy for me
public boolean formSupplyConvoy() {
Direction directionForChain = getSupplyConvoyDirection(myHQ);
RobotInfo minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, myHQ, directionForChain);
if (minerAtEdge == null){
goToLocation(myHQ.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY));
return true;
} else if (minerAtEdge.ID == rc.getID()) {
return true;
}
RobotInfo previousMiner = null;
try {
while ((minerAtEdge != null || !minerAtEdge.type.isBuilding) && minerAtEdge.location.distanceSquaredTo(getRallyPoint()) > 4) {
directionForChain = getSupplyConvoyDirection(minerAtEdge.location);
previousMiner = minerAtEdge;
minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, minerAtEdge.location, directionForChain);
if (minerAtEdge == null) {
goToLocation(previousMiner.location.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY));
return true;
} else if (minerAtEdge.ID == rc.getID()) {
return true;
}
}
} catch (GameActionException e) {
e.printStackTrace();
}
return false;
}
public Direction getSupplyConvoyDirection(MapLocation startLocation) {
Direction directionForChain = myHQ.directionTo(theirHQ);
MapLocation locationToGo = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL) {
RobotInfo robotInDirection;
try {
robotInDirection = rc.senseRobotAtLocation(locationToGo);
if (robotInDirection == null || !robotInDirection.type.isBuilding) {
return directionForChain;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
Direction[] directions = {Direction.NORTH, Direction.NORTH_EAST, Direction.EAST, Direction.SOUTH_EAST, Direction.SOUTH, Direction.SOUTH_WEST, Direction.WEST, Direction.NORTH_WEST};
for (int i = 0; i < directions.length; i++) {
locationToGo = startLocation.add(directions[i], smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (directions[i] != directionForChain && directions[i] != Direction.OMNI && directions[i] != Direction.NONE
&& rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL) {
RobotInfo robotInDirection;
try {
robotInDirection = rc.senseRobotAtLocation(locationToGo);
if (robotInDirection == null || !robotInDirection.type.isBuilding) {
return directions[i];
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
}
return Direction.NONE;
}
public RobotInfo getUnitAtEdgeOfSupplyRangeOf(RobotType unitType, MapLocation startLocation, Direction directionForChain) {
MapLocation locationInChain = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (rc.canSenseLocation(locationInChain)) {
try {
return rc.senseRobotAtLocation(locationInChain);
} catch (GameActionException e) {
e.printStackTrace();
}
}
return null;
}
public MapLocation getSecondBaseLocation() {
Direction directionToTheirHQ = myHQ.directionTo(theirHQ);
MapLocation secondBase = null;
if (directionToTheirHQ == Direction.EAST || directionToTheirHQ == Direction.WEST) {
secondBase = getSecondBaseLocationInDirections(Direction.NORTH, Direction.SOUTH);
} else if (directionToTheirHQ == Direction.NORTH || directionToTheirHQ == Direction.SOUTH) {
secondBase = getSecondBaseLocationInDirections(Direction.EAST, Direction.WEST);
} else {
Direction[] directions = breakdownDirection(directionToTheirHQ);
secondBase = getSecondBaseLocationInDirections(directions[0], directions[1]);
}
if (secondBase != null) {
secondBase = secondBase.add(myHQ.directionTo(secondBase), 4);
}
return secondBase;
}
public MapLocation getSecondBaseLocationInDirections(Direction dir1, Direction dir2) {
MapLocation towers[] = rc.senseTowerLocations();
int maxDistance = Integer.MIN_VALUE;
int maxDistanceIndex = -1;
Direction dirToEnemy = myHQ.directionTo(theirHQ);
Direction dir1left = dir1.rotateLeft();
Direction dir1right = dir1.rotateRight();
Direction dir2left = dir2.rotateLeft();
Direction dir2right = dir2.rotateRight();
for (int i = 0; i<towers.length; i++) {
Direction dirToTower = myHQ.directionTo(towers[i]);
if (dirToTower == dir1 || dirToTower == dir2
|| (dir1left != dirToEnemy && dirToTower == dir1left)
|| (dir1right != dirToEnemy && dirToTower == dir1right)
|| (dir2left != dirToEnemy && dirToTower == dir2left)
|| (dir2right != dirToEnemy && dirToTower == dir2right)) {
int distanceToTower = myHQ.distanceSquaredTo(towers[i]);
if (distanceToTower > maxDistance) {
maxDistance = distanceToTower;
maxDistanceIndex = i;
}
}
}
if (maxDistanceIndex != -1) {
return towers[maxDistanceIndex];
}
return null;
}
public void beginningOfTurn() {
if (rc.senseEnemyHQLocation() != null) {
this.theirHQ = rc.senseEnemyHQLocation();
}
}
public void endOfTurn() {
}
public void go() throws GameActionException {
beginningOfTurn();
execute();
endOfTurn();
}
public void execute() throws GameActionException {
rc.yield();
}
public void supplyAndYield() throws GameActionException {
transferSupplies();
rc.yield();
}
public int myContainDirection = smuConstants.CLOCKWISE;
public MapLocation myContainPreviousLocation;
public void contain() {
MapLocation enemyHQ = rc.senseEnemyHQLocation();
MapLocation[] enemyTowers = rc.senseEnemyTowerLocations();
MapLocation myLocation = rc.getLocation();
int radiusFromHQ = 24;
if (enemyTowers.length >= 2) {
radiusFromHQ = 35;
}
if (myLocation.distanceSquaredTo(enemyHQ) > radiusFromHQ + 3) {
// move towards the HQ
try {
moveOptimally();
} catch (GameActionException e) {
e.printStackTrace();
}
} else {
MapLocation locationToGo = null;
Direction directionToGo = null;
if (myContainDirection == smuConstants.CLOCKWISE) {
directionToGo = getClockwiseDirection(myLocation, enemyHQ);
} else {
directionToGo = getCounterClockwiseDirection(myLocation, enemyHQ);
}
locationToGo = myLocation.add(directionToGo);
if (rc.isPathable(RobotType.DRONE, locationToGo)) {
if (isLocationSafe(locationToGo)) {
goToLocation(locationToGo);
} else {
Direction[] directions = breakdownDirection(directionToGo);
for (int i = 0; i < directions.length; i++) {
locationToGo = myLocation.add(directions[i]);
if (isLocationSafe(locationToGo)) {
goToLocation(locationToGo);
myContainPreviousLocation = myLocation;
return;
}
}
}
} else if (myContainPreviousLocation.equals(myLocation)){
if (myContainDirection == smuConstants.CLOCKWISE) {
myContainDirection = smuConstants.COUNTERCLOCKWISE;
} else {
myContainDirection = smuConstants.CLOCKWISE;
}
}
}
myContainPreviousLocation = myLocation;
}
public boolean isLocationSafe(MapLocation location) {
if (location.distanceSquaredTo(theirHQ) > RobotType.HQ.attackRadiusSquared) {
for (MapLocation tower : rc.senseEnemyTowerLocations()) {
if (location.distanceSquaredTo(tower) <= RobotType.TOWER.attackRadiusSquared) {
return false;
}
}
return true;
}
return false;
}
public Direction[] breakdownDirection(Direction direction) {
Direction[] breakdown = new Direction[2];
switch(direction) {
case NORTH_EAST:
breakdown[0] = Direction.NORTH;
breakdown[1] = Direction.EAST;
break;
case SOUTH_EAST:
breakdown[0] = Direction.SOUTH;
breakdown[1] = Direction.EAST;
break;
case NORTH_WEST:
breakdown[0] = Direction.NORTH;
breakdown[1] = Direction.WEST;
break;
case SOUTH_WEST:
breakdown[0] = Direction.SOUTH;
breakdown[1] = Direction.WEST;
break;
default:
break;
}
return breakdown;
}
public Direction getClockwiseDirection(MapLocation myLocation, MapLocation anchor) {
Direction directionToAnchor = myLocation.directionTo(anchor);
if (directionToAnchor.equals(Direction.EAST) || directionToAnchor.equals(Direction.SOUTH_EAST)) {
return Direction.NORTH_EAST;
} else if (directionToAnchor.equals(Direction.SOUTH) || directionToAnchor.equals(Direction.SOUTH_WEST)) {
return Direction.SOUTH_EAST;
} else if (directionToAnchor.equals(Direction.WEST) || directionToAnchor.equals(Direction.NORTH_WEST)) {
return Direction.SOUTH_WEST;
} else if (directionToAnchor.equals(Direction.NORTH) || directionToAnchor.equals(Direction.NORTH_EAST)) {
return Direction.NORTH_WEST;
}
return Direction.NONE;
}
public Direction getCounterClockwiseDirection(MapLocation myLocation, MapLocation anchor) {
Direction oppositeDirection = getClockwiseDirection(myLocation, anchor);
if (oppositeDirection.equals(Direction.NORTH_EAST)) {
return Direction.SOUTH_WEST;
} else if (oppositeDirection.equals(Direction.SOUTH_EAST)) {
return Direction.NORTH_WEST;
} else if (oppositeDirection.equals(Direction.SOUTH_WEST)) {
return Direction.NORTH_EAST;
} else if (oppositeDirection.equals(Direction.NORTH_WEST)) {
return Direction.SOUTH_WEST;
}
return Direction.NONE;
}
// Defend
public boolean defendSelf() {
RobotInfo[] nearbyEnemies = getEnemiesInAttackRange();
if(nearbyEnemies != null && nearbyEnemies.length > 0) {
try {
if (rc.isWeaponReady()) {
attackLeastHealthEnemyInRange();
}
} catch (GameActionException e) {
e.printStackTrace();
}
return true;
}
return false;
}
public boolean defendTeammates() {
RobotInfo[] engagedRobots = getRobotsEngagedInAttack();
if(engagedRobots != null && engagedRobots.length>0) { // Check broadcasts for enemies that are being attacked
// TODO: Calculate which enemy is attacking/within range/closest to teammate
// For now, just picking the first enemy
// Once our unit is in range of the other unit, A1 will takeover
for (RobotInfo robot : engagedRobots) {
if (robot.team == theirTeam) {
goToLocation(robot.location);
}
}
return true;
}
return false;
}
public boolean defendTowerHoles() {
int towerHoleX = -1;
try {
towerHoleX = rc.readBroadcast(smuIndices.TOWER_HOLES_BEGIN);
} catch (GameActionException e1) {
e1.printStackTrace();
}
boolean defendingHole = false;
if(towerHoleX != -1) {
int towerHolesIndex = smuIndices.TOWER_HOLES_BEGIN;
int towerHoleY;
do {
try {
towerHoleX = rc.readBroadcast(towerHolesIndex);
towerHolesIndex++;
towerHoleY = rc.readBroadcast(towerHolesIndex);
towerHolesIndex++;
if (towerHoleX != -1) {
MapLocation holeLocation = new MapLocation(towerHoleX, towerHoleY);
RobotInfo[] nearbyTeammates = rc.senseNearbyRobots(holeLocation, 5, myTeam);
if (nearbyTeammates.length < smuConstants.NUM_HOLE_PROTECTORS && rc.getLocation().distanceSquaredTo(holeLocation) <= smuConstants.DISTANCE_TO_START_PROTECTING_SQUARED) {
defendingHole = true;
towerHoleX = -1;
goToLocation(holeLocation);
}
}
} catch (GameActionException e) {
e.printStackTrace();
}
} while(towerHoleX != -1);
}
return defendingHole;
}
public boolean defendTowers() {
MapLocation[] myTowers = rc.senseTowerLocations();
MapLocation closestTower = null;
try {
closestTower = getRallyPoint();
} catch (GameActionException e) {
e.printStackTrace();
}
int closestDist = Integer.MAX_VALUE;
for (MapLocation tower : myTowers) {
RobotInfo[] nearbyRobots = getTeammatesNearTower(tower);
if (nearbyRobots.length < smuConstants.NUM_TOWER_PROTECTORS && rc.getLocation().distanceSquaredTo(tower) <= smuConstants.DISTANCE_TO_START_PROTECTING_SQUARED) { //tower underprotected
int dist = tower.distanceSquaredTo(theirHQ);
if (dist < closestDist) {
closestDist = dist;
closestTower = tower;
}
}
}
goToLocation(closestTower);
return true;
}
public boolean defend() {
// A1, Protect Self
boolean isProtectingSelf = defendSelf();
if (isProtectingSelf) {
return true;
}
// A2, Protect Nearby
boolean isProtectingTeammates = defendTeammates();
if (isProtectingTeammates) {
return true;
}
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack &&
Clock.getRoundNum() > smuConstants.roundToDefendTowers &&
myType != RobotType.BEAVER && myType != RobotType.MINER) {
// B1, Protect Holes Between Towers
boolean isProtectingHoles = defendTowerHoles();
if (isProtectingHoles) {
return true;
}
if(myType != RobotType.BEAVER && myType != RobotType.MINER) {
// B2, Protect Towers
boolean isProtectingTowers = defendTowers();
if (isProtectingTowers) {
return true;
}
}
}
return false;
}
public int RobotTypeToInt(RobotType type){
switch(type) {
case AEROSPACELAB:
return 1;
case BARRACKS:
return 2;
case BASHER:
return 3;
case BEAVER:
return 4;
case COMMANDER:
return 5;
case COMPUTER:
return 6;
case DRONE:
return 7;
case HANDWASHSTATION:
return 8;
case HELIPAD:
return 9;
case HQ:
return 10;
case LAUNCHER:
return 11;
case MINER:
return 12;
case MINERFACTORY:
return 13;
case MISSILE:
return 14;
case SOLDIER:
return 15;
case SUPPLYDEPOT:
return 16;
case TANK:
return 17;
case TANKFACTORY:
return 18;
case TECHNOLOGYINSTITUTE:
return 19;
case TOWER:
return 20;
case TRAININGFIELD:
return 21;
default:
return -1;
}
}
public RobotType IntToRobotType(int type){
switch(type) {
case 1:
return RobotType.AEROSPACELAB;
case 2:
return RobotType.BARRACKS;
case 3:
return RobotType.BASHER;
case 4:
return RobotType.BEAVER;
case 5:
return RobotType.COMMANDER;
case 6:
return RobotType.COMPUTER;
case 7:
return RobotType.DRONE;
case 8:
return RobotType.HANDWASHSTATION;
case 9:
return RobotType.HELIPAD;
case 10:
return RobotType.HQ;
case 11:
return RobotType.LAUNCHER;
case 12:
return RobotType.MINER;
case 13:
return RobotType.MINERFACTORY;
case 14:
return RobotType.MISSILE;
case 15:
return RobotType.SOLDIER;
case 16:
return RobotType.SUPPLYDEPOT;
case 17:
return RobotType.TANK;
case 18:
return RobotType.TANKFACTORY;
case 19:
return RobotType.TECHNOLOGYINSTITUTE;
case 20:
return RobotType.TOWER;
case 21:
return RobotType.TRAININGFIELD;
default:
return null;
}
}
// //Returns a weight representing the 'need' for the RobotType
// public double getWeightOfRobotType(RobotType type) throws GameActionException {
// int typeInt = RobotTypeToInt(type);
// if (rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) == 0) return 0;
// double weight = rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt) +
// (rc.readBroadcast(smuIndices.freqRoundToFinish + typeInt) - rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt)) /
// rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) * rc.readBroadcast(smuIndices.freqNum[typeInt]);
// return weight;
//Returns a weight representing the 'need' for the RobotType
public double getWeightOfRobotType(RobotType type) throws GameActionException {
int typeInt = RobotTypeToInt(type);
int round = Clock.getRoundNum();
double weight;
//Return zero if unit is not desired. (Divide by zero protection)
//System.out.println("type: "+IntToRobotType(typeInt));
if (rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) == 0) {
//System.out.println("Error: No desired "+IntToRobotType(typeInt));
return 0;
}
if (rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt) >= rc.readBroadcast(smuIndices.freqRoundToFinish + typeInt)) {
//System.out.println("Error: build > finish for: "+IntToRobotType(typeInt));
return 0;
}
if (round < rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt)) {
//System.out.println("Error: Too early for "+IntToRobotType(typeInt));
return 0;
}
//The weight is equal to the surface drawn by z = x^(m*y)
double x = (double)(round - rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt)) / (double) (rc.readBroadcast(smuIndices.freqRoundToFinish + typeInt) - rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt));
double y = (double)rc.readBroadcast(smuIndices.freqNum[typeInt]) / (double) rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt);
weight = smuConstants.weightScaleMagic * Math.pow(x, (smuConstants.weightExponentMagic + y));
//System.out.println("type: "+IntToRobotType(typeInt)+" x: " + x + " y: " + y + " weight: " + weight);
return weight;
}
/**
* Simple helpers, more logic for these later
*/
public RobotInfo[] getEnemiesInAttackRange() {
return rc.senseNearbyRobots(myRange, theirTeam);
}
public void goToLocation(MapLocation location) {
try {
if (rc.canSenseLocation(location) && rc.senseRobotAtLocation(location) != null
&& rc.getLocation().distanceSquaredTo(location)<3) { // 3 squares
return;
}
} catch (GameActionException e1) {
e1.printStackTrace();
}
Direction direction = getMoveDir(location);
if (direction != null && rc.isCoreReady()) {
try {
rc.move(direction);
} catch (GameActionException e) {
e.printStackTrace();
}
}
}
public RobotInfo[] getRobotsEngagedInAttack() {
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(smuConstants.PROTECT_OTHERS_RANGE);
boolean hasEnemy = false;
boolean hasFriendly = false;
for (RobotInfo robot : nearbyRobots) {
if(robot.team == theirTeam) {
hasEnemy = true;
if (hasFriendly) {
return nearbyRobots;
}
} else {
hasFriendly = true;
if (hasEnemy) {
return nearbyRobots;
}
}
}
return null;
}
public RobotInfo[] getTeammatesInAttackRange() {
return rc.senseNearbyRobots(myRange, myTeam);
}
public RobotInfo[] getTeammatesNearTower(MapLocation towerLocation) {
return rc.senseNearbyRobots(towerLocation, RobotType.TOWER.attackRadiusSquared, myTeam);
}
// Find out if there are any holes between a teams tower and their HQ
public MapLocation[] computeHoles() {
MapLocation[] towerLocations = rc.senseTowerLocations();
MapLocation[][] towerRadii = new MapLocation[towerLocations.length][];
for(int i = 0; i < towerLocations.length; i++) {
// Get all map locations that a tower can attack
MapLocation[] locations = MapLocation.getAllMapLocationsWithinRadiusSq(towerLocations[i], RobotType.TOWER.attackRadiusSquared);
Arrays.sort(locations);
towerRadii[i] = locations;
}
if(towerRadii.length == 0 || towerRadii[0] == null) {
return null;
}
// Naively say, if overlapping by two towers, there is no path
int[] overlapped = new int[towerRadii.length];
int holesBroadcastIndex = smuIndices.TOWER_HOLES_BEGIN;
for(int i = 0; i<towerRadii.length; i++) {
MapLocation[] locations = towerRadii[i];
boolean coveredLeft = false;
boolean coveredRight = false;
boolean coveredTop = false;
boolean coveredBottom = false;
for (int j = 0; j < towerRadii.length; j++) {
if (j != i) {
MapLocation[] otherLocations = towerRadii[j];
if (locations[0].x <= otherLocations[otherLocations.length-1].x &&
otherLocations[0].x <= locations[locations.length-1].x &&
locations[0].y <= otherLocations[otherLocations.length-1].y &&
otherLocations[0].y <= locations[locations.length-1].y) {
overlapped[i]++;
Direction otherTowerDir = towerLocations[i].directionTo(towerLocations[j]);
if (otherTowerDir.equals(Direction.EAST) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.SOUTH_EAST)) {
coveredLeft = true;
}
if (otherTowerDir.equals(Direction.WEST) || otherTowerDir.equals(Direction.NORTH_WEST) || otherTowerDir.equals(Direction.SOUTH_WEST)) {
coveredRight = true;
}
if (otherTowerDir.equals(Direction.NORTH) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.NORTH_WEST)) {
coveredTop = true;
}
if (otherTowerDir.equals(Direction.SOUTH) || otherTowerDir.equals(Direction.SOUTH_EAST) || otherTowerDir.equals(Direction.SOUTH_WEST)) {
coveredBottom = true;
}
}
}
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x - 1, locations[0].y))) {
overlapped[i]++;
coveredLeft = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[locations.length-1].x + 1, locations[0].y))) {
overlapped[i]++;
coveredRight = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[0].y - 1))) {
overlapped[i]++;
coveredTop = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[locations.length-1].y + 1))) {
overlapped[i]++;
coveredBottom = true;
}
//System.out.println("Tower " + i + " overlapped " + overlapped[i] + " " + towerLocations[i]);
if (overlapped[i] < 2) {
try {
int towerAttackRadius = (int) Math.sqrt(RobotType.TOWER.attackRadiusSquared) + 1;
if (!coveredLeft) {
//System.out.println("Tower " + towerLocations[i] + " Not covered left");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x - towerAttackRadius);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y);
holesBroadcastIndex+=2;
}
if (!coveredRight) {
//System.out.println("Tower " + towerLocations[i] + " Not covered right");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x + towerAttackRadius);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y);
holesBroadcastIndex+=2;
}
if (!coveredTop) {
//System.out.println("Tower " + towerLocations[i] + " Not covered top");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y - towerAttackRadius);
holesBroadcastIndex+=2;
}
if (!coveredBottom) {
//System.out.println("Tower " + towerLocations[i] + " Not covered bottom");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y + towerAttackRadius);
holesBroadcastIndex+=2;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
}
// Signify end of holes
try {
rc.broadcast(holesBroadcastIndex, -1);
} catch (GameActionException e) {
e.printStackTrace();
}
//System.out.println("BYTEEND on " + Clock.getRoundNum() + ": " + Clock.getBytecodeNum());
return null;
}
}
public static class HQ extends BaseBot {
public HQ(RobotController rc) throws GameActionException {
super(rc);
computeStrategy();
computeHoles();
}
public void computeStrategy() throws GameActionException{
boolean launcherStrategy = false;
boolean soldierBasherTankStrategy = true;
// [desiredNumOf, roundToBuild, roundToFinish]
int[] strategyAEROSPACELAB = new int[3];
int[] strategyBARRACKS = new int[3];
int[] strategyBASHER = new int[3];
int[] strategyBEAVER = new int[3];
int[] strategyCOMMANDER = new int[3];
int[] strategyCOMPUTER = new int[3];
int[] strategyDRONE = new int[3];
int[] strategyHANDWASHSTATION = new int[3];
int[] strategyHELIPAD = new int[3];
int[] strategyHQ = new int[3];
int[] strategyLAUNCHER = new int[3];
int[] strategyMINER = new int[3];
int[] strategyMINERFACTORY = new int[3];
int[] strategyMISSILE = new int[3];
int[] strategySOLDIER = new int[3];
int[] strategySUPPLYDEPOT = new int[3];
int[] strategyTANK = new int[3];
int[] strategyTANKFACTORY = new int[3];
int[] strategyTECHNOLOGYINSTITUTE = new int[3];
int[] strategyTOWER = new int[3];
int[] strategyTRAININGFIELD = new int[3];
if(soldierBasherTankStrategy){
strategyAEROSPACELAB = new int[] {0, 0, 0};
strategyBARRACKS = new int[] {4, 500, 1500};
strategyBASHER = new int[] {50, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 0};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {0, 0, 0};
strategyHANDWASHSTATION = new int[] {3, 1700, 1900};
strategyHELIPAD = new int[] {0, 0, 0};
strategyHQ = new int[] {0, 0, 0};
strategyLAUNCHER = new int[] {0, 0, 0};
strategyMINER = new int[] {50, 1, 500};
strategyMINERFACTORY = new int[] {2, 1, 250};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {120, 200, 1200};
strategySUPPLYDEPOT = new int[] {10, 700, 1400};
strategyTANK = new int[] {20, 1100, 1800};
strategyTANKFACTORY = new int[] {2, 1000, 1400};
strategyTECHNOLOGYINSTITUTE = new int[] {0, 0, 0};
strategyTOWER = new int[] {0, 0, 0};
strategyTRAININGFIELD = new int[] {0, 0, 0};
}
if(launcherStrategy){
strategyAEROSPACELAB = new int[] {2, 1000, 1400};
strategyBARRACKS = new int[] {4, 500, 1500};
strategyBASHER = new int[] {0, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 0};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {0, 0, 0};
strategyHANDWASHSTATION = new int[] {3, 1700, 1900};
strategyHELIPAD = new int[] {1, 1, 600};
strategyHQ = new int[] {0, 0, 0};
strategyLAUNCHER = new int[] {20, 1100, 1700};
strategyMINER = new int[] {30, 1, 500};
strategyMINERFACTORY = new int[] {2, 1, 250};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {120, 200, 1200};
strategySUPPLYDEPOT = new int[] {10, 700, 1500};
strategyTANK = new int[] {0, 1100, 1800};
strategyTANKFACTORY = new int[] {0, 1000, 1400};
strategyTECHNOLOGYINSTITUTE = new int[] {0, 0, 0};
strategyTOWER = new int[] {0, 0, 0};
strategyTRAININGFIELD = new int[] {0, 0, 0};
}
int[][] strategyArray = new int[][] {strategyAEROSPACELAB, strategyBARRACKS, strategyBASHER, strategyBEAVER, strategyCOMMANDER, strategyCOMPUTER, strategyDRONE, strategyHANDWASHSTATION, strategyHELIPAD, strategyHQ, strategyLAUNCHER, strategyMINER, strategyMINERFACTORY, strategyMISSILE, strategySOLDIER, strategySUPPLYDEPOT, strategyTANK, strategyTANKFACTORY, strategyTECHNOLOGYINSTITUTE, strategyTOWER, strategyTRAININGFIELD};
for (int i = 1; i < strategyArray.length; i++) {
rc.broadcast(smuIndices.freqDesiredNumOf + i, strategyArray[i-1][0]);
rc.broadcast(smuIndices.freqRoundToBuild + i, strategyArray[i-1][1]);
rc.broadcast(smuIndices.freqRoundToFinish + i, strategyArray[i-1][2]);
}
}
public boolean checkContainment() throws GameActionException {
RobotInfo[] enemyRobotsContaining = rc.senseNearbyRobots(50, theirTeam);
if (enemyRobotsContaining.length > 4) {
rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.CURRENTLY_BEING_CONTAINED);
return true;
} else {
rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.NOT_CURRENTLY_BEING_CONTAINED);
return false;
}
}
public void setRallyPoint() throws GameActionException {
MapLocation rallyPoint = null;
boolean beingContained = checkContainment();
if (!beingContained) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
MapLocation[] ourTowers = rc.senseTowerLocations();
if (ourTowers != null && ourTowers.length > 0) {
int closestTower = -1;
int closestDistanceToEnemyHQ = Integer.MAX_VALUE;
for (int i = 0; i < ourTowers.length; i++) {
int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ);
if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) {
closestDistanceToEnemyHQ = currDistanceToEnemyHQ;
closestTower = i;
}
}
rallyPoint = ourTowers[closestTower].add(ourTowers[closestTower].directionTo(theirHQ), 2);
}
}
else {
MapLocation[] enemyTowers = rc.senseEnemyTowerLocations();
if (enemyTowers == null || enemyTowers.length <= smuConstants.numTowersRemainingToAttackHQ) {
rallyPoint = rc.senseEnemyHQLocation();
} else {
rallyPoint = enemyTowers[0];
}
}
} else {
rallyPoint = getSecondBaseLocation();
if (rallyPoint != null) {
rallyPoint = rallyPoint.add(rallyPoint.directionTo(theirHQ), 8);
}
}
if (rallyPoint != null) {
rc.broadcast(smuIndices.RALLY_POINT_X, rallyPoint.x);
rc.broadcast(smuIndices.RALLY_POINT_Y, rallyPoint.y);
}
}
public void execute() throws GameActionException {
spawnOptimally();
setRallyPoint();
attackLeastHealthEnemyInRange();
transferSupplies();
rc.yield();
}
}
//BEAVER
public static class Beaver extends BaseBot {
public MapLocation secondBase;
public Beaver(RobotController rc) {
super(rc);
Random rand = new Random(rc.getID());
if (rand.nextDouble() < smuConstants.percentBeaversToGoToSecondBase) {
secondBase = getSecondBaseLocation();
}
}
public void execute() throws GameActionException {
if (secondBase != null && rc.getLocation().distanceSquaredTo(secondBase) > 6) {
goToLocation(secondBase);
}
buildOptimally();
transferSupplies();
if (Clock.getRoundNum() > 400) defend();
if (rc.isCoreReady()) {
//mine
if (rc.senseOre(rc.getLocation()) > 0) {
rc.mine();
}
else {
moveOptimally();
}
}
rc.yield();
}
}
//MINERFACTORY
public static class Minerfactory extends BaseBot {
public Minerfactory(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//MINER
public static class Miner extends BaseBot {
public Miner(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
boolean inConvoy = false;
if (Clock.getRoundNum()>smuConstants.roundToFormSupplyConvoy
&& rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) != smuConstants.CURRENTLY_BEING_CONTAINED) {
inConvoy = formSupplyConvoy();
}
if (!inConvoy) {
if (!defend()) {
if (rc.isCoreReady()) {
//mine
if (rc.senseOre(rc.getLocation()) > 0) {
rc.mine();
}
else {
moveOptimally();
}
}
}
} else if(!defendSelf()) {
if (rc.isCoreReady()) {
if (rc.senseOre(rc.getLocation()) > 0) {
rc.mine();
}
}
}
transferSupplies();
rc.yield();
}
}
//BARRACKS
public static class Barracks extends BaseBot {
public Barracks(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//SOLDIER
public static class Soldier extends BaseBot {
public Soldier(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (!defend()) {
moveToRallyPoint();
}
transferSupplies();
rc.yield();
}
}
//BASHER
public static class Basher extends BaseBot {
public Basher(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
boolean hasTakenAction = false;
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
hasTakenAction = defendTowerHoles();
if (!hasTakenAction) {
hasTakenAction = defendTowers();
}
}
if (!hasTakenAction) {
moveToRallyPoint();
}
transferSupplies();
rc.yield();
}
}
//TANK
public static class Tank extends BaseBot {
public Tank(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (!defend()) {
moveToRallyPoint();
}
transferSupplies();
rc.yield();
}
}
//DRONE
public static class Drone extends BaseBot {
public Drone(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (!defendSelf()) {
if (Clock.getRoundNum() > 1800) {
moveToRallyPoint();
} else {
contain();
}
}
transferSupplies();
rc.yield();
}
}
//TOWER
public static class Tower extends BaseBot {
public Tower(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
attackLeastHealthEnemyInRange();
rc.yield();
}
}
//SUPPLYDEPOT
public static class Supplydepot extends BaseBot {
public Supplydepot(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
rc.yield();
}
}
//HANDWASHSTATION
public static class Handwashstation extends BaseBot {
public Handwashstation(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
rc.yield();
}
}
//TANKFACTORY
public static class Tankfactory extends BaseBot {
public Tankfactory(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//HELIPAD
public static class Helipad extends BaseBot {
public Helipad(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//AEROSPACELAB
public static class Aerospacelab extends BaseBot {
public Aerospacelab(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//LAUNCHER
public static class Launcher extends BaseBot {
public Launcher(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (Clock.getRoundNum() > smuConstants.roundToLaunchAttack && rc.getMissileCount() > 0) {
Direction targetDir = getMoveDir(theirHQ);
if (targetDir != null && rc.isWeaponReady()){
if (rc.canLaunch(targetDir)){
rc.launchMissile(getMoveDir(theirHQ));
}
}
}
moveToRallyPoint();
rc.yield();
}
}
//MISSILE
public static class Missile extends BaseBot {
public Missile(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
moveToRallyPoint();
if (getTeammatesInAttackRange().length <= 1 && getTeammatesInAttackRange().length > 4){
rc.explode();
}
rc.yield();
}
}
} |
package org.apache.james.smtpserver;
import org.apache.avalon.cornerstone.services.connection.ConnectionHandler;
import org.apache.avalon.cornerstone.services.scheduler.PeriodicTimeTrigger;
import org.apache.avalon.cornerstone.services.scheduler.Target;
import org.apache.avalon.cornerstone.services.scheduler.TimeScheduler;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.james.BaseConnectionHandler;
import org.apache.james.Constants;
import org.apache.james.core.MailHeaders;
import org.apache.james.core.MailImpl;
import org.apache.james.services.MailServer;
import org.apache.james.services.UsersRepository;
import org.apache.james.services.UsersStore;
import org.apache.james.util.*;
import org.apache.mailet.MailAddress;
import javax.mail.MessagingException;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;
/**
* Provides SMTP functionality by carrying out the server side of the SMTP
* interaction.
*
* @author Serge Knystautas <sergek@lokitech.com>
* @author Federico Barbieri <scoobie@systemy.it>
* @author Jason Borden <jborden@javasense.com>
* @author Matthew Pangaro <mattp@lokitech.com>
* @author Danny Angus <danny@thought.co.uk>
* @author Peter M. Goldstein <farsight@alum.mit.edu>
*
* @version This is $Revision: 1.30 $
*/
public class SMTPHandler
extends BaseConnectionHandler
implements ConnectionHandler, Composable, Configurable, Target {
/**
* SMTP Server identification string used in SMTP headers
*/
private final static String SOFTWARE_TYPE = "JAMES SMTP Server "
+ Constants.SOFTWARE_VERSION;
// Keys used to store/lookup data in the internal state hash map
private final static String CURRENT_HELO_MODE = "CURRENT_HELO_MODE"; // HELO or EHLO
private final static String SENDER = "SENDER_ADDRESS"; // Sender's email address
private final static String MESG_FAILED = "MESG_FAILED"; // Message failed flag
private final static String MESG_SIZE = "MESG_SIZE"; // The size of the message
private final static String RCPT_VECTOR = "RCPT_VECTOR"; // The message recipients
/**
* The character array that indicates termination of an SMTP connection
*/
private final static char[] SMTPTerminator = { '\r', '\n', '.', '\r', '\n' };
/**
* Static Random instance used to generate SMTP ids
*/
private final static Random random = new Random();
/**
* Static RFC822DateFormat used to generate date headers
*/
private final static RFC822DateFormat rfc822DateFormat = new RFC822DateFormat();
/**
* The text string for the SMTP HELO command.
*/
private final static String COMMAND_HELO = "HELO";
/**
* The text string for the SMTP EHLO command.
*/
private final static String COMMAND_EHLO = "EHLO";
/**
* The text string for the SMTP AUTH command.
*/
private final static String COMMAND_AUTH = "AUTH";
/**
* The text string for the SMTP MAIL command.
*/
private final static String COMMAND_MAIL = "MAIL";
/**
* The text string for the SMTP RCPT command.
*/
private final static String COMMAND_RCPT = "RCPT";
/**
* The text string for the SMTP NOOP command.
*/
private final static String COMMAND_NOOP = "NOOP";
/**
* The text string for the SMTP RSET command.
*/
private final static String COMMAND_RSET = "RSET";
/**
* The text string for the SMTP DATA command.
*/
private final static String COMMAND_DATA = "DATA";
/**
* The text string for the SMTP QUIT command.
*/
private final static String COMMAND_QUIT = "QUIT";
/**
* The text string for the SMTP HELP command.
*/
private final static String COMMAND_HELP = "HELP";
/**
* The text string for the SMTP VRFY command.
*/
private final static String COMMAND_VRFY = "VRFY";
/**
* The text string for the SMTP EXPN command.
*/
private final static String COMMAND_EXPN = "EXPN";
/**
* The text string for the SMTP AUTH type PLAIN.
*/
private final static String AUTH_TYPE_PLAIN = "PLAIN";
/**
* The text string for the SMTP AUTH type LOGIN.
*/
private final static String AUTH_TYPE_LOGIN = "LOGIN";
/**
* The text string for the SMTP MAIL command SIZE option.
*/
private final static String MAIL_OPTION_SIZE = "SIZE";
/**
* The TCP/IP socket over which the SMTP
* dialogue is occurring.
*/
private Socket socket;
/**
* The incoming stream of bytes coming from the socket.
*/
private InputStream in;
/**
* The writer to which outgoing messages are written.
*/
private PrintWriter out;
/**
* A Reader wrapper for the incoming stream of bytes coming from the socket.
*/
private BufferedReader inReader;
/**
* The remote host name obtained by lookup on the socket.
*/
private String remoteHost;
/**
* The remote IP address of the socket.
*/
private String remoteIP;
/**
* The user name of the authenticated user associated with this SMTP transaction.
*/
private String authenticatedUser;
/**
* The id associated with this particular SMTP interaction.
*/
private String smtpID;
/**
* Whether authentication is required to use
* this SMTP server.
*/
private boolean authRequired = false;
/**
* Whether the server verifies that the user
* actually sending an email matches the
* authentication credentials attached to the
* SMTP interaction.
*/
private boolean verifyIdentity = false;
/**
* The maximum message size allowed by this SMTP server. The default
* value, 0, means no limit.
*/
private long maxmessagesize = 0;
/**
* The number of bytes to read before resetting the connection timeout
* timer. Defaults to 20,000 bytes.
*/
private int lengthReset = 20000;
/**
* The scheduler used to handle timeouts for the SMTP interaction.
*/
private TimeScheduler scheduler;
/**
* The user repository for this server - used to authenticate
* users.
*/
private UsersRepository users;
/**
* The internal mail server service.
*/
private MailServer mailServer;
/**
* The hash map that holds variables for the SMTP message transfer in progress.
*
* This hash map should only be used to store variable set in a particular
* set of sequential MAIL-RCPT-DATA commands, as described in RFC 2821. Per
* connection values should be stored as member variables in this class.
*/
private HashMap state = new HashMap();
/**
* @see org.apache.avalon.framework.component.Composable#compose(ComponentManager)
*/
public void compose(final ComponentManager componentManager) throws ComponentException {
mailServer = (MailServer) componentManager.lookup("org.apache.james.services.MailServer");
scheduler =
(TimeScheduler) componentManager.lookup(
"org.apache.avalon.cornerstone.services.scheduler.TimeScheduler");
UsersStore usersStore =
(UsersStore) componentManager.lookup("org.apache.james.services.UsersStore");
users = usersStore.getRepository("LocalUsers");
}
/**
* Pass the <code>Configuration</code> to the instance.
*
* @param configuration the class configurations.
* @throws ConfigurationException if an error occurs
*/
public void configure(Configuration configuration) throws ConfigurationException {
super.configure(configuration);
authRequired = configuration.getChild("authRequired").getValueAsBoolean(false);
verifyIdentity = configuration.getChild("verifyIdentity").getValueAsBoolean(false);
// get the message size limit from the conf file and multiply
// by 1024, to put it in bytes
maxmessagesize = configuration.getChild( "maxmessagesize" ).getValueAsLong( 0 ) * 1024;
if (getLogger().isDebugEnabled()) {
getLogger().debug("Max message size is: " + maxmessagesize);
}
//how many bytes to read before updating the timer that data is being transfered
lengthReset = configuration.getChild("lengthReset").getValueAsInteger(20000);
}
/**
* @see org.apache.avalon.cornerstone.services.connection.ConnectionHandler#handleConnection(Socket)
*/
public void handleConnection(Socket connection) throws IOException {
try {
this.socket = connection;
in = new BufferedInputStream(socket.getInputStream(), 1024);
// An ASCII encoding can be used because all transmissions other
// that those in the DATA command are guaranteed
// to be ASCII
inReader = new BufferedReader(new InputStreamReader(in, "ASCII"));
out = new InternetPrintWriter(socket.getOutputStream(), true);
remoteIP = socket.getInetAddress().getHostAddress();
remoteHost = socket.getInetAddress().getHostName();
smtpID = random.nextInt(1024) + "";
resetState();
} catch (Exception e) {
StringBuffer exceptionBuffer =
new StringBuffer(256)
.append("Cannot open connection from ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append("): ")
.append(e.getMessage());
String exceptionString = exceptionBuffer.toString();
getLogger().error(exceptionString, e );
throw new RuntimeException(exceptionString);
}
if (getLogger().isInfoEnabled()) {
StringBuffer infoBuffer =
new StringBuffer(128)
.append("Connection from ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(")");
getLogger().info(infoBuffer.toString());
}
try {
// Initially greet the connector
// Format is: Sat, 24 Jan 1998 13:16:09 -0500
final PeriodicTimeTrigger trigger = new PeriodicTimeTrigger( timeout, -1 );
scheduler.addTrigger( this.toString(), trigger, this );
StringBuffer responseBuffer =
new StringBuffer(192)
.append("220 ")
.append(this.helloName)
.append(" SMTP Server (")
.append(SOFTWARE_TYPE)
.append(") ready ")
.append(rfc822DateFormat.format(new Date()));
String responseString = responseBuffer.toString();
writeLoggedFlushedResponse(responseString);
while (parseCommand(readCommandLine())) {
scheduler.resetTrigger(this.toString());
}
getLogger().debug("Closing socket.");
scheduler.removeTrigger(this.toString());
} catch (SocketException se) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(64)
.append("Socket to ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") closed remotely.");
getLogger().debug(errorBuffer.toString(), se );
}
} catch ( InterruptedIOException iioe ) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(64)
.append("Socket to ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") timeout.");
getLogger().debug( errorBuffer.toString(), iioe );
}
} catch ( IOException ioe ) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Exception handling socket to ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") : ")
.append(ioe.getMessage());
getLogger().debug( errorBuffer.toString(), ioe );
}
} catch (Exception e) {
if (getLogger().isDebugEnabled()) {
getLogger().debug( "Exception opening socket: "
+ e.getMessage(), e );
}
} finally {
try {
socket.close();
} catch (IOException e) {
if (getLogger().isErrorEnabled()) {
getLogger().error("Exception closing socket: "
+ e.getMessage());
}
}
}
}
/**
* Callback method called when the the PeriodicTimeTrigger in
* handleConnection is triggered. In this case the trigger is
* being used as a timeout, so the method simply closes the connection.
*
* @param triggerName the name of the trigger
*
* TODO: Remove this interface from the class and change the mechanism
*/
public void targetTriggered(final String triggerName) {
getLogger().error("Connection timeout on socket with " + remoteHost + " (" + remoteIP + ")");
try {
out.println("Connection timeout. Closing connection");
socket.close();
} catch (IOException e) {
// Ignored
}
}
/**
* This method logs at a "DEBUG" level the response string that
* was sent to the SMTP client. The method is provided largely
* as syntactic sugar to neaten up the code base. It is declared
* private and final to encourage compiler inlining.
*
* @param responseString the response string sent to the client
*/
private final void logResponseString(String responseString) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Sent: " + responseString);
}
}
/**
* Write and flush a response string. The response is also logged.
* Should be used for the last line of a multi-line response or
* for a single line response.
*
* @param responseString the response string sent to the client
*/
final void writeLoggedFlushedResponse(String responseString) {
out.println(responseString);
out.flush();
logResponseString(responseString);
}
/**
* Write a response string. The response is also logged.
* Used for multi-line responses.
*
* @param responseString the response string sent to the client
*/
final void writeLoggedResponse(String responseString) {
out.println(responseString);
out.flush();
logResponseString(responseString);
}
/**
* Reads a line of characters off the command line.
*
* @return the trimmed input line
* @throws IOException if an exception is generated reading in the input characters
*/
final String readCommandLine() throws IOException {
return inReader.readLine().trim();
}
/**
* Sets the user name associated with this SMTP interaction.
*
* @param userID the user name
*/
private void setUser(String userID) {
authenticatedUser = userID;
}
/**
* Returns the user name associated with this SMTP interaction.
*
* @return the user name
*/
private String getUser() {
return authenticatedUser;
}
/**
* Resets message-specific, but not authenticated user, state.
*
*/
private void resetState() {
state.clear();
}
/**
* This method parses SMTP commands read off the wire in handleConnection.
* Actual processing of the command (possibly including additional back and
* forth communication with the client) is delegated to one of a number of
* command specific handler methods. The primary purpose of this method is
* to parse the raw command string to determine exactly which handler should
* be called. It returns true if expecting additional commands, false otherwise.
*
* @param rawCommand the raw command string passed in over the socket
*
* @return whether additional commands are expected.
*/
private boolean parseCommand(String rawCommand) throws Exception {
String argument = null;
boolean returnValue = true;
String command = rawCommand;
if (rawCommand == null) {
return false;
}
if ((state.get(MESG_FAILED) == null) && (getLogger().isDebugEnabled())) {
getLogger().debug("Command received: " + command);
}
int spaceIndex = command.indexOf(" ");
if (spaceIndex > 0) {
argument = command.substring(spaceIndex + 1);
command = command.substring(0, spaceIndex);
}
command = command.toUpperCase(Locale.US);
if (command.equals(COMMAND_HELO)) {
doHELO(argument);
} else if (command.equals(COMMAND_EHLO)) {
doEHLO(argument);
} else if (command.equals(COMMAND_AUTH)) {
doAUTH(argument);
} else if (command.equals(COMMAND_MAIL)) {
doMAIL(argument);
} else if (command.equals(COMMAND_RCPT)) {
doRCPT(argument);
} else if (command.equals(COMMAND_NOOP)) {
doNOOP(argument);
} else if (command.equals(COMMAND_RSET)) {
doRSET(argument);
} else if (command.equals(COMMAND_DATA)) {
doDATA(argument);
} else if (command.equals(COMMAND_QUIT)) {
doQUIT(argument);
returnValue = false;
} else if (command.equals(COMMAND_VRFY)) {
doVRFY(argument);
} else if (command.equals(COMMAND_EXPN)) {
doEXPN(argument);
} else if (command.equals(COMMAND_HELP)) {
doHELP(argument);
} else {
if (state.get(MESG_FAILED) == null) {
doUnknownCmd(command, argument);
}
}
return returnValue;
}
/**
* Handler method called upon receipt of a HELO command.
* Responds with a greeting and informs the client whether
* client authentication is required.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doHELO(String argument) {
String responseString = null;
if (argument == null) {
responseString = "501 Domain address required: " + COMMAND_HELO;
writeLoggedFlushedResponse(responseString);
} else {
resetState();
state.put(CURRENT_HELO_MODE, COMMAND_HELO);
StringBuffer responseBuffer = new StringBuffer(256);
if (authRequired) {
//This is necessary because we're going to do a multiline response
responseBuffer.append("250-");
} else {
responseBuffer.append("250 ");
}
responseBuffer.append(helloName)
.append(" Hello ")
.append(argument)
.append(" (")
.append(remoteHost)
.append(" [")
.append(remoteIP)
.append("])");
responseString = responseBuffer.toString();
out.println(responseString);
if (authRequired) {
logResponseString(responseString);
responseString = "250 AUTH LOGIN PLAIN";
out.println(responseString);
}
}
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a EHLO command.
* Responds with a greeting and informs the client whether
* client authentication is required.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doEHLO(String argument) {
String responseString = null;
if (argument == null) {
responseString = "501 Domain address required: " + COMMAND_EHLO;
writeLoggedFlushedResponse(responseString);
} else {
resetState();
state.put(CURRENT_HELO_MODE, COMMAND_EHLO);
// Extension defined in RFC 1870
if (maxmessagesize > 0) {
responseString = "250-SIZE " + maxmessagesize;
writeLoggedResponse(responseString);
}
StringBuffer responseBuffer = new StringBuffer(256);
if (authRequired) {
//This is necessary because we're going to do a multiline response
responseBuffer.append("250-");
} else {
responseBuffer.append("250 ");
}
responseBuffer.append(helloName)
.append(" Hello ")
.append(argument)
.append(" (")
.append(remoteHost)
.append(" [")
.append(remoteIP)
.append("])");
responseString = responseBuffer.toString();
if (authRequired) {
writeLoggedResponse(responseString);
responseString = "250 AUTH LOGIN PLAIN";
}
writeLoggedFlushedResponse(responseString);
}
}
/**
* Handler method called upon receipt of a AUTH command.
* Handles client authentication to the SMTP server.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doAUTH(String argument)
throws Exception {
String responseString = null;
if (getUser() != null) {
responseString = "503 User has previously authenticated. "
+ " Further authentication is not required!";
writeLoggedFlushedResponse(responseString);
} else if (argument == null) {
responseString = "501 Usage: AUTH (authentication type) <challenge>";
writeLoggedFlushedResponse(responseString);
} else {
String initialResponse = null;
if ((argument != null) && (argument.indexOf(" ") > 0)) {
initialResponse = argument.substring(argument.indexOf(" ") + 1);
argument = argument.substring(0,argument.indexOf(" "));
}
String authType = argument.toUpperCase(Locale.US);
if (authType.equals(AUTH_TYPE_PLAIN)) {
doPlainAuth(initialResponse);
return;
} else if (authType.equals(AUTH_TYPE_LOGIN)) {
doLoginAuth(initialResponse);
return;
} else {
doUnknownAuth(authType, initialResponse);
return;
}
}
}
/**
* Carries out the Plain AUTH SASL exchange.
*
* @param initialResponse the initial response line passed in with the AUTH command
*/
private void doPlainAuth(String initialResponse)
throws IOException {
String userpass = null, user = null, pass = null, responseString = null;
if (initialResponse == null) {
responseString = "334 OK. Continue authentication";
writeLoggedFlushedResponse(responseString);
userpass = readCommandLine();
} else {
userpass = initialResponse.trim();
}
try {
if (userpass != null) {
userpass = Base64.decodeAsString(userpass);
}
if (userpass != null) {
StringTokenizer authTokenizer = new StringTokenizer(userpass, "\0");
user = authTokenizer.nextToken();
pass = authTokenizer.nextToken();
}
}
catch (Exception e) {
// Ignored - this exception in parsing will be dealt
// with in the if clause below
}
// Authenticate user
if ((user == null) || (pass == null)) {
responseString = "501 Could not decode parameters for AUTH PLAIN";
writeLoggedFlushedResponse(responseString);
} else if (users.test(user, pass)) {
setUser(user);
responseString = "235 Authentication Successful";
writeLoggedFlushedResponse(responseString);
getLogger().info("AUTH method PLAIN succeeded");
} else {
responseString = "535 Authentication Failed";
writeLoggedFlushedResponse(responseString);
getLogger().error("AUTH method PLAIN failed");
}
return;
}
/**
* Carries out the Login AUTH SASL exchange.
*
* @param initialResponse the initial response line passed in with the AUTH command
*/
private void doLoginAuth(String initialResponse)
throws IOException {
String user = null, pass = null, responseString = null;
if (initialResponse == null) {
responseString = "334 VXNlcm5hbWU6"; // base64 encoded "Username:"
writeLoggedFlushedResponse(responseString);
user = readCommandLine();
} else {
user = initialResponse.trim();
}
if (user != null) {
try {
user = Base64.decodeAsString(user);
} catch (Exception e) {
// Ignored - this parse error will be
// addressed in the if clause below
user = null;
}
}
responseString = "334 UGFzc3dvcmQ6"; // base64 encoded "Password:"
writeLoggedFlushedResponse(responseString);
pass = readCommandLine();
if (pass != null) {
try {
pass = Base64.decodeAsString(pass);
} catch (Exception e) {
// Ignored - this parse error will be
// addressed in the if clause below
pass = null;
}
}
// Authenticate user
if ((user == null) || (pass == null)) {
responseString = "501 Could not decode parameters for AUTH LOGIN";
} else if (users.test(user, pass)) {
setUser(user);
responseString = "235 Authentication Successful";
if (getLogger().isDebugEnabled()) {
// TODO: Make this string a more useful debug message
getLogger().debug("AUTH method LOGIN succeeded");
}
} else {
responseString = "535 Authentication Failed";
// TODO: Make this string a more useful error message
getLogger().error("AUTH method LOGIN failed");
}
writeLoggedFlushedResponse(responseString);
return;
}
/**
* Handles the case of an unrecognized auth type.
*
* @param authType the unknown auth type
* @param initialResponse the initial response line passed in with the AUTH command
*/
private void doUnknownAuth(String authType, String initialResponse) {
String responseString = "504 Unrecognized Authentication Type";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("AUTH method ")
.append(authType)
.append(" is an unrecognized authentication type");
getLogger().error(errorBuffer.toString());
}
return;
}
/**
* Handler method called upon receipt of a MAIL command.
* Sets up handler to deliver mail as the stated sender.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doMAIL(String argument) {
String responseString = null;
String sender = null;
if ((argument != null) && (argument.indexOf(":") > 0)) {
int colonIndex = argument.indexOf(":");
sender = argument.substring(colonIndex + 1);
argument = argument.substring(0, colonIndex);
}
if (state.containsKey(SENDER)) {
responseString = "503 Sender already specified";
writeLoggedFlushedResponse(responseString);
} else if (argument == null || !argument.toUpperCase(Locale.US).equals("FROM")
|| sender == null) {
responseString = "501 Usage: MAIL FROM:<sender>";
writeLoggedFlushedResponse(responseString);
} else {
sender = sender.trim();
int lastChar = sender.lastIndexOf('>');
// Check to see if any options are present and, if so, whether they are correctly formatted
// (separated from the closing angle bracket by a ' ').
if ((lastChar > 0) && (sender.length() > lastChar + 2) && (sender.charAt(lastChar + 1) == ' ')) {
String mailOptionString = sender.substring(lastChar + 2);
// Remove the options from the sender
sender = sender.substring(0, lastChar + 1);
StringTokenizer optionTokenizer = new StringTokenizer(mailOptionString, " ");
while (optionTokenizer.hasMoreElements()) {
String mailOption = optionTokenizer.nextToken();
int equalIndex = mailOptionString.indexOf('=');
String mailOptionName = mailOption;
String mailOptionValue = "";
if (equalIndex > 0) {
mailOptionName = mailOption.substring(0, equalIndex).toUpperCase(Locale.US);
mailOptionValue = mailOption.substring(equalIndex + 1);
}
// Handle the SIZE extension keyword
if (mailOptionName.startsWith(MAIL_OPTION_SIZE)) {
if (!(doMailSize(mailOptionValue))) {
return;
}
} else {
// Unexpected option attached to the Mail command
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("MAIL command had unrecognized/unexpected option ")
.append(mailOptionName)
.append(" with value ")
.append(mailOptionValue);
getLogger().debug(debugBuffer.toString());
}
}
}
}
if (!sender.startsWith("<") || !sender.endsWith(">")) {
responseString = "501 Syntax error in MAIL command";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("Error parsing sender address: ")
.append(sender)
.append(": did not start and end with < >");
getLogger().error(errorBuffer.toString());
}
return;
}
MailAddress senderAddress = null;
//Remove < and >
sender = sender.substring(1, sender.length() - 1);
if (sender.length() == 0) {
//This is the <> case. Let senderAddress == null
} else {
if (sender.indexOf("@") < 0) {
sender = sender + "@localhost";
}
try {
senderAddress = new MailAddress(sender);
} catch (Exception pe) {
responseString = "501 Syntax error in sender address";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Error parsing sender address: ")
.append(sender)
.append(": ")
.append(pe.getMessage());
getLogger().error(errorBuffer.toString());
}
return;
}
}
state.put(SENDER, senderAddress);
StringBuffer responseBuffer =
new StringBuffer(128)
.append("250 Sender <")
.append(sender)
.append("> OK");
responseString = responseBuffer.toString();
writeLoggedFlushedResponse(responseString);
}
}
/**
* Handles the SIZE MAIL option.
*
* @param mailOptionValue the option string passed in with the SIZE option
* @returns true if further options should be processed, false otherwise
*/
private boolean doMailSize(String mailOptionValue) {
int size = 0;
try {
size = Integer.parseInt(mailOptionValue);
} catch (NumberFormatException pe) {
// This is a malformed option value. We return an error
String responseString = "501 Syntactically incorrect value for SIZE parameter";
writeLoggedFlushedResponse(responseString);
getLogger().error("Rejected syntactically incorrect value for SIZE parameter.");
return false;
}
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("MAIL command option SIZE received with value ")
.append(size)
.append(".");
getLogger().debug(debugBuffer.toString());
}
if ((maxmessagesize > 0) && (size > maxmessagesize)) {
// Let the client know that the size limit has been hit.
String responseString = "552 Message size exceeds fixed maximum message size";
writeLoggedFlushedResponse(responseString);
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Rejected message from ")
.append(state.get(SENDER).toString())
.append(" from host ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") of size ")
.append(size)
.append(" exceeding system maximum message size of ")
.append(maxmessagesize)
.append("based on SIZE option.");
getLogger().error(errorBuffer.toString());
return false;
} else {
// put the message size in the message state so it can be used
// later to restrict messages for user quotas, etc.
state.put(MESG_SIZE, new Integer(size));
}
return true;
}
/**
* Handler method called upon receipt of a RCPT command.
* Reads recipient. Does some connection validation.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doRCPT(String argument) {
String responseString = null;
String recipient = null;
if ((argument != null) && (argument.indexOf(":") > 0)) {
int colonIndex = argument.indexOf(":");
recipient = argument.substring(colonIndex + 1);
argument = argument.substring(0, colonIndex);
}
if (!state.containsKey(SENDER)) {
responseString = "503 Need MAIL before RCPT";
writeLoggedFlushedResponse(responseString);
} else if (argument == null || !argument.toUpperCase(Locale.US).equals("TO")
|| recipient == null) {
responseString = "501 Usage: RCPT TO:<recipient>";
writeLoggedFlushedResponse(responseString);
} else {
Collection rcptColl = (Collection) state.get(RCPT_VECTOR);
if (rcptColl == null) {
rcptColl = new Vector();
}
recipient = recipient.trim();
int lastChar = recipient.lastIndexOf('>');
// Check to see if any options are present and, if so, whether they are correctly formatted
// (separated from the closing angle bracket by a ' ').
if ((lastChar > 0) && (recipient.length() > lastChar + 2) && (recipient.charAt(lastChar + 1) == ' ')) {
String rcptOptionString = recipient.substring(lastChar + 2);
// Remove the options from the recipient
recipient = recipient.substring(0, lastChar + 1);
StringTokenizer optionTokenizer = new StringTokenizer(rcptOptionString, " ");
while (optionTokenizer.hasMoreElements()) {
String rcptOption = optionTokenizer.nextToken();
int equalIndex = rcptOptionString.indexOf('=');
String rcptOptionName = rcptOption;
String rcptOptionValue = "";
if (equalIndex > 0) {
rcptOptionName = rcptOption.substring(0, equalIndex).toUpperCase(Locale.US);
rcptOptionValue = rcptOption.substring(equalIndex + 1);
}
// Unexpected option attached to the RCPT command
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("RCPT command had unrecognized/unexpected option ")
.append(rcptOptionName)
.append(" with value ")
.append(rcptOptionValue);
getLogger().debug(debugBuffer.toString());
}
}
}
if (!recipient.startsWith("<") || !recipient.endsWith(">")) {
responseString = "501 Syntax error in parameters or arguments";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(192)
.append("Error parsing recipient address: ")
.append(recipient)
.append(": did not start and end with < >");
getLogger().error(errorBuffer.toString());
}
return;
}
MailAddress recipientAddress = null;
//Remove < and >
recipient = recipient.substring(1, recipient.length() - 1);
if (recipient.indexOf("@") < 0) {
recipient = recipient + "@localhost";
}
try {
recipientAddress = new MailAddress(recipient);
} catch (Exception pe) {
responseString = "501 Syntax error in recipient address";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(192)
.append("Error parsing recipient address: ")
.append(recipient)
.append(": ")
.append(pe.getMessage());
getLogger().error(errorBuffer.toString());
}
return;
}
if (authRequired) {
// Make sure the mail is being sent locally if not
// authenticated else reject.
if (getUser() == null) {
String toDomain = recipientAddress.getHost();
if (!mailServer.isLocalServer(toDomain)) {
responseString = "530 Authentication Required";
writeLoggedFlushedResponse(responseString);
getLogger().error("Rejected message - authentication is required for mail request");
return;
}
} else {
// Identity verification checking
if (verifyIdentity) {
String authUser = (getUser()).toLowerCase(Locale.US);
MailAddress senderAddress = (MailAddress) state.get(SENDER);
boolean domainExists = false;
if ((!authUser.equals(senderAddress.getUser())) ||
(!mailServer.isLocalServer(senderAddress.getHost()))) {
responseString = "503 Incorrect Authentication for Specified Email Address";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("User ")
.append(authUser)
.append(" authenticated, however tried sending email as ")
.append(senderAddress);
getLogger().error(errorBuffer.toString());
}
return;
}
}
}
}
rcptColl.add(recipientAddress);
state.put(RCPT_VECTOR, rcptColl);
StringBuffer responseBuffer =
new StringBuffer(96)
.append("250 Recipient <")
.append(recipient)
.append("> OK");
responseString = responseBuffer.toString();
writeLoggedFlushedResponse(responseString);
}
}
/**
* Handler method called upon receipt of a NOOP command.
* Just sends back an OK and logs the command.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doNOOP(String argument) {
String responseString = "250 OK";
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a RSET command.
* Resets message-specific, but not authenticated user, state.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doRSET(String argument) {
String responseString = "";
if ((argument == null) || (argument.length() == 0)) {
resetState();
responseString = "250 OK";
} else {
responseString = "500 Unexpected argument provided with RSET command";
}
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a DATA command.
* Reads in message data, creates header, and delivers to
* mail server service for delivery.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doDATA(String argument) {
String responseString = null;
if ((argument != null) && (argument.length() > 0)) {
responseString = "500 Unexpected argument provided with DATA command";
writeLoggedFlushedResponse(responseString);
}
if (!state.containsKey(SENDER)) {
responseString = "503 No sender specified";
writeLoggedFlushedResponse(responseString);
} else if (!state.containsKey(RCPT_VECTOR)) {
responseString = "503 No recipients specified";
writeLoggedFlushedResponse(responseString);
} else {
responseString = "354 Ok Send data ending with <CRLF>.<CRLF>";
writeLoggedFlushedResponse(responseString);
try {
// Setup the input stream to notify the scheduler periodically
InputStream msgIn =
new SchedulerNotifyInputStream(in, scheduler, this.toString(), 20000);
// Look for data termination
msgIn = new CharTerminatedInputStream(msgIn, SMTPTerminator);
// if the message size limit has been set, we'll
// wrap msgIn with a SizeLimitedInputStream
if (maxmessagesize > 0) {
if (getLogger().isDebugEnabled()) {
StringBuffer logBuffer =
new StringBuffer(128)
.append("Using SizeLimitedInputStream ")
.append(" with max message size: ")
.append(maxmessagesize);
getLogger().debug(logBuffer.toString());
}
msgIn = new SizeLimitedInputStream(msgIn, maxmessagesize);
}
// Removes the dot stuffing
msgIn = new SMTPInputStream(msgIn);
// Parse out the message headers
MailHeaders headers = new MailHeaders(msgIn);
// If headers do not contains minimum REQUIRED headers fields,
// add them
if (!headers.isSet(RFC2822Headers.DATE)) {
headers.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
}
if (!headers.isSet(RFC2822Headers.FROM) && state.get(SENDER) != null) {
headers.setHeader(RFC2822Headers.FROM, state.get(SENDER).toString());
}
// Determine the Return-Path
String returnPath = headers.getHeader(RFC2822Headers.RETURN_PATH, "\r\n");
headers.removeHeader(RFC2822Headers.RETURN_PATH);
if (returnPath == null) {
if (state.get(SENDER) == null) {
returnPath = "<>";
} else {
StringBuffer returnPathBuffer =
new StringBuffer(64)
.append("<")
.append(state.get(SENDER))
.append(">");
returnPath = returnPathBuffer.toString();
}
}
// We will rebuild the header object to put Return-Path and our
// Received header at the top
Enumeration headerLines = headers.getAllHeaderLines();
headers = new MailHeaders();
// Put the Return-Path first
headers.addHeaderLine(RFC2822Headers.RETURN_PATH + ": " + returnPath);
// Put our Received header next
StringBuffer headerLineBuffer =
new StringBuffer(128)
.append(RFC2822Headers.RECEIVED + ": from ")
.append(remoteHost)
.append(" ([")
.append(remoteIP)
.append("])");
headers.addHeaderLine(headerLineBuffer.toString());
headerLineBuffer =
new StringBuffer(256)
.append(" by ")
.append(this.helloName)
.append(" (")
.append(SOFTWARE_TYPE)
.append(") with SMTP ID ")
.append(smtpID);
if (((Collection) state.get(RCPT_VECTOR)).size() == 1) {
// Only indicate a recipient if they're the only recipient
// (prevents email address harvesting and large headers in
// bulk email)
headers.addHeaderLine(headerLineBuffer.toString());
headerLineBuffer =
new StringBuffer(256)
.append(" for <")
.append(((Vector) state.get(RCPT_VECTOR)).get(0).toString())
.append(">;");
headers.addHeaderLine(headerLineBuffer.toString());
} else {
// Put the ; on the end of the 'by' line
headerLineBuffer.append(";");
headers.addHeaderLine(headerLineBuffer.toString());
}
headers.addHeaderLine(" " + rfc822DateFormat.format(new Date()));
// Add all the original message headers back in next
while (headerLines.hasMoreElements()) {
headers.addHeaderLine((String) headerLines.nextElement());
}
ByteArrayInputStream headersIn = new ByteArrayInputStream(headers.toByteArray());
MailImpl mail =
new MailImpl(
mailServer.getId(),
(MailAddress) state.get(SENDER),
(Vector) state.get(RCPT_VECTOR),
new SequenceInputStream(headersIn, msgIn));
// If the message size limit has been set, we'll
// call mail.getSize() to force the message to be
// loaded. Need to do this to enforce the size limit
if (maxmessagesize > 0) {
mail.getMessageSize();
}
mail.setRemoteHost(remoteHost);
mail.setRemoteAddr(remoteIP);
mailServer.sendMail(mail);
if (getLogger().isDebugEnabled()) {
getLogger().debug("Successfully sent mail to spool: " + mail.getName());
}
} catch (MessagingException me) {
// Grab any exception attached to this one.
Exception e = me.getNextException();
// If there was an attached exception, and it's a
// MessageSizeException
if (e != null && e instanceof MessageSizeException) {
// Add an item to the state to suppress
// logging of extra lines of data
// that are sent after the size limit has
// been hit.
state.put(MESG_FAILED, Boolean.TRUE);
// then let the client know that the size
// limit has been hit.
responseString = "552 Error processing message: "
+ e.getMessage();
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Rejected message from ")
.append(state.get(SENDER).toString())
.append(" from host ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") exceeding system maximum message size of ")
.append(maxmessagesize);
getLogger().error(errorBuffer.toString());
} else {
responseString = "451 Error processing message: "
+ me.getMessage();
getLogger().error("Unknown error occurred while processing DATA.", me);
}
writeLoggedFlushedResponse(responseString);
return;
}
resetState();
responseString = "250 Message received";
writeLoggedFlushedResponse(responseString);
}
}
/**
* Handler method called upon receipt of a VRFY command.
* This method informs the client that the command is
* not implemented.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doVRFY(String argument) {
String responseString = "502 VRFY is not supported";
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a EXPN command.
* This method informs the client that the command is
* not implemented.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doEXPN(String argument) {
String responseString = "502 EXPN is not supported";
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a HELP command.
* This method informs the client that the command is
* not implemented.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doHELP(String argument) {
String responseString = "502 HELP is not supported";
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a QUIT command.
* This method informs the client that the connection is
* closing.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doQUIT(String argument) {
String responseString = "";
if ((argument == null) || (argument.length() == 0)) {
StringBuffer responseBuffer =
new StringBuffer(128)
.append("221 ")
.append(helloName)
.append(" Service closing transmission channel");
responseString = responseBuffer.toString();
} else {
responseString = "500 Unexpected argument provided with QUIT command";
}
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of an unrecognized command.
* Returns an error response and logs the command.
*
* @param command the command parsed by the SMTP client
* @param argument the argument passed in with the command by the SMTP client
*/
private void doUnknownCmd(String command, String argument) {
StringBuffer responseBuffer =
new StringBuffer(128)
.append("500 ")
.append(helloName)
.append(" Syntax error, command unrecognized: ")
.append(command);
String responseString = responseBuffer.toString();
writeLoggedFlushedResponse(responseString);
}
} |
package com.ecyrd.jspwiki.render;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.event.WikiEvent;
import com.ecyrd.jspwiki.event.WikiEventListener;
import com.ecyrd.jspwiki.event.WikiEventUtils;
import com.ecyrd.jspwiki.event.WikiPageEvent;
import com.ecyrd.jspwiki.modules.InternalModule;
import com.ecyrd.jspwiki.parser.JSPWikiMarkupParser;
import com.ecyrd.jspwiki.parser.MarkupParser;
import com.ecyrd.jspwiki.parser.WikiDocument;
import com.ecyrd.jspwiki.providers.CachingProvider;
import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.base.NeedsRefreshException;
/**
* This class provides a facade towards the differing rendering routines. You should
* use the routines in this manager instead of the ones in WikiEngine, if you don't
* want the different side effects to occur - such as WikiFilters.
* <p>
* This class also manages a rendering cache, i.e. documents are stored between calls.
* You may control the size of the cache by using the "jspwiki.renderingManager.cacheSize"
* parameter in jspwiki.properties. The property value is the number of items that
* are stored in the cache. By default, the value of this parameter is taken from
* the "jspwiki.cachingProvider.cacheSize" parameter (i.e. the rendering cache is
* the same size as the page cache), but you may control them separately.
* <p>
* You can turn caching completely off by stating a cacheSize of zero.
*
* @author jalkanen
* @since 2.4
*/
public class RenderingManager implements WikiEventListener, InternalModule
{
private static Logger log = Logger.getLogger( RenderingManager.class );
private int m_cacheExpiryPeriod = 24*60*60; // This can be relatively long
private WikiEngine m_engine;
public static final String PROP_CACHESIZE = "jspwiki.renderingManager.capacity";
private static final int DEFAULT_CACHESIZE = 1000;
private static final String VERSION_DELIMITER = "::";
private static final String OSCACHE_ALGORITHM = "com.opensymphony.oscache.base.algorithm.LRUCache";
private static final String PROP_RENDERER = "jspwiki.renderingManager.renderer";
public static final String DEFAULT_RENDERER = XHTMLRenderer.class.getName();
/**
* Stores the WikiDocuments that have been cached.
*/
private Cache m_documentCache;
private Constructor m_rendererConstructor;
public static final String WYSIWYG_EDITOR_MODE = "WYSIWYG_EDITOR_MODE";
public static final String VAR_EXECUTE_PLUGINS = "_PluginContent.execute";
/**
* Initializes the RenderingManager.
* Checks for cache size settings, initializes the document cache.
* Looks for alternative WikiRenderers, initializes one, or the default
* XHTMLRenderer, for use.
*
* @param engine A WikiEngine instance.
* @param properties A list of properties to get parameters from.
*/
public void initialize( WikiEngine engine, Properties properties )
throws WikiException
{
m_engine = engine;
int cacheSize = TextUtil.getIntegerProperty( properties, PROP_CACHESIZE, -1 );
if( cacheSize == -1 )
{
cacheSize = TextUtil.getIntegerProperty( properties,
CachingProvider.PROP_CACHECAPACITY,
DEFAULT_CACHESIZE );
}
if( cacheSize > 0 )
{
m_documentCache = new Cache(true,false,false,false,
OSCACHE_ALGORITHM,
cacheSize);
}
else
{
log.info( "RenderingManager caching is disabled." );
}
String renderImplName = properties.getProperty( PROP_RENDERER );
if( renderImplName == null )
{
renderImplName = DEFAULT_RENDERER;
}
Class[] rendererParams = { WikiContext.class, WikiDocument.class };
try
{
Class c = Class.forName( renderImplName );
m_rendererConstructor = c.getConstructor( rendererParams );
}
catch( ClassNotFoundException e )
{
log.error( "Unable to find WikiRenderer implementation " + renderImplName );
}
catch( SecurityException e )
{
log.error( "Unable to access the WikiRenderer(WikiContext,WikiDocument) constructor for " + renderImplName );
}
catch( NoSuchMethodException e )
{
log.error( "Unable to locate the WikiRenderer(WikiContext,WikiDocument) constructor for " + renderImplName );
}
if( m_rendererConstructor == null )
{
throw new WikiException( "Failed to get WikiRenderer '" + renderImplName + "'." );
}
log.info( "Rendering content with " + renderImplName + "." );
WikiEventUtils.addWikiEventListener(m_engine, WikiPageEvent.POST_SAVE_BEGIN, this);
}
/**
* Returns the default Parser for this context.
*
* @param context the wiki context
* @param pagedata the page data
* @return A MarkupParser instance.
*/
public MarkupParser getParser( WikiContext context, String pagedata )
{
MarkupParser parser = new JSPWikiMarkupParser( context, new StringReader(pagedata) );
return parser;
}
/**
* Returns a cached document, if one is found.
*
* @param context the wiki context
* @param pagedata the page data
* @return the rendered wiki document
* @throws IOException
*/
// FIXME: The cache management policy is not very good: deleted/changed pages
// should be detected better.
protected WikiDocument getRenderedDocument( WikiContext context, String pagedata )
throws IOException
{
String pageid = context.getRealPage().getName()+VERSION_DELIMITER+context.getRealPage().getVersion();
boolean wasUpdated = false;
if( m_documentCache != null )
{
try
{
WikiDocument doc = (WikiDocument) m_documentCache.getFromCache( pageid,
m_cacheExpiryPeriod );
wasUpdated = true;
// This check is needed in case the different filters have actually
// changed the page data.
// FIXME: Figure out a faster method
if( pagedata.equals(doc.getPageData()) )
{
if( log.isDebugEnabled() ) log.debug("Using cached HTML for page "+pageid );
return doc;
}
}
catch( NeedsRefreshException e )
{
if( log.isDebugEnabled() ) log.debug("Re-rendering and storing "+pageid );
}
}
// Refresh the data content
try
{
MarkupParser parser = getParser( context, pagedata );
WikiDocument doc = parser.parse();
doc.setPageData( pagedata );
if( m_documentCache != null )
{
m_documentCache.putInCache( pageid, doc );
wasUpdated = true;
}
return doc;
}
catch( IOException ex )
{
log.error("Unable to parse",ex);
}
finally
{
if( m_documentCache != null && !wasUpdated ) m_documentCache.cancelUpdate( pageid );
}
return null;
}
/**
* Simply renders a WikiDocument to a String. This version does not get the document
* from the cache - in fact, it does not cache the document at all. This is
* very useful, if you have something that you want to render outside the caching
* routines. Because the cache is based on full pages, and the cache keys are
* based on names, use this routine if you're rendering anything for yourself.
*
* @param context The WikiContext to render in
* @param doc A proper WikiDocument
* @return Rendered HTML.
* @throws IOException If the WikiDocument is poorly formed.
*/
public String getHTML( WikiContext context, WikiDocument doc )
throws IOException
{
WikiRenderer rend = getRenderer( context, doc );
return rend.getString();
}
/**
* Returns a WikiRenderer instance, initialized with the given
* context and doc. The object is an XHTMLRenderer, unless overridden
* in jspwiki.properties with PROP_RENDERER.
*/
public WikiRenderer getRenderer( WikiContext context, WikiDocument doc )
{
Object[] params = { context, doc };
WikiRenderer rval = null;
try
{
rval = (WikiRenderer)m_rendererConstructor.newInstance( params );
}
catch( Exception e )
{
log.error( "Unable to create WikiRenderer", e );
}
return rval;
}
/**
* Convinience method for rendering, using the default parser and renderer. Note that
* you can't use this method to do any arbitrary rendering, as the pagedata MUST
* be the data from the that the WikiContext refers to - this method caches the HTML
* internally, and will return the cached version. If the pagedata is different
* from what was cached, will re-render and store the pagedata into the internal cache.
*
* @param context the wiki context
* @param pagedata the page data
* @return XHTML data.
*/
public String getHTML( WikiContext context, String pagedata )
{
try
{
WikiDocument doc = getRenderedDocument( context, pagedata );
return getHTML( context, doc );
}
catch( IOException e )
{
log.error("Unable to parse",e);
}
return null;
}
/**
* Flushes the document cache in response to a POST_SAVE_BEGIN event.
*
* @see com.ecyrd.jspwiki.event.WikiEventListener#actionPerformed(com.ecyrd.jspwiki.event.WikiEvent)
*/
// @SuppressWarnings("deprecation")
public void actionPerformed(WikiEvent event)
{
if( (event instanceof WikiPageEvent) && (event.getType() == WikiPageEvent.POST_SAVE_BEGIN) )
{
if( m_documentCache != null )
{
String pageName = ((WikiPageEvent) event).getPageName();
m_documentCache.flushPattern( pageName );
Collection referringPages = m_engine.getReferenceManager().findReferrers( pageName );
// Flush also those pages that refer to this page (if an nonexistant page
// appears; we need to flush the HTML that refers to the now-existant page
if( referringPages != null )
{
Iterator i = referringPages.iterator();
while (i.hasNext())
{
String page = (String) i.next();
if( log.isDebugEnabled() ) log.debug( "Flushing " + page );
m_documentCache.flushPattern( page );
}
}
}
}
}
} |
package com.michaldabski.filemanager;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.michaldabski.filemanager.R;
import com.michaldabski.filemanager.clipboard.Clipboard;
import com.michaldabski.filemanager.clipboard.ClipboardFileAdapter;
import com.michaldabski.filemanager.clipboard.Clipboard.ClipboardListener;
import com.michaldabski.filemanager.favourites.FavouritesManager;
import com.michaldabski.filemanager.favourites.FavouritesManager.FavouritesListener;
import com.michaldabski.filemanager.folders.FolderFragment;
import com.michaldabski.filemanager.nav_drawer.NavDrawerAdapter;
import com.michaldabski.filemanager.nav_drawer.NavDrawerAdapter.NavDrawerItem;
import com.michaldabski.utils.FontApplicator;
import com.readystatesoftware.systembartint.SystemBarTintManager;
public class MainActivity extends Activity implements OnItemClickListener, ClipboardListener, FavouritesListener
{
private static final String LOG_TAG = "Main Activity";
public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
File lastFolder=null;
private FontApplicator fontApplicator;
private SystemBarTintManager tintManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tintManager = new SystemBarTintManager(this);
setupDrawers();
Clipboard.getInstance().addListener(this);
fontApplicator = new FontApplicator(getApplicationContext(), "Roboto_Light.ttf").applyFont(getWindow().getDecorView());
}
public FontApplicator getFontApplicator()
{
return fontApplicator;
}
@Override
protected void onDestroy()
{
Clipboard.getInstance().removeListener(this);
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getFavouritesManager().removeFavouritesListener(this);
super.onDestroy();
}
public void setLastFolder(File lastFolder)
{
this.lastFolder = lastFolder;
}
@Override
protected void onPause()
{
if (lastFolder != null)
{
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
}
super.onPause();
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
}
public void setActionbarVisible(boolean visible)
{
if (visible)
{
getActionBar().show();
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.accent_color);
}
else
{
getActionBar().hide();
tintManager.setStatusBarTintEnabled(false);
tintManager.setStatusBarTintResource(android.R.color.transparent);
}
}
private void setupDrawers()
{
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
{
boolean actionBarShown = false;;
@Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
setActionbarVisible(true);
invalidateOptionsMenu();
}
@Override
public void onDrawerClosed(View drawerView)
{
actionBarShown=false;
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0 && actionBarShown == false)
{
actionBarShown = true;
setActionbarVisible(true);
}
else if (slideOffset <= 0) actionBarShown = false;
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
// drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setupNavDrawer();
setupClipboardDrawer();
}
void setupNavDrawer()
{
FileManagerApplication application = (FileManagerApplication) getApplication();
loadFavourites(application.getFavouritesManager());
application.getFavouritesManager().addFavouritesListener(this);
// add listview header to push items below the actionbar
LayoutInflater inflater = getLayoutInflater();
ListView navListView = (ListView) findViewById(R.id.listNavigation);
View header = inflater.inflate(R.layout.list_header_actionbar_padding, navListView, false);
SystemBarTintManager systemBarTintManager = new SystemBarTintManager(this);
int headerHeight = systemBarTintManager.getConfig().getPixelInsetTop(true);
header.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, headerHeight));
navListView.addHeaderView(header, null, false);
int footerHeight = systemBarTintManager.getConfig().getPixelInsetBottom();
if (footerHeight > 0)
{
View footer = inflater.inflate(R.layout.list_header_actionbar_padding, navListView, false);
footer.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, footerHeight));
navListView.addFooterView(footer, null, false);
}
}
void setupClipboardDrawer()
{
// add listview header to push items below the actionbar
LayoutInflater inflater = getLayoutInflater();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
View header = inflater.inflate(R.layout.list_header_actionbar_padding, clipboardListView, false);
SystemBarTintManager systemBarTintManager = new SystemBarTintManager(this);
int headerHeight = systemBarTintManager.getConfig().getPixelInsetTop(true);
header.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, headerHeight));
clipboardListView.addHeaderView(header, null, false);
int footerHeight = systemBarTintManager.getConfig().getPixelInsetBottom();
int rightPadding = systemBarTintManager.getConfig().getPixelInsetRight();
if (footerHeight > 0)
{
View footer = inflater.inflate(R.layout.list_header_actionbar_padding, clipboardListView, false);
footer.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, footerHeight));
clipboardListView.addFooterView(footer, null, false);
}
if (rightPadding > 0)
{
clipboardListView.setPadding(clipboardListView.getPaddingLeft(), clipboardListView.getPaddingTop(),
clipboardListView.getPaddingRight()+rightPadding, clipboardListView.getPaddingBottom());
}
onClipboardContentsChange(Clipboard.getInstance());
}
void loadFavourites(FavouritesManager favouritesManager)
{
ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
NavDrawerAdapter navDrawerAdapter = new NavDrawerAdapter(this, new ArrayList<NavDrawerAdapter.NavDrawerItem>(favouritesManager.getFolders()));
navDrawerAdapter.setFontApplicator(fontApplicator);
listNavigation.setAdapter(navDrawerAdapter);
listNavigation.setOnItemClickListener(this);
}
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
if (getFragmentManager().findFragmentById(R.id.fragment) == null)
{
FolderFragment folderFragment = new FolderFragment();
if (getIntent().hasExtra(EXTRA_DIR))
{
Bundle args = new Bundle();
args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
folderFragment.setArguments(args);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, folderFragment)
.commit();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId())
{
case R.id.menu_about:
startActivity(new Intent(getApplicationContext(), AboutActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFragment(Fragment fragment)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment, fragment)
.commit();
}
public void goBack()
{
getFragmentManager().popBackStack();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
return super.onPrepareOptionsMenu(menu);
}
public FolderFragment getFolderFragment()
{
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment);
if (fragment instanceof FolderFragment)
return (FolderFragment) fragment;
else return null;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch (arg0.getId())
{
case R.id.listNavigation:
NavDrawerItem item = (NavDrawerItem) arg0.getItemAtPosition(arg2);
if (item.onClicked(this))
drawerLayout.closeDrawers();
break;
case R.id.listClipboard:
break;
default:
break;
}
}
public File getLastFolder()
{
return lastFolder;
}
@Override
public void onClipboardContentsChange(Clipboard clipboard)
{
invalidateOptionsMenu();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
if (clipboard.isEmpty() && drawerLayout != null)
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
else
{
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
FileManagerApplication application = (FileManagerApplication) getApplication();
if (clipboardListView != null)
{
ClipboardFileAdapter clipboardFileAdapter = new ClipboardFileAdapter(this, clipboard, application.getFileIconResolver());
clipboardFileAdapter.setFontApplicator(fontApplicator);
clipboardListView.setAdapter(clipboardFileAdapter);
}
}
}
@Override
public void onFavouritesChanged(FavouritesManager favouritesManager)
{
loadFavourites(favouritesManager);
}
} |
package com.phantommentalists.Twenty14;
/**
*
*
* and open the template in the editor.
*
*/
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Relay;
/**
*
* ChopSticks allocation
*
* @author mburt001
*
*/
public class ChopSticks {
public Relay left;
public Relay right;
public Solenoid extendSolenoid;
public Solenoid retractSolenoid;
/**
* ChopSticks()
*
* not finished public ChopSticks
*/
public ChopSticks() {
left = new Relay(Parameters.leftChopStickRelayChannel);
right = new Relay(Parameters.rightChopStickRelayChannel);
extendSolenoid = new Solenoid(Parameters.loaderOutSolenoidChannel);
retractSolenoid = new Solenoid(Parameters.loaderInSolenoidChannel);
}
/**
*
* turnOnChopSticks()
*
* This method turns both left and right ChopSticks on.
*/
public void turnOnChopSticks() {
left.set(Relay.Value.kForward);
right.set(Relay.Value.kReverse);
}
/**
* turnOffChopSticks()
*
* This method turns both left and right ChopSticks off.
*/
public void turnOffChopSticks() {
left.set(Relay.Value.kOff);
right.set(Relay.Value.kOff);
}
/**
* isChopSticksOn()
*
* This method returns whether or not the ChopSticks are on or off, rotating or stationary.
*/
public boolean isChopSticksOn() {
if (left.get() != Relay.Value.kOff && right.get() != Relay.Value.kOff) {
return true;
}
return false;
}
/**
* isChopSticksOff()
*
* This method returns whether or not the ChopSticks are on or off, rotating or stationary.
*/
public boolean isChopSticksOff() {
if (left.get() == Relay.Value.kOff && right.get() == Relay.Value.kOff) {
return true;
}
return false;
}
} |
package com.phantommentalists.Twenty14;
/*
* Parameters allocation
*/
public class Parameters {
public static final int frontDriveCanId = -1;
public static final int frontLeftSteeringCanId = -1;
public static final int frontRightCanId = -1;
public static final int rearCanId = -1;
public static final int rearLeftSteeringCanId = -1;
public static final int rearRightSteeringCanId = -1;
public static final int steeringProportionalValue = -1;
public static final int steeringIntegralValue = -1;
public static final int steeringDerivativeValue = -1;
public static final double maxMotorVoltage = 12.0;
public final static int oneInSolenoidChannel = -1;
public final static int oneOutsolenoidChannel = -1;
public final static int twoInSolenoidChannel = -1;
public final static int twoOutsolenoidChannel = -1;
public final static int threeInSolenoidChannel = -1;
public final static int threeOutsolenoidChannel = -1;
public final static int fourInSolenoidChannel = -1;
public final static int fourOutsolenoidChannel = -1;
public static final double kJoyStickDeadband = 0.05;
static double kJoystickDeadband;
static int kLowGearButton;
static int kHighGearButton;
} |
package com.scorpius_enterprises.io.iqm;
import com.scorpius_enterprises.log.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.LinkedList;
/**
* {@link IqmLoader com.scorpius_enterprises.io.iqm.IqmLoader}
*
* @author Scorple
* @since 2017-03-24
*/
public class IqmLoader
{
public static void loadIBO(final String fileName,
final int[] numIndices,
final float[][] posCoordArray,
final float[][] texCoordArray,
final float[][] normalVecCompArray,
final int[][] vertexIndexArray)
{
LinkedList<Float> posCoordList = new LinkedList<>();
LinkedList<Float> texCoordList = new LinkedList<>();
LinkedList<Float> normalVecCompList = new LinkedList<>();
LinkedList<Integer> vertexIndexList = new LinkedList<>();
float[] iPosCoordArray;
int posCoordArrayIndex = 0;
float[] iTexCoordArray;
int texCoordArrayIndex = 0;
float[] iNormalVecCompArray;
int normalVecCompArrayIndex = 0;
int[] iVertexIndexArray;
int vertexIndexArrayIndex = 0;
Header header = new Header();
Vertex[] vertices;
VertexArray[] vertexArrays;
Triangle[] triangles;
Mesh[] meshes;
InputStream is = IqmLoader.class.getClass().getResourceAsStream(fileName);
header.load(is);
int fileSize = header.getFilesize();
byte[] buf = new byte[fileSize];
byte[] headerBuf = header.getBuf();
System.arraycopy(headerBuf, 0, buf, 0, headerBuf.length);
try
{
is.read(buf, Header.HEADER_SIZE, fileSize - Header.HEADER_SIZE);
}
catch (IOException e)
{
e.printStackTrace();
}
vertices = new Vertex[header.getNum_vertexes()];
iPosCoordArray = new float[header.getNum_vertexes() * VertexArray.NUM_POSITION_COMPONENTS];
iTexCoordArray = new float[header.getNum_vertexes() * VertexArray.NUM_TEXCOORD_COMPONENTS];
iNormalVecCompArray = new float[header.getNum_vertexes() * VertexArray.NUM_NORMAL_COMPONENTS];
iVertexIndexArray = new int[header.getNum_triangles() * 3];
vertexArrays = new VertexArray[header.getNum_vertexarrays()];
for (int i = 0; i < header.getNum_vertexarrays(); ++i)
{
VertexArray vertexArray = new VertexArray();
vertexArray.load(header, buf, i, vertices.length);
vertexArrays[i] = vertexArray;
}
for (int i = 0; i < header.getNum_vertexes(); ++i)
{
vertices[i] = new Vertex();
Vertex vertex = vertices[i];
for (int j = 0; j < header.getNum_vertexarrays(); ++j)
{
VertexArray vertexArray = vertexArrays[j];
byte[] compBuf;
ByteBuffer bb;
switch (vertexArray.getType())
{
case VertexArray.TYPE_IQM_POSITION:
float[] position = new float[VertexArray.NUM_POSITION_COMPONENTS];
compBuf = new byte[VertexArray.NUM_POSITION_COMPONENTS * VertexArray.FLOAT_SIZE];
System.arraycopy(buf,
vertexArray.getOffset() + compBuf.length * i,
compBuf,
0,
compBuf.length);
bb = ByteBuffer.wrap(compBuf);
bb.order(ByteOrder.LITTLE_ENDIAN);
for (int k = 0; k < VertexArray.NUM_POSITION_COMPONENTS; ++k)
{
position[k] = bb.getFloat();
}
vertex.setPosition(position);
iPosCoordArray[posCoordArrayIndex++] = position[0];
iPosCoordArray[posCoordArrayIndex++] = position[2];
iPosCoordArray[posCoordArrayIndex++] = -position[1];
break;
case VertexArray.TYPE_IQM_TEXCOORD:
float[] texcoord = new float[VertexArray.NUM_TEXCOORD_COMPONENTS];
compBuf = new byte[VertexArray.NUM_TEXCOORD_COMPONENTS * VertexArray.FLOAT_SIZE];
System.arraycopy(buf,
vertexArray.getOffset() + compBuf.length * i,
compBuf,
0,
compBuf.length);
bb = ByteBuffer.wrap(compBuf);
bb.order(ByteOrder.LITTLE_ENDIAN);
for (int k = 0; k < VertexArray.NUM_TEXCOORD_COMPONENTS; ++k)
{
texcoord[k] = bb.getFloat();
iTexCoordArray[texCoordArrayIndex++] = texcoord[k];
}
vertex.setTexcoord(texcoord);
break;
case VertexArray.TYPE_IQM_NORMAL:
float[] normal = new float[VertexArray.NUM_NORMAL_COMPONENTS];
compBuf = new byte[VertexArray.NUM_NORMAL_COMPONENTS * VertexArray.FLOAT_SIZE];
System.arraycopy(buf,
vertexArray.getOffset() + compBuf.length * i,
compBuf,
0,
compBuf.length);
bb = ByteBuffer.wrap(compBuf);
bb.order(ByteOrder.LITTLE_ENDIAN);
for (int k = 0; k < VertexArray.NUM_NORMAL_COMPONENTS; ++k)
{
normal[k] = bb.getFloat();
}
vertex.setNormal(normal);
iNormalVecCompArray[normalVecCompArrayIndex++] = normal[0];
iNormalVecCompArray[normalVecCompArrayIndex++] = normal[2];
iNormalVecCompArray[normalVecCompArrayIndex++] = -normal[1];
break;
case VertexArray.TYPE_IQM_TANGENT:
float[] tangent = new float[VertexArray.NUM_TANGENT_COMPONENTS];
compBuf = new byte[VertexArray.NUM_TANGENT_COMPONENTS * VertexArray.FLOAT_SIZE];
System.arraycopy(buf,
vertexArray.getOffset() + compBuf.length * i,
compBuf,
0,
compBuf.length);
bb = ByteBuffer.wrap(compBuf);
bb.order(ByteOrder.LITTLE_ENDIAN);
for (int k = 0; k < VertexArray.NUM_TANGENT_COMPONENTS; ++k)
{
tangent[k] = bb.getFloat();
}
vertex.setTangent(tangent);
break;
case VertexArray.TYPE_IQM_BLENDINDEXES:
compBuf = new byte[VertexArray.NUM_BLENDINDEXES_COMPONENTS];
System.arraycopy(buf,
vertexArray.getOffset() + compBuf.length * i,
compBuf,
0,
compBuf.length);
vertex.setBlendindices(compBuf);
break;
case VertexArray.TYPE_IQM_BLENDWEIGHTS:
compBuf = new byte[VertexArray.NUM_BLENDWEIGHTS_COMPONENTS];
System.arraycopy(buf,
vertexArray.getOffset() + compBuf.length * i,
compBuf,
0,
compBuf.length);
vertex.setBlendweights(compBuf);
break;
case VertexArray.TYPE_IQM_COLOR:
compBuf = new byte[VertexArray.NUM_COLOR_COMPONENTS];
System.arraycopy(buf,
vertexArray.getOffset() + compBuf.length * i,
compBuf,
0,
compBuf.length);
vertex.setColor(compBuf);
break;
}
}
StringBuilder sbp = new StringBuilder();
sbp.append("vp");
for (float j : vertex.getPosition())
{
sbp.append(" ").append(j);
}
Logger.logD(sbp.toString());
StringBuilder sbt = new StringBuilder();
sbt.append("vt");
for (float j : vertex.getTexcoord())
{
sbt.append(" ").append(j);
}
Logger.logD(sbt.toString());
StringBuilder sbn = new StringBuilder();
sbn.append("vn");
for (float j : vertex.getNormal())
{
sbn.append(" ").append(j);
}
Logger.logD(sbn.toString());
}
triangles = new Triangle[header.getNum_triangles()];
for (int i = 0; i < header.getNum_triangles(); ++i)
{
Triangle triangle = new Triangle();
triangle.load(header, buf, i);
triangles[i] = triangle;
StringBuilder sb = new StringBuilder();
sb.append("fm");
for (int j : triangle.getVertexes())
{
sb.append(" ").append(j);
iVertexIndexArray[vertexIndexArrayIndex++] = j;
}
Logger.logD(sb.toString());
}
meshes = new Mesh[header.getNum_meshes()];
for (int i = 0; i < header.getNum_meshes(); ++i)
{
Mesh mesh = new Mesh();
mesh.load(header, buf, i);
meshes[i] = mesh;
}
if (numIndices != null)
{
numIndices[0] = header.getNum_triangles() * 3;
Logger.logI("" + numIndices[0]);
}
if (posCoordArray != null)
{
posCoordArray[0] = iPosCoordArray;
}
if (texCoordArray != null)
{
texCoordArray[0] = iTexCoordArray;
}
if (normalVecCompArray != null)
{
normalVecCompArray[0] = iNormalVecCompArray;
}
if (vertexIndexArray != null)
{
vertexIndexArray[0] = iVertexIndexArray;
}
}
} |
package com.thaiopensource.relaxng;
/**
* A skeleton implementation of <code>Schema</code>.
*
* @author <a href="mailto:jjc@jclark.com">James Clark</a>
*/
public abstract class AbstractSchema implements Schema {
/**
* Calls <code>createValidator(null)</code>.
*/
public ValidatorHandler createValidator() {
return createValidator(null);
}
} |
package com.wakatime.intellij.plugin;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Dependencies {
private static String pythonLocation = null;
private static String resourcesLocation = null;
public static boolean isPythonInstalled() {
return Dependencies.getPythonLocation() != null;
}
public static String getResourcesLocation() {
if (Dependencies.resourcesLocation == null) {
String separator = "[\\\\/]";
Dependencies.resourcesLocation = WakaTime.class.getResource("WakaTime.class").getPath()
.replaceFirst("file:", "")
.replaceAll("%20", " ")
.replaceFirst("com" + separator + "wakatime" + separator + "intellij" + separator + "plugin" + separator + "WakaTime.class", "")
.replaceFirst("WakaTime.jar!" + separator, "") + "WakaTime-resources";
if (System.getProperty("os.name").startsWith("Windows") && Dependencies.resourcesLocation.startsWith("/")) {
Dependencies.resourcesLocation = Dependencies.resourcesLocation.substring(1);
}
}
return Dependencies.resourcesLocation;
}
public static String getPythonLocation() {
if (Dependencies.pythonLocation != null)
return Dependencies.pythonLocation;
ArrayList<String> paths = new ArrayList<String>();
paths.add("/");
paths.add("/");
paths.add("/usr/local/bin/");
paths.add("/usr/bin/");
paths.add(getPythonFromRegistry(WinRegistry.HKEY_CURRENT_USER));
paths.add(getPythonFromRegistry(WinRegistry.HKEY_LOCAL_MACHINE));
for (String path : paths) {
if (path != null) {
try {
String[] cmds = {combinePaths(path, "pythonw"), "--version"};
Runtime.getRuntime().exec(cmds);
Dependencies.pythonLocation = combinePaths(path, "pythonw");
break;
} catch (Exception e) {
try {
String[] cmds = {combinePaths(path, "python"), "--version"};
Runtime.getRuntime().exec(cmds);
Dependencies.pythonLocation = combinePaths(path, "python");
break;
} catch (Exception e2) { }
}
}
}
if (Dependencies.pythonLocation != null) {
WakaTime.log.debug("Found python binary: " + Dependencies.pythonLocation);
} else {
WakaTime.log.warn("Could not find python binary.");
}
return Dependencies.pythonLocation;
}
public static String getPythonFromRegistry(int hkey) {
String path = null;
if (System.getProperty("os.name").contains("Windows")) {
try {
String key = "Software\\\\Python\\\\PythonCore";
for (String version : WinRegistry.readStringSubKeys(hkey, key)) {
path = WinRegistry.readString(hkey, key + "\\" + version + "\\InstallPath", "");
if (path != null) {
break;
}
}
} catch (IllegalAccessException e) {
WakaTime.log.debug(e);
} catch (InvocationTargetException e) {
WakaTime.log.debug(e);
} catch (NullPointerException e) {
WakaTime.log.debug(e);
}
}
return path;
}
public static boolean isCLIInstalled() {
File cli = new File(Dependencies.getCLILocation());
return (cli.exists() && !cli.isDirectory());
}
public static boolean isCLIOld() {
if (!Dependencies.isCLIInstalled()) {
return false;
}
ArrayList<String> cmds = new ArrayList<String>();
cmds.add(Dependencies.getPythonLocation());
cmds.add(Dependencies.getCLILocation());
cmds.add("--version");
try {
Process p = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
p.waitFor();
String output = "";
String s;
while ((s = stdInput.readLine()) != null) {
output += s;
}
while ((s = stdError.readLine()) != null) {
output += s;
}
WakaTime.log.debug("wakatime cli version check output: \"" + output + "\"");
WakaTime.log.debug("wakatime cli version check exit code: " + p.exitValue());
if (p.exitValue() == 0) {
String cliVersion = latestCliVersion();
WakaTime.log.debug("Current cli version from GitHub: " + cliVersion);
if (output.contains(cliVersion))
return false;
}
} catch (Exception e) { }
return true;
}
public static String latestCliVersion() {
String url = "https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py";
String aboutText = getUrlAsString(url);
Pattern p = Pattern.compile("__version_info__ = \\('([0-9]+)', '([0-9]+)', '([0-9]+)'\\)");
Matcher m = p.matcher(aboutText);
if (m.find()) {
return m.group(1) + "." + m.group(2) + "." + m.group(3);
}
return "Unknown";
}
public static String getCLILocation() {
return combinePaths(Dependencies.getResourcesLocation(), "wakatime-master", "wakatime", "cli.py");
}
public static void installCLI() {
File cli = new File(Dependencies.getCLILocation());
if (!cli.getParentFile().getParentFile().getParentFile().exists())
cli.getParentFile().getParentFile().getParentFile().mkdirs();
String url = "https://codeload.github.com/wakatime/wakatime/zip/master";
String zipFile = combinePaths(cli.getParentFile().getParentFile().getParentFile().getAbsolutePath(), "wakatime-cli.zip");
File outputDir = cli.getParentFile().getParentFile().getParentFile();
// Delete old wakatime-master directory if it exists
File dir = cli.getParentFile().getParentFile();
if (dir.exists()) {
deleteDirectory(dir);
}
// download wakatime-master.zip file
if (downloadFile(url, zipFile)) {
try {
Dependencies.unzip(zipFile, outputDir);
File oldZipFile = new File(zipFile);
oldZipFile.delete();
} catch (IOException e) {
WakaTime.log.error(e);
}
}
}
public static void upgradeCLI() {
File cliDir = new File(new File(Dependencies.getCLILocation()).getParent());
cliDir.delete();
Dependencies.installCLI();
}
public static void installPython() {
if (System.getProperty("os.name").contains("Windows")) {
String url = "https:
if (System.getenv("ProgramFiles(x86)") != null) {
url = "https:
}
File cli = new File(Dependencies.getCLILocation());
String outFile = combinePaths(cli.getParentFile().getParentFile().getAbsolutePath(), "python.msi");
if (downloadFile(url, outFile)) {
// execute python msi installer
ArrayList<String> cmds = new ArrayList<String>();
cmds.add("msiexec");
cmds.add("/i");
cmds.add(outFile);
cmds.add("/norestart");
cmds.add("/qb!");
try {
Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static boolean downloadFile(String url, String saveAs) {
File outFile = new File(saveAs);
// create output directory if does not exist
File outDir = outFile.getParentFile();
if (!outDir.exists())
outDir.mkdirs();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(downloadUrl.openStream());
fos = new FileOutputStream(saveAs);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
return true;
} catch (RuntimeException e) {
WakaTime.log.error(e);
try {
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection)downloadUrl.openConnection();
InputStream inputStream = conn.getInputStream();
fos = new FileOutputStream(saveAs);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
inputStream.close();
return true;
} catch (NoSuchAlgorithmException e1) {
WakaTime.log.error(e1);
} catch (KeyManagementException e1) {
WakaTime.log.error(e1);
} catch (IOException e1) {
WakaTime.log.error(e1);
}
} catch (IOException e) {
WakaTime.log.error(e);
}
return false;
}
public static String getUrlAsString(String url) {
StringBuilder text = new StringBuilder();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
try {
InputStream inputStream = downloadUrl.openStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
} catch (RuntimeException e) {
WakaTime.log.error(e);
try {
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection)downloadUrl.openConnection();
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
} catch (NoSuchAlgorithmException e1) {
WakaTime.log.error(e1);
} catch (KeyManagementException e1) {
WakaTime.log.error(e1);
} catch (IOException e1) {
WakaTime.log.error(e1);
}
} catch (IOException e) {
WakaTime.log.error(e);
}
return text.toString();
}
private static void unzip(String zipFile, File outputDir) throws IOException {
if(!outputDir.exists())
outputDir.mkdirs();
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir, fileName);
if (ze.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
path.delete();
}
private static String combinePaths(String... args) {
File path = null;
for (String arg : args) {
if (path == null)
path = new File(arg);
else
path = new File(path, arg);
}
if (path == null)
return null;
return path.toString();
}
} |
package com.xtuple.packworkflow.main;
import com.google.android.glass.app.Card;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
//import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import com.google.android.glass.touchpad.GestureDetector;
import com.google.android.glass.touchpad.Gesture;
public class MainActivity extends Activity {
// create variable instances
private static final String TAG = MainActivity.class.getSimpleName();
private GestureDetector mGestureDetector;
private static final int SCANDIT_CODE_REQUEST =2;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//keeps the camera on
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Card card1 = new Card(this);
card1.setText("Welcome to PackWorkflow!!");
card1.setFootnote("xTuple");
View card1View = card1.getView();
setContentView(card1View);
mGestureDetector = createGestureDetector(this);
}
/**
* Boiler plate google code
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CAMERA) {
// Stop the preview and release the camera.
// Execute your logic as quickly as possible
// so the capture happens quickly.
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
protected void onResume() {
super.onResume();
// Re-acquire the camera and start the preview.
}
public void scanBarcode(){
Intent i = new Intent(getApplicationContext(), ScanditSDKDemoSimple.class);
i.putExtra("VariableParameter","Value");
startActivityForResult(i, SCANDIT_CODE_REQUEST);
Log.d("@@@@", "Asking for Barcode");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SCANDIT_CODE_REQUEST && resultCode == RESULT_OK){
Log.d("before","SCANDIT_CODE_REQUEST");
String contents = data.getStringExtra("SCAN_RESULT");
Log.d("after","SCANDIT_CODE_REQUEST");
Card newCard = new Card(this);
newCard.setImageLayout(Card.ImageLayout.FULL);
newCard.setText(contents);
newCard.setFootnote("xTuple");
View card1View1 = newCard.getView();
setContentView(card1View1);
}
super.onActivityResult(requestCode, resultCode, data);
}
/*
* end of boiler plate
*/
private GestureDetector createGestureDetector(Context context) {
GestureDetector gestureDetector = new GestureDetector(context);
//Create a base listener for generic gestures
gestureDetector.setBaseListener( new GestureDetector.BaseListener() {
@Override
public boolean onGesture(Gesture gesture) {
if (gesture == Gesture.TAP) {
Log.d("@@@@", "TAP");
scanBarcode();
// do something on tap
return true;
} else if (gesture == Gesture.TWO_TAP) {
// do something on two finger tap
Log.d("@@@@", "2-TAP");
return true;
} else if (gesture == Gesture.SWIPE_RIGHT) {
// do something on right (forward) swipe
Log.d("@@@@", "SWIPE_RIGHT");
return true;
} else if (gesture == Gesture.SWIPE_LEFT) {
// do something on left (backwards) swipe
Log.d("@@@@", "SWIPE_LEFT");
return true;
}
else if (gesture == Gesture.LONG_PRESS) {
// do something on left (backwards) swipe
Log.d("@@@@", "LONG_PRESS");
return true;
}
else if (gesture == Gesture.THREE_LONG_PRESS) {
// do something on left (backwards) swipe
Log.d("@@@@", "THREE_LONG_PRESS");
return true;
}
else if (gesture == Gesture.THREE_TAP) {
Log.d("@@@@", "THREE_TAP");
return true;
}
else if (gesture == Gesture.TWO_LONG_PRESS) {
Log.d("@@@@", "TWO_LONG_PRESS");
return true;
}
else if (gesture == Gesture.TWO_SWIPE_DOWN) {
Log.d("@@@@", "TWO_SWIPE_DOWN");
return true;
}
else if (gesture == Gesture.TWO_SWIPE_LEFT) {
Log.d("@@@@", "TWO_SWIPE_LEFT");
return true;
}
else if (gesture == Gesture. TWO_SWIPE_RIGHT) {
Log.d("@@@@", " TWO_SWIPE_RIGHT");
return true;
}
else if (gesture == Gesture. TWO_SWIPE_UP) {
Log.d("@@@@", " TWO_SWIPE_UP");
return true;
}
return false;
}
});
gestureDetector.setFingerListener(new GestureDetector.FingerListener() {
@Override
public void onFingerCountChanged(int previousCount, int currentCount) {
// do something on finger count changes
}
});
gestureDetector.setScrollListener(new GestureDetector.ScrollListener() {
@Override
public boolean onScroll(float displacement, float delta, float velocity) {
return true;
// do something on scrolling
}
});
return gestureDetector;
}
/*
* Send generic motion events to the gesture detector
*/
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mGestureDetector != null) {
return mGestureDetector.onMotionEvent(event);
}
return false;
}
} |
package me.nallar.patched.world;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.google.common.collect.ImmutableSetMultimap;
import javassist.is.faulty.ThreadLocals;
import me.nallar.tickthreading.Log;
import me.nallar.tickthreading.collections.ForcedChunksRedirectMap;
import me.nallar.tickthreading.minecraft.TickThreading;
import me.nallar.tickthreading.minecraft.entitylist.EntityList;
import me.nallar.tickthreading.minecraft.entitylist.LoadedTileEntityList;
import me.nallar.tickthreading.patcher.Declare;
import net.minecraft.block.Block;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.profiler.Profiler;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ReportedException;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderServer;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import org.cliffc.high_scale_lib.NonBlockingHashMapLong;
@SuppressWarnings ("unchecked")
public abstract class PatchWorld extends World {
private int forcedUpdateCount;
@Declare
public ThreadLocal<Boolean> inPlaceEvent_;
@Declare
public org.cliffc.high_scale_lib.NonBlockingHashMapLong<Integer> redstoneBurnoutMap_;
@Declare
public Set<Entity> unloadedEntitySet_;
@Declare
public Set<TileEntity> tileEntityRemovalSet_;
@Declare
public com.google.common.collect.ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> forcedChunks_;
@Declare
public int tickCount_;
private boolean warnedWrongList;
@Declare
public int dimensionId_;
private String cachedName;
private boolean multiverseName;
public void construct() {
tickCount = rand.nextInt(240); // So when different worlds do every N tick actions,
// they won't all happen at the same time even if the worlds loaded at the same time
tileEntityRemovalSet = new HashSet<TileEntity>();
unloadedEntitySet = new HashSet<Entity>();
redstoneBurnoutMap = new NonBlockingHashMapLong<Integer>();
if (dimensionId == 0) {
dimensionId = provider.dimensionId;
}
}
public PatchWorld(ISaveHandler par1ISaveHandler, String par2Str, WorldProvider par3WorldProvider, WorldSettings par4WorldSettings, Profiler par5Profiler) {
super(par1ISaveHandler, par2Str, par3WorldProvider, par4WorldSettings, par5Profiler);
}
@Override
@Declare
public void setDimension(int dimensionId) {
this.dimensionId = dimensionId;
if (provider.dimensionId != dimensionId) {
multiverseName = true;
provider.dimensionId = dimensionId;
}
cachedName = null;
Log.info("Set dimension ID for " + this.getName());
if (TickThreading.instance.getManager(this) != null) {
Log.severe("Set corrected dimension too late!");
}
}
@Override
@Declare
public int getDimension() {
return dimensionId;
}
@Override
@Declare
public String getName() {
String name = cachedName;
if (name != null) {
return name;
}
int dimensionId = getDimension();
if (multiverseName) {
name = worldInfo.getWorldName();
if (name.startsWith("world_")) {
name = name.substring(6);
}
} else {
name = provider.getDimensionName();
}
cachedName = name = (name + '/' + dimensionId + (isRemote ? "-r" : ""));
return name;
}
@Override
public boolean isBlockNormalCube(int x, int y, int z) {
int id = getBlockIdWithoutLoad(x, y, z);
if (id == -1) {
return false;
}
Block block = Block.blocksList[id];
return block != null && block.isBlockNormalCube(this, x, y, z);
}
@Override
public void removeEntity(Entity entity) {
if (entity == null) {
return;
}
try {
if (entity.riddenByEntity != null) {
entity.riddenByEntity.mountEntity(null);
}
if (entity.ridingEntity != null) {
entity.mountEntity(null);
}
entity.setDead();
// The next instanceof, somehow, seems to throw NPEs. I don't even. :(
if (entity instanceof EntityPlayer) {
this.playerEntities.remove(entity);
this.updateAllPlayersSleepingFlag();
}
} catch (Exception e) {
Log.severe("Exception removing a player entity", e);
}
}
@Override
public int getBlockId(int x, int y, int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y >= 0 && y < 256) {
try {
return getChunkFromChunkCoords(x >> 4, z >> 4).getBlockID(x & 15, y, z & 15);
} catch (Throwable t) {
Log.severe("Exception getting block ID in " + Log.name(this) + " at x,y,z" + x + ',' + y + ',' + z, t);
}
}
return 0;
}
@Override
@Declare
public int getBlockIdWithoutLoad(int x, int y, int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y >= 0 && y < 256) {
try {
Chunk chunk = ((ChunkProviderServer) chunkProvider).getChunkIfExists(x >> 4, z >> 4);
return chunk == null ? -1 : chunk.getBlockID(x & 15, y, z & 15);
} catch (Throwable t) {
Log.severe("Exception getting block ID in " + Log.name(this) + " at x,y,z" + x + ',' + y + ',' + z, t);
}
}
return 0;
}
@Override
@Declare
public Chunk getChunkFromChunkCoordsForceLoad(int x, int z) {
return chunkProvider.loadChunk(x, z);
}
@Override
@Declare
public int getBlockIdForceLoad(int x, int y, int z) {
if (y >= 256) {
return 0;
} else {
return chunkProvider.loadChunk(x >> 4, z >> 4).getBlockID(x & 15, y, z & 15);
}
}
@Override
public EntityPlayer getClosestPlayer(double x, double y, double z, double maxRange) {
double closestRange = Double.MAX_VALUE;
EntityPlayer target = null;
for (EntityPlayer playerEntity : (Iterable<EntityPlayer>) this.playerEntities) {
if (!playerEntity.capabilities.disableDamage && playerEntity.isEntityAlive()) {
double distanceSq = playerEntity.getDistanceSq(x, y, z);
if ((maxRange < 0.0D || distanceSq < (maxRange * maxRange)) && (distanceSq < closestRange)) {
closestRange = distanceSq;
target = playerEntity;
}
}
}
return target;
}
@SuppressWarnings ("ConstantConditions")
@Override
public EntityPlayer getClosestVulnerablePlayer(double x, double y, double z, double maxRange) {
double closestRange = Double.MAX_VALUE;
EntityPlayer target = null;
for (EntityPlayer playerEntity : (Iterable<EntityPlayer>) this.playerEntities) {
if (!playerEntity.capabilities.disableDamage && playerEntity.isEntityAlive()) {
double distanceSq = playerEntity.getDistanceSq(x, y, z);
double effectiveMaxRange = maxRange;
if (playerEntity.isSneaking()) {
effectiveMaxRange = maxRange * 0.800000011920929D;
}
if (playerEntity.getHasActivePotion()) {
float var18 = playerEntity.func_82243_bO();
if (var18 < 0.1F) {
var18 = 0.1F;
}
effectiveMaxRange *= (double) (0.7F * var18);
}
if ((maxRange < 0.0D || distanceSq < (effectiveMaxRange * effectiveMaxRange)) && (distanceSq < closestRange)) {
closestRange = distanceSq;
target = playerEntity;
}
}
}
return target;
}
@Override
public EntityPlayer getPlayerEntityByName(String name) {
for (EntityPlayer player : (Iterable<EntityPlayer>) playerEntities) {
if (name.equals(player.username)) {
return player;
}
}
return null;
}
@Override
protected void notifyBlockOfNeighborChange(int x, int y, int z, int par4) {
if (!this.editingBlocks && !this.isRemote) {
int var5 = this.getBlockIdWithoutLoad(x, y, z);
Block var6 = var5 < 1 ? null : Block.blocksList[var5];
if (var6 != null) {
try {
var6.onNeighborBlockChange(this, x, y, z, par4);
} catch (Throwable t) {
Log.severe("Exception while updating block neighbours", t);
}
}
}
}
@Override
public ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> getPersistentChunks() {
return forcedChunks == null ? ForcedChunksRedirectMap.emptyMap : forcedChunks;
}
@Override
public TileEntity getBlockTileEntity(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
Chunk chunk = this.getChunkFromChunkCoords(x >> 4, z >> 4);
return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
@Declare
public TileEntity getTEWithoutLoad(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
Chunk chunk = ((ChunkProviderServer) this.chunkProvider).getChunkIfExists(x >> 4, z >> 4);
return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
@Declare
public TileEntity getTEForceLoad(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
return chunkProvider.loadChunk(x >> 4, z >> 4).getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
public void updateEntityWithOptionalForce(Entity entity, boolean notForced) {
int x = MathHelper.floor_double(entity.posX);
int z = MathHelper.floor_double(entity.posZ);
boolean periodicUpdate = forcedUpdateCount++ % 19 == 0;
Boolean isForced_ = entity.isForced;
if (isForced_ == null || periodicUpdate) {
entity.isForced = isForced_ = getPersistentChunks().containsKey(new ChunkCoordIntPair(x >> 4, z >> 4));
}
boolean isForced = isForced_;
Boolean canUpdate_ = entity.canUpdate;
if (canUpdate_ == null || periodicUpdate) {
byte range = isForced ? (byte) 0 : 48;
entity.canUpdate = canUpdate_ = !notForced || this.checkChunksExist(x - range, 0, z - range, x + range, 0, z + range);
} else if (canUpdate_) {
entity.canUpdate = canUpdate_ = !notForced || chunkExists(x >> 4, z >> 4);
}
boolean canUpdate = canUpdate_;
if (canUpdate) {
entity.lastTickPosX = entity.posX;
entity.lastTickPosY = entity.posY;
entity.lastTickPosZ = entity.posZ;
entity.prevRotationYaw = entity.rotationYaw;
entity.prevRotationPitch = entity.rotationPitch;
if (notForced && entity.addedToChunk) {
if (entity.ridingEntity != null) {
entity.updateRidden();
} else {
++entity.ticksExisted;
entity.onUpdate();
}
}
this.theProfiler.startSection("chunkCheck");
if (Double.isNaN(entity.posX) || Double.isInfinite(entity.posX)) {
entity.posX = entity.lastTickPosX;
}
if (Double.isNaN(entity.posY) || Double.isInfinite(entity.posY)) {
entity.posY = entity.lastTickPosY;
}
if (Double.isNaN(entity.posZ) || Double.isInfinite(entity.posZ)) {
entity.posZ = entity.lastTickPosZ;
}
if (Double.isNaN((double) entity.rotationPitch) || Double.isInfinite((double) entity.rotationPitch)) {
entity.rotationPitch = entity.prevRotationPitch;
}
if (Double.isNaN((double) entity.rotationYaw) || Double.isInfinite((double) entity.rotationYaw)) {
entity.rotationYaw = entity.prevRotationYaw;
}
int cX = MathHelper.floor_double(entity.posX / 16.0D);
int cY = MathHelper.floor_double(entity.posY / 16.0D);
int cZ = MathHelper.floor_double(entity.posZ / 16.0D);
if (!entity.addedToChunk || entity.chunkCoordX != cX || entity.chunkCoordY != cY || entity.chunkCoordZ != cZ) {
if (entity.addedToChunk) {
Chunk chunk = getChunkIfExists(entity.chunkCoordX, entity.chunkCoordZ);
if (chunk != null) {
chunk.removeEntityAtIndex(entity, entity.chunkCoordY);
}
}
Chunk chunk = getChunkIfExists(cX, cZ);
if (chunk != null) {
entity.addedToChunk = true;
chunk.addEntity(entity);
} else {
entity.addedToChunk = false;
}
}
this.theProfiler.endSection();
if (notForced && entity.addedToChunk && entity.riddenByEntity != null) {
if (!entity.riddenByEntity.isDead && entity.riddenByEntity.ridingEntity == entity) {
this.updateEntity(entity.riddenByEntity);
} else {
entity.riddenByEntity.ridingEntity = null;
entity.riddenByEntity = null;
}
}
}
}
@Override
public void addLoadedEntities(List par1List) {
EntityTracker entityTracker = null;
//noinspection RedundantCast
if (((Object) this instanceof WorldServer)) {
entityTracker = ((WorldServer) (Object) this).getEntityTracker();
}
for (int var2 = 0; var2 < par1List.size(); ++var2) {
Entity entity = (Entity) par1List.get(var2);
if (MinecraftForge.EVENT_BUS.post(new EntityJoinWorldEvent(entity, this))) {
par1List.remove(var2
} else if (entityTracker == null || !entityTracker.isTracking(entity.entityId)) {
loadedEntityList.add(entity);
this.obtainEntitySkin(entity);
}
}
}
@Override
@Declare
public boolean hasCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
List collidingBoundingBoxes = (List) ThreadLocals.collidingBoundingBoxes.get();
collidingBoundingBoxes.clear();
int minX = MathHelper.floor_double(par2AxisAlignedBB.minX);
int maxX = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D);
int minY = MathHelper.floor_double(par2AxisAlignedBB.minY);
int maxY = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D);
int minZ = MathHelper.floor_double(par2AxisAlignedBB.minZ);
int maxZ = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D);
int ystart = ((minY - 1) < 0) ? 0 : (minY - 1);
for (int chunkx = (minX >> 4); chunkx <= ((maxX - 1) >> 4); chunkx++) {
int cx = chunkx << 4;
for (int chunkz = (minZ >> 4); chunkz <= ((maxZ - 1) >> 4); chunkz++) {
Chunk chunk = this.getChunkIfExists(chunkx, chunkz);
if (chunk == null) {
continue;
}
// Compute ranges within chunk
int cz = chunkz << 4;
int xstart = (minX < cx) ? cx : minX;
int xend = (maxX < (cx + 16)) ? maxX : (cx + 16);
int zstart = (minZ < cz) ? cz : minZ;
int zend = (maxZ < (cz + 16)) ? maxZ : (cz + 16);
// Loop through blocks within chunk
for (int x = xstart; x < xend; x++) {
for (int z = zstart; z < zend; z++) {
for (int y = ystart; y < maxY; y++) {
int blkid = chunk.getBlockID(x - cx, y, z - cz);
if (blkid > 0) {
Block block = Block.blocksList[blkid];
if (block != null) {
block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity);
}
if (!collidingBoundingBoxes.isEmpty()) {
return true;
}
}
}
}
}
}
}
double var14 = 0.25D;
List<Entity> var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), 100);
for (Entity aVar16 : var16) {
AxisAlignedBB var13 = aVar16.getBoundingBox();
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
return true;
}
var13 = par1Entity.getCollisionBox(aVar16);
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
return true;
}
}
return false;
}
@Override
@Declare
public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) {
List collidingBoundingBoxes = (List) ThreadLocals.collidingBoundingBoxes.get();
collidingBoundingBoxes.clear();
int var3 = MathHelper.floor_double(par2AxisAlignedBB.minX);
int var4 = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D);
int var5 = MathHelper.floor_double(par2AxisAlignedBB.minY);
int var6 = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D);
int var7 = MathHelper.floor_double(par2AxisAlignedBB.minZ);
int var8 = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D);
int ystart = ((var5 - 1) < 0) ? 0 : (var5 - 1);
for (int chunkx = (var3 >> 4); chunkx <= ((var4 - 1) >> 4); chunkx++) {
int cx = chunkx << 4;
for (int chunkz = (var7 >> 4); chunkz <= ((var8 - 1) >> 4); chunkz++) {
Chunk chunk = this.getChunkIfExists(chunkx, chunkz);
if (chunk == null) {
continue;
}
// Compute ranges within chunk
int cz = chunkz << 4;
// Compute ranges within chunk
int xstart = (var3 < cx) ? cx : var3;
int xend = (var4 < (cx + 16)) ? var4 : (cx + 16);
int zstart = (var7 < cz) ? cz : var7;
int zend = (var8 < (cz + 16)) ? var8 : (cz + 16);
// Loop through blocks within chunk
for (int x = xstart; x < xend; x++) {
for (int z = zstart; z < zend; z++) {
for (int y = ystart; y < var6; y++) {
int blkid = chunk.getBlockID(x - cx, y, z - cz);
if (blkid > 0) {
Block block = Block.blocksList[blkid];
if (block != null) {
block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity);
}
}
}
}
}
}
}
double var14 = 0.25D;
List<Entity> var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), limit);
for (Entity aVar16 : var16) {
AxisAlignedBB var13 = aVar16.getBoundingBox();
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
collidingBoundingBoxes.add(var13);
}
var13 = par1Entity.getCollisionBox(aVar16);
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
collidingBoundingBoxes.add(var13);
}
}
return collidingBoundingBoxes;
}
@Override
public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
return getCollidingBoundingBoxes(par1Entity, par2AxisAlignedBB, 2000);
}
@Override
public void addTileEntity(Collection tileEntities) {
List dest = scanningTileEntities ? addedTileEntityList : loadedTileEntityList;
for (TileEntity tileEntity : (Iterable<TileEntity>) tileEntities) {
try {
tileEntity.validate();
} catch (Throwable t) {
Log.severe("Tile Entity " + tileEntity + " failed to validate, it will be ignored.", t);
}
if (tileEntity.canUpdate()) {
dest.add(tileEntity);
}
}
}
@Override
@Declare
public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) {
List entitiesWithinAABBExcludingEntity = (List) ThreadLocals.entitiesWithinAABBExcludingEntity.get();
entitiesWithinAABBExcludingEntity.clear();
int minX = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D);
int maxX = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D);
int minZ = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D);
int maxZ = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D);
for (int x = minX; x <= maxX; ++x) {
for (int z = minZ; z <= maxZ; ++z) {
Chunk chunk = getChunkIfExists(x, z);
if (chunk != null) {
chunk.getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity, limit);
}
}
}
return entitiesWithinAABBExcludingEntity;
}
@Override
public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
List entitiesWithinAABBExcludingEntity = (List) ThreadLocals.entitiesWithinAABBExcludingEntity.get();
entitiesWithinAABBExcludingEntity.clear();
int var3 = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D);
int var4 = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D);
int var5 = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D);
int var6 = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D);
for (int var7 = var3; var7 <= var4; ++var7) {
for (int var8 = var5; var8 <= var6; ++var8) {
Chunk chunk = getChunkIfExists(var7, var8);
if (chunk != null) {
chunk.getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity);
}
}
}
return entitiesWithinAABBExcludingEntity;
}
@Override
public int countEntities(Class entityType) {
if (loadedEntityList instanceof EntityList) {
return ((EntityList) this.loadedEntityList).manager.getEntityCount(entityType);
}
int count = 0;
for (Entity e : (Iterable<Entity>) this.loadedEntityList) {
if (entityType.isAssignableFrom(e.getClass())) {
++count;
}
}
return count;
}
@Override
public boolean checkChunksExist(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
if (minY > 255 || maxY < 0) {
return false;
}
minX >>= 4;
minZ >>= 4;
maxX >>= 4;
maxZ >>= 4;
for (int x = minX; x <= maxX; ++x) {
for (int z = minZ; z <= maxZ; ++z) {
if (!chunkProvider.chunkExists(x, z)) {
return false;
}
}
}
return true;
}
@Override
public void unloadEntities(List entitiesToUnload) {
for (Entity entity : (Iterable<Entity>) entitiesToUnload) {
if (!(entity instanceof EntityPlayerMP)) {
unloadedEntitySet.add(entity);
}
}
}
@Override
public void updateEntities() {
this.theProfiler.startSection("entities");
this.theProfiler.startSection("global");
int var1;
Entity var2;
CrashReport var4;
CrashReportCategory var5;
for (var1 = 0; var1 < this.weatherEffects.size(); ++var1) {
var2 = (Entity) this.weatherEffects.get(var1);
try {
++var2.ticksExisted;
var2.onUpdate();
} catch (Throwable var6) {
var4 = CrashReport.makeCrashReport(var6, "Ticking entity");
var5 = var4.makeCategory("Entity being ticked");
var2.func_85029_a(var5);
throw new ReportedException(var4);
}
if (var2.isDead) {
this.weatherEffects.remove(var1
}
}
this.theProfiler.endStartSection("remove");
int var3;
int var13;
if (this.loadedEntityList instanceof EntityList) {
((EntityList) this.loadedEntityList).manager.batchRemoveEntities(unloadedEntitySet);
} else {
this.loadedEntityList.removeAll(this.unloadedEntitySet);
for (Entity entity : unloadedEntitySet) {
var3 = entity.chunkCoordX;
var13 = entity.chunkCoordZ;
if (entity.addedToChunk) {
Chunk chunk = getChunkIfExists(var3, var13);
if (chunk != null) {
chunk.removeEntity(entity);
}
}
releaseEntitySkin(entity);
}
}
this.unloadedEntitySet.clear();
this.theProfiler.endStartSection("regular");
boolean shouldTickThreadingTick = true;
if (this.loadedEntityList instanceof EntityList) {
((EntityList) this.loadedEntityList).manager.doTick();
shouldTickThreadingTick = false;
} else {
for (var1 = 0; var1 < this.loadedEntityList.size(); ++var1) {
var2 = (Entity) this.loadedEntityList.get(var1);
if (var2.ridingEntity != null) {
if (!var2.ridingEntity.isDead && var2.ridingEntity.riddenByEntity == var2) {
continue;
}
var2.ridingEntity.riddenByEntity = null;
var2.ridingEntity = null;
}
this.theProfiler.startSection("tick");
if (!var2.isDead) {
try {
this.updateEntity(var2);
} catch (Throwable var7) {
var4 = CrashReport.makeCrashReport(var7, "Ticking entity");
var5 = var4.makeCategory("Entity being ticked");
var2.func_85029_a(var5);
throw new ReportedException(var4);
}
}
this.theProfiler.endSection();
this.theProfiler.startSection("remove");
if (var2.isDead) {
var3 = var2.chunkCoordX;
var13 = var2.chunkCoordZ;
if (var2.addedToChunk) {
Chunk chunk = getChunkIfExists(var3, var13);
if (chunk != null) {
chunk.removeEntity(var2);
}
}
this.loadedEntityList.remove(var1
this.releaseEntitySkin(var2);
}
this.theProfiler.endSection();
}
}
this.theProfiler.endStartSection("tileEntities");
if (this.loadedEntityList instanceof EntityList) {
if (shouldTickThreadingTick) {
((EntityList) this.loadedEntityList).manager.doTick();
}
} else {
this.scanningTileEntities = true;
Iterator var14 = this.loadedTileEntityList.iterator();
while (var14.hasNext()) {
TileEntity var9 = (TileEntity) var14.next();
if (!var9.isInvalid() && var9.func_70309_m() && this.blockExists(var9.xCoord, var9.yCoord, var9.zCoord)) {
try {
var9.updateEntity();
} catch (Throwable var8) {
var4 = CrashReport.makeCrashReport(var8, "Ticking tile entity");
var5 = var4.makeCategory("Tile entity being ticked");
var9.func_85027_a(var5);
throw new ReportedException(var4);
}
}
if (var9.isInvalid()) {
var14.remove();
Chunk var11 = this.getChunkIfExists(var9.xCoord >> 4, var9.zCoord >> 4);
if (var11 != null) {
var11.cleanChunkBlockTileEntity(var9.xCoord & 15, var9.yCoord, var9.zCoord & 15);
}
}
}
}
this.theProfiler.endStartSection("removingTileEntities");
if (!this.tileEntityRemovalSet.isEmpty()) {
if (loadedTileEntityList instanceof LoadedTileEntityList) {
((LoadedTileEntityList) loadedTileEntityList).manager.batchRemoveTileEntities(tileEntityRemovalSet);
} else {
if (!warnedWrongList && loadedTileEntityList.getClass() != ArrayList.class) {
Log.severe("TickThreading's replacement loaded tile entity list has been replaced by one from another mod!\n" +
"Class: " + loadedTileEntityList.getClass() + ", toString(): " + loadedTileEntityList);
warnedWrongList = true;
}
for (TileEntity tile : tileEntityRemovalSet) {
tile.onChunkUnload();
}
this.loadedTileEntityList.removeAll(tileEntityRemovalSet);
}
tileEntityRemovalSet.clear();
}
this.scanningTileEntities = false;
this.theProfiler.endStartSection("pendingTileEntities");
if (!this.addedTileEntityList.isEmpty()) {
for (TileEntity te : (Iterable<TileEntity>) this.addedTileEntityList) {
if (te.isInvalid()) {
Chunk var15 = this.getChunkIfExists(te.xCoord >> 4, te.zCoord >> 4);
if (var15 != null) {
var15.cleanChunkBlockTileEntity(te.xCoord & 15, te.yCoord, te.zCoord & 15);
}
} else {
if (!this.loadedTileEntityList.contains(te)) {
this.loadedTileEntityList.add(te);
}
}
}
this.addedTileEntityList.clear();
}
this.theProfiler.endSection();
this.theProfiler.endSection();
}
@Override
public boolean isBlockProvidingPowerTo(int par1, int par2, int par3, int par4) {
int id = this.getBlockIdWithoutLoad(par1, par2, par3);
return id > 0 && Block.blocksList[id].isProvidingStrongPower(this, par1, par2, par3, par4);
}
@Override
public boolean isBlockIndirectlyProvidingPowerTo(int x, int y, int z, int direction) {
int id = this.getBlockIdWithoutLoad(x, y, z);
if (id < 1) {
return false;
}
Block block = Block.blocksList[id];
return block != null && ((block.isBlockNormalCube(this, x, y, z) && this.isBlockGettingPowered(x, y, z)) || block.isProvidingWeakPower(this, x, y, z, direction));
}
@Override
@Declare
public Chunk getChunkIfExists(int x, int z) {
return ((ChunkProviderServer) chunkProvider).getChunkIfExists(x, z);
}
@Override
@Declare
public Chunk getChunkFromBlockCoordsIfExists(int x, int z) {
return this.getChunkIfExists(x >> 4, z >> 4);
}
@Override
public void markTileEntityForDespawn(TileEntity tileEntity) {
tileEntityRemovalSet.add(tileEntity);
}
@Override
@Declare
public void setBlockTileEntityWithoutValidate(int x, int y, int z, TileEntity tileEntity) {
if (tileEntity == null || tileEntity.isInvalid()) {
return;
}
if (tileEntity.canUpdate()) {
(scanningTileEntities ? addedTileEntityList : loadedTileEntityList).add(tileEntity);
}
Chunk chunk = getChunkFromChunkCoords(x >> 4, z >> 4);
if (chunk != null) {
chunk.setChunkBlockTileEntityWithoutValidate(x & 15, y, z & 15, tileEntity);
}
}
@Override
@Declare
public boolean setBlockAndMetadataWithUpdateWithoutValidate(int x, int y, int z, int id, int meta, boolean update) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y >= 0 && y < 256) {
Chunk chunk = this.getChunkFromChunkCoords(x >> 4, z >> 4);
if (!chunk.setBlockIDWithMetadataWithoutValidate(x & 15, y, z & 15, id, meta)) {
return false;
}
this.theProfiler.startSection("checkLight");
this.updateAllLightTypes(x, y, z);
this.theProfiler.endSection();
if (update) {
this.markBlockForUpdate(x, y, z);
}
return true;
}
return false;
}
} |
package org.nohope.typetools;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public final class TTime {
private TTime() {
}
public static int deltaInSeconds(final DateTime ts1, final DateTime ts2) {
final Period delta = new Period(ts1, ts2);
final int deltaSec = delta.toStandardSeconds().getSeconds();
return Math.abs(deltaSec);
}
public static void setUtcTimezone() {
final DateTimeZone defaultZone = DateTimeZone.forID("UTC");
DateTimeZone.setDefault(defaultZone);
setDefaultTimezone("Etc/UTC");
}
private static void setDefaultTimezone(final String id) {
TimeZone.setDefault(TimeZone.getTimeZone(id));
}
/**
* Creates {@link XMLGregorianCalendar XMLGregorianCalendar} for given date in {@code UTC} timezone.
* @see #xmlDate(java.util.Date, String)
*/
public static XMLGregorianCalendar xmlUtcDate(final Date date) {
return xmlDate(date, "UTC");
}
/**
* Creates {@link XMLGregorianCalendar XMLGregorianCalendar} for given date in given timezone.
* @see #xmlDate(java.util.Date, String)
*/
public static XMLGregorianCalendar xmlDate(final Date date, final String timezoneId) {
final GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(date);
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
} catch (DatatypeConfigurationException e) {
throw new IllegalStateException(e);
}
}
} |
package org.pwd.web.audit;
import org.pwd.domain.audit.Audit;
import org.pwd.domain.audit.AuditRepository;
import org.pwd.domain.audit.WebsiteAudit;
import org.pwd.domain.audit.WebsiteAuditRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
/**
* @author bartosz.walacik
*/
@Controller
@RequestMapping("/audits")
public class AuditController {
private final AuditRepository auditRepository;
private final WebsiteAuditRepository websiteAuditRepository;
@Autowired
public AuditController(AuditRepository auditRepository, WebsiteAuditRepository websiteAuditRepository) {
this.auditRepository = auditRepository;
this.websiteAuditRepository = websiteAuditRepository;
}
@RequestMapping(value = "/{auditId}", method = RequestMethod.GET)
public String showAudit(@PathVariable int auditId, Model model) {
Audit audit = auditRepository.findOne(auditId);
List<WebsiteAudit> websiteAudits = websiteAuditRepository.findByAudit(audit);
model.addAttribute("audit", audit);
model.addAttribute("websiteAudits", websiteAudits);
return "audit";
}
} |
package dr.app.beauti.treespanel;
import dr.app.beauti.BeautiFrame;
import dr.app.tools.TemporalRooting;
import dr.evolution.tree.Tree;
import dr.gui.chart.*;
import dr.gui.tree.JTreeDisplay;
import dr.gui.tree.SquareTreePainter;
import dr.stats.Regression;
import javax.swing.*;
import java.awt.*;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: PriorsPanel.java,v 1.9 2006/09/05 13:29:34 rambaut Exp $
*/
public class TreeDisplayPanel extends JPanel {
private Tree tree = null;
BeautiFrame frame = null;
JTabbedPane tabbedPane = new JTabbedPane();
JTreeDisplay treePanel;
JTreeDisplay scaledTreePanel;
JChartPanel rootToTipPanel;
JChart rootToTipChart;
public TreeDisplayPanel(BeautiFrame parent) {
super(new BorderLayout());
this.frame = parent;
treePanel = new JTreeDisplay(new SquareTreePainter());
tabbedPane.add("Tree", treePanel);
rootToTipChart = new JChart(new LinearAxis(), new LinearAxis(Axis.AT_ZERO, Axis.AT_MINOR_TICK));
rootToTipPanel = new JChartPanel(rootToTipChart, "", "time", "divergence");
rootToTipPanel.setOpaque(false);
tabbedPane.add("Root-to-tip", rootToTipPanel);
scaledTreePanel = new JTreeDisplay(new SquareTreePainter());
tabbedPane.add("Re-scaled tree", scaledTreePanel);
setOpaque(false);
add(tabbedPane, BorderLayout.CENTER);
}
public void setTree(Tree tree) {
this.tree = tree;
setupPanel();
}
private void setupPanel() {
if (tree != null) {
treePanel.setTree(tree);
TemporalRooting temporalRooting = new TemporalRooting(tree);
Regression r = temporalRooting.getRootToTipRegression(tree);
rootToTipChart.removeAllPlots();
rootToTipChart.addPlot(new ScatterPlot(r.getXData(), r.getYData()));
rootToTipChart.addPlot(new RegressionPlot(r));
rootToTipChart.getXAxis().addRange(r.getXIntercept(), r.getXData().getMax());
scaledTreePanel.setTree(temporalRooting.adjustTreeToConstraints(tree, null));
} else {
treePanel.setTree(null);
rootToTipChart.removeAllPlots();
scaledTreePanel.setTree(null);
}
repaint();
}
} |
package dr.evomodel.antigenic;
import dr.evolution.util.*;
import dr.inference.model.*;
import dr.math.MathUtils;
import dr.math.LogTricks;
import dr.math.distributions.NormalDistribution;
import dr.util.*;
import dr.xml.*;
import java.io.*;
import java.util.*;
import java.util.logging.Logger;
/**
* @author Andrew Rambaut
* @author Trevor Bedford
* @author Marc Suchard
* @version $Id$
*/
/*
Both virus locations and serum locations are shifted by the parameter locationDrift.
A location is increased by locationDrift x offset.
Offset is set to 0 for the earliest virus and increasing with difference in date from earliest virus.
This makes the raw virusLocations and serumLocations parameters not directly interpretable.
*/
public class AntigenicLikelihood extends AbstractModelLikelihood implements Citable {
private static final boolean CHECK_INFINITE = false;
private static final boolean USE_THRESHOLDS = true;
private static final boolean USE_INTERVALS = true;
public final static String ANTIGENIC_LIKELIHOOD = "antigenicLikelihood";
// column indices in table
private static final int VIRUS_ISOLATE = 0;
private static final int VIRUS_STRAIN = 1;
private static final int VIRUS_DATE = 2;
private static final int SERUM_ISOLATE = 3;
private static final int SERUM_STRAIN = 4;
private static final int SERUM_DATE = 5;
private static final int TITRE = 6;
public enum MeasurementType {
INTERVAL,
POINT,
THRESHOLD,
MISSING
}
public AntigenicLikelihood(
int mdsDimension,
Parameter mdsPrecisionParameter,
Parameter locationDriftParameter,
TaxonList strainTaxa,
MatrixParameter virusLocationsParameter,
MatrixParameter serumLocationsParameter,
MatrixParameter locationsParameter,
CompoundParameter tipTraitsParameter,
Parameter virusOffsetsParameter,
Parameter serumOffsetsParameter,
Parameter serumPotenciesParameter,
Parameter virusAviditiesParameter,
DataTable<String[]> dataTable,
boolean mergeIsolates,
double intervalWidth) {
super(ANTIGENIC_LIKELIHOOD);
List<String> strainNames = new ArrayList<String>();
List<String> virusNames = new ArrayList<String>();
List<String> serumNames = new ArrayList<String>();
Map<String, Double> strainDateMap = new HashMap<String, Double>();
this.intervalWidth = intervalWidth;
boolean useIntervals = USE_INTERVALS && intervalWidth > 0.0;
int thresholdCount = 0;
earliestDate = Double.POSITIVE_INFINITY;
for (int i = 0; i < dataTable.getRowCount(); i++) {
String[] values = dataTable.getRow(i);
int serumIsolate = serumLabels.indexOf(values[SERUM_ISOLATE]);
if (serumIsolate == -1) {
serumLabels.add(values[SERUM_ISOLATE]);
serumIsolate = serumLabels.size() - 1;
}
int serumStrain = -1;
String serumStrainName;
if (mergeIsolates) {
serumStrainName = values[SERUM_STRAIN];
} else {
serumStrainName = values[SERUM_ISOLATE];
}
if (strainTaxa != null) {
serumStrain = strainTaxa.getTaxonIndex(serumStrainName);
throw new UnsupportedOperationException("Should extract dates from taxon list...");
} else {
serumStrain = strainNames.indexOf(serumStrainName);
if (serumStrain == -1) {
strainNames.add(serumStrainName);
double date = Double.parseDouble(values[SERUM_DATE]);
strainDateMap.put(serumStrainName, date);
serumStrain = strainNames.size() - 1;
}
int thisStrain = serumNames.indexOf(serumStrainName);
if (thisStrain == -1) {
serumNames.add(serumStrainName);
}
}
double serumDate = Double.parseDouble(values[SERUM_DATE]);
if (serumStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized serum strain name, " + values[SERUM_STRAIN] + ", in row " + (i+1));
}
int virusIsolate = virusLabels.indexOf(values[VIRUS_ISOLATE]);
if (virusIsolate == -1) {
virusLabels.add(values[VIRUS_ISOLATE]);
virusIsolate = virusLabels.size() - 1;
}
int virusStrain = -1;
String virusStrainName = values[VIRUS_STRAIN];
if (strainTaxa != null) {
virusStrain = strainTaxa.getTaxonIndex(virusStrainName);
} else {
virusStrain = strainNames.indexOf(virusStrainName);
if (virusStrain == -1) {
strainNames.add(virusStrainName);
double date = Double.parseDouble(values[VIRUS_DATE]);
strainDateMap.put(virusStrainName, date);
virusStrain = strainNames.size() - 1;
}
int thisStrain = virusNames.indexOf(virusStrainName);
if (thisStrain == -1) {
virusNames.add(virusStrainName);
}
}
if (virusStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized virus strain name, " + values[VIRUS_STRAIN] + ", in row " + (i+1));
}
double virusDate = Double.parseDouble(values[VIRUS_DATE]);
boolean isThreshold = false;
double rawTitre = Double.NaN;
if (values[TITRE].length() > 0) {
try {
rawTitre = Double.parseDouble(values[TITRE]);
} catch (NumberFormatException nfe) {
// check if threshold below
if (values[TITRE].contains("<")) {
rawTitre = Double.parseDouble(values[TITRE].replace("<",""));
isThreshold = true;
thresholdCount++;
}
// check if threshold above
if (values[TITRE].contains(">")) {
throw new IllegalArgumentException("Error in measurement: unsupported greater than threshold at row " + (i+1));
}
}
}
if (serumDate < earliestDate) {
earliestDate = serumDate;
}
if (virusDate < earliestDate) {
earliestDate = virusDate;
}
MeasurementType type = (isThreshold ? MeasurementType.THRESHOLD : (useIntervals ? MeasurementType.INTERVAL : MeasurementType.POINT));
Measurement measurement = new Measurement(serumIsolate, serumStrain, serumDate, virusIsolate, virusStrain, virusDate, type, rawTitre);
if (USE_THRESHOLDS || !isThreshold) {
measurements.add(measurement);
}
}
double[] maxColumnTitre = new double[serumLabels.size()];
double[] maxRowTitre = new double[virusLabels.size()];
for (Measurement measurement : measurements) {
double titre = measurement.log2Titre;
if (Double.isNaN(titre)) {
titre = measurement.log2Titre;
}
if (titre > maxColumnTitre[measurement.serumIsolate]) {
maxColumnTitre[measurement.serumIsolate] = titre;
}
if (titre > maxRowTitre[measurement.virusIsolate]) {
maxRowTitre[measurement.virusIsolate] = titre;
}
}
if (strainTaxa != null) {
this.strains = strainTaxa;
// fill in the strain name array for local use
for (int i = 0; i < strains.getTaxonCount(); i++) {
strainNames.add(strains.getTaxon(i).getId());
}
} else {
Taxa taxa = new Taxa();
for (String strain : strainNames) {
taxa.addTaxon(new Taxon(strain));
}
this.strains = taxa;
}
this.mdsDimension = mdsDimension;
this.mdsPrecisionParameter = mdsPrecisionParameter;
addVariable(mdsPrecisionParameter);
this.locationDriftParameter = locationDriftParameter;
addVariable(locationDriftParameter);
this.locationsParameter = locationsParameter;
setupLocationsParameter(this.locationsParameter, strainNames);
this.virusLocationsParameter = virusLocationsParameter;
if (this.virusLocationsParameter != null) {
setupSubsetLocationsParameter(virusLocationsParameter, locationsParameter, virusNames);
}
this.serumLocationsParameter = serumLocationsParameter;
if (this.serumLocationsParameter != null) {
setupSubsetLocationsParameter(serumLocationsParameter, locationsParameter, serumNames);
}
this.tipTraitsParameter = tipTraitsParameter;
if (tipTraitsParameter != null) {
setupTipTraitsParameter(this.tipTraitsParameter, strainNames);
}
this.virusOffsetsParameter = virusOffsetsParameter;
if (virusOffsetsParameter != null) {
setupOffsetParameter(virusOffsetsParameter, virusNames, strainDateMap, earliestDate);
}
this.serumOffsetsParameter = serumOffsetsParameter;
if (serumOffsetsParameter != null) {
setupOffsetParameter(serumOffsetsParameter, serumNames, strainDateMap, earliestDate);
}
this.serumPotenciesParameter = setupSerumEffects(serumPotenciesParameter, maxColumnTitre);
this.virusAviditiesParameter = setupVirusEffects(virusAviditiesParameter, maxRowTitre);
StringBuilder sb = new StringBuilder();
sb.append("\tAntigenicLikelihood:\n");
sb.append("\t\t" + this.strains.getTaxonCount() + " strains\n");
sb.append("\t\t" + virusNames.size() + " viruses\n");
sb.append("\t\t" + serumNames.size() + " sera\n");
sb.append("\t\t" + virusLabels.size() + " unique viruses\n");
sb.append("\t\t" + serumLabels.size() + " unique sera\n");
sb.append("\t\t" + measurements.size() + " assay measurements\n");
if (USE_THRESHOLDS) {
sb.append("\t\t" + thresholdCount + " thresholded measurements\n");
}
if (useIntervals) {
sb.append("\n\t\tAssuming a log 2 measurement interval width of " + intervalWidth + "\n");
}
Logger.getLogger("dr.evomodel").info(sb.toString());
locationChanged = new boolean[this.locationsParameter.getParameterCount()];
serumEffectChanged = new boolean[maxColumnTitre.length];
virusEffectChanged = new boolean[maxRowTitre.length];
logLikelihoods = new double[measurements.size()];
storedLogLikelihoods = new double[measurements.size()];
setupInitialLocations();
makeDirty();
}
private Parameter setupVirusEffects(Parameter virusAviditiesParameter, double[] maxRowTitre) {
// If no row parameter is given, then we will only use the serum effects
if (virusAviditiesParameter != null) {
virusAviditiesParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
virusAviditiesParameter.setDimension(virusLabels.size());
addVariable(virusAviditiesParameter);
String[] labelArray = new String[virusLabels.size()];
virusLabels.toArray(labelArray);
virusAviditiesParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxRowTitre.length; i++) {
virusAviditiesParameter.setParameterValueQuietly(i, maxRowTitre[i]);
}
}
return virusAviditiesParameter;
}
private Parameter setupSerumEffects(Parameter serumPotenciesParameter, double[] maxColumnTitre) {
// If no serum potencies parameter is given, make one to hold maximum values for scaling titres...
if (serumPotenciesParameter == null) {
serumPotenciesParameter = new Parameter.Default("serumPotencies");
} else {
serumPotenciesParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
addVariable(serumPotenciesParameter);
}
serumPotenciesParameter.setDimension(serumLabels.size());
String[] labelArray = new String[serumLabels.size()];
serumLabels.toArray(labelArray);
serumPotenciesParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxColumnTitre.length; i++) {
serumPotenciesParameter.setParameterValueQuietly(i, maxColumnTitre[i]);
}
return serumPotenciesParameter;
}
protected void setupLocationsParameter(MatrixParameter locationsParameter, List<String> strains) {
locationsParameter.setColumnDimension(mdsDimension);
locationsParameter.setRowDimension(strains.size());
for (int i = 0; i < strains.size(); i++) {
locationsParameter.getParameter(i).setId(strains.get(i));
}
addVariable(this.locationsParameter);
}
protected void setupSubsetLocationsParameter(MatrixParameter subsetLocationsParameter, MatrixParameter locationsParameter, List<String> strains) {
for (int i = 0; i < locationsParameter.getParameterCount(); i++) {
Parameter parameter = locationsParameter.getParameter(i);
if (strains.contains(parameter.getId())) {
subsetLocationsParameter.addParameter(parameter);
}
}
}
private void setupOffsetParameter(Parameter datesParameter, List<String> strainNames, Map<String, Double> strainDateMap, double earliest) {
datesParameter.setDimension(strainNames.size());
String[] labelArray = new String[strainNames.size()];
strainNames.toArray(labelArray);
datesParameter.setDimensionNames(labelArray);
for (int i = 0; i < strainNames.size(); i++) {
Double date = strainDateMap.get(strainNames.get(i)) - new Double(earliest);
if (date == null) {
throw new IllegalArgumentException("Date missing for strain: " + strainNames.get(i));
}
datesParameter.setParameterValue(i, date);
}
}
private void setupTipTraitsParameter(CompoundParameter tipTraitsParameter, List<String> strainNames) {
tipIndices = new int[strainNames.size()];
for (int i = 0; i < strainNames.size(); i++) {
tipIndices[i] = -1;
}
for (int i = 0; i < tipTraitsParameter.getParameterCount(); i++) {
Parameter tip = tipTraitsParameter.getParameter(i);
String label = tip.getParameterName();
int index = findStrain(label, strainNames);
if (index != -1) {
if (tipIndices[index] != -1) {
throw new IllegalArgumentException("Duplicated tip name: " + label);
}
tipIndices[index] = i;
// rather than setting these here, we set them when the locations are set so the changes propagate
// through to the diffusion model.
// Parameter location = locationsParameter.getParameter(index);
// for (int dim = 0; dim < mdsDimension; dim++) {
// tip.setParameterValue(dim, location.getParameterValue(dim));
} else {
// The tree may contain viruses not present in the assay data
}
}
// we are only setting this parameter not listening to it:
// addVariable(this.tipTraitsParameter);
}
private final int findStrain(String label, List<String> strainNames) {
int index = 0;
for (String strainName : strainNames) {
if (label.startsWith(strainName)) {
return index;
}
index ++;
}
return -1;
}
private void setupInitialLocations() {
for (int i = 0; i < locationsParameter.getParameterCount(); i++) {
for (int j = 0; j < mdsDimension; j++) {
double r = MathUtils.nextGaussian();
locationsParameter.getParameter(i).setParameterValue(j, r);
}
}
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
if (variable == locationsParameter) {
int loc = index / mdsDimension;
locationChanged[loc] = true;
if (tipTraitsParameter != null && tipIndices[loc] != -1) {
Parameter location = locationsParameter.getParameter(loc);
Parameter tip = tipTraitsParameter.getParameter(tipIndices[loc]);
int dim = index % mdsDimension;
tip.setParameterValue(dim, location.getParameterValue(dim));
}
} else if (variable == mdsPrecisionParameter) {
setLocationChangedFlags(true);
} else if (variable == locationDriftParameter) {
setLocationChangedFlags(true);
} else if (variable == serumPotenciesParameter) {
serumEffectChanged[index] = true;
} else if (variable == virusAviditiesParameter) {
virusEffectChanged[index] = true;
} else {
// could be a derived class's parameter
}
likelihoodKnown = false;
}
@Override
protected void storeState() {
System.arraycopy(logLikelihoods, 0, storedLogLikelihoods, 0, logLikelihoods.length);
}
@Override
protected void restoreState() {
double[] tmp = logLikelihoods;
logLikelihoods = storedLogLikelihoods;
storedLogLikelihoods = tmp;
likelihoodKnown = false;
}
@Override
protected void acceptState() {
}
public Model getModel() {
return this;
}
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = computeLogLikelihood();
}
return logLikelihood;
}
// This function can be overwritten to implement other sampling densities, i.e. discrete ranks
private double computeLogLikelihood() {
double precision = mdsPrecisionParameter.getParameterValue(0);
double sd = 1.0 / Math.sqrt(precision);
logLikelihood = 0.0;
int i = 0;
for (Measurement measurement : measurements) {
if (locationChanged[measurement.virusStrain] || locationChanged[measurement.serumStrain] || serumEffectChanged[measurement.serumIsolate] || virusEffectChanged[measurement.virusIsolate]) {
// the row strain is shifted
double mapDistance = computeDistance(measurement.virusStrain, measurement.serumStrain, measurement.virusDate, measurement.serumDate);
double expectation = calculateBaseline(measurement.serumIsolate, measurement.virusIsolate) - mapDistance;
switch (measurement.type) {
case INTERVAL: {
double minTitre = measurement.log2Titre;
double maxTitre = measurement.log2Titre + intervalWidth;
logLikelihoods[i] = computeMeasurementIntervalLikelihood(minTitre, maxTitre, expectation, sd);
} break;
case POINT: {
logLikelihoods[i] = computeMeasurementLikelihood(measurement.log2Titre, expectation, sd);
} break;
case THRESHOLD: {
logLikelihoods[i] = computeMeasurementThresholdLikelihood(measurement.log2Titre, expectation, sd);
} break;
case MISSING:
break;
}
}
logLikelihood += logLikelihoods[i];
i++;
}
likelihoodKnown = true;
setLocationChangedFlags(false);
setSerumEffectChangedFlags(false);
setVirusEffectChangedFlags(false);
return logLikelihood;
}
private void setLocationChangedFlags(boolean flag) {
for (int i = 0; i < locationChanged.length; i++) {
locationChanged[i] = flag;
}
}
private void setSerumEffectChangedFlags(boolean flag) {
for (int i = 0; i < serumEffectChanged.length; i++) {
serumEffectChanged[i] = flag;
}
}
private void setVirusEffectChangedFlags(boolean flag) {
for (int i = 0; i < virusEffectChanged.length; i++) {
virusEffectChanged[i] = flag;
}
}
// offset virus and serum location when computing
protected double computeDistance(int virusStrain, int serumStrain, double virusDate, double serumDate) {
if (virusStrain == serumStrain) {
return 0.0;
}
Parameter vLoc = locationsParameter.getParameter(virusStrain);
Parameter sLoc = locationsParameter.getParameter(serumStrain);
double sum = 0.0;
// first dimension is shifted
double vxOffset = locationDriftParameter.getParameterValue(0) * (virusDate - earliestDate);
double vxLoc = vLoc.getParameterValue(0) + vxOffset;
double sxOffset = locationDriftParameter.getParameterValue(0) * (serumDate - earliestDate);
double sxLoc = sLoc.getParameterValue(0) + sxOffset;
double difference = vxLoc - sxLoc;
sum += difference * difference;
// other dimensions are not
for (int i = 1; i < mdsDimension; i++) {
difference = vLoc.getParameterValue(i) - sLoc.getParameterValue(i);
sum += difference * difference;
}
return Math.sqrt(sum);
}
/**
* Calculates the expected log2 titre when mapDistance = 0
* @param serum
* @param virus
* @return
*/
private double calculateBaseline(int serum, int virus) {
double baseline;
double serumEffect = serumPotenciesParameter.getParameterValue(serum);
if (virusAviditiesParameter != null) {
double virusEffect = virusAviditiesParameter.getParameterValue(virus);
baseline = 0.5 * (virusEffect + serumEffect);
} else {
baseline = serumEffect;
}
return baseline;
}
private static double computeMeasurementLikelihood(double titre, double expectation, double sd) {
double lnL = NormalDistribution.logPdf(titre, expectation, sd);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite point measurement");
}
return lnL;
}
private static double computeMeasurementThresholdLikelihood(double titre, double expectation, double sd) {
// real titre is somewhere between -infinity and measured 'titre'
// want the lower tail of the normal CDF
double lnL = NormalDistribution.cdf(titre, expectation, sd, true); // returns logged CDF
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite threshold measurement");
}
return lnL;
}
private static double computeMeasurementIntervalLikelihood(double minTitre, double maxTitre, double expectation, double sd) {
// real titre is somewhere between measured minTitre and maxTitre
double cdf1 = NormalDistribution.cdf(maxTitre, expectation, sd, true); // returns logged CDF
double cdf2 = NormalDistribution.cdf(minTitre, expectation, sd, true); // returns logged CDF
double lnL = LogTricks.logDiff(cdf1, cdf2);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
// this occurs when the interval is in the far tail of the distribution, cdf1 == cdf2
// instead return logPDF of the point
lnL = NormalDistribution.logPdf(minTitre, expectation, sd);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite interval measurement");
}
}
return lnL;
}
public void makeDirty() {
likelihoodKnown = false;
setLocationChangedFlags(true);
}
private class Measurement {
private Measurement(final int serumIsolate, final int serumStrain, final double serumDate, final int virusIsolate, final int virusStrain, final double virusDate, final MeasurementType type, final double titre) {
this.serumIsolate = serumIsolate;
this.serumStrain = serumStrain;
this.serumDate = serumDate;
this.virusIsolate = virusIsolate;
this.virusStrain = virusStrain;
this.virusDate = virusDate;
this.type = type;
this.titre = titre;
this.log2Titre = Math.log(titre) / Math.log(2);
}
final int serumIsolate;
final int serumStrain;
final double serumDate;
final int virusIsolate;
final int virusStrain;
final double virusDate;
final MeasurementType type;
final double titre;
final double log2Titre;
};
private final List<Measurement> measurements = new ArrayList<Measurement>();
private final List<String> serumLabels = new ArrayList<String>();
private final List<String> virusLabels = new ArrayList<String>();
private final int mdsDimension;
private final double intervalWidth;
private final Parameter mdsPrecisionParameter;
private final Parameter locationDriftParameter;
private final MatrixParameter locationsParameter;
private final MatrixParameter virusLocationsParameter;
private final MatrixParameter serumLocationsParameter;
private double earliestDate;
private final Parameter virusOffsetsParameter;
private final Parameter serumOffsetsParameter;
private final CompoundParameter tipTraitsParameter;
private final TaxonList strains;
private int[] tipIndices;
private final Parameter serumPotenciesParameter;
private final Parameter virusAviditiesParameter;
private double logLikelihood = 0.0;
private boolean likelihoodKnown = false;
private final boolean[] locationChanged;
private final boolean[] serumEffectChanged;
private final boolean[] virusEffectChanged;
private double[] logLikelihoods;
private double[] storedLogLikelihoods;
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String FILE_NAME = "fileName";
public final static String TIP_TRAIT = "tipTrait";
public final static String LOCATIONS = "locations";
public final static String VIRUS_LOCATIONS = "virusLocations";
public final static String SERUM_LOCATIONS = "serumLocations";
public static final String MDS_DIMENSION = "mdsDimension";
public static final String MERGE_ISOLATES = "mergeIsolates";
public static final String INTERVAL_WIDTH = "intervalWidth";
public static final String MDS_PRECISION = "mdsPrecision";
public static final String LOCATION_DRIFT = "locationDrift";
public static final String VIRUS_AVIDITIES = "virusAvidities";
public static final String SERUM_POTENCIES = "serumPotencies";
public final static String VIRUS_OFFSETS = "virusOffsets";
public final static String SERUM_OFFSETS = "serumOffsets";
public static final String STRAINS = "strains";
public String getParserName() {
return ANTIGENIC_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FILE_NAME);
DataTable<String[]> assayTable;
try {
assayTable = DataTable.Text.parse(new FileReader(fileName), true, false);
} catch (IOException e) {
throw new XMLParseException("Unable to read assay data from file: " + e.getMessage());
}
System.out.println("Loaded HI table file: " + fileName);
boolean mergeIsolates = xo.getAttribute(MERGE_ISOLATES, false);
int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION);
double intervalWidth = 0.0;
if (xo.hasAttribute(INTERVAL_WIDTH)) {
intervalWidth = xo.getDoubleAttribute(INTERVAL_WIDTH);
}
CompoundParameter tipTraitParameter = null;
if (xo.hasChildNamed(TIP_TRAIT)) {
tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
}
TaxonList strains = null;
if (xo.hasChildNamed(STRAINS)) {
strains = (TaxonList) xo.getElementFirstChild(STRAINS);
}
MatrixParameter virusLocationsParameter = null;
if (xo.hasChildNamed(VIRUS_LOCATIONS)) {
virusLocationsParameter = (MatrixParameter) xo.getElementFirstChild(VIRUS_LOCATIONS);
}
MatrixParameter serumLocationsParameter = null;
if (xo.hasChildNamed(SERUM_LOCATIONS)) {
serumLocationsParameter = (MatrixParameter) xo.getElementFirstChild(SERUM_LOCATIONS);
}
MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION);
Parameter locationDrift = (Parameter) xo.getElementFirstChild(LOCATION_DRIFT);
Parameter virusOffsetsParameter = null;
if (xo.hasChildNamed(VIRUS_OFFSETS)) {
virusOffsetsParameter = (Parameter) xo.getElementFirstChild(VIRUS_OFFSETS);
}
Parameter serumOffsetsParameter = null;
if (xo.hasChildNamed(SERUM_OFFSETS)) {
serumOffsetsParameter = (Parameter) xo.getElementFirstChild(SERUM_OFFSETS);
}
Parameter serumPotenciesParameter = null;
if (xo.hasChildNamed(SERUM_POTENCIES)) {
serumPotenciesParameter = (Parameter) xo.getElementFirstChild(SERUM_POTENCIES);
}
Parameter virusAviditiesParameter = null;
if (xo.hasChildNamed(VIRUS_AVIDITIES)) {
virusAviditiesParameter = (Parameter) xo.getElementFirstChild(VIRUS_AVIDITIES);
}
AntigenicLikelihood AGL = new AntigenicLikelihood(
mdsDimension,
mdsPrecision,
locationDrift,
strains,
virusLocationsParameter,
serumLocationsParameter,
locationsParameter,
tipTraitParameter,
virusOffsetsParameter,
serumOffsetsParameter,
serumPotenciesParameter,
virusAviditiesParameter,
assayTable,
mergeIsolates,
intervalWidth);
Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL));
return AGL;
} |
package dr.evomodel.antigenic;
import dr.evolution.util.*;
import dr.inference.model.*;
import dr.math.MathUtils;
import dr.math.distributions.NormalDistribution;
import dr.util.*;
import dr.xml.*;
import java.io.*;
import java.util.*;
import java.util.logging.Logger;
/**
* @author Andrew Rambaut
* @author Trevor Bedford
* @author Marc Suchard
* @version $Id$
*/
public class AntigenicLikelihood extends AbstractModelLikelihood implements Citable {
private static final boolean CHECK_INFINITE = false;
private static final boolean USE_THRESHOLDS = true;
private static final boolean USE_INTERVALS = true;
public final static String ANTIGENIC_LIKELIHOOD = "antigenicLikelihood";
// column indices in table
private static final int COLUMN_LABEL = 0;
private static final int SERUM_STRAIN = 2;
private static final int ROW_LABEL = 1;
private static final int VIRUS_STRAIN = 3;
private static final int SERUM_DATE = 4;
private static final int VIRUS_DATE = 5;
private static final int TITRE = 6;
public enum MeasurementType {
INTERVAL,
POINT,
THRESHOLD,
MISSING
}
public AntigenicLikelihood(
int mdsDimension,
Parameter mdsPrecisionParameter,
TaxonList strainTaxa,
MatrixParameter locationsParameter,
Parameter datesParameter,
Parameter columnParameter,
Parameter rowParameter,
DataTable<String[]> dataTable,
double intervalWidth,
List<String> virusLocationStatisticList) {
super(ANTIGENIC_LIKELIHOOD);
List<String> strainNames = new ArrayList<String>();
Map<String, Double> strainDateMap = new HashMap<String, Double>();
this.intervalWidth = intervalWidth;
boolean useIntervals = USE_INTERVALS && intervalWidth > 0.0;
int thresholdCount = 0;
for (int i = 0; i < dataTable.getRowCount(); i++) {
String[] values = dataTable.getRow(i);
int column = columnLabels.indexOf(values[COLUMN_LABEL]);
if (column == -1) {
columnLabels.add(values[0]);
column = columnLabels.size() - 1;
}
int columnStrain = -1;
if (strainTaxa != null) {
columnStrain = strainTaxa.getTaxonIndex(values[SERUM_STRAIN]);
} else {
columnStrain = strainNames.indexOf(values[SERUM_STRAIN]);
if (columnStrain == -1) {
strainNames.add(values[SERUM_STRAIN]);
Double date = Double.parseDouble(values[SERUM_DATE]);
strainDateMap.put(values[SERUM_STRAIN], date);
columnStrain = strainNames.size() - 1;
}
}
if (columnStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized serum strain name, " + values[SERUM_STRAIN] + ", in row " + (i+1));
}
int row = rowLabels.indexOf(values[ROW_LABEL]);
if (row == -1) {
rowLabels.add(values[ROW_LABEL]);
row = rowLabels.size() - 1;
}
int rowStrain = -1;
if (strainTaxa != null) {
rowStrain = strainTaxa.getTaxonIndex(values[VIRUS_STRAIN]);
} else {
rowStrain = strainNames.indexOf(values[VIRUS_STRAIN]);
if (rowStrain == -1) {
strainNames.add(values[VIRUS_STRAIN]);
Double date = Double.parseDouble(values[VIRUS_DATE]);
strainDateMap.put(values[VIRUS_STRAIN], date);
rowStrain = strainNames.size() - 1;
}
}
if (rowStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized virus strain name, " + values[VIRUS_STRAIN] + ", in row " + (i+1));
}
boolean isThreshold = false;
double rawTitre = Double.NaN;
if (values[TITRE].length() > 0) {
try {
rawTitre = Double.parseDouble(values[TITRE]);
} catch (NumberFormatException nfe) {
// check if threshold below
if (values[TITRE].contains("<")) {
rawTitre = Double.parseDouble(values[TITRE].replace("<",""));
isThreshold = true;
thresholdCount++;
}
// check if threshold above
if (values[TITRE].contains(">")) {
throw new IllegalArgumentException("Error in measurement: unsupported greater than threshold at row " + (i+1));
}
}
}
MeasurementType type = (isThreshold ? MeasurementType.THRESHOLD : (useIntervals ? MeasurementType.INTERVAL : MeasurementType.POINT));
Measurement measurement = new Measurement(column, columnStrain, row, rowStrain, type, rawTitre);
if (USE_THRESHOLDS || !isThreshold) {
measurements.add(measurement);
}
}
double[] maxColumnTitre = new double[columnLabels.size()];
double[] maxRowTitre = new double[rowLabels.size()];
for (Measurement measurement : measurements) {
double titre = measurement.log2Titre;
if (Double.isNaN(titre)) {
titre = measurement.log2Titre;
}
if (titre > maxColumnTitre[measurement.column]) {
maxColumnTitre[measurement.column] = titre;
}
if (titre > maxRowTitre[measurement.row]) {
maxRowTitre[measurement.row] = titre;
}
}
if (strainTaxa != null) {
this.strains = strainTaxa;
// fill in the strain name array for local use
for (int i = 0; i < strains.getTaxonCount(); i++) {
strainNames.add(strains.getTaxon(i).getId());
}
} else {
Taxa taxa = new Taxa();
for (String strain : strainNames) {
taxa.addTaxon(new Taxon(strain));
}
this.strains = taxa;
}
this.mdsDimension = mdsDimension;
this.mdsPrecisionParameter = mdsPrecisionParameter;
addVariable(mdsPrecisionParameter);
this.locationsParameter = locationsParameter;
setupLocationsParameter(this.locationsParameter, strainNames);
addVariable(this.locationsParameter);
if (datesParameter != null) {
// this parameter is not used in this class but is setup to be used in other classes
datesParameter.setDimension(strainNames.size());
String[] labelArray = new String[strainNames.size()];
strainNames.toArray(labelArray);
datesParameter.setDimensionNames(labelArray);
for (int i = 0; i < strainNames.size(); i++) {
Double date = strainDateMap.get(strainNames.get(i));
if (date == null) {
throw new IllegalArgumentException("Date missing for strain: " + strainNames.get(i));
}
datesParameter.setParameterValue(i, date);
}
}
// If no column parameter is given, make one to hold maximum values for scaling titres...
if (columnParameter == null) {
this.columnEffectsParameter = new Parameter.Default("columnEffects");
} else {
this.columnEffectsParameter = columnParameter;
this.columnEffectsParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
addVariable(this.columnEffectsParameter);
}
this.columnEffectsParameter.setDimension(columnLabels.size());
String[] labelArray = new String[columnLabels.size()];
columnLabels.toArray(labelArray);
this.columnEffectsParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxColumnTitre.length; i++) {
this.columnEffectsParameter.setParameterValueQuietly(i, maxColumnTitre[i]);
}
// If no row parameter is given, then we will only use the column effects
this.rowEffectsParameter = rowParameter;
if (this.rowEffectsParameter != null) {
this.rowEffectsParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
this.rowEffectsParameter.setDimension(rowLabels.size());
addVariable(this.rowEffectsParameter);
labelArray = new String[rowLabels.size()];
rowLabels.toArray(labelArray);
this.rowEffectsParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxRowTitre.length; i++) {
this.rowEffectsParameter.setParameterValueQuietly(i, maxRowTitre[i]);
}
}
StringBuilder sb = new StringBuilder();
sb.append("\tAntigenicLikelihood:\n");
sb.append("\t\t" + this.strains.getTaxonCount() + " strains\n");
sb.append("\t\t" + columnLabels.size() + " unique columns\n");
sb.append("\t\t" + rowLabels.size() + " unique rows\n");
sb.append("\t\t" + measurements.size() + " assay measurements\n");
if (USE_THRESHOLDS) {
sb.append("\t\t" + thresholdCount + " thresholded measurements\n");
}
if (useIntervals) {
sb.append("\n\t\tAssuming a log 2 measurement interval width of " + intervalWidth + "\n");
}
Logger.getLogger("dr.evomodel").info(sb.toString());
// initial locations
double earliestDate = datesParameter.getParameterValue(0);
for (int i=0; i<datesParameter.getDimension(); i++) {
double date = datesParameter.getParameterValue(i);
if (earliestDate > date) {
earliestDate = date;
}
}
for (int i = 0; i < locationsParameter.getParameterCount(); i++) {
String name = strainNames.get(i);
double date = (double) strainDateMap.get(strainNames.get(i));
double diff = (date-earliestDate);
locationsParameter.getParameter(i).setParameterValueQuietly(0, diff + MathUtils.nextGaussian());
for (int j = 1; j < mdsDimension; j++) {
double r = MathUtils.nextGaussian();
locationsParameter.getParameter(i).setParameterValueQuietly(j, r);
}
}
locationChanged = new boolean[this.locationsParameter.getParameterCount()];
logLikelihoods = new double[measurements.size()];
storedLogLikelihoods = new double[measurements.size()];
makeDirty();
}
protected void setupLocationsParameter(MatrixParameter locationsParameter, List<String> strains) {
locationsParameter.setColumnDimension(mdsDimension);
locationsParameter.setRowDimension(strains.size());
for (int i = 0; i < strains.size(); i++) {
locationsParameter.getParameter(i).setId(strains.get(i));
}
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
if (variable == locationsParameter) {
locationChanged[index / mdsDimension] = true;
} else if (variable == mdsPrecisionParameter) {
setLocationChangedFlags(true);
} else if (variable == columnEffectsParameter) {
setLocationChangedFlags(true);
} else if (variable == rowEffectsParameter) {
setLocationChangedFlags(true);
} else {
// could be a derived class's parameter
}
likelihoodKnown = false;
}
@Override
protected void storeState() {
System.arraycopy(logLikelihoods, 0, storedLogLikelihoods, 0, logLikelihoods.length);
}
@Override
protected void restoreState() {
double[] tmp = logLikelihoods;
logLikelihoods = storedLogLikelihoods;
storedLogLikelihoods = tmp;
likelihoodKnown = false;
}
@Override
protected void acceptState() {
}
public Model getModel() {
return this;
}
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = computeLogLikelihood();
}
return logLikelihood;
}
// This function can be overwritten to implement other sampling densities, i.e. discrete ranks
private double computeLogLikelihood() {
double precision = mdsPrecisionParameter.getParameterValue(0);
double sd = 1.0 / Math.sqrt(precision);
logLikelihood = 0.0;
int i = 0;
for (Measurement measurement : measurements) {
if (locationChanged[measurement.rowStrain] || locationChanged[measurement.columnStrain]) {
double mapDistance = computeDistance(measurement.rowStrain, measurement.columnStrain);
double logNormalization = calculateTruncationNormalization(mapDistance, sd);
switch (measurement.type) {
case INTERVAL: {
// once transformed the lower titre becomes the higher distance
double minHiDistance = transformTitre(measurement.log2Titre + 1.0, measurement.column, measurement.row);
double maxHiDistance = transformTitre(measurement.log2Titre, measurement.column, measurement.row);
logLikelihoods[i] = computeMeasurementIntervalLikelihood(minHiDistance, maxHiDistance, mapDistance, sd) - logNormalization;
} break;
case POINT: {
double hiDistance = transformTitre(measurement.log2Titre, measurement.column, measurement.row);
logLikelihoods[i] = computeMeasurementLikelihood(hiDistance, mapDistance, sd) - logNormalization;
} break;
case THRESHOLD: {
double hiDistance = transformTitre(measurement.log2Titre, measurement.column, measurement.row);
logLikelihoods[i] = computeMeasurementThresholdLikelihood(hiDistance, mapDistance, sd) - logNormalization;
} break;
case MISSING:
break;
}
}
logLikelihood += logLikelihoods[i];
i++;
}
likelihoodKnown = true;
setLocationChangedFlags(false);
return logLikelihood;
}
private void setLocationChangedFlags(boolean flag) {
for (int i = 0; i < locationChanged.length; i++) {
locationChanged[i] = flag;
}
}
protected double computeDistance(int rowStrain, int columnStrain) {
if (rowStrain == columnStrain) {
return 0.0;
}
Parameter X = locationsParameter.getParameter(rowStrain);
Parameter Y = locationsParameter.getParameter(columnStrain);
double sum = 0.0;
for (int i = 0; i < mdsDimension; i++) {
double difference = X.getParameterValue(i) - Y.getParameterValue(i);
sum += difference * difference;
}
return Math.sqrt(sum);
}
/**
* Transforms a titre into log2 space and normalizes it with respect to a unit normal
* @param titre
* @param column
* @param row
* @return
*/
private double transformTitre(double titre, int column, int row) {
double t;
double columnEffect = columnEffectsParameter.getParameterValue(column);
if (rowEffectsParameter != null) {
double rowEffect = rowEffectsParameter.getParameterValue(row);
t = ((rowEffect + columnEffect) * 0.5) - titre;
} else {
t = columnEffect - titre;
}
return t;
}
private static double computeMeasurementIntervalLikelihood(double minDistance, double maxDistance, double mean, double sd) {
double cdf1 = NormalDistribution.cdf(minDistance, mean, sd, false);
double cdf2 = NormalDistribution.cdf(maxDistance, mean, sd, false);
double lnL = Math.log(cdf2 - cdf1);
if (cdf1 == cdf2) {
lnL = Math.log(cdf1);
}
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double computeMeasurementIntervalLikelihood_CDF(double minDistance, double maxDistance, double mean, double sd) {
double cdf1 = NormalDistribution.cdf(minDistance, mean, sd, false);
double cdf2 = NormalDistribution.cdf(maxDistance, mean, sd, false);
double lnL = Math.log(cdf1 - cdf2);
if (cdf1 == cdf2) {
lnL = Math.log(cdf1);
}
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double computeMeasurementLikelihood(double distance, double mean, double sd) {
double lnL = NormalDistribution.logPdf(distance, mean, sd);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
// private static double computeMeasurementLowerBoundLikelihood(double transformedMinTitre) {
// // a lower bound in non-transformed titre so the bottom tail of the distribution
// double cdf = NormalDistribution.standardTail(transformedMinTitre, false);
// double lnL = Math.log(cdf);
// if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
// throw new RuntimeException("infinite");
// return lnL;
private static double computeMeasurementThresholdLikelihood(double distance, double mean, double sd) {
// a upper bound in non-transformed titre so the upper tail of the distribution
// using special tail function of NormalDistribution (see main() in NormalDistribution for test)
double tail = NormalDistribution.tailCDF(distance, mean, sd);
double lnL = Math.log(tail);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double calculateTruncationNormalization(double distance, double sd) {
return NormalDistribution.cdf(distance, 0.0, sd, true);
}
public void makeDirty() {
likelihoodKnown = false;
setLocationChangedFlags(true);
}
private class Measurement {
private Measurement(final int column, final int columnStrain, final int row, final int rowStrain, final MeasurementType type, final double titre) {
this.column = column;
this.columnStrain = columnStrain;
this.row = row;
this.rowStrain = rowStrain;
this.type = type;
this.log2Titre = Math.log(titre) / Math.log(2);
}
final int column;
final int row;
final int columnStrain;
final int rowStrain;
final MeasurementType type;
final double log2Titre;
};
private final List<Measurement> measurements = new ArrayList<Measurement>();
private final List<String> columnLabels = new ArrayList<String>();
private final List<String> rowLabels = new ArrayList<String>();
private final int mdsDimension;
private final double intervalWidth;
private final Parameter mdsPrecisionParameter;
private final MatrixParameter locationsParameter;
private final TaxonList strains;
// private final CompoundParameter tipTraitParameter;
private final Parameter columnEffectsParameter;
private final Parameter rowEffectsParameter;
private double logLikelihood = 0.0;
private boolean likelihoodKnown = false;
private final boolean[] locationChanged;
private double[] logLikelihoods;
private double[] storedLogLikelihoods;
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String FILE_NAME = "fileName";
public final static String TIP_TRAIT = "tipTrait";
public final static String LOCATIONS = "locations";
public final static String DATES = "dates";
public static final String MDS_DIMENSION = "mdsDimension";
public static final String INTERVAL_WIDTH = "intervalWidth";
public static final String MDS_PRECISION = "mdsPrecision";
public static final String COLUMN_EFFECTS = "columnEffects";
public static final String ROW_EFFECTS = "rowEffects";
public static final String STRAINS = "strains";
public String getParserName() {
return ANTIGENIC_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FILE_NAME);
DataTable<String[]> assayTable;
try {
assayTable = DataTable.Text.parse(new FileReader(fileName), true, false);
} catch (IOException e) {
throw new XMLParseException("Unable to read assay data from file: " + e.getMessage());
}
System.out.println("Loaded HI table file: " + fileName);
int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION);
double intervalWidth = 0.0;
if (xo.hasAttribute(INTERVAL_WIDTH)) {
intervalWidth = xo.getDoubleAttribute(INTERVAL_WIDTH);
}
// CompoundParameter tipTraitParameter = null;
// if (xo.hasChildNamed(TIP_TRAIT)) {
// tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
TaxonList strains = null;
if (xo.hasChildNamed(STRAINS)) {
strains = (TaxonList) xo.getElementFirstChild(STRAINS);
}
MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
Parameter datesParameter = null;
if (xo.hasChildNamed(DATES)) {
datesParameter = (Parameter) xo.getElementFirstChild(DATES);
}
Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION);
Parameter columnEffectsParameter = null;
if (xo.hasChildNamed(COLUMN_EFFECTS)) {
columnEffectsParameter = (Parameter) xo.getElementFirstChild(COLUMN_EFFECTS);
}
Parameter rowEffectsParameter = null;
if (xo.hasChildNamed(ROW_EFFECTS)) {
rowEffectsParameter = (Parameter) xo.getElementFirstChild(ROW_EFFECTS);
}
AntigenicLikelihood AGL = new AntigenicLikelihood(
mdsDimension,
mdsPrecision,
strains,
locationsParameter,
datesParameter,
columnEffectsParameter,
rowEffectsParameter,
assayTable,
intervalWidth,
null);
Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL));
return AGL;
} |
package replicant;
import javax.annotation.Nonnull;
import org.realityforge.braincheck.BrainCheckConfig;
import static org.realityforge.braincheck.Guards.*;
/**
* Provide access to global configuration settings.
*/
public final class Replicant
{
private Replicant()
{
}
/**
* Return true if zones are enabled, false otherwise.
*
* @return true if zones are enabled, false otherwise.
*/
public static boolean areZonesEnabled()
{
return ReplicantConfig.areZonesEnabled();
}
/**
* Return true if invariants will be checked.
*
* @return true if invariants will be checked.
*/
public static boolean shouldCheckInvariants()
{
return ReplicantConfig.checkInvariants() && BrainCheckConfig.checkInvariants();
}
/**
* Return true if apiInvariants will be checked.
*
* @return true if apiInvariants will be checked.
*/
public static boolean shouldCheckApiInvariants()
{
return ReplicantConfig.checkApiInvariants() && BrainCheckConfig.checkApiInvariants();
}
/**
* Return true if should record key when tracking requests through the system, false otherwise.
*
* @return true if should record key when tracking requests through the system, false otherwise.
*/
public static boolean shouldRecordRequestKey()
{
return ReplicantConfig.shouldRecordRequestKey();
}
/**
* Return true if a data load action should result in the local entity state being validated, false otherwise.
*
* @return true if a data load action should result in the local entity state being validated, false otherwise.
*/
public static boolean shouldValidateRepositoryOnLoad()
{
return shouldCheckInvariants() && ReplicantConfig.shouldValidateRepositoryOnLoad();
}
/**
* Return true if request debugging can be enabled at runtime, false otherwise.
*
* @return true if request debugging can be enabled at runtime, false otherwise.
*/
public static boolean canRequestsDebugOutputBeEnabled()
{
return ReplicantConfig.canRequestsDebugOutputBeEnabled();
}
/**
* Return true if subscription debugging can be enabled at runtime, false otherwise.
*
* @return true if subscription debugging can be enabled at runtime, false otherwise.
*/
public static boolean canSubscriptionsDebugOutputBeEnabled()
{
return ReplicantConfig.canSubscriptionsDebugOutputBeEnabled();
}
/**
* Return the ReplicantContext from the provider.
*
* @return the ReplicantContext.
*/
@Nonnull
public static ReplicantContext context()
{
return areZonesEnabled() ? ReplicantZoneHolder.context() : ReplicantContextHolder.context();
}
/**
* Create a new zone.
* This zone is not yet activated.
*
* @return the new zone.
*/
@Nonnull
public static Zone createZone()
{
if ( shouldCheckApiInvariants() )
{
apiInvariant( Replicant::areZonesEnabled,
() -> "Replicant-0001: Invoked Replicant.createZone() but zones are not enabled." );
}
return new Zone();
}
/**
* Save the old zone and make the specified zone the current zone.
*/
@SuppressWarnings( "ConstantConditions" )
static void activateZone( @Nonnull final Zone zone )
{
ReplicantZoneHolder.activateZone( zone );
}
/**
* Restore the old zone.
* This takes the zone that was current when {@link #activateZone(Zone)} was called for the active zone
* and restores it to being the current zone.
*/
@SuppressWarnings( "ConstantConditions" )
static void deactivateZone( @Nonnull final Zone zone )
{
ReplicantZoneHolder.deactivateZone( zone );
}
/**
* Return the current zone.
*
* @return the current zone.
*/
@Nonnull
static Zone currentZone()
{
return ReplicantZoneHolder.currentZone();
}
} |
package dr.evomodel.antigenic;
import dr.evolution.util.*;
import dr.inference.model.*;
import dr.math.MathUtils;
import dr.math.distributions.NormalDistribution;
import dr.util.*;
import dr.xml.*;
import java.io.*;
import java.util.*;
import java.util.logging.Logger;
/**
* @author Andrew Rambaut
* @author Trevor Bedford
* @author Marc Suchard
* @version $Id$
*/
public class AntigenicLikelihood extends AbstractModelLikelihood implements Citable {
public final static boolean CHECK_INFINITE = false;
public final static String ANTIGENIC_LIKELIHOOD = "antigenicLikelihood";
// column indices in table
private static final int COLUMN_LABEL = 0;
private static final int SERUM_STRAIN = 2;
private static final int ROW_LABEL = 1;
private static final int VIRUS_STRAIN = 3;
private static final int SERUM_DATE = 4;
private static final int VIRUS_DATE = 5;
private static final int TITRE = 6;
public enum MeasurementType {
INTERVAL,
POINT,
THRESHOLD,
MISSING
}
public AntigenicLikelihood(
int mdsDimension,
Parameter mdsPrecisionParameter,
TaxonList strainTaxa,
MatrixParameter locationsParameter,
Parameter datesParameter,
Parameter columnParameter,
Parameter rowParameter,
DataTable<String[]> dataTable,
double intervalWidth,
List<String> virusLocationStatisticList) {
super(ANTIGENIC_LIKELIHOOD);
List<String> strainNames = new ArrayList<String>();
Map<String, Double> strainDateMap = new HashMap<String, Double>();
this.intervalWidth = intervalWidth;
boolean useIntervals = intervalWidth > 0.0;
int thresholdCount = 0;
for (int i = 0; i < dataTable.getRowCount(); i++) {
String[] values = dataTable.getRow(i);
int column = columnLabels.indexOf(values[COLUMN_LABEL]);
if (column == -1) {
columnLabels.add(values[0]);
column = columnLabels.size() - 1;
}
int columnStrain = -1;
if (strainTaxa != null) {
columnStrain = strainTaxa.getTaxonIndex(values[SERUM_STRAIN]);
} else {
columnStrain = strainNames.indexOf(values[SERUM_STRAIN]);
if (columnStrain == -1) {
strainNames.add(values[SERUM_STRAIN]);
Double date = Double.parseDouble(values[VIRUS_DATE]);
strainDateMap.put(values[SERUM_STRAIN], date);
columnStrain = strainNames.size() - 1;
}
}
if (columnStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized serum strain name, " + values[SERUM_STRAIN] + ", in row " + (i+1));
}
int row = rowLabels.indexOf(values[ROW_LABEL]);
if (row == -1) {
rowLabels.add(values[ROW_LABEL]);
row = rowLabels.size() - 1;
}
int rowStrain = -1;
if (strainTaxa != null) {
rowStrain = strainTaxa.getTaxonIndex(values[VIRUS_STRAIN]);
} else {
rowStrain = strainNames.indexOf(values[VIRUS_STRAIN]);
if (rowStrain == -1) {
strainNames.add(values[VIRUS_STRAIN]);
Double date = Double.parseDouble(values[VIRUS_DATE]);
strainDateMap.put(values[VIRUS_STRAIN], date);
rowStrain = strainNames.size() - 1;
}
}
if (rowStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized virus strain name, " + values[VIRUS_STRAIN] + ", in row " + (i+1));
}
boolean isThreshold = false;
double rawTitre = Double.NaN;
if (values[TITRE].length() > 0) {
try {
rawTitre = Double.parseDouble(values[TITRE]);
} catch (NumberFormatException nfe) {
// check if threshold below
if (values[TITRE].contains("<")) {
rawTitre = Double.parseDouble(values[TITRE].replace("<",""));
isThreshold = true;
thresholdCount++;
}
// check if threshold above
if (values[TITRE].contains(">")) {
throw new IllegalArgumentException("Error in measurement: unsupported greater than threshold at row " + (i+1));
}
}
}
MeasurementType type = (isThreshold ? MeasurementType.THRESHOLD : (useIntervals ? MeasurementType.INTERVAL : MeasurementType.POINT));
Measurement measurement = new Measurement(column, columnStrain, row, rowStrain, type, rawTitre);
measurements.add(measurement);
}
double[] maxColumnTitre = new double[columnLabels.size()];
double[] maxRowTitre = new double[rowLabels.size()];
for (Measurement measurement : measurements) {
double titre = measurement.log2Titre;
if (Double.isNaN(titre)) {
titre = measurement.log2Titre;
}
if (titre > maxColumnTitre[measurement.column]) {
maxColumnTitre[measurement.column] = titre;
}
if (titre > maxRowTitre[measurement.row]) {
maxRowTitre[measurement.row] = titre;
}
}
if (strainTaxa != null) {
this.strains = strainTaxa;
// fill in the strain name array for local use
for (int i = 0; i < strains.getTaxonCount(); i++) {
strainNames.add(strains.getTaxon(i).getId());
}
} else {
Taxa taxa = new Taxa();
for (String strain : strainNames) {
taxa.addTaxon(new Taxon(strain));
}
this.strains = taxa;
}
this.mdsDimension = mdsDimension;
this.mdsPrecisionParameter = mdsPrecisionParameter;
addVariable(mdsPrecisionParameter);
this.locationsParameter = locationsParameter;
setupLocationsParameter(this.locationsParameter, strainNames);
addVariable(this.locationsParameter);
if (datesParameter != null) {
// this parameter is not used in this class but is setup to be used in other classes
datesParameter.setDimension(strainNames.size());
String[] labelArray = new String[strainNames.size()];
strainNames.toArray(labelArray);
datesParameter.setDimensionNames(labelArray);
for (int i = 0; i < strainNames.size(); i++) {
Double date = strainDateMap.get(strainNames.get(i));
if (date == null) {
throw new IllegalArgumentException("Date missing for strain: " + strainNames.get(i));
}
datesParameter.setParameterValue(i, date);
}
}
// If no column parameter is given, make one to hold maximum values for scaling titres...
if (columnParameter == null) {
this.columnEffectsParameter = new Parameter.Default("columnEffects");
} else {
this.columnEffectsParameter = columnParameter;
}
this.columnEffectsParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
this.columnEffectsParameter.setDimension(columnLabels.size());
addVariable(this.columnEffectsParameter);
String[] labelArray = new String[columnLabels.size()];
columnLabels.toArray(labelArray);
this.columnEffectsParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxColumnTitre.length; i++) {
this.columnEffectsParameter.setParameterValueQuietly(i, maxColumnTitre[i]);
}
// If no row parameter is given, then we will only use the column effects
this.rowEffectsParameter = rowParameter;
if (this.rowEffectsParameter != null) {
this.rowEffectsParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
this.rowEffectsParameter.setDimension(rowLabels.size());
addVariable(this.rowEffectsParameter);
labelArray = new String[rowLabels.size()];
rowLabels.toArray(labelArray);
this.rowEffectsParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxRowTitre.length; i++) {
this.rowEffectsParameter.setParameterValueQuietly(i, maxRowTitre[i]);
}
}
StringBuilder sb = new StringBuilder();
sb.append("\tAntigenicLikelihood:\n");
sb.append("\t\t" + this.strains.getTaxonCount() + " strains\n");
sb.append("\t\t" + columnLabels.size() + " unique columns\n");
sb.append("\t\t" + rowLabels.size() + " unique rows\n");
sb.append("\t\t" + measurements.size() + " assay measurements\n");
sb.append("\t\t" + thresholdCount + " thresholded measurements\n");
if (useIntervals) {
sb.append("\n\t\tAssuming a log 2 measurement interval width of " + intervalWidth + "\n");
}
Logger.getLogger("dr.evomodel").info(sb.toString());
// initial locations
double earliestDate = datesParameter.getParameterValue(0);
for (int i=0; i<datesParameter.getDimension(); i++) {
double date = datesParameter.getParameterValue(i);
if (earliestDate > date) {
earliestDate = date;
}
}
for (int i = 0; i < locationsParameter.getParameterCount(); i++) {
String name = strainNames.get(i);
double date = (double) strainDateMap.get(strainNames.get(i));
double diff = (date-earliestDate);
locationsParameter.getParameter(i).setParameterValueQuietly(0, diff + MathUtils.nextGaussian());
for (int j = 1; j < mdsDimension; j++) {
double r = MathUtils.nextGaussian();
locationsParameter.getParameter(i).setParameterValueQuietly(j, r);
}
}
locationChanged = new boolean[this.locationsParameter.getParameterCount()];
logLikelihoods = new double[measurements.size()];
storedLogLikelihoods = new double[measurements.size()];
makeDirty();
}
protected void setupLocationsParameter(MatrixParameter locationsParameter, List<String> strains) {
locationsParameter.setColumnDimension(mdsDimension);
locationsParameter.setRowDimension(strains.size());
for (int i = 0; i < strains.size(); i++) {
locationsParameter.getParameter(i).setId(strains.get(i));
}
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
if (variable == locationsParameter) {
locationChanged[index / mdsDimension] = true;
} else if (variable == mdsPrecisionParameter) {
setLocationChangedFlags(true);
} else if (variable == columnEffectsParameter) {
setLocationChangedFlags(true);
} else if (variable == rowEffectsParameter) {
setLocationChangedFlags(true);
} else {
// could be a derived class's parameter
}
likelihoodKnown = false;
}
@Override
protected void storeState() {
System.arraycopy(logLikelihoods, 0, storedLogLikelihoods, 0, logLikelihoods.length);
}
@Override
protected void restoreState() {
double[] tmp = logLikelihoods;
logLikelihoods = storedLogLikelihoods;
storedLogLikelihoods = tmp;
likelihoodKnown = false;
}
@Override
protected void acceptState() {
}
@Override
public Model getModel() {
return this;
}
@Override
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = computeLogLikelihood();
}
return logLikelihood;
}
// This function can be overwritten to implement other sampling densities, i.e. discrete ranks
private double computeLogLikelihood() {
double precision = mdsPrecisionParameter.getParameterValue(0);
double sd = 1.0 / Math.sqrt(precision);
logLikelihood = 0.0;
int i = 0;
for (Measurement measurement : measurements) {
if (locationChanged[measurement.rowStrain] || locationChanged[measurement.columnStrain]) {
double distance = computeDistance(measurement.rowStrain, measurement.columnStrain);
double logNormalization = calculateTruncationNormalization(distance, sd);
switch (measurement.type) {
case INTERVAL: {
double minTitre = transformTitre(measurement.log2Titre, measurement.column, measurement.row, distance, sd);
double maxTitre = transformTitre(measurement.log2Titre + 1.0, measurement.column, measurement.row, distance, sd);
logLikelihoods[i] = computeMeasurementIntervalLikelihood(minTitre, maxTitre) - logNormalization;
} break;
case POINT: {
double titre = transformTitre(measurement.log2Titre, measurement.column, measurement.row, distance, sd);
logLikelihoods[i] = computeMeasurementLikelihood(titre) - logNormalization;
} break;
case THRESHOLD: {
double maxTitre = transformTitre(measurement.log2Titre, measurement.column, measurement.row, distance, sd);
logLikelihoods[i] = computeMeasurementThresholdLikelihood(maxTitre) - logNormalization;
} break;
case MISSING:
break;
}
}
logLikelihood += logLikelihoods[i];
i++;
}
likelihoodKnown = true;
setLocationChangedFlags(false);
return logLikelihood;
}
private void setLocationChangedFlags(boolean flag) {
for (int i = 0; i < locationChanged.length; i++) {
locationChanged[i] = flag;
}
}
protected double computeDistance(int rowStrain, int columnStrain) {
if (rowStrain == columnStrain) {
return 0.0;
}
Parameter X = locationsParameter.getParameter(rowStrain);
Parameter Y = locationsParameter.getParameter(columnStrain);
double sum = 0.0;
for (int i = 0; i < mdsDimension; i++) {
double difference = X.getParameterValue(i) - Y.getParameterValue(i);
sum += difference * difference;
}
return Math.sqrt(sum);
}
/**
* Transforms a titre into log2 space and normalizes it with respect to a unit normal
* @param titre
* @param column
* @param row
* @param mean
* @param sd
* @return
*/
private double transformTitre(double titre, int column, int row, double mean, double sd) {
double t;
double columnEffect = columnEffectsParameter.getParameterValue(column);
if (rowEffectsParameter != null) {
double rowEffect = rowEffectsParameter.getParameterValue(row);
t = ((rowEffect + columnEffect) * 0.5) - titre;
} else {
t = columnEffect - titre;
}
return (t - mean) / sd;
}
private static double computeMeasurementIntervalLikelihood_CDF(double minTitre, double maxTitre) {
// once transformed, the minTitre will be the greater value
double cdf1 = NormalDistribution.standardCDF(minTitre, false);
double cdf2 = NormalDistribution.standardCDF(maxTitre, false);
double lnL = Math.log(cdf1 - cdf2);
if (cdf1 == cdf2) {
lnL = Math.log(cdf1);
}
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double computeMeasurementIntervalLikelihood(double minTitre, double maxTitre) {
// once transformed, the minTitre will be the greater value
double cdf1 = NormalDistribution.standardTail(minTitre, true);
double cdf2 = NormalDistribution.standardTail(maxTitre, true);
double lnL = Math.log(cdf2 - cdf1);
if (cdf1 == cdf2) {
lnL = Math.log(cdf1);
}
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double computeMeasurementLikelihood(double titre) {
double lnL = NormalDistribution.logPdf(titre, 0.0, 1.0);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
// private static double computeMeasurementLowerBoundLikelihood(double transformedMinTitre) {
// // a lower bound in non-transformed titre so the bottom tail of the distribution
// double cdf = NormalDistribution.standardTail(transformedMinTitre, false);
// double lnL = Math.log(cdf);
// if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
// throw new RuntimeException("infinite");
// return lnL;
private static double computeMeasurementThresholdLikelihood(double transformedMaxTitre) {
// a upper bound in non-transformed titre so the upper tail of the distribution
// using special tail function of NormalDistribution (see main() in NormalDistribution for test)
double tail = NormalDistribution.standardTail(transformedMaxTitre, true);
double lnL = Math.log(tail);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double calculateTruncationNormalization(double distance, double sd) {
return NormalDistribution.cdf(distance, 0.0, sd, true);
}
@Override
public void makeDirty() {
likelihoodKnown = false;
setLocationChangedFlags(true);
}
private class Measurement {
private Measurement(final int column, final int columnStrain, final int row, final int rowStrain, final MeasurementType type, final double titre) {
this.column = column;
this.columnStrain = columnStrain;
this.row = row;
this.rowStrain = rowStrain;
this.type = type;
this.log2Titre = Math.log(titre) / Math.log(2);
}
final int column;
final int row;
final int columnStrain;
final int rowStrain;
final MeasurementType type;
final double log2Titre;
};
private final List<Measurement> measurements = new ArrayList<Measurement>();
private final List<String> columnLabels = new ArrayList<String>();
private final List<String> rowLabels = new ArrayList<String>();
private final int mdsDimension;
private final double intervalWidth;
private final Parameter mdsPrecisionParameter;
private final MatrixParameter locationsParameter;
private final TaxonList strains;
// private final CompoundParameter tipTraitParameter;
private final Parameter columnEffectsParameter;
private final Parameter rowEffectsParameter;
private double logLikelihood = 0.0;
private boolean likelihoodKnown = false;
private final boolean[] locationChanged;
private double[] logLikelihoods;
private double[] storedLogLikelihoods;
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String FILE_NAME = "fileName";
public final static String TIP_TRAIT = "tipTrait";
public final static String LOCATIONS = "locations";
public final static String DATES = "dates";
public static final String MDS_DIMENSION = "mdsDimension";
public static final String INTERVAL_WIDTH = "intervalWidth";
public static final String MDS_PRECISION = "mdsPrecision";
public static final String COLUMN_EFFECTS = "columnEffects";
public static final String ROW_EFFECTS = "rowEffects";
public static final String STRAINS = "strains";
public String getParserName() {
return ANTIGENIC_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FILE_NAME);
DataTable<String[]> assayTable;
try {
assayTable = DataTable.Text.parse(new FileReader(fileName), true, false);
} catch (IOException e) {
throw new XMLParseException("Unable to read assay data from file: " + e.getMessage());
}
int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION);
double intervalWidth = 0.0;
if (xo.hasAttribute(INTERVAL_WIDTH)) {
intervalWidth = xo.getDoubleAttribute(INTERVAL_WIDTH);
}
// CompoundParameter tipTraitParameter = null;
// if (xo.hasChildNamed(TIP_TRAIT)) {
// tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
TaxonList strains = null;
if (xo.hasChildNamed(STRAINS)) {
strains = (TaxonList) xo.getElementFirstChild(STRAINS);
}
MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
Parameter datesParameter = null;
if (xo.hasChildNamed(DATES)) {
datesParameter = (Parameter) xo.getElementFirstChild(DATES);
}
Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION);
Parameter columnEffectsParameter = (Parameter) xo.getElementFirstChild(COLUMN_EFFECTS);
Parameter rowEffectsParameter = (Parameter) xo.getElementFirstChild(ROW_EFFECTS);
AntigenicLikelihood AGL = new AntigenicLikelihood(
mdsDimension,
mdsPrecision,
strains,
locationsParameter,
datesParameter,
columnEffectsParameter,
rowEffectsParameter,
assayTable,
intervalWidth,
null);
Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL));
return AGL;
} |
package org.fxmisc.richtext;
import java.util.regex.Pattern;
// For multi-character line terminators, it is important that any subsequence
// is also a valid line terminator, because we support splicing text at any
// position, even within line terminators.
public enum LineTerminator {
CR("\r"),
LF("\n"),
CRLF("\r\n");
public static LineTerminator from(String s) {
for(LineTerminator t: values()) {
if(t.asString().equals(s)) {
return t;
}
}
throw new IllegalArgumentException("Not a line terminator: " + s);
}
public static boolean isLineTerminatorChar(char c) {
return c == '\r' || c == '\n';
}
private static final Pattern regex = Pattern.compile("\r\n|\r|\n");
public static Pattern regex() {
return regex;
}
private final String s;
private LineTerminator(String s) {
this.s = s;
}
public String asString() { return s; }
public int length() { return s.length(); }
public LineTerminator trim(int length) {
return from(s.substring(0, length));
}
public LineTerminator subSequence(int start) {
return from(s.substring(start));
}
} |
package org.klomp.snark;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import net.i2p.crypto.SHA1;
/**
* Maintains pieces on disk. Can be used to store and retrieve pieces.
*/
public class Storage
{
private MetaInfo metainfo;
private long[] lengths;
private RandomAccessFile[] rafs;
private String[] names;
private Object[] RAFlock; // lock on RAF access
private long[] RAFtime; // when was RAF last accessed, or 0 if closed
private File[] RAFfile; // File to make it easier to reopen
/** priorities by file; default 0; may be null. @since 0.8.1 */
private int[] priorities;
private final StorageListener listener;
private I2PSnarkUtil _util;
private /* FIXME final FIXME */ BitField bitfield; // BitField to represent the pieces
private int needed; // Number of pieces needed
private boolean _probablyComplete; // use this to decide whether to open files RO
// XXX - Not always set correctly
int piece_size;
int pieces;
boolean changed;
/** The default piece size. */
private static final int MIN_PIECE_SIZE = 256*1024;
/** note that we start reducing max number of peer connections above 1MB */
public static final int MAX_PIECE_SIZE = 2*1024*1024;
/** The maximum number of pieces in a torrent. */
public static final int MAX_PIECES = 10*1024;
public static final long MAX_TOTAL_SIZE = MAX_PIECE_SIZE * (long) MAX_PIECES;
/**
* Creates a new storage based on the supplied MetaInfo. This will
* try to create and/or check all needed files in the MetaInfo.
*
* @exception IOException when creating and/or checking files fails.
*/
public Storage(I2PSnarkUtil util, MetaInfo metainfo, StorageListener listener)
throws IOException
{
_util = util;
this.metainfo = metainfo;
this.listener = listener;
needed = metainfo.getPieces();
_probablyComplete = false;
bitfield = new BitField(needed);
}
/**
* Creates a storage from the existing file or directory together
* with an appropriate MetaInfo file as can be announced on the
* given announce String location.
*/
public Storage(I2PSnarkUtil util, File baseFile, String announce, StorageListener listener)
throws IOException
{
_util = util;
this.listener = listener;
// Create names, rafs and lengths arrays.
getFiles(baseFile);
long total = 0;
ArrayList lengthsList = new ArrayList();
for (int i = 0; i < lengths.length; i++)
{
long length = lengths[i];
total += length;
lengthsList.add(new Long(length));
}
piece_size = MIN_PIECE_SIZE;
pieces = (int) ((total - 1)/piece_size) + 1;
while (pieces > MAX_PIECES && piece_size < MAX_PIECE_SIZE)
{
piece_size = piece_size*2;
pieces = (int) ((total - 1)/piece_size) +1;
}
// Note that piece_hashes and the bitfield will be filled after
// the MetaInfo is created.
byte[] piece_hashes = new byte[20*pieces];
bitfield = new BitField(pieces);
needed = 0;
List files = new ArrayList();
for (int i = 0; i < names.length; i++)
{
List file = new ArrayList();
StringTokenizer st = new StringTokenizer(names[i], File.separator);
while (st.hasMoreTokens())
{
String part = st.nextToken();
file.add(part);
}
files.add(file);
}
if (files.size() == 1) // FIXME: ...and if base file not a directory or should this be the only check?
// this makes a bad metainfo if the directory has only one file in it
{
files = null;
lengthsList = null;
}
// Note that the piece_hashes are not correctly setup yet.
metainfo = new MetaInfo(announce, baseFile.getName(), null, files,
lengthsList, piece_size, piece_hashes, total);
}
// Creates piece hashes for a new storage.
// This does NOT create the files, just the hashes
public void create() throws IOException
{
// if (true) {
fast_digestCreate();
// } else {
// orig_digestCreate();
}
/*
private void orig_digestCreate() throws IOException {
// Calculate piece_hashes
MessageDigest digest = null;
try
{
digest = MessageDigest.getInstance("SHA");
}
catch(NoSuchAlgorithmException nsa)
{
throw new InternalError(nsa.toString());
}
byte[] piece_hashes = metainfo.getPieceHashes();
byte[] piece = new byte[piece_size];
for (int i = 0; i < pieces; i++)
{
int length = getUncheckedPiece(i, piece);
digest.update(piece, 0, length);
byte[] hash = digest.digest();
for (int j = 0; j < 20; j++)
piece_hashes[20 * i + j] = hash[j];
bitfield.set(i);
if (listener != null)
listener.storageChecked(this, i, true);
}
if (listener != null)
listener.storageAllChecked(this);
// Reannounce to force recalculating the info_hash.
metainfo = metainfo.reannounce(metainfo.getAnnounce());
}
*/
/** FIXME we can run out of fd's doing this,
* maybe some sort of global close-RAF-right-away flag
* would do the trick */
private void fast_digestCreate() throws IOException {
// Calculate piece_hashes
SHA1 digest = new SHA1();
byte[] piece_hashes = metainfo.getPieceHashes();
byte[] piece = new byte[piece_size];
for (int i = 0; i < pieces; i++)
{
int length = getUncheckedPiece(i, piece);
digest.update(piece, 0, length);
byte[] hash = digest.digest();
for (int j = 0; j < 20; j++)
piece_hashes[20 * i + j] = hash[j];
bitfield.set(i);
}
// Reannounce to force recalculating the info_hash.
metainfo = metainfo.reannounce(metainfo.getAnnounce());
}
private void getFiles(File base) throws IOException
{
ArrayList files = new ArrayList();
addFiles(files, base);
int size = files.size();
names = new String[size];
lengths = new long[size];
rafs = new RandomAccessFile[size];
RAFlock = new Object[size];
RAFtime = new long[size];
RAFfile = new File[size];
priorities = new int[size];
int i = 0;
Iterator it = files.iterator();
while (it.hasNext())
{
File f = (File)it.next();
names[i] = f.getPath();
if (base.isDirectory() && names[i].startsWith(base.getPath()))
names[i] = names[i].substring(base.getPath().length() + 1);
lengths[i] = f.length();
RAFlock[i] = new Object();
RAFfile[i] = f;
i++;
}
}
private void addFiles(List l, File f)
{
if (!f.isDirectory())
l.add(f);
else
{
File[] files = f.listFiles();
if (files == null)
{
_util.debug("WARNING: Skipping '" + f
+ "' not a normal file.", Snark.WARNING);
return;
}
for (int i = 0; i < files.length; i++)
addFiles(l, files[i]);
}
}
/**
* Returns the MetaInfo associated with this Storage.
*/
public MetaInfo getMetaInfo()
{
return metainfo;
}
/**
* How many pieces are still missing from this storage.
*/
public int needed()
{
return needed;
}
/**
* Whether or not this storage contains all pieces if the MetaInfo.
*/
public boolean complete()
{
return needed == 0;
}
/**
* @param file canonical path (non-directory)
* @return number of bytes remaining; -1 if unknown file
* @since 0.7.14
*/
public long remaining(String file) {
long bytes = 0;
for (int i = 0; i < rafs.length; i++) {
File f = RAFfile[i];
// use canonical in case snark dir or sub dirs are symlinked
String canonical = null;
if (f != null) {
try {
canonical = f.getCanonicalPath();
} catch (IOException ioe) {
f = null;
}
}
if (f != null && canonical.equals(file)) {
if (complete())
return 0;
int psz = metainfo.getPieceLength(0);
long start = bytes;
long end = start + lengths[i];
int pc = (int) (bytes / psz);
long rv = 0;
if (!bitfield.get(pc))
rv = Math.min(psz - (start % psz), lengths[i]);
int pieces = metainfo.getPieces();
for (int j = pc + 1; (((long)j) * psz) < end && j < pieces; j++) {
if (!bitfield.get(j)) {
if (((long)(j+1))*psz < end)
rv += psz;
else
rv += end - (((long)j) * psz);
}
}
return rv;
}
bytes += lengths[i];
}
return -1;
}
/**
* @param file canonical path (non-directory)
* @since 0.8.1
*/
public int getPriority(String file) {
if (complete() || metainfo.getFiles() == null || priorities == null)
return 0;
for (int i = 0; i < rafs.length; i++) {
File f = RAFfile[i];
// use canonical in case snark dir or sub dirs are symlinked
if (f != null) {
try {
String canonical = f.getCanonicalPath();
if (canonical.equals(file))
return priorities[i];
} catch (IOException ioe) {}
}
}
return 0;
}
/**
* Must call setPiecePriorities() after calling this
* @param file canonical path (non-directory)
* @param priority default 0; <0 to disable
* @since 0.8.1
*/
public void setPriority(String file, int pri) {
if (complete() || metainfo.getFiles() == null || priorities == null)
return;
for (int i = 0; i < rafs.length; i++) {
File f = RAFfile[i];
// use canonical in case snark dir or sub dirs are symlinked
if (f != null) {
try {
String canonical = f.getCanonicalPath();
if (canonical.equals(file)) {
priorities[i] = pri;
return;
}
} catch (IOException ioe) {}
}
}
}
/**
* Get the file priorities array.
* @return null on error, if complete, or if only one file
* @since 0.8.1
*/
public int[] getFilePriorities() {
return priorities;
}
/**
* Set the file priorities array.
* Only call this when stopped, but after check()
* @param p may be null
* @since 0.8.1
*/
void setFilePriorities(int[] p) {
priorities = p;
}
/**
* Call setPriority() for all changed files first,
* then call this.
* Set the piece priority to the highest priority
* of all files spanning the piece.
* Caller must pass array to the PeerCoordinator.
* @return null on error, if complete, or if only one file
* @since 0.8.1
*/
public int[] getPiecePriorities() {
if (complete() || metainfo.getFiles() == null || priorities == null)
return null;
int[] rv = new int[metainfo.getPieces()];
int file = 0;
long pcEnd = -1;
long fileEnd = lengths[0] - 1;
int psz = metainfo.getPieceLength(0);
for (int i = 0; i < rv.length; i++) {
pcEnd += psz;
int pri = priorities[file];
while (fileEnd <= pcEnd && file < lengths.length - 1) {
file++;
long oldFileEnd = fileEnd;
fileEnd += lengths[file];
if (priorities[file] > pri && oldFileEnd < pcEnd)
pri = priorities[file];
}
rv[i] = pri;
}
return rv;
}
/**
* The BitField that tells which pieces this storage contains.
* Do not change this since this is the current state of the storage.
*/
public BitField getBitField()
{
return bitfield;
}
public String getBaseName() {
return filterName(metainfo.getName());
}
/**
* Creates (and/or checks) all files from the metainfo file list.
*/
public void check(String rootDir) throws IOException
{
check(rootDir, 0, null);
}
/** use a saved bitfield and timestamp from a config file */
public void check(String rootDir, long savedTime, BitField savedBitField) throws IOException
{
File base = new File(rootDir, filterName(metainfo.getName()));
boolean useSavedBitField = savedTime > 0 && savedBitField != null;
List files = metainfo.getFiles();
if (files == null)
{
// Create base as file.
_util.debug("Creating/Checking file: " + base, Snark.NOTICE);
if (!base.createNewFile() && !base.exists())
throw new IOException("Could not create file " + base);
lengths = new long[1];
rafs = new RandomAccessFile[1];
names = new String[1];
RAFlock = new Object[1];
RAFtime = new long[1];
RAFfile = new File[1];
lengths[0] = metainfo.getTotalLength();
RAFlock[0] = new Object();
RAFfile[0] = base;
if (useSavedBitField) {
long lm = base.lastModified();
if (lm <= 0 || lm > savedTime)
useSavedBitField = false;
}
names[0] = base.getName();
}
else
{
// Create base as dir.
_util.debug("Creating/Checking directory: " + base, Snark.NOTICE);
if (!base.mkdir() && !base.isDirectory())
throw new IOException("Could not create directory " + base);
List ls = metainfo.getLengths();
int size = files.size();
long total = 0;
lengths = new long[size];
rafs = new RandomAccessFile[size];
names = new String[size];
RAFlock = new Object[size];
RAFtime = new long[size];
RAFfile = new File[size];
for (int i = 0; i < size; i++)
{
File f = createFileFromNames(base, (List)files.get(i));
lengths[i] = ((Long)ls.get(i)).longValue();
RAFlock[i] = new Object();
RAFfile[i] = f;
total += lengths[i];
if (useSavedBitField) {
long lm = base.lastModified();
if (lm <= 0 || lm > savedTime)
useSavedBitField = false;
}
names[i] = f.getName();
}
// Sanity check for metainfo file.
long metalength = metainfo.getTotalLength();
if (total != metalength)
throw new IOException("File lengths do not add up "
+ total + " != " + metalength);
}
if (useSavedBitField) {
bitfield = savedBitField;
needed = metainfo.getPieces() - bitfield.count();
_probablyComplete = complete();
_util.debug("Found saved state and files unchanged, skipping check", Snark.NOTICE);
} else {
// the following sets the needed variable
changed = true;
checkCreateFiles();
}
if (complete()) {
_util.debug("Torrent is complete", Snark.NOTICE);
} else {
// fixme saved priorities
if (files != null)
priorities = new int[files.size()];
_util.debug("Still need " + needed + " out of " + metainfo.getPieces() + " pieces", Snark.NOTICE);
}
}
/**
* Reopen the file descriptors for a restart
* Do existence check but no length check or data reverification
*/
public void reopen(String rootDir) throws IOException
{
File base = new File(rootDir, filterName(metainfo.getName()));
List files = metainfo.getFiles();
if (files == null)
{
// Reopen base as file.
_util.debug("Reopening file: " + base, Snark.NOTICE);
if (!base.exists())
throw new IOException("Could not reopen file " + base);
}
else
{
// Reopen base as dir.
_util.debug("Reopening directory: " + base, Snark.NOTICE);
if (!base.isDirectory())
throw new IOException("Could not reopen directory " + base);
int size = files.size();
for (int i = 0; i < size; i++)
{
File f = getFileFromNames(base, (List)files.get(i));
if (!f.exists())
throw new IOException("Could not reopen file " + f);
}
}
}
private static final char[] ILLEGAL = new char[] {
'<', '>', ':', '"', '/', '\\', '|', '?', '*',
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
private static String filterName(String name)
{
if (name.equals(".") || name.equals(" "))
return "_";
String rv = name;
if (rv.startsWith("."))
rv = '_' + rv.substring(1);
if (rv.endsWith(".") || rv.endsWith(" "))
rv = rv.substring(0, rv.length() - 1) + '_';
for (int i = 0; i < ILLEGAL.length; i++) {
if (rv.indexOf(ILLEGAL[i]) >= 0)
rv = rv.replace(ILLEGAL[i], '_');
}
return rv;
}
private File createFileFromNames(File base, List names) throws IOException
{
File f = null;
Iterator it = names.iterator();
while (it.hasNext())
{
String name = filterName((String)it.next());
if (it.hasNext())
{
// Another dir in the hierarchy.
f = new File(base, name);
if (!f.mkdir() && !f.isDirectory())
throw new IOException("Could not create directory " + f);
base = f;
}
else
{
// The final element (file) in the hierarchy.
f = new File(base, name);
if (!f.createNewFile() && !f.exists())
throw new IOException("Could not create file " + f);
}
}
return f;
}
public static File getFileFromNames(File base, List names)
{
Iterator it = names.iterator();
while (it.hasNext())
{
String name = filterName((String)it.next());
base = new File(base, name);
}
return base;
}
/**
* This is called at the beginning, and at presumed completion,
* so we have to be careful about locking.
*/
private void checkCreateFiles() throws IOException
{
// Whether we are resuming or not,
// if any of the files already exists we assume we are resuming.
boolean resume = false;
_probablyComplete = true;
needed = metainfo.getPieces();
// Make sure all files are available and of correct length
for (int i = 0; i < rafs.length; i++)
{
long length = RAFfile[i].length();
if(RAFfile[i].exists() && length == lengths[i])
{
if (listener != null)
listener.storageAllocated(this, length);
resume = true; // XXX Could dynamicly check
}
else if (length == 0) {
changed = true;
synchronized(RAFlock[i]) {
allocateFile(i);
// close as we go so we don't run out of file descriptors
try {
closeRAF(i);
} catch (IOException ioe) {}
}
} else {
_util.debug("File '" + names[i] + "' exists, but has wrong length - repairing corruption", Snark.ERROR);
changed = true;
_probablyComplete = false; // to force RW
synchronized(RAFlock[i]) {
checkRAF(i);
rafs[i].setLength(lengths[i]);
try {
closeRAF(i);
} catch (IOException ioe) {}
}
}
}
// Check which pieces match and which don't
if (resume)
{
pieces = metainfo.getPieces();
byte[] piece = new byte[metainfo.getPieceLength(0)];
int file = 0;
long fileEnd = lengths[0];
long pieceEnd = 0;
for (int i = 0; i < pieces; i++)
{
int length = getUncheckedPiece(i, piece);
boolean correctHash = metainfo.checkPiece(i, piece, 0, length);
// close as we go so we don't run out of file descriptors
pieceEnd += length;
while (fileEnd <= pieceEnd) {
synchronized(RAFlock[file]) {
try {
closeRAF(file);
} catch (IOException ioe) {}
}
if (++file >= rafs.length)
break;
fileEnd += lengths[file];
}
if (correctHash)
{
bitfield.set(i);
needed
}
if (listener != null)
listener.storageChecked(this, i, correctHash);
}
}
_probablyComplete = complete();
// close all the files so we don't end up with a zillion open ones;
// we will reopen as needed
// Now closed above to avoid running out of file descriptors
//for (int i = 0; i < rafs.length; i++) {
// synchronized(RAFlock[i]) {
// try {
// closeRAF(i);
// } catch (IOException ioe) {}
if (listener != null) {
listener.storageAllChecked(this);
if (needed <= 0)
listener.storageCompleted(this);
}
}
/** this calls openRAF(); caller must synnchronize and call closeRAF() */
private void allocateFile(int nr) throws IOException
{
// caller synchronized
openRAF(nr, false);
// XXX - Is this the best way to make sure we have enough space for
// the whole file?
listener.storageCreateFile(this, names[nr], lengths[nr]);
final int ZEROBLOCKSIZE = metainfo.getPieceLength(0);
byte[] zeros;
try {
zeros = new byte[ZEROBLOCKSIZE];
} catch (OutOfMemoryError oom) {
throw new IOException(oom.toString());
}
int i;
for (i = 0; i < lengths[nr]/ZEROBLOCKSIZE; i++)
{
rafs[nr].write(zeros);
if (listener != null)
listener.storageAllocated(this, ZEROBLOCKSIZE);
}
int size = (int)(lengths[nr] - i*ZEROBLOCKSIZE);
rafs[nr].write(zeros, 0, size);
// caller will close rafs[nr]
if (listener != null)
listener.storageAllocated(this, size);
}
/**
* Closes the Storage and makes sure that all RandomAccessFiles are
* closed. The Storage is unusable after this.
*/
public void close() throws IOException
{
if (rafs == null) return;
for (int i = 0; i < rafs.length; i++)
{
// if we had an IOE in check(), the RAFlock may be null
if (RAFlock[i] == null)
continue;
try {
synchronized(RAFlock[i]) {
closeRAF(i);
}
} catch (IOException ioe) {
_util.debug("Error closing " + RAFfile[i], Snark.ERROR, ioe);
// gobble gobble
}
}
changed = false;
}
/**
* Returns a byte array containing a portion of the requested piece or null if
* the storage doesn't contain the piece yet.
*/
public byte[] getPiece(int piece, int off, int len) throws IOException
{
if (!bitfield.get(piece))
return null;
//Catch a common place for OOMs esp. on 1MB pieces
byte[] bs;
try {
bs = new byte[len];
} catch (OutOfMemoryError oom) {
_util.debug("Out of memory, can't honor request for piece " + piece, Snark.WARNING, oom);
return null;
}
getUncheckedPiece(piece, bs, off, len);
return bs;
}
/**
* Put the piece in the Storage if it is correct.
*
* @return true if the piece was correct (sha metainfo hash
* matches), otherwise false.
* @exception IOException when some storage related error occurs.
*/
public boolean putPiece(int piece, byte[] ba) throws IOException
{
// First check if the piece is correct.
// Copy the array first to be paranoid.
byte[] bs = (byte[]) ba.clone();
int length = bs.length;
boolean correctHash = metainfo.checkPiece(piece, bs, 0, length);
if (listener != null)
listener.storageChecked(this, piece, correctHash);
if (!correctHash)
return false;
synchronized(bitfield)
{
if (bitfield.get(piece))
return true; // No need to store twice.
}
// Early typecast, avoid possibly overflowing a temp integer
long start = (long) piece * (long) metainfo.getPieceLength(0);
int i = 0;
long raflen = lengths[i];
while (start > raflen)
{
i++;
start -= raflen;
raflen = lengths[i];
}
int written = 0;
int off = 0;
while (written < length)
{
int need = length - written;
int len = (start + need < raflen) ? need : (int)(raflen - start);
synchronized(RAFlock[i])
{
checkRAF(i);
rafs[i].seek(start);
rafs[i].write(bs, off + written, len);
}
written += len;
if (need - len > 0)
{
i++;
raflen = lengths[i];
start = 0;
}
}
changed = true;
// do this after the write, so we know it succeeded, and we don't set the
// needed count to zero, which would cause checkRAF() to open the file readonly.
boolean complete = false;
synchronized(bitfield)
{
if (!bitfield.get(piece))
{
bitfield.set(piece);
needed
complete = needed == 0;
}
}
if (complete) {
// do we also need to close all of the files and reopen
// them readonly?
// Do a complete check to be sure.
// Temporarily resets the 'needed' variable and 'bitfield', then call
// checkCreateFiles() which will set 'needed' and 'bitfield'
// and also call listener.storageCompleted() if the double-check
// was successful.
// Todo: set a listener variable so the web shows "checking" and don't
// have the user panic when completed amount goes to zero temporarily?
needed = metainfo.getPieces();
bitfield = new BitField(needed);
checkCreateFiles();
if (needed > 0) {
if (listener != null)
listener.setWantedPieces(this);
_util.debug("WARNING: Not really done, missing " + needed
+ " pieces", Snark.WARNING);
}
}
return true;
}
private int getUncheckedPiece(int piece, byte[] bs)
throws IOException
{
return getUncheckedPiece(piece, bs, 0, metainfo.getPieceLength(piece));
}
private int getUncheckedPiece(int piece, byte[] bs, int off, int length)
throws IOException
{
// XXX - copy/paste code from putPiece().
// Early typecast, avoid possibly overflowing a temp integer
long start = ((long) piece * (long) metainfo.getPieceLength(0)) + off;
int i = 0;
long raflen = lengths[i];
while (start > raflen)
{
i++;
start -= raflen;
raflen = lengths[i];
}
int read = 0;
while (read < length)
{
int need = length - read;
int len = (start + need < raflen) ? need : (int)(raflen - start);
synchronized(RAFlock[i])
{
checkRAF(i);
rafs[i].seek(start);
rafs[i].readFully(bs, read, len);
}
read += len;
if (need - len > 0)
{
i++;
raflen = lengths[i];
start = 0;
}
}
return length;
}
/**
* Close unused RAFs - call periodically
*/
private static final long RAFCloseDelay = 7*60*1000;
public void cleanRAFs() {
long cutoff = System.currentTimeMillis() - RAFCloseDelay;
for (int i = 0; i < RAFlock.length; i++) {
synchronized(RAFlock[i]) {
if (RAFtime[i] > 0 && RAFtime[i] < cutoff) {
try {
closeRAF(i);
} catch (IOException ioe) {}
}
}
}
}
/*
* For each of the following,
* caller must synchronize on RAFlock[i]
* ... except at the beginning if you're careful
*/
/**
* This must be called before using the RAF to ensure it is open
*/
private void checkRAF(int i) throws IOException {
if (RAFtime[i] > 0) {
RAFtime[i] = System.currentTimeMillis();
return;
}
openRAF(i);
}
private void openRAF(int i) throws IOException {
openRAF(i, _probablyComplete);
}
private void openRAF(int i, boolean readonly) throws IOException {
rafs[i] = new RandomAccessFile(RAFfile[i], (readonly || !RAFfile[i].canWrite()) ? "r" : "rw");
RAFtime[i] = System.currentTimeMillis();
}
/**
* Can be called even if not open
*/
private void closeRAF(int i) throws IOException {
RAFtime[i] = 0;
if (rafs[i] == null)
return;
rafs[i].close();
rafs[i] = null;
}
} |
package dr.inference.operators;
import dr.inference.model.Bounds;
import dr.inference.model.Parameter;
import dr.inferencexml.operators.RandomWalkOperatorParser;
import dr.math.MathUtils;
import dr.util.Transform;
import java.util.ArrayList;
import java.util.List;
/**
* A generic random walk operator for use with a multi-dimensional parameters.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: RandomWalkOperator.java,v 1.16 2005/06/14 10:40:34 rambaut Exp $
*/
public class RandomWalkOperator extends AbstractAdaptableOperator {
public enum BoundaryCondition {
rejecting,
reflecting,
absorbing,
log,
logit
}
public RandomWalkOperator(Parameter parameter, double windowSize, BoundaryCondition bc, double weight, AdaptationMode mode) {
this(parameter, null, windowSize, bc, weight, mode);
}
public RandomWalkOperator(Parameter parameter, Parameter updateIndex, double windowSize, BoundaryCondition boundaryCondition,
double weight, AdaptationMode mode) {
super(mode);
this.parameter = parameter;
this.windowSize = windowSize;
this.boundaryCondition = boundaryCondition;
setWeight(weight);
if (updateIndex != null) {
updateMap = new ArrayList<Integer>();
for (int i = 0; i < updateIndex.getDimension(); i++) {
if (updateIndex.getParameterValue(i) == 1.0)
updateMap.add(i);
}
updateMapSize=updateMap.size();
}
}
/**
* @return the parameter this operator acts on.
*/
public Parameter getParameter() {
return parameter;
}
public final double getWindowSize() {
return windowSize;
}
public final BoundaryCondition getBoundaryCondition() {
return boundaryCondition;
}
/**
* change the parameter and return the hastings ratio.
*/
public double doOperation() {
// a random dimension to perturb
if (parameter.getDimension() <= 0) {
throw new RuntimeException("Illegal Dimension");
}
int dim;
if (updateMap == null) {
dim = MathUtils.nextInt(parameter.getDimension());
} else {
dim = updateMap.get(MathUtils.nextInt(updateMapSize));
}
// a random point around old value within windowSize * 2
double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize;
double oldValue = parameter.getParameterValue(dim);
final Bounds<Double> bounds = parameter.getBounds();
final double lower = bounds.getLowerLimit(dim);
final double upper = bounds.getUpperLimit(dim);
if (boundaryCondition == BoundaryCondition.logit) {
// scale oldValue to [0,1]
double x1 = (oldValue - lower) / (upper - lower);
// logit transform it, add the draw, inverse transform it
double x2 = Transform.LOGIT.inverse(Transform.LOGIT.transform(x1) + draw);
// parameter takes new value scaled back into interval [lower, upper]
parameter.setParameterValue(dim, (x2 * (upper - lower)) + lower);
// HR is the ratio of Jacobians for the before and after values in interval [0,1]
return Transform.LOGIT.getLogJacobian(x1) - Transform.LOGIT.getLogJacobian(x2);
} else if (boundaryCondition == BoundaryCondition.log) {
// offset oldValue to [0,+Inf]
double x1 = oldValue - lower;
// logit transform it, add the draw, inverse transform it
double x2 = Transform.LOG.inverse(Transform.LOG.transform(x1) + draw);
// parameter takes new value tranlated back into interval [lower, +Inf]
parameter.setParameterValue(dim, x2 + lower);
// HR is the ratio of Jacobians for the before and after values
return Transform.LOG.getLogJacobian(x1) - Transform.LOG.getLogJacobian(x2);
} else {
double newValue = oldValue + draw;
if (boundaryCondition == BoundaryCondition.reflecting) {
newValue = reflectValue(newValue, lower, upper);
} else if (boundaryCondition == BoundaryCondition.absorbing && (newValue < lower || newValue > upper)) {
return 0.0;
} else if (boundaryCondition == BoundaryCondition.rejecting && (newValue < lower || newValue > upper)) {
return Double.NEGATIVE_INFINITY;
}
parameter.setParameterValue(dim, newValue);
return 0.0;
}
}
public static double reflectValue(double value, double lower, double upper) {
double newValue = value;
if (upper == lower) {
newValue = upper;
} else if (value < lower) {
if (Double.isInfinite(upper)) {
// we are only going to reflect once as the upper bound is at infinity...
newValue = lower + (lower - value);
} else {
double remainder = lower - value;
double widths = Math.floor(remainder / (upper - lower));
remainder -= (upper - lower) * widths;
// even reflections
if (widths % 2 == 0) {
newValue = lower + remainder;
// odd reflections
} else {
newValue = upper - remainder;
}
}
} else if (value > upper) {
if (Double.isInfinite(lower)) {
// we are only going to reflect once as the lower bound is at -infinity...
newValue = upper - (newValue - upper);
} else {
double remainder = value - upper;
double widths = Math.floor(remainder / (upper - lower));
remainder -= (upper - lower) * widths;
// even reflections
if (widths % 2 == 0) {
newValue = upper - remainder;
// odd reflections
} else {
newValue = lower + remainder;
}
}
}
return newValue;
}
public double reflectValueLoop(double value, double lower, double upper) {
double newValue = value;
while (newValue < lower || newValue > upper) {
if (newValue < lower) {
newValue = lower + (lower - newValue);
}
if (newValue > upper) {
newValue = upper - (newValue - upper);
}
}
return newValue;
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return parameter.getParameterName();
}
@Override
protected double getAdaptableParameterValue() {
return Math.log(windowSize);
}
@Override
protected void setAdaptableParameterValue(double value) {
windowSize = Math.exp(value);
}
@Override
public double getRawParameter() {
return windowSize;
}
@Override
public String getAdaptableParameterName() {
return "windowSize";
}
public String toString() {
return RandomWalkOperatorParser.RANDOM_WALK_OPERATOR + "(" + parameter.getParameterName() + ", " + windowSize + ", " + getWeight() + ")";
}
//PRIVATE STUFF
protected Parameter parameter = null;
private double windowSize = 0.01;
private List<Integer> updateMap = null;
private int updateMapSize;
private final BoundaryCondition boundaryCondition;
} |
package saschpe.poker.activity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.support.wearable.activity.WearableActivity;
import android.support.wearable.view.drawer.WearableActionDrawer;
import android.support.wearable.view.drawer.WearableDrawerLayout;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import saschpe.poker.R;
import saschpe.poker.adapter.WearCardArrayAdapter;
import saschpe.poker.util.PlanningPoker;
import saschpe.poker.widget.recycler.SpacesItemDecoration;
public class MainActivity extends WearableActivity implements
WearableActionDrawer.OnMenuItemClickListener {
private static final String PREFS_FLAVOR = "flavor";
private static final String STATE_FLAVOR = "flavor";
private static final SimpleDateFormat AMBIENT_DATE_FORMAT =
new SimpleDateFormat("HH:mm", Locale.US);
private PlanningPoker.Flavor flavor;
private WearCardArrayAdapter arrayAdapter;
private WearableActionDrawer actionDrawer;
private WearableDrawerLayout drawerLayout;
private RecyclerView recyclerView;
private TextView clock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAmbientEnabled();
if (savedInstanceState != null) {
flavor = (PlanningPoker.Flavor) savedInstanceState.getSerializable(STATE_FLAVOR);
} else {
// Either load flavor from previous invocation or use default
String flavorString = PreferenceManager.getDefaultSharedPreferences(this)
.getString(PREFS_FLAVOR, PlanningPoker.Flavor.FIBONACCI.toString());
flavor = PlanningPoker.Flavor.fromString(flavorString);
}
clock = (TextView) findViewById(R.id.clock);
// Compute spacing between cards
float marginDp = getResources().getDimension(R.dimen.activity_horizontal_margin) / 8;
int spacePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, marginDp, getResources().getDisplayMetrics());
// Setup recycler
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SpacesItemDecoration(spacePx, layoutManager.getOrientation()));
updateFlavor();
recyclerView.setAdapter(arrayAdapter);
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
// Main Wearable Drawer Layout that wraps all content
drawerLayout = (WearableDrawerLayout) findViewById(R.id.drawer_layout);
// Bottom Action Drawer
actionDrawer = (WearableActionDrawer) findViewById(R.id.bottom_action_drawer);
// Populate Action Drawer Menu
Menu menu = actionDrawer.getMenu();
getMenuInflater().inflate(R.menu.action_drawer, menu);
switch (flavor) {
case FIBONACCI:
menu.findItem(R.id.fibonacci).setChecked(true);
break;
case T_SHIRT_SIZES:
menu.findItem(R.id.t_shirt_sizes).setChecked(true);
break;
}
actionDrawer.setOnMenuItemClickListener(this);
// Peeks action drawer on the bottom.
drawerLayout.peekDrawer(Gravity.BOTTOM);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Persist current flavor for next invocation
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString(PREFS_FLAVOR, flavor.toString())
.apply();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_FLAVOR, flavor);
}
@Override
public void onEnterAmbient(Bundle ambientDetails) {
super.onEnterAmbient(ambientDetails);
updateDisplay();
}
@Override
public void onUpdateAmbient() {
super.onUpdateAmbient();
updateDisplay();
}
@Override
public void onExitAmbient() {
updateDisplay();
super.onExitAmbient();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.fibonacci:
flavor = PlanningPoker.Flavor.FIBONACCI;
updateFlavor();
item.setChecked(true);
break;
case R.id.t_shirt_sizes:
flavor = PlanningPoker.Flavor.T_SHIRT_SIZES;
updateFlavor();
item.setChecked(true);
break;
case R.id.version_info:
startActivity(new Intent(this, InfoActivity.class));
break;
}
actionDrawer.closeDrawer();
return super.onOptionsItemSelected(item);
}
private void updateDisplay() {
if (isAmbient()) {
arrayAdapter.setViewType(WearCardArrayAdapter.DARK_CARD_VIEW_TYPE);
clock.setText(AMBIENT_DATE_FORMAT.format(new Date()));
clock.setVisibility(View.VISIBLE);
drawerLayout.closeDrawer(Gravity.BOTTOM);
} else {
arrayAdapter.setViewType(WearCardArrayAdapter.LIGHT_CARD_VIEW_TYPE);
clock.setVisibility(View.GONE);
}
}
private void updateFlavor() {
switch (flavor) {
case FIBONACCI:
if (arrayAdapter == null) {
arrayAdapter = new WearCardArrayAdapter(this, PlanningPoker.FIBONACCI_LIST, WearCardArrayAdapter.LIGHT_CARD_VIEW_TYPE);
} else {
arrayAdapter.replaceAll(PlanningPoker.FIBONACCI_LIST);
}
recyclerView.scrollToPosition(PlanningPoker.FIBONACCI_POSITION);
break;
case T_SHIRT_SIZES:
if (arrayAdapter == null) {
arrayAdapter = new WearCardArrayAdapter(this, PlanningPoker.T_SHIRT_SIZE_LIST, WearCardArrayAdapter.LIGHT_CARD_VIEW_TYPE);
} else {
arrayAdapter.replaceAll(PlanningPoker.T_SHIRT_SIZE_LIST);
}
recyclerView.scrollToPosition(PlanningPoker.T_SHIRT_SIZE_POSITION);
break;
}
}
} |
package dr.inference.operators;
import dr.inference.model.Bounds;
import dr.inference.model.Parameter;
import dr.inferencexml.operators.RandomWalkOperatorParser;
import dr.math.MathUtils;
import dr.util.Transform;
import java.util.ArrayList;
import java.util.List;
/**
* A generic random walk operator for use with a multi-dimensional parameters.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: RandomWalkOperator.java,v 1.16 2005/06/14 10:40:34 rambaut Exp $
*/
public class RandomWalkOperator extends AbstractAdaptableOperator {
public enum BoundaryCondition {
rejecting,
reflecting,
absorbing,
log,
logit
}
public RandomWalkOperator(Parameter parameter, double windowSize, BoundaryCondition bc, double weight, AdaptationMode mode) {
this(parameter, null, windowSize, bc, weight, mode);
}
public RandomWalkOperator(Parameter parameter, Parameter updateIndex, double windowSize, BoundaryCondition boundaryCondition,
double weight, AdaptationMode mode) {
super(mode);
this.parameter = parameter;
this.windowSize = windowSize;
this.boundaryCondition = boundaryCondition;
setWeight(weight);
if (updateIndex != null) {
updateMap = new ArrayList<Integer>();
for (int i = 0; i < updateIndex.getDimension(); i++) {
if (updateIndex.getParameterValue(i) == 1.0)
updateMap.add(i);
}
updateMapSize=updateMap.size();
}
}
/**
* @return the parameter this operator acts on.
*/
public Parameter getParameter() {
return parameter;
}
public final double getWindowSize() {
return windowSize;
}
public final BoundaryCondition getBoundaryCondition() {
return boundaryCondition;
}
/**
* change the parameter and return the hastings ratio.
*/
public double doOperation() {
// a random dimension to perturb
if (parameter.getDimension() <= 0) {
throw new RuntimeException("Illegal Dimension");
}
int dim;
if (updateMap == null) {
dim = MathUtils.nextInt(parameter.getDimension());
} else {
dim = updateMap.get(MathUtils.nextInt(updateMapSize));
}
// a random point around old value within windowSize * 2
double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize;
double oldValue = parameter.getParameterValue(dim);
final Bounds<Double> bounds = parameter.getBounds();
final double lower = bounds.getLowerLimit(dim);
final double upper = bounds.getUpperLimit(dim);
if (boundaryCondition == BoundaryCondition.logit) {
// scale oldValue to [0,1]
double x1 = (oldValue - lower) / (upper - lower);
// logit transform it, add the draw, inverse transform it
double x2 = Transform.LOGIT.inverse(Transform.LOGIT.transform(x1) + draw);
// parameter takes new value scaled back into interval [lower, upper]
parameter.setParameterValue(dim, (x2 * (upper - lower)) + lower);
// HR is the ratio of Jacobians for the before and after values in interval [0,1]
return Transform.LOGIT.getLogJacobian(x1) - Transform.LOGIT.getLogJacobian(x2);
} else if (boundaryCondition == BoundaryCondition.log) {
// offset oldValue to [0,+Inf]
double x1 = oldValue - lower;
// logit transform it, add the draw, inverse transform it
double x2 = Transform.LOG.inverse(Transform.LOG.transform(x1) + draw);
// parameter takes new value tranlated back into interval [lower, +Inf]
parameter.setParameterValue(dim, x2 + lower);
// HR is the ratio of Jacobians for the before and after values
return Transform.LOG.getLogJacobian(x1) - Transform.LOG.getLogJacobian(x2);
} else {
double newValue = oldValue + draw;
if (boundaryCondition == BoundaryCondition.reflecting) {
newValue = reflectValue(newValue, lower, upper);
} else if (boundaryCondition == BoundaryCondition.absorbing && (newValue < lower || newValue > upper)) {
return 0.0;
} else if (boundaryCondition == BoundaryCondition.rejecting && (newValue < lower || newValue > upper)) {
return Double.NEGATIVE_INFINITY;
}
parameter.setParameterValue(dim, newValue);
if (parameter.check()) {
return 0.0;
} else {
return Double.NEGATIVE_INFINITY;
}
}
}
public static double reflectValue(double value, double lower, double upper) {
double newValue = value;
if (upper == lower) {
newValue = upper;
} else if (value < lower) {
if (Double.isInfinite(upper)) {
// we are only going to reflect once as the upper bound is at infinity...
newValue = lower + (lower - value);
} else {
// double remainder = lower - value;
// double widths = Math.floor(remainder / (upper - lower));
// remainder -= (upper - lower) * widths;
final double ratio = (lower - value) / (upper - lower);
final double widths = Math.floor(ratio);
final double remainder = (ratio - widths) * (upper - lower);
// even reflections
if (widths % 2 == 0) {
newValue = lower + remainder;
// odd reflections
} else {
newValue = upper - remainder;
}
}
} else if (value > upper) {
if (Double.isInfinite(lower)) {
// we are only going to reflect once as the lower bound is at -infinity...
newValue = upper - (newValue - upper);
} else {
// double remainder = value - upper;
// double widths = Math.floor(remainder / (upper - lower));
// remainder -= (upper - lower) * widths;
final double ratio = (value - upper) / (upper - lower);
final double widths = Math.floor(ratio);
final double remainder = (ratio - widths) * (upper - lower);
// even reflections
if (widths % 2 == 0) {
newValue = upper - remainder;
// odd reflections
} else {
newValue = lower + remainder;
}
}
}
return newValue;
}
public double reflectValueLoop(double value, double lower, double upper) {
double newValue = value;
while (newValue < lower || newValue > upper) {
if (newValue < lower) {
newValue = lower + (lower - newValue);
}
if (newValue > upper) {
newValue = upper - (newValue - upper);
}
}
return newValue;
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return RandomWalkOperatorParser.RANDOM_WALK_OPERATOR + "(" + parameter.getParameterName() + ")";
}
@Override
protected double getAdaptableParameterValue() {
return Math.log(windowSize);
}
@Override
protected void setAdaptableParameterValue(double value) {
windowSize = Math.exp(value);
}
@Override
public double getRawParameter() {
return windowSize;
}
@Override
public String getAdaptableParameterName() {
return "windowSize";
}
public String toString() {
return RandomWalkOperatorParser.RANDOM_WALK_OPERATOR + "(" + parameter.getParameterName() + ", " + windowSize + ", " + getWeight() + ")";
}
//PRIVATE STUFF
protected Parameter parameter = null;
private double windowSize = 0.01;
private List<Integer> updateMap = null;
private int updateMapSize;
private final BoundaryCondition boundaryCondition;
} |
package edacc.configurator.aac.racing;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.rosuda.JRI.Rengine;
import edacc.api.API;
import edacc.configurator.aac.AAC;
import edacc.configurator.aac.InstanceIdSeed;
import edacc.configurator.aac.Parameters;
import edacc.configurator.aac.SolverConfiguration;
import edacc.configurator.aac.course.StratifiedClusterCourse;
import edacc.configurator.aac.util.RInterface;
import edacc.model.ConfigurationScenarioDAO;
import edacc.model.ExperimentDAO;
import edacc.model.ExperimentResult;
import edacc.model.Instance;
import edacc.model.InstanceDAO;
import edacc.model.ResultCode;
import edacc.model.StatusCode;
import edacc.model.Experiment.Cost;
import edacc.configurator.aac.JobListener;
public class DefaultSMBO extends RacingMethods implements JobListener {
SolverConfiguration bestSC;
int incumbentNumber;
int num_instances;
private int numSCs = 0;
private int curThreshold = 0;
private List<InstanceIdSeed> completeCourse;
private Rengine rengine;
private Map<Integer, Integer> limitByInstance = new HashMap<Integer, Integer>();
private int increaseIncumbentRunsEvery = 32;
private String featureFolder = null;
private String featureCacheFolder = null;
private boolean useClusterCourse = false;
// when selecting jobs from the incumbent, prefer jobs that didn't time out
private boolean aggressiveJobSelection = false;
private boolean adaptiveCapping = false;
private float slackFactor = 1.5f;
private boolean clusterSizeExpansion = false;
StratifiedClusterCourse course = null;
//public boolean initialDesignMode = true;
HashSet<Integer> stopEvalSolverConfigIds = new HashSet<Integer>();
Set<SolverConfiguration> challengers = new HashSet<SolverConfiguration>();
public DefaultSMBO(AAC aac, Random rng, API api, Parameters parameters, List<SolverConfiguration> firstSCs, List<SolverConfiguration> referenceSCs) throws Exception {
super(aac, rng, api, parameters, firstSCs, referenceSCs);
aac.addJobListener(this);
incumbentNumber = 0;
num_instances = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(parameters.getIdExperiment()).getCourse().getInitialLength();
String val;
if ((val = parameters.getRacingMethodParameters().get("DefaultSMBO_increaseIncumbentRunsEvery")) != null)
increaseIncumbentRunsEvery = Integer.valueOf(val);
if ((val = parameters.getRacingMethodParameters().get("DefaultSMBO_aggressiveJobSelection")) != null)
aggressiveJobSelection = Integer.valueOf(val) == 1;
if ((val = parameters.getRacingMethodParameters().get("DefaultSMBO_featureFolder")) != null)
featureFolder = val;
if ((val = parameters.getRacingMethodParameters().get("DefaultSMBO_featureCacheFolder")) != null)
featureCacheFolder = val;
if ((val = parameters.getRacingMethodParameters().get("DefaultSMBO_useClusterCourse")) != null)
useClusterCourse = Integer.valueOf(val) == 1;
if ((val = parameters.getRacingMethodParameters().get("DefaultSMBO_adaptiveCapping")) != null)
adaptiveCapping = Integer.valueOf(val) == 1;
if ((val = parameters.getRacingMethodParameters().get("DefaultSMBO_slackFactor")) != null)
slackFactor = Float.valueOf(val);
if ((val = parameters.getRacingMethodParameters().get("DefaultSMBO_clusterSizeExpansion")) != null)
clusterSizeExpansion = Integer.valueOf(val) == 1;
if (useClusterCourse) {
rengine = RInterface.getRengine();
if (rengine.eval("library(asbio)") == null) {
rengine.end();
throw new Exception("Did not find R library asbio (try running install.packages(\"asbio\")).");
}
if (rengine.eval("library(survival)") == null) {
rengine.end();
throw new Exception("Did not find R library survival (should come with R though).");
}
course = new StratifiedClusterCourse(rengine, api.getExperimentInstances(parameters.getIdExperiment()), null, null, parameters.getMaxParcoursExpansionFactor(), rng, featureFolder, featureCacheFolder);
this.completeCourse = course.getCourse();
List<Instance> instances = InstanceDAO.getAllByExperimentId(parameters.getIdExperiment());
Map<Integer, Instance> instanceById = new HashMap<Integer, Instance>();
for (Instance i: instances) instanceById.put(i.getId(), i);
pacc.log("[DefaultSMBO] Clustered instances into " + course.getK() + " clusters. Complete course:");
for (InstanceIdSeed isp: completeCourse) {
pacc.log("[DefaultSMBO] " + instanceById.get(isp.instanceId) + ", " + isp.seed);
}
}
curThreshold = increaseIncumbentRunsEvery;
if (!firstSCs.isEmpty()) {
initBestSC(firstSCs.get(0));
}
}
private void initBestSC(SolverConfiguration sc) throws Exception {
this.bestSC = firstSCs.get(0);
bestSC.setIncumbentNumber(incumbentNumber++);
pacc.log("i " + pacc.getWallTime() + " ," + bestSC.getCost() + ", n.A.," + bestSC.getIdSolverConfiguration() + ", n.A.," + bestSC.getParameterConfiguration().toString());
int expansion = 0;
if (bestSC.getJobCount() < parameters.getMaxParcoursExpansionFactor() * num_instances) {
if (clusterSizeExpansion)
expansion = Math.min(parameters.getMaxParcoursExpansionFactor() * num_instances - bestSC.getJobCount(), parameters.getInitialDefaultParcoursLength());
else
expansion = Math.min(parameters.getMaxParcoursExpansionFactor() * num_instances - bestSC.getJobCount(), course.getK());
if (useClusterCourse) {
for (int i = 0; i < expansion; i++) {
pacc.addJob(bestSC, completeCourse.get(bestSC.getJobCount()).seed,
completeCourse.get(bestSC.getJobCount()).instanceId, parameters.getMaxParcoursExpansionFactor()
* num_instances - bestSC.getJobCount());
}
} else {
pacc.expandParcoursSC(bestSC, expansion);
}
}
if (expansion > 0) {
pacc.log("c Expanding parcours of best solver config " + bestSC.getIdSolverConfiguration() + " by " + expansion);
}
// update the status of the jobs of bestSC and if first level wait
// also for jobs to finish
if (expansion > 0) {
pacc.log("c Waiting for currently best solver config " + bestSC.getIdSolverConfiguration() + " to finish " + expansion + "job(s)");
while (true) {
pacc.updateJobsStatus(bestSC);
if (bestSC.getNotStartedJobs().isEmpty() && bestSC.getRunningJobs().isEmpty()) {
break;
}
pacc.sleep(1000);
}
pacc.validateIncumbent(bestSC);
} else {
pacc.updateJobsStatus(bestSC);
}
}
public String toString(){
return "DefaultSMBO racing method";
}
@Override
public int compareTo(SolverConfiguration sc1, SolverConfiguration sc2) {
return sc1.compareTo(sc2);
}
@Override
public void solverConfigurationsFinished(List<SolverConfiguration> scs) throws Exception {
/*if (initialDesignMode) {
pacc.updateJobsStatus(bestSC);
scs.clear();
scs.addAll(challengers);
scs.add(bestSC);
}*/
for (SolverConfiguration sc : scs) {
if (sc.getJobCount() != sc.getFinishedJobs().size()) continue;
if (sc == bestSC) {
continue;
}
for (ExperimentResult er : sc.getJobs()) {
ExperimentResult apiER = api.getJob(er.getId());
if (limitByInstance.get(er.getInstanceId()) == null) continue;
er.setCPUTimeLimit(limitByInstance.get(er.getInstanceId()));
apiER.setCPUTimeLimit(limitByInstance.get(er.getInstanceId()));
if (er.getResultTime() > limitByInstance.get(er.getInstanceId()) && er.getResultCode().isCorrect()) {
pacc.log("Setting time limit exceeded to job " + er.getId() + ".");
er.setStatus(StatusCode.TIMELIMIT);
apiER.setStatus(StatusCode.TIMELIMIT);
er.setResultCode(ResultCode.UNKNOWN);
apiER.setResultCode(ResultCode.UNKNOWN);
}
}
int comp = compareTo(sc, bestSC);
if (!stopEvalSolverConfigIds.contains(sc.getIdSolverConfiguration()) && comp >= 0) {
if (sc.getJobCount() == bestSC.getJobCount()) {
sc.setFinished(true);
// all jobs from bestSC computed and won against
// best:
if (comp > 0) {
challengers.remove(sc);
bestSC = sc;
sc.setIncumbentNumber(incumbentNumber++);
pacc.log("new incumbent: " + sc.getIdSolverConfiguration() + ":" + pacc.getWallTime() + ":" + pacc.getCumulatedCPUTime() + ":" + sc.getCost());
pacc.log("i " + pacc.getWallTime() + "," + sc.getCost() + ",n.A. ," + sc.getIdSolverConfiguration() + ",n.A. ," + sc.getParameterConfiguration().toString());
pacc.validateIncumbent(bestSC);
} else {
pacc.log("c Configuration " + sc.getIdSolverConfiguration() + " tied with incumbent");
}
} else {
int generated = 0;
if (clusterSizeExpansion){
if (aggressiveJobSelection) {
generated = pacc.addRandomJobAggressive(course.getK(), sc, bestSC, sc.getJobCount());
} else {
generated = pacc.addRandomJob(course.getK(), sc, bestSC, sc.getJobCount());
}
}
else
if (aggressiveJobSelection) {
generated = pacc.addRandomJobAggressive(sc.getJobCount(), sc, bestSC, sc.getJobCount());
} else {
generated = pacc.addRandomJob(sc.getJobCount(), sc, bestSC, sc.getJobCount());
}
if (generated > 0) {
pacc.log("c Generated " + generated + " jobs for solver config id " + sc.getIdSolverConfiguration());
}
pacc.addSolverConfigurationToListNewSC(sc);
}
} else {// lost against best on part of the actual (or should not be evaluated anymore)
// parcours:
stopEvalSolverConfigIds.remove(sc.getIdSolverConfiguration());
challengers.remove(sc);
sc.setFinished(true);
if (parameters.isDeleteSolverConfigs())
api.removeSolverConfig(sc.getIdSolverConfiguration());
pacc.log("d Solver config " + sc.getIdSolverConfiguration() + " with cost " + sc.getCost() + " lost against best solver config on " + sc.getJobCount() + " runs.");
api.updateSolverConfigurationName(sc.getIdSolverConfiguration(), "* " + sc.getName());
numSCs += 1;
if (numSCs > curThreshold && bestSC.getJobCount() < parameters.getMaxParcoursExpansionFactor() * num_instances) {
pacc.log("c Expanding parcours of best solver config " + bestSC.getIdSolverConfiguration() + " by 1");
if (useClusterCourse) {
if (bestSC.getJobCount() < completeCourse.size()) {
if (clusterSizeExpansion){
for (int i=0;i<course.getK();i++)
pacc.addJob(bestSC, completeCourse.get(bestSC.getJobCount()).seed,
completeCourse.get(bestSC.getJobCount()).instanceId, bestSC.getJobCount());
}
else{
pacc.addJob(bestSC, completeCourse.get(bestSC.getJobCount()).seed,
completeCourse.get(bestSC.getJobCount()).instanceId, bestSC.getJobCount());
}
} else {
pacc.log("c Incumbent reached maximum number of evaluations. No more jobs are generated for it.");
}
} else {
pacc.expandParcoursSC(bestSC, 1);
}
pacc.addSolverConfigurationToListNewSC(bestSC);
curThreshold += increaseIncumbentRunsEvery;
}
}
}
}
@Override
public void solverConfigurationsCreated(List<SolverConfiguration> scs) throws Exception {
if (scs.isEmpty())
return;
if (bestSC == null) {
initBestSC(scs.get(0));
scs.remove(0);
}
// First, check if we can update the incumbent
this.solverConfigurationsFinished(new LinkedList<SolverConfiguration>(challengers));
for (SolverConfiguration sc : scs) {
/*if (initialDesignMode) {
if (useClusterCourse) {
for (int i = 0; i < parameters.getInitialDefaultParcoursLength(); i++) {
pacc.addJob(sc, completeCourse.get(sc.getJobCount()).seed,
completeCourse.get(sc.getJobCount()).instanceId, sc.getJobCount());
}
} else {
pacc.expandParcoursSC(sc, parameters.getInitialDefaultParcoursLength());
}
} else {*/
if (clusterSizeExpansion){
if (aggressiveJobSelection) {
pacc.addRandomJobAggressive(course.getK(), sc, bestSC, sc.getJobCount());
} else {
pacc.addRandomJob(course.getK(), sc, bestSC, sc.getJobCount());
}
}
else{
if (aggressiveJobSelection) {
pacc.addRandomJobAggressive(parameters.getMinRuns(), sc, bestSC, sc.getJobCount());
} else {
pacc.addRandomJob(parameters.getMinRuns(), sc, bestSC, sc.getJobCount());
}
}
pacc.addSolverConfigurationToListNewSC(sc);
}
//if (!initialDesignMode) {
/* for (int i = 0; i < scs.size(); i++) {
numSCs += 1;
if (numSCs > curThreshold && bestSC.getJobCount() < parameters.getMaxParcoursExpansionFactor() * num_instances) {
pacc.log("c Expanding parcours of best solver config " + bestSC.getIdSolverConfiguration() + " by 1");
if (useClusterCourse) {
if (bestSC.getJobCount() < completeCourse.size()) {
pacc.addJob(bestSC, completeCourse.get(bestSC.getJobCount()).seed,
completeCourse.get(bestSC.getJobCount()).instanceId, bestSC.getJobCount());
} else {
pacc.log("c Incumbent reached maximum number of evaluations. No more jobs are generated for it.");
}
} else {
pacc.expandParcoursSC(bestSC, 1);
}
pacc.addSolverConfigurationToListNewSC(bestSC);
curThreshold += increaseIncumbentRunsEvery;
}
}*/
challengers.addAll(scs);
}
@Override
public int computeOptimalExpansion(int coreCount, int jobs, int listNewSCSize) {
if (coreCount < parameters.getMinCPUCount() || coreCount > parameters.getMaxCPUCount()) {
pacc.log("w Warning: Current core count is " + coreCount);
}
if (parameters.getJobCPUTimeLimit() > 10) {
if (Math.max(0, coreCount - jobs) > 0) {
pacc.log("c [DefaultSMBO] coreCount: " + coreCount + ", Jobs to finish: " + jobs);
}
return Math.max(0, coreCount - jobs);
} else {
return Math.max(0, 2 * coreCount - jobs);
}
/*if (challengers.size() > 0) {
return 0;
}
else {
pacc.log("c Requesting " + coreCount + " configurations from search");
return coreCount;
}*/
/*int min_sc = (Math.max(Math.round(4.f * coreCount), 8) - jobs) / parameters.getMinRuns();
if (min_sc > 0) {
res = (Math.max(Math.round(6.f * coreCount), 8) - jobs) / parameters.getMinRuns();
}
if (listNewSCSize == 0 && res == 0) {
res = 1;
}
return res;*/
}
@Override
public List<String> getParameters() {
List<String> p = new LinkedList<String>();
p.add("%
p.add("DefaultSMBO_adaptiveCapping = " + (adaptiveCapping ? 1 : 0) + " % (Use adaptive capping mechanism)");
p.add("DefaultSMBO_increaseIncumbentRunsEvery = " + increaseIncumbentRunsEvery + " % (How many challengers does the incumbent have to beat to gain additional runs)");
p.add("DefaultSMBO_aggressiveJobSelection = " + (aggressiveJobSelection ? 1 : 0) + " % (Challengers should start on instances where the best configuration did not time out)");
p.add("DefaultSMBO_featureFolder = " + featureFolder + " % (Instance feature computation folder containing a features.propertiers file)");
p.add("DefaultSMBO_featureCacheFolder = " + featureCacheFolder + " % (Temporary folder used for caching instance features)");
p.add("DefaultSMBO_useClusterCourse = " + (useClusterCourse ? 1 : 0) + " % (Cluster instances using instance properties for improved handling of heterogenous instance sets)");
p.add("DefaultSMBO_slackFactor = " + slackFactor + " % (Slack factor used with adaptive capping (new timeout = slackFactor * best known time))");
p.add("DefaultSMBO_adaptiveCapping = " + (adaptiveCapping ? 1 : 0) + " % (Lower time limit on instances according to the results of the best configuration)");
p.add("DefaultSMBO_clusterSizeExpansion = " + clusterSizeExpansion + " % (If the cluster course is used, give the incumbent configuration k additional runs instead of one (k = no. of clusters))");
return p;
}
@Override
public List<SolverConfiguration> getBestSolverConfigurations() {
List<SolverConfiguration> res = new LinkedList<SolverConfiguration>();
if (bestSC != null) {
res.add(bestSC);
}
return res;
}
@Override
public void stopEvaluation(List<SolverConfiguration> scs) throws Exception {
for (SolverConfiguration sc : scs) {
stopEvalSolverConfigIds.add(sc.getIdSolverConfiguration());
}
}
@Override
public void raceFinished() {
// TODO Auto-generated method stub
}
@Override
public void jobsFinished(List<ExperimentResult> result) throws Exception {
// adapt instance specific limits
if (adaptiveCapping && ExperimentDAO.getById(parameters.getIdExperiment()).getDefaultCost().equals(Cost.resultTime)) {
boolean anyIncumbentRunsFinished = false;
for (ExperimentResult run: result) {
if (run.getSolverConfigId() == bestSC.getIdSolverConfiguration()) {
anyIncumbentRunsFinished = true;
break;
}
}
if (!anyIncumbentRunsFinished) return;
for (Instance instance: api.getExperimentInstances(parameters.getIdExperiment())) {
double incumbentAvg = 0.0f;
int count = 0;
for (ExperimentResult run: bestSC.getFinishedJobs()) {
if (run.getInstanceId() == instance.getId()) {
incumbentAvg += parameters.getStatistics().getCostFunction().singleCost(run);
count++;
}
}
if (count > 0) {
incumbentAvg /= count;
int newLimit = Math.max(1, Math.min((int)Math.ceil(slackFactor * incumbentAvg), parameters.getJobCPUTimeLimit()));
if (limitByInstance.get(instance.getId()) != null && limitByInstance.get(instance.getId()) == newLimit) {
// limit did not change
continue;
}
limitByInstance.put(instance.getId(), newLimit);
pacc.changeCPUTimeLimit(instance.getId(), newLimit, new LinkedList<SolverConfiguration>(challengers), false, false);
}
}
}
}
} |
package de.diddiz.utils.sql.databases;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* A simple class containing a {@link Connection}. {@code SimpleDatabase} is meant to be used for local databases like sqlite or H2.
*
* Sub-classes should add methods to handle common queries, so the actual code doesn't have to handle SQL stuff.
*/
public abstract class SimpleDatabase implements AutoCloseable
{
/**
* Do never close this manually. When the database is no longer needed use {@link #close()} instead.
*/
protected final Connection conn;
public SimpleDatabase(String driver, String url, String user, String pw) throws SQLException {
try {
Class.forName(driver);
} catch (final ClassNotFoundException ex) {
throw new AssertionError(ex);
}
conn = DriverManager.getConnection(url, user, pw);
// Initialize database
try (Statement st = conn.createStatement()) {
initializeTables(st);
}
}
@Override
public void close() throws SQLException {
conn.close();
}
/**
* This method is called every time a connection is created.
*
* Please use <code>CREATE TABLE IF NOT EXISTS [...]</code>.
*/
protected abstract void initializeTables(Statement st) throws SQLException;
protected static String escape(String str) {
if (str.indexOf('\'') > 0)
str = str.replace("'", "''");
return str;
}
} |
package de.kuehweg.sqltool.itrysql;
import de.kuehweg.sqltool.common.DialogDictionary;
import de.kuehweg.sqltool.common.FileUtil;
import de.kuehweg.sqltool.common.ProvidedAudioClip;
import de.kuehweg.sqltool.common.RomanNumber;
import de.kuehweg.sqltool.common.UserPreferencesManager;
import de.kuehweg.sqltool.common.sqlediting.ConnectionSetting;
import de.kuehweg.sqltool.common.sqlediting.ManagedConnectionSettings;
import de.kuehweg.sqltool.common.sqlediting.SQLHistory;
import de.kuehweg.sqltool.common.sqlediting.SQLHistoryKeeper;
import de.kuehweg.sqltool.common.sqlediting.StatementExtractor;
import de.kuehweg.sqltool.database.ConnectionHolder;
import de.kuehweg.sqltool.database.JDBCType;
import de.kuehweg.sqltool.dialog.AlertBox;
import de.kuehweg.sqltool.dialog.ConnectionDialog;
import de.kuehweg.sqltool.dialog.ErrorMessage;
import de.kuehweg.sqltool.dialog.License;
import de.kuehweg.sqltool.dialog.action.ExecuteAction;
import de.kuehweg.sqltool.dialog.action.ExecutionGUIUpdater;
import de.kuehweg.sqltool.dialog.action.FontAction;
import de.kuehweg.sqltool.dialog.action.SchemaTreeBuilderTask;
import de.kuehweg.sqltool.dialog.action.ScriptAction;
import de.kuehweg.sqltool.dialog.action.TutorialAction;
import de.kuehweg.sqltool.dialog.component.ConnectionComponentController;
import de.kuehweg.sqltool.dialog.component.QueryResultTableView;
import de.kuehweg.sqltool.dialog.component.ServerComponentController;
import de.kuehweg.sqltool.dialog.component.SourceFileDropTargetUtil;
import de.kuehweg.sqltool.dialog.environment.ExecutionInputEnvironment;
import de.kuehweg.sqltool.dialog.environment.ExecutionProgressEnvironment;
import de.kuehweg.sqltool.dialog.environment.ExecutionResultEnvironment;
import de.kuehweg.sqltool.dialog.util.WebViewWithHSQLDBBugfix;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.prefs.BackingStoreException;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Slider;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;
import javafx.scene.control.ToolBar;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import javax.xml.bind.JAXBException;
public class iTrySQLController implements Initializable, SQLHistoryKeeper,
EventHandler<WindowEvent> {
@FXML
private TitledPane accordionPreferences;
@FXML
private TitledPane accordionSchemaTreeView;
@FXML
private CheckBox autoCommit;
@FXML
private ComboBox<ProvidedAudioClip> beepSelection;
@FXML
private Slider beepVolume;
@FXML
private TextField connectionDbName;
@FXML
private Button connectionDirectoryChoice;
@FXML
private TextField connectionName;
@FXML
private ComboBox<ConnectionSetting> connectionSelection;
@FXML
private ComboBox<JDBCType> connectionType;
@FXML
private TextField connectionUrl;
@FXML
private TextField connectionUser;
@FXML
private TextArea dbOutput;
@FXML
private ProgressBar executionProgressIndicator;
@FXML
private Label executionTime;
@FXML
private CheckBox limitMaxRows;
@FXML
private MenuBar menuBar;
@FXML
private MenuItem menuItemClose;
@FXML
private MenuItem menuItemCommit;
@FXML
private MenuItem menuItemConnect;
@FXML
private MenuItem menuItemDisconnect;
@FXML
private MenuItem menuItemCopy;
@FXML
private MenuItem menuItemCut;
@FXML
private MenuItem menuItemExecute;
@FXML
private MenuItem menuItemExecuteScript;
@FXML
private MenuItem menuItemFileOpenScript;
@FXML
private MenuItem menuItemFileSaveScript;
@FXML
private MenuItem menuItemPaste;
@FXML
private MenuItem menuItemRollback;
@FXML
private MenuItem menuItemNewSession;
@FXML
private Button refreshTree;
@FXML
private HBox resultTableContainer;
@FXML
private TreeView<String> schemaTreeView;
@FXML
private ComboBox<ConnectionSetting> serverConnectionSelection;
@FXML
private TableView<SQLHistory> sqlHistory;
@FXML
private TableColumn<SQLHistory, String> sqlHistoryColumnStatement;
@FXML
private TableColumn<SQLHistory, String> sqlHistoryColumnTimestamp;
@FXML
private Button startServer;
@FXML
private Button shutdownServer;
@FXML
private TextArea statementInput;
@FXML
private AnchorPane statementPane;
@FXML
private Tab tabDbOutput;
@FXML
private Tab tabHistory;
@FXML
private TabPane tabPaneProtocols;
@FXML
private Tab tabResult;
@FXML
private ToolBar toolBar;
@FXML
private Button toolbarCommit;
@FXML
private Button toolbarExecute;
@FXML
private Button toolbarRollback;
@FXML
private Button toolbarTabDbOutputClear;
@FXML
private Button toolbarTabDbOutputExport;
@FXML
private Button toolbarTabDbOutputZoomIn;
@FXML
private Button toolbarTabDbOutputZoomOut;
@FXML
private Button toolbarTabTableViewExport;
@FXML
private Button toolbarTutorialData;
@FXML
private Button toolbarZoomIn;
@FXML
private Button toolbarZoomOut;
@FXML
private VBox connectionSettings;
@FXML
private Button createConnection;
@FXML
private Button editConnection;
@FXML
private Button removeConnection;
@FXML
private Button exportConnections;
@FXML
private Button importConnections;
@FXML
private Label permanentMessage;
@FXML
private TextField serverAlias;
@FXML
private WebView syntaxDefinitionView;
// my own special creation
private ConnectionHolder connectionHolder;
private ObservableList<SQLHistory> sqlHistoryItems;
private ConnectionComponentController connectionComponentController;
private ServerComponentController serverComponentController;
private static int countWindows = 1;
@Override
public void initialize(final URL fxmlFileLocation,
final ResourceBundle resources) {
assert accordionPreferences != null : "fx:id=\"accordionPreferences\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert accordionSchemaTreeView != null : "fx:id=\"accordionSchemaTreeView\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert autoCommit != null : "fx:id=\"autoCommit\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert beepSelection != null : "fx:id=\"beepSelection\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert beepVolume != null : "fx:id=\"beepVolume\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert connectionDbName != null : "fx:id=\"connectionDbName\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert connectionDirectoryChoice != null : "fx:id=\"connectionDirectoryChoice\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert connectionName != null : "fx:id=\"connectionName\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert connectionSelection != null : "fx:id=\"connectionSelection\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert connectionSettings != null : "fx:id=\"connectionSettings\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert connectionType != null : "fx:id=\"connectionType\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert connectionUrl != null : "fx:id=\"connectionUrl\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert connectionUser != null : "fx:id=\"connectionUser\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert createConnection != null : "fx:id=\"createConnection\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert dbOutput != null : "fx:id=\"dbOutput\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert editConnection != null : "fx:id=\"editConnection\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert executionProgressIndicator != null : "fx:id=\"executionProgressIndicator\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert executionTime != null : "fx:id=\"executionTime\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert limitMaxRows != null : "fx:id=\"limitMaxRows\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuBar != null : "fx:id=\"menuBar\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemClose != null : "fx:id=\"menuItemClose\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemCommit != null : "fx:id=\"menuItemCommit\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemConnect != null : "fx:id=\"menuItemConnect\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemDisconnect != null : "fx:id=\"menuItemDisconnect\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemCopy != null : "fx:id=\"menuItemCopy\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemCut != null : "fx:id=\"menuItemCut\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemExecute != null : "fx:id=\"menuItemExecute\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemExecuteScript != null : "fx:id=\"menuItemExecuteScript\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemFileOpenScript != null : "fx:id=\"menuItemFileOpenScript\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemFileSaveScript != null : "fx:id=\"menuItemFileSaveScript\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemPaste != null : "fx:id=\"menuItemPaste\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemRollback != null : "fx:id=\"menuItemRollback\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert menuItemNewSession != null : "fx:id=\"menuItemNewSession\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert permanentMessage != null : "fx:id=\"permanentMessage\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert refreshTree != null : "fx:id=\"refreshTree\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert removeConnection != null : "fx:id=\"removeConnection\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert resultTableContainer != null : "fx:id=\"resultTableContainer\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert schemaTreeView != null : "fx:id=\"schemaTreeView\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert serverAlias != null : "fx:id=\"serverAlias\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert serverConnectionSelection != null : "fx:id=\"serverConnectionSelection\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert shutdownServer != null : "fx:id=\"shutdownServer\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert sqlHistory != null : "fx:id=\"sqlHistory\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert sqlHistoryColumnStatement != null : "fx:id=\"sqlHistoryColumnStatement\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert sqlHistoryColumnTimestamp != null : "fx:id=\"sqlHistoryColumnTimestamp\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert startServer != null : "fx:id=\"startServer\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert statementInput != null : "fx:id=\"statementInput\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert statementPane != null : "fx:id=\"statementPane\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert tabDbOutput != null : "fx:id=\"tabDbOutput\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert tabHistory != null : "fx:id=\"tabHistory\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert tabPaneProtocols != null : "fx:id=\"tabPaneProtocols\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert tabResult != null : "fx:id=\"tabResult\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolBar != null : "fx:id=\"toolBar\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarCommit != null : "fx:id=\"toolbarCommit\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarExecute != null : "fx:id=\"toolbarExecute\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarRollback != null : "fx:id=\"toolbarRollback\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarTabDbOutputClear != null : "fx:id=\"toolbarTabDbOutputClear\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarTabDbOutputExport != null : "fx:id=\"toolbarTabDbOutputExport\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarTabTableViewExport != null : "fx:id=\"toolbarTabTableViewExport\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarTutorialData != null : "fx:id=\"toolbarTutorialData\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarZoomIn != null : "fx:id=\"toolbarZoomIn\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarTabDbOutputZoomOut != null : "fx:id=\"toolbarTabDbOutputZoomOut\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarTabDbOutputZoomIn != null : "fx:id=\"toolbarTabDbOutputZoomIn\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert toolbarZoomOut != null : "fx:id=\"toolbarZoomOut\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert syntaxDefinitionView != null : "fx:id=\"syntaxDefinitionView\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert exportConnections != null : "fx:id=\"exportConnections\" was not injected: check your FXML file 'iTrySQL.fxml'.";
assert importConnections != null : "fx:id=\"importConnections\" was not injected: check your FXML file 'iTrySQL.fxml'.";
fixWebViewWithHSQLDBBug();
initializeContinued();
}
// sollte mit wenigen Handgriffen des Anwenders der Normalzustand
private void fixWebViewWithHSQLDBBug() {
syntaxDefinitionView.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent t) {
WebViewWithHSQLDBBugfix.fix();
}
});
syntaxDefinitionView.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent t) {
WebViewWithHSQLDBBugfix.fix();
}
});
}
public void about(final ActionEvent event) {
// FIXME
WebViewWithHSQLDBBugfix.fix();
final License aboutBox = new License();
aboutBox.showAndWait();
}
public void autoCommit(final ActionEvent event) {
// Auto-Commit ist keine echte Benutzereinstellung sondern wird pro
// Verbindung gesteuert, z.T. auch durch JDBC-Vorgaben
if (getConnectionHolder().getConnection() == null) {
final AlertBox msg = new AlertBox(
DialogDictionary.MESSAGEBOX_WARNING.toString(),
DialogDictionary.MSG_NO_DB_CONNECTION.toString(),
DialogDictionary.COMMON_BUTTON_OK.toString());
msg.askUserFeedback();
} else {
try {
connectionHolder.getConnection().setAutoCommit(
autoCommit.isSelected());
} catch (final SQLException ex) {
final ErrorMessage msg = new ErrorMessage(
DialogDictionary.MESSAGEBOX_ERROR.toString(),
DialogDictionary.ERR_AUTO_COMMIT_FAILURE.toString(),
DialogDictionary.COMMON_BUTTON_OK.toString());
msg.askUserFeedback();
}
}
}
public void newSession(final ActionEvent event) {
final String title = DialogDictionary.APPLICATION.toString() + "("
+ new RomanNumber(countWindows++).toString().toLowerCase()
+ ")";
final ITrySQLStage iTrySQLStage = new ITrySQLStage((Stage) menuBar
.getScene().getWindow(), title);
iTrySQLStage.show();
}
public void clipboardCopy(final ActionEvent event) {
// currently no action
}
public void clipboardCut(final ActionEvent event) {
// currently no action
}
public void clipboardPaste(final ActionEvent event) {
// currently no action
}
public void connect(final ActionEvent event) {
final ConnectionDialog connectionDialog = new ConnectionDialog();
connectionDialog.showAndWait();
final ConnectionSetting connectionSetting = connectionDialog
.getConnectionSetting();
if (connectionSetting != null) {
getConnectionHolder().connect(connectionSetting);
controlAutoCommitCheckBoxState();
refreshTree(event);
if (connectionSetting.getType() == JDBCType.HSQL_IN_MEMORY) {
permanentMessage.setText(MessageFormat.format(
DialogDictionary.PATTERN_MESSAGE_IN_MEMORY_DATABASE
.toString(), connectionSetting.getName()));
permanentMessage.visibleProperty().set(true);
} else {
permanentMessage.visibleProperty().set(false);
}
// FIXME
WebViewWithHSQLDBBugfix.fix();
}
}
public void disconnect(final ActionEvent event) {
getConnectionHolder().disconnect();
refreshTree(null);
permanentMessage.visibleProperty().set(false);
}
public void execute(final ActionEvent event) {
// Markierter Text?
String sql = statementInput.getSelectedText();
// sonst die Anweisung, in der sich die Eingabemarkierung befindet
if (sql.trim().length() == 0) {
sql = StatementExtractor
.extractStatementAtCaretPosition(statementInput.getText(),
statementInput.getCaretPosition());
}
createExecuteAction().handleExecuteAction(sql);
}
public void executeScript(final ActionEvent event) {
createExecuteAction().handleExecuteAction(statementInput.getText());
}
public void commit(final ActionEvent event) {
createExecuteAction().handleExecuteAction("COMMIT");
}
public void rollback(final ActionEvent event) {
createExecuteAction().handleExecuteAction("ROLLBACK");
}
public void fontAction(final ActionEvent event) {
FontAction.handleFontAction(event);
}
public void tutorialAction(final ActionEvent event) {
new TutorialAction().createTutorial(createExecuteAction());
}
public void fileOpenScriptAction(final ActionEvent event) {
new ScriptAction(statementInput).loadScript();
}
public void fileSaveScriptAction(final ActionEvent event) {
new ScriptAction(statementInput).saveScript();
}
public void limitMaxRows(final ActionEvent event) {
UserPreferencesManager.getSharedInstance().setLimitMaxRows(
limitMaxRows.isSelected());
}
public void quit(final ActionEvent event) {
Platform.exit();
}
public void toolbarTabDbOutputClearAction(final ActionEvent event) {
dbOutput.clear();
}
private void export(final DialogDictionary fileChooserTitle,
final Window attachChooser, final String filenameExtension,
final String exportContent) {
final FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(fileChooserTitle.toString());
final File file = fileChooser.showSaveDialog(attachChooser);
if (file != null) {
try {
FileUtil.writeFile(FileUtil.enforceExtension(
file.toURI().toURL(), filenameExtension),
exportContent);
} catch (final IOException ex) {
final ErrorMessage msg = new ErrorMessage(
DialogDictionary.MESSAGEBOX_ERROR.toString(),
DialogDictionary.ERR_FILE_SAVE_FAILED.toString(),
DialogDictionary.COMMON_BUTTON_OK.toString());
msg.askUserFeedback();
}
}
}
public void toolbarTabDbOutputExportAction(final ActionEvent event) {
export(DialogDictionary.LABEL_SAVE_OUTPUT, ((Node) event.getSource())
.getScene().getWindow(), "txt", dbOutput.getText());
}
public void toolbarTabTableViewExportAction(final ActionEvent event) {
if (resultTableContainer.getChildren() != null) {
for (final Node node : resultTableContainer.getChildren()) {
if (ExecutionGUIUpdater.RESULT_TABLE_ID.equals(node.getId())) {
export(DialogDictionary.LABEL_SAVE_OUTPUT_HTML,
((Node) event.getSource()).getScene().getWindow(),
"html", ((QueryResultTableView) node).toHtml());
}
}
}
}
public void refreshTree(final ActionEvent event) {
final Task<Void> refreshTask = new SchemaTreeBuilderTask(
getConnectionHolder().getConnection(), schemaTreeView);
final Thread th = new Thread(refreshTask);
th.setDaemon(true);
th.start();
}
public void cancelConnectionSettings(final ActionEvent event) {
connectionComponentController.cancelEdit();
}
public void changeConnection(final ActionEvent event) {
connectionComponentController.changeConnection();
}
public void changeConnectionType(final ActionEvent event) {
connectionComponentController.changeConnectionType();
}
public void chooseDbDirectory(final ActionEvent event) {
connectionComponentController.chooseDbDirectory();
}
public void createConnection(final ActionEvent event) {
connectionComponentController.createConnection();
}
public void editConnection(final ActionEvent event) {
connectionComponentController.editConnection();
}
public void removeConnection(final ActionEvent event) {
connectionComponentController.removeConnection();
serverComponentController.refreshServerConnectionSettings();
}
public void saveConnectionSettings(final ActionEvent event) {
connectionComponentController.saveConnectionSettings();
serverComponentController.refreshServerConnectionSettings();
}
public void exportConnections(ActionEvent event) {
final FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(DialogDictionary.LABEL_EXPORT_CONNECTIONS.
toString());
final File file = fileChooser.showSaveDialog(((Node) event.getSource())
.getScene().getWindow());
if (file != null) {
try {
new ManagedConnectionSettings().exportToFile(file);
} catch (JAXBException ex) {
final ErrorMessage msg = new ErrorMessage(
DialogDictionary.MESSAGEBOX_ERROR.toString(),
DialogDictionary.ERR_FILE_SAVE_FAILED.toString(),
DialogDictionary.COMMON_BUTTON_OK.toString());
msg.askUserFeedback();
}
}
}
public void importConnections(ActionEvent event) {
final FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(DialogDictionary.LABEL_IMPORT_CONNECTIONS.
toString());
final File file = fileChooser.showOpenDialog(((Node) event.getSource())
.getScene().getWindow());
if (file != null) {
try {
new ManagedConnectionSettings().importFromFile(file);
connectionComponentController.saveConnectionSettings();
serverComponentController.refreshServerConnectionSettings();
} catch (JAXBException | BackingStoreException ex) {
final ErrorMessage msg = new ErrorMessage(
DialogDictionary.MESSAGEBOX_ERROR.toString(),
DialogDictionary.ERR_FILE_OPEN_FAILED.toString(),
DialogDictionary.COMMON_BUTTON_OK.toString());
msg.askUserFeedback();
}
}
}
public void changeServerConnection(final ActionEvent event) {
serverComponentController.changeServerConnection();
}
public void startServer(final ActionEvent event) {
serverComponentController.startServer();
}
public void shutdownServer(final ActionEvent event) {
serverComponentController.shutdownServer();
}
private void initializeContinued() {
initializeConnectionComponentController();
initializeServerComponentController();
prepareHistory();
initializeUserPreferences();
setupTooltips();
setupMenu();
controlAutoCommitCheckBoxState();
permanentMessage.visibleProperty().set(false);
refreshTree(null);
SourceFileDropTargetUtil.transformIntoSourceFileDropTarget(
statementPane, statementInput);
syntaxDefinitionView.getEngine().load(
this.getClass().getResource("/resources/syntax/index.html")
.toExternalForm());
}
private void initializeUserPreferences() {
statementInput.setStyle("-fx-font-size: "
+ UserPreferencesManager.getSharedInstance().
getFontSizeStatementInput()
+ ";");
dbOutput.setStyle("-fx-font-size: "
+ UserPreferencesManager.getSharedInstance().
getFontSizeDbOutput()
+ ";");
limitMaxRows.setSelected(UserPreferencesManager.getSharedInstance()
.isLimitMaxRows());
beepSelection.getItems().clear();
beepSelection.getItems().addAll(ProvidedAudioClip.values());
beepSelection.setValue(UserPreferencesManager.getSharedInstance().
getBeepAudioClip());
beepSelection.valueProperty().addListener(
new ChangeListener<ProvidedAudioClip>() {
@Override
public void changed(
ObservableValue<? extends ProvidedAudioClip> ov,
ProvidedAudioClip oldValue, ProvidedAudioClip newValue) {
if (newValue != null) {
UserPreferencesManager.getSharedInstance().setBeepAudioClip(
newValue);
}
}
});
beepVolume.valueProperty().set(UserPreferencesManager.
getSharedInstance().getBeepVolume());
beepVolume.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(
ObservableValue<? extends Number> ov, Number oldValue,
Number newValue) {
if (newValue != null) {
UserPreferencesManager.getSharedInstance().setBeepVolume(
newValue.doubleValue());
}
}
});
}
private void initializeConnectionComponentController() {
final ConnectionComponentController.Builder builder =
new ConnectionComponentController.Builder(
connectionSettings);
builder.connectionName(connectionName);
builder.connectionSelection(connectionSelection);
builder.connectionType(connectionType);
builder.connectionUrl(connectionUrl);
builder.connectionUser(connectionUser);
builder.dbName(connectionDbName);
builder.browseButton(connectionDirectoryChoice);
builder.editButton(editConnection);
builder.removeButton(removeConnection);
connectionComponentController = builder.build();
}
private void initializeServerComponentController() {
serverComponentController = new ServerComponentController.Builder()
.serverConnectionSelection(serverConnectionSelection)
.startButton(startServer).shutdownButton(shutdownServer)
.serverAlias(serverAlias).build();
serverComponentController.refreshServerConnectionSettings();
}
private void setupTooltips() {
Tooltip.install(toolbarExecute, new Tooltip(
DialogDictionary.TOOLTIP_EXECUTE.toString()));
Tooltip.install(toolbarCommit, new Tooltip(
DialogDictionary.TOOLTIP_COMMIT.toString()));
Tooltip.install(toolbarRollback, new Tooltip(
DialogDictionary.TOOLTIP_ROLLBACK.toString()));
Tooltip.install(toolbarZoomOut, new Tooltip(
DialogDictionary.TOOLTIP_DECREASE_FONTSIZE.toString()));
Tooltip.install(toolbarZoomIn, new Tooltip(
DialogDictionary.TOOLTIP_INCREASE_FONTSIZE.toString()));
Tooltip.install(toolbarTutorialData, new Tooltip(
DialogDictionary.TOOLTIP_TUTORIAL_DATA.toString()));
Tooltip.install(toolbarTabTableViewExport, new Tooltip(
DialogDictionary.TOOLTIP_EXPORT_RESULT.toString()));
Tooltip.install(toolbarTabDbOutputExport, new Tooltip(
DialogDictionary.TOOLTIP_EXPORT_OUTPUT.toString()));
Tooltip.install(toolbarTabDbOutputClear, new Tooltip(
DialogDictionary.TOOLTIP_CLEAR_OUTPUT.toString()));
Tooltip.install(toolbarTabDbOutputZoomOut, new Tooltip(
DialogDictionary.TOOLTIP_DECREASE_FONTSIZE.toString()));
Tooltip.install(toolbarTabDbOutputZoomIn, new Tooltip(
DialogDictionary.TOOLTIP_INCREASE_FONTSIZE.toString()));
}
private void setupMenu() {
menuItemExecute.setAccelerator(new KeyCodeCombination(KeyCode.ENTER,
KeyCombination.SHORTCUT_DOWN));
menuItemExecuteScript.setAccelerator(new KeyCodeCombination(
KeyCode.ENTER, KeyCombination.SHORTCUT_DOWN,
KeyCombination.SHIFT_DOWN));
menuItemFileOpenScript.setAccelerator(new KeyCodeCombination(KeyCode.O,
KeyCombination.SHORTCUT_DOWN));
menuItemFileSaveScript.setAccelerator(new KeyCodeCombination(KeyCode.S,
KeyCombination.SHORTCUT_DOWN));
menuItemNewSession.setAccelerator(new KeyCodeCombination(KeyCode.N,
KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
menuItemConnect.setAccelerator(new KeyCodeCombination(KeyCode.L,
KeyCombination.SHORTCUT_DOWN));
menuItemDisconnect.disableProperty().bind(
Bindings.not(getConnectionHolder().connectedProperty()));
}
private void controlAutoCommitCheckBoxState() {
if (getConnectionHolder().getConnection() != null) {
try {
autoCommit.setSelected(connectionHolder.getConnection()
.getAutoCommit());
} catch (final SQLException ex) {
autoCommit.setSelected(true);
}
}
}
private void prepareHistory() {
sqlHistoryItems = FXCollections.observableArrayList();
sqlHistoryColumnTimestamp
.setCellValueFactory(
new PropertyValueFactory<SQLHistory, String>(
"timestamp"));
sqlHistoryColumnStatement
.setCellValueFactory(
new PropertyValueFactory<SQLHistory, String>(
"sqlForDisplay"));
sqlHistory.setItems(sqlHistoryItems);
sqlHistory.getSelectionModel().selectedItemProperty()
.addListener(new ChangeListener<SQLHistory>() {
@Override
public void changed(
final ObservableValue<? extends SQLHistory> ov,
final SQLHistory oldValue, final SQLHistory newValue) {
if (newValue != null) {
statementInput.appendText(newValue.getOriginalSQL());
}
}
});
}
private ExecuteAction createExecuteAction() {
final ExecutionInputEnvironment input =
new ExecutionInputEnvironment.Builder(
getConnectionHolder()).limitMaxRows(
UserPreferencesManager.getSharedInstance().isLimitMaxRows())
.build();
final ExecutionProgressEnvironment progress =
new ExecutionProgressEnvironment.Builder(
executionProgressIndicator).executionTime(executionTime)
.build();
final ExecutionResultEnvironment result =
new ExecutionResultEnvironment.Builder()
.tabPaneContainingResults(tabPaneProtocols)
.tabResult(tabResult)
.tabDbOutput(tabDbOutput)
.dbOutput(dbOutput)
.historyKeeper(this)
.resultTableContainer(resultTableContainer).build();
return new ExecuteAction(input, progress, result);
}
@Override
public void handle(final WindowEvent event) {
getConnectionHolder().disconnect();
}
@Override
public void addExecutedSQLToHistory(final String sql) {
if (sql != null && sql.trim().length() > 0) {
sqlHistoryItems.add(0, new SQLHistory(sql));
}
}
public ConnectionHolder getConnectionHolder() {
if (connectionHolder == null) {
connectionHolder = new ConnectionHolder();
}
return connectionHolder;
}
} |
package de.lmu.ifi.dbs.algorithm;
import de.lmu.ifi.dbs.algorithm.result.CorrelationAnalysisSolution;
import de.lmu.ifi.dbs.data.RealVector;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.Distance;
import de.lmu.ifi.dbs.linearalgebra.LinearEquation;
import de.lmu.ifi.dbs.linearalgebra.Matrix;
import de.lmu.ifi.dbs.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.pca.LinearLocalPCA;
import de.lmu.ifi.dbs.utilities.Description;
import de.lmu.ifi.dbs.utilities.QueryResult;
import de.lmu.ifi.dbs.utilities.Util;
import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings;
import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.utilities.optionhandling.WrongParameterValueException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
/**
* Dependency derivator computes quantitativly linear dependencies among
* attributes of a given dataset based on a linear correlation PCA.
*
* @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>)
*/
public class DependencyDerivator<D extends Distance<D>> extends
DistanceBasedAlgorithm<RealVector, D>
{
/**
* Holds the class specific debug status.
*/
private static final boolean DEBUG = LoggingConfiguration.DEBUG;
/**
* The logger of this class.
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Parameter name for alpha - threshold to discern strong from weak
* Eigenvectors.
*/
public static final String ALPHA_P = "alpha";
/**
* Default value for alpha.
*/
public static final double ALPHA_DEFAULT = 0.85;
/**
* Description for parameter alpha - threshold to discern strong from weak
* Eigenvectors.
*/
public static final String ALPHA_D = "<double>threshold to discern strong from weak Eigenvectors ([0:1)) - default: "
+ ALPHA_DEFAULT
+ ". Corresponds to the percentage of variance, that is to be explained by a set of strongest Eigenvectors.";
/**
* Parameter for correlation dimensionality.
*/
public static final String DIMENSIONALITY_P = "corrdim";
/**
* Description for parameter correlation dimensionality.
*/
public static final String DIMENSIONALITY_D = "<int>desired correlation dimensionality (> 0 - number of strong Eigenvectors). This parameter is ignored, if parameter "
+ ALPHA_P + " is set.";
/**
* Parameter for output accuracy (number of fraction digits).
*/
public static final String OUTPUT_ACCURACY_P = "accuracy";
/**
* Default value for output accuracy (number of fraction digits).
*/
public static final int OUTPUT_ACCURACY_DEFAULT = 4;
/**
* Description for parameter output accuracy (number of fraction digits).
*/
public static final String OUTPUT_ACCURACY_D = "<integer>output accuracy fraction digits (>0) (default: "
+ OUTPUT_ACCURACY_DEFAULT + ").";
/**
* Parameter for size of random sample.
*/
public static final String SAMPLE_SIZE_P = "sampleSize";
/**
* Description for parameter for size of random sample.
*/
public static final String SAMPLE_SIZE_D = "<int>size (> 0) of random sample to use (default: use of complete dataset).";
/**
* Flag for use of random sample.
*/
public static final String RANDOM_SAMPLE_F = "randomSample";
/**
* Description for flag for use of random sample.
*/
public static final String RANDOM_SAMPLE_D = "flag to use random sample (use knn query around centroid, if flag is not set). Flag is ignored if no sample size is specified.";
/**
* Holds alpha.
*/
protected double alpha;
/**
* Holds the correlation dimensionality.
*/
protected int corrdim;
/**
* Holds size of sample.
*/
protected int sampleSize;
/**
* Holds the object performing the pca.
*/
private LinearLocalPCA pca;
/**
* Holds the solution.
*/
protected CorrelationAnalysisSolution solution;
/**
* Number format for output of solution.
*/
public final NumberFormat NF = NumberFormat.getInstance(Locale.US);
/**
* Provides a dependency derivator, setting parameters alpha and output
* accuracy additionally to parameters of super class.
*/
public DependencyDerivator()
{
super();
parameterToDescription.put(ALPHA_P + OptionHandler.EXPECTS_VALUE,
ALPHA_D);
parameterToDescription.put(OUTPUT_ACCURACY_P
+ OptionHandler.EXPECTS_VALUE, OUTPUT_ACCURACY_D);
parameterToDescription.put(SAMPLE_SIZE_P + OptionHandler.EXPECTS_VALUE,
SAMPLE_SIZE_D);
parameterToDescription.put(RANDOM_SAMPLE_F, RANDOM_SAMPLE_D);
parameterToDescription.put(DIMENSIONALITY_P
+ OptionHandler.EXPECTS_VALUE, DIMENSIONALITY_D);
optionHandler = new OptionHandler(parameterToDescription, this
.getClass().getName());
}
/**
* @see Algorithm#getDescription()
*/
public Description getDescription()
{
return new Description(
"DependencyDerivator",
"Deriving numerical inter-dependencies on data",
"Derives an equality-system describing dependencies between attributes in a correlation-cluster",
"unpublished");
}
/**
* Calls {@link #runInTime(Database, Integer) run(db,null)}.
*
* @see AbstractAlgorithm#runInTime(Database)
*/
protected void runInTime(Database<RealVector> db)
throws IllegalStateException
{
runInTime(db, null);
}
public void runInTime(Database<RealVector> db,
Integer correlationDimensionality) throws IllegalStateException
{
if (isVerbose())
{
logger.info("retrieving database objects...\n");
}
List<Integer> dbIDs = new ArrayList<Integer>();
for (Iterator<Integer> idIter = db.iterator(); idIter.hasNext();)
{
dbIDs.add(idIter.next());
}
RealVector centroidDV = Util.centroid(db, dbIDs);
List<Integer> ids;
if (this.sampleSize >= 0)
{
if (optionHandler.isSet(RANDOM_SAMPLE_F))
{
ids = db.randomSample(this.sampleSize, 1);
} else
{
List<QueryResult<D>> queryResults = db
.kNNQueryForObject(centroidDV, this.sampleSize, this
.getDistanceFunction());
ids = new ArrayList<Integer>(this.sampleSize);
for (QueryResult<D> qr : queryResults)
{
ids.add(qr.getID());
}
}
} else
{
ids = dbIDs;
}
if (isVerbose())
{
logger.info("PCA...\n");
}
if (correlationDimensionality != null)
{
pca.run(ids, db, correlationDimensionality);
} else if (!optionHandler.isSet(ALPHA_P)
&& optionHandler.isSet(DIMENSIONALITY_P))
{
pca.run(ids, db, corrdim);
} else
{
pca.run(ids, db, alpha);
}
Matrix weakEigenvectors = pca.getEigenvectors().times(
pca.getSelectionMatrixOfWeakEigenvectors());
Matrix transposedWeakEigenvectors = weakEigenvectors.transpose();
if (DEBUG)
{
StringBuilder log = new StringBuilder();
log.append("strong Eigenvectors:\n");
log.append(pca.getEigenvectors().times(
pca.getSelectionMatrixOfStrongEigenvectors()).toString(NF));
log.append('\n');
log.append("transposed weak Eigenvectors:\n");
log.append(transposedWeakEigenvectors.toString(NF));
log.append('\n');
log.append("Eigenvalues:\n");
log.append(Util.format(pca.getEigenvalues(), " , ", 2));
log.append('\n');
logger.fine(log.toString());
}
Matrix centroid = centroidDV.getColumnVector();
Matrix B = transposedWeakEigenvectors.times(centroid);
if (DEBUG)
{
StringBuilder log = new StringBuilder();
log.append("Centroid:\n");
log.append(centroid);
log.append('\n');
log.append("tEV * Centroid\n");
log.append(B);
log.append('\n');
logger.fine(log.toString());
}
Matrix gaussJordan = new Matrix(transposedWeakEigenvectors
.getRowDimension(), transposedWeakEigenvectors
.getColumnDimension()
+ B.getColumnDimension());
gaussJordan.setMatrix(0,
transposedWeakEigenvectors.getRowDimension() - 1, 0,
transposedWeakEigenvectors.getColumnDimension() - 1,
transposedWeakEigenvectors);
gaussJordan.setMatrix(0, gaussJordan.getRowDimension() - 1,
transposedWeakEigenvectors.getColumnDimension(), gaussJordan
.getColumnDimension() - 1, B);
if (isVerbose())
{
// TODO was issn hier???
System.out.println("Gauss-Jordan-Elimination of "
+ gaussJordan.toString(NF));
Iterator<Integer> it = db.iterator();
while (it.hasNext())
{
Integer id = it.next();
RealVector dv = db.get(id);
double[][] values = new double[dv.getDimensionality()][1];
for (int i = 1; i <= dv.getDimensionality(); i++)
{
values[i - 1][0] = dv.getValue(i).doubleValue();
}
}
}
double[][] a = new double[transposedWeakEigenvectors.getRowDimension()][transposedWeakEigenvectors
.getColumnDimension()];
double[][] we = transposedWeakEigenvectors.getArray();
double[] b = B.getColumn(0).getRowPackedCopy();
System.arraycopy(we, 0, a, 0, transposedWeakEigenvectors
.getRowDimension());
LinearEquation lq = new LinearEquation(a, b);
lq.solveByTotalPivotSearch();
Matrix solution = lq.getEquationMatrix();
// System.out.println("gaussJordanElimination ");
// System.out.println(gaussJordan.gaussJordanElimination().toString(NF));
// System.out.println("exact gaussJordanElimination");
// System.out.println(gaussJordan.exactGaussJordanElimination().toString(NF));
// Matrix solution =gaussJordan.gaussJordanElimination();
// Matrix solution = gaussJordan.exactGaussJordanElimination();
Matrix strongEigenvectors = pca.getEigenvectors().times(
pca.getSelectionMatrixOfStrongEigenvectors());
this.solution = new CorrelationAnalysisSolution(solution, db,
strongEigenvectors, centroid, NF);
if (isVerbose())
{
System.out.println("Solution:");
System.out.println("Standard deviation "
+ this.solution.getStandardDeviation());
System.out.println(solution.toString(NF));
}
}
/**
* @see Algorithm#getResult()
*/
public CorrelationAnalysisSolution getResult()
{
return solution;
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws ParameterException
{
String[] remainingParameters = super.setParameters(args);
// alpha or dim
if (optionHandler.isSet(ALPHA_P))
{
String alphaString = optionHandler.getOptionValue(ALPHA_P);
try
{
alpha = Double.parseDouble(alphaString);
if (alpha < 0 || alpha >= 1)
{
throw new WrongParameterValueException(ALPHA_P,
alphaString, ALPHA_D);
}
} catch (NumberFormatException e)
{
throw new WrongParameterValueException(ALPHA_P, alphaString,
ALPHA_D, e);
}
} else if (optionHandler.isSet(DIMENSIONALITY_P))
{
String corrDimString = optionHandler
.getOptionValue(DIMENSIONALITY_P);
try
{
corrdim = Integer.parseInt(corrDimString);
if (corrdim < 0)
{
throw new WrongParameterValueException(DIMENSIONALITY_P,
corrDimString, DIMENSIONALITY_D);
}
} catch (NumberFormatException e)
{
throw new WrongParameterValueException(DIMENSIONALITY_P,
corrDimString, DIMENSIONALITY_D, e);
}
} else
{
alpha = ALPHA_DEFAULT;
}
// accuracy
int accuracy;
if (optionHandler.isSet(OUTPUT_ACCURACY_P))
{
String accuracyString = optionHandler
.getOptionValue(OUTPUT_ACCURACY_P);
try
{
accuracy = Integer.parseInt(accuracyString);
if (accuracy < 0)
{
throw new WrongParameterValueException(OUTPUT_ACCURACY_P,
accuracyString, OUTPUT_ACCURACY_D);
}
} catch (NumberFormatException e)
{
throw new WrongParameterValueException(OUTPUT_ACCURACY_P,
accuracyString, OUTPUT_ACCURACY_D, e);
}
} else
{
accuracy = OUTPUT_ACCURACY_DEFAULT;
}
NF.setMaximumFractionDigits(accuracy);
NF.setMinimumFractionDigits(accuracy);
// sample size
if (optionHandler.isSet(SAMPLE_SIZE_P))
{
String sampleSizeString = optionHandler
.getOptionValue(SAMPLE_SIZE_P);
try
{
int sampleSize = Integer.parseInt(sampleSizeString);
if (sampleSize < 0)
{
throw new WrongParameterValueException(SAMPLE_SIZE_P,
sampleSizeString, SAMPLE_SIZE_D);
}
} catch (NumberFormatException e)
{
throw new WrongParameterValueException(SAMPLE_SIZE_P,
sampleSizeString, SAMPLE_SIZE_D, e);
}
} else
{
sampleSize = -1;
}
// pca
pca = new LinearLocalPCA();
remainingParameters = pca.setParameters(remainingParameters);
setParameters(args, remainingParameters);
return remainingParameters;
}
/**
* Returns the parameter setting of this algorithm.
*
* @return the parameter setting of this algorithm
*/
public List<AttributeSettings> getAttributeSettings()
{
List<AttributeSettings> attributeSettings = super
.getAttributeSettings();
AttributeSettings mySettings = attributeSettings.get(0);
if (optionHandler.isSet(ALPHA_P)
|| !optionHandler.isSet(DIMENSIONALITY_P))
mySettings.addSetting(ALPHA_P, Double.toString(alpha));
else if (optionHandler.isSet(DIMENSIONALITY_P))
mySettings.addSetting(DIMENSIONALITY_P, Integer.toString(corrdim));
if (optionHandler.isSet(SAMPLE_SIZE_P))
mySettings.addSetting(SAMPLE_SIZE_P, Integer.toString(sampleSize));
attributeSettings.addAll(pca.getAttributeSettings());
return attributeSettings;
}
} |
package de.ust.skill.common.java.internal;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import de.ust.skill.common.java.api.Access;
import de.ust.skill.common.java.api.SkillException;
import de.ust.skill.common.java.api.SkillFile;
import de.ust.skill.common.java.api.StringAccess;
import de.ust.skill.common.java.internal.fieldTypes.Annotation;
import de.ust.skill.common.jvm.streams.FileInputStream;
import de.ust.skill.common.jvm.streams.FileOutputStream;
/**
* Implementation common to all skill states independent of type declarations.
*
* @author Timm Felden
*/
public abstract class SkillState implements SkillFile {
/**
* if we are on windows, then we have to change some implementation details
*/
public static final boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
// types by skill name
protected final HashMap<String, StoragePool<?, ?>> poolByName;
public StoragePool<?, ?> pool(String name) {
return poolByName.get(name);
}
/**
* write mode this state is operating on
*/
private Mode writeMode;
/**
* path that will be targeted as binary file
*/
private Path path;
/**
* a file input stream keeping the handle to a file for potential write operations
*
* @note this is a consequence of the retarded windows file system
*/
private FileInputStream input;
/**
* dirty flag used to prevent append after delete operations
*/
private boolean dirty = false;
/**
* This pool is used for all asynchronous (de)serialization operations.
*/
static ThreadPoolExecutor pool = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
Runtime.getRuntime().availableProcessors(), 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
final Thread t = new Thread(r);
t.setDaemon(true);
t.setName("SkillStatePoolThread");
return t;
}
});
final StringPool strings;
/**
* Types required for reflective IO
*/
final Annotation annotationType;
/**
* Path and mode management can be done for arbitrary states.
*/
protected SkillState(StringPool strings, Path path, Mode mode, ArrayList<StoragePool<?, ?>> types,
HashMap<String, StoragePool<?, ?>> poolByName, Annotation annotationType) {
this.strings = strings;
this.path = path;
this.input = strings.getInStream();
this.writeMode = mode;
this.types = types;
this.poolByName = poolByName;
this.annotationType = annotationType;
}
@SuppressWarnings("unchecked")
protected final void finalizePools(FileInputStream in) {
try {
StoragePool.establishNextPools(types);
// allocate instances
final Semaphore barrier = new Semaphore(0, false);
{
int reads = 0;
HashSet<String> fieldNames = new HashSet<>();
for (StoragePool<?, ?> p : (ArrayList<StoragePool<?, ?>>) allTypes()) {
// set owners
if (p instanceof BasePool<?>) {
((BasePool<?>) p).owner = this;
reads += ((BasePool<?>) p).performAllocations(barrier);
}
// add missing field declarations
fieldNames.clear();
for (de.ust.skill.common.java.api.FieldDeclaration<?> f : p.dataFields)
fieldNames.add(f.name());
// ensure existence of known fields
for (String n : p.knownFields) {
if (!fieldNames.contains(n))
p.addKnownField(n, strings, annotationType);
}
}
barrier.acquire(reads);
}
// read field data
{
int reads = 0;
// async reads will post their errors in this queue
final ArrayList<SkillException> readErrors = new ArrayList<SkillException>();
for (StoragePool<?, ?> p : (ArrayList<StoragePool<?, ?>>) allTypes()) {
// @note this loop must happen in type order!
// read known fields
for (FieldDeclaration<?, ?> f : p.dataFields)
reads += f.finish(barrier, readErrors, in);
}
// fix types in the Annotation-runtime type, because we need it
// in offset calculation
this.annotationType.fixTypes(poolByName);
// await async reads
barrier.acquire(reads);
for (SkillException e : readErrors) {
e.printStackTrace();
}
if (!readErrors.isEmpty())
throw readErrors.get(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
final public StringAccess Strings() {
return strings;
}
@Override
public final boolean contains(SkillObject target) {
if (null != target)
try {
if (0 < target.skillID)
return target == poolByName.get(target.skillName()).getByID(target.skillID);
else if (0 == target.skillID)
return true; // will evaluate to a null pointer if stored
return poolByName.get(target.skillName()).newObjects.contains(target);
} catch (Exception e) {
// out of bounds or similar mean its not one of ours
return false;
}
return true;
}
@Override
final public void delete(SkillObject target) {
if (null != target) {
dirty |= target.skillID > 0;
poolByName.get(target.skillName()).delete(target);
}
}
@Override
final public void changePath(Path path) throws IOException {
switch (writeMode) {
case Write:
break;
case Append:
// catch erroneous behavior
if (this.path.equals(path))
return;
Files.deleteIfExists(path);
Files.copy(this.path, path);
break;
default:
// dead!
return;
}
this.path = path;
}
@Override
final public Path currentPath() {
return path;
}
@Override
final public void changeMode(Mode writeMode) {
// pointless
if (this.writeMode == writeMode)
return;
switch (writeMode) {
case Write:
this.writeMode = writeMode;
case Append:
// write -> append
throw new IllegalArgumentException(
"Cannot change write mode from Write to Append, try to use open(<path>, Create, Append) instead.");
case ReadOnly:
throw new IllegalArgumentException("Cannot change from read only, to a write mode.");
default:
// dead, if not used by DAUs
return;
}
}
@Override
public final void loadLazyData() {
// ensure that strings are loaded
int id = strings.idMap.size();
while (--id != 0) {
strings.get(0);
}
// ensure that lazy fields have been loaded
for (StoragePool<?, ?> p : types)
for (FieldDeclaration<?, ?> f : p.dataFields)
if (f instanceof LazyField<?, ?>)
((LazyField<?, ?>) f).ensureLoaded();
}
@Override
public void check() throws SkillException {
// TODO type restrictions
// TODO make pools check fields, because they can optimize checks per
// instance and remove redispatching, if no
// restrictions apply anyway
for (StoragePool<?, ?> p : types)
for (FieldDeclaration<?, ?> f : p.dataFields)
try {
f.check();
} catch (SkillException e) {
throw new SkillException(
String.format("check failed in %s.%s:\n %s", p.name, f.name, e.getMessage()), e);
}
}
@Override
public void flush() throws SkillException {
try {
switch (writeMode) {
case Write:
if (isWindows) {
// we have to write into a temporary file and move the file
// afterwards
Path target = path;
File f = File.createTempFile("write", ".sf");
f.createNewFile();
f.deleteOnExit();
changePath(f.toPath());
new StateWriter(this, FileOutputStream.write(makeInStream()));
File targetFile = target.toFile();
if (targetFile.exists())
targetFile.delete();
f.renameTo(targetFile);
changePath(target);
} else
new StateWriter(this, FileOutputStream.write(makeInStream()));
return;
case Append:
// dirty appends will automatically become writes
if (dirty) {
changeMode(Mode.Write);
flush();
} else
new StateAppender(this, FileOutputStream.append(makeInStream()));
return;
case ReadOnly:
throw new SkillException("Cannot flush a read only file. Note: close will turn a file into read only.");
default:
// dead
break;
}
} catch (SkillException e) {
throw e;
} catch (IOException e) {
throw new SkillException("failed to create or complete out stream", e);
} catch (Exception e) {
throw new SkillException("unexpected exception", e);
}
}
/**
* @return the file input stream matching our current status
*/
private FileInputStream makeInStream() throws IOException {
if (null == input || !path.equals(input.path()))
input = FileInputStream.open(path, false);
return input;
}
@Override
public void close() throws SkillException {
// flush if required
if (Mode.ReadOnly != writeMode) {
flush();
this.writeMode = Mode.ReadOnly;
}
// close file stream to work around issue with broken Windows FS
if (null != input)
try {
input.close();
} catch (IOException e) {
// we don't care
e.printStackTrace();
}
}
// types in type order
final protected ArrayList<StoragePool<?, ?>> types;
@Override
final public Iterable<? extends Access<? extends SkillObject>> allTypes() {
return types;
}
@Override
final public Stream<? extends Access<? extends SkillObject>> allTypesStream() {
return types.stream();
}
} |
package httpserv;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
/**
*
* @author jochen
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
Option[] opts = new Option[2];
opts[0] = new Option("--help", "-h", false);
opts[1] = new Option("--accept", "-a", true);
if (!parseOptions(args, opts)) {
return;
}
HttpServer server = HttpServer.create(
new InetSocketAddress((Integer) opts[1].value), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
} catch (Exception e) {
e.printStackTrace();
}
} // TODO code application logic here
static boolean parseOptions(String[] args, Option[] inout_options) {
if (args.length == 0) {
printUsage();
return false;
}
boolean bWrongArgs = true;
Option currentOpt = null;
for (String s : args) {
// get the value for an option
if (currentOpt != null && currentOpt.bHasValue) {
//now we expect the value for the option
//check the type
try {
if (currentOpt.sLong.equals("--accept")) {
currentOpt.value = Integer.decode(s);
}
} catch (Exception e ) {
printUsage();
return false;
}
currentOpt = null;
continue;
} else {
currentOpt = null;
}
// get the option
for (Option o : inout_options) {
if (s.equals(o.sLong) || s.equals(o.sShort)) {
bWrongArgs = false;
//special handling for --help
if (o.sLong.equals("--help")) {
printUsage();
return false;
}
else
{
currentOpt = o;
if (!o.bHasValue) {
o.bSet = true;
}
break;
}
}
}
}
if (bWrongArgs) {
printUsage();
return false;
}
return true;
}
static void printUsage() {
String usage = new String(
"Usage: \n" +
"java -jar httpserv [options] \n" +
"\n" +
"Options are: \n" +
"-h --help \t this help \n" +
"-a --accept port \t the port number to which this server listens \n");
System.out.println(usage);
}
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange xchange) throws IOException {
try {
//First get the path to the file
File fileCurrent = new File(".");
String sRequestPath = xchange.getRequestURI().getPath();
System.out.println("requested: " + sRequestPath);
File fileRequest = new File(new File(".").getCanonicalPath(), sRequestPath);
if (!fileRequest.exists()) {
throw new Exception("The file " + fileRequest.toString() + " does not exist!\n");
}
else if (fileRequest.isDirectory()) {
throw new Exception(fileRequest.toString() + " is a directory!\n");
}
//Read the file into a byte array
byte[] data = new byte[(int) fileRequest.length()];
FileInputStream fr = new FileInputStream(fileRequest);
int count = fr.read(data);
//set the Content-type header
Headers h = xchange.getResponseHeaders();
String canonicalPath = fileRequest.getCanonicalPath();
int lastIndex = canonicalPath.lastIndexOf(".");
String fileExtension = canonicalPath.substring(lastIndex + 1);
if (fileExtension.equalsIgnoreCase("crl"))
{
//h.set("Content-Type","application/x-pkcs7-crl");
h.set("Content-Type","application/pkix-crl");
}
else if (fileExtension.equalsIgnoreCase("crt")
|| fileExtension.equalsIgnoreCase("cer")
|| fileExtension.equalsIgnoreCase("der"))
{
h.set("Content-Type", "application/x-x509-ca-cert");
}
//write out the requested file
xchange.sendResponseHeaders(200, data.length);
OutputStream os = xchange.getResponseBody();
os.write(data);
os.close();
System.out.println("delivered: " + fileRequest.toString());
} catch (Exception e) {
xchange.sendResponseHeaders(404, e.getMessage().length());
OutputStream os = xchange.getResponseBody();
os.write(e.getMessage().getBytes());
os.close();
System.out.println("Error: " + e.getMessage());
}
}
}
class Option {
Option(String _sLong, String _sShort, boolean _bHasValue) {
sLong = _sLong;
sShort = _sShort;
bHasValue = _bHasValue;
}
String sLong;
String sShort;
boolean bHasValue;
Object value;
//indicates if this option was set if it does not need a value. Otherwise value
//is set.
boolean bSet;
} |
package snowballmadness;
import java.util.*;
import com.google.common.base.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
/**
* This class is the base class that hosts the logic that triggers when a
* snowball hits a target.
*
* We keep these in a weak hash map, so it is important that this object (and
* all subclasses) not hold onto a reference to a Snowball, or that snowball may
* never be collected.
*
* @author DanJ
*/
public abstract class SnowballLogic {
// Logic
/**
* This is called when the snowball is launched.
*
* @param snowball The snowball being launched.
* @param info Other information about the snowball.
*/
public void launch(Snowball snowball, SnowballInfo info) {
}
/**
* this is called every many times every second.
*
* @param snowball A snowball that gets a chance to do something.
* @param info Other information about the snowball.
*/
public void tick(Snowball snowball, SnowballInfo info) {
}
/**
* This is called when the snowball hits something and returns teh damange
* to be done (which can be 0).
*
* @param snowball The snowball hitting something.
* @param info Other information about the snowball.
* @param target The entity that was hit.
* @param damage The damage the snowball is expected to do..
* @return The damage teh snowball will do.
*/
public double damage(Snowball snowball, SnowballInfo info, Entity target, double proposedDamage) {
return proposedDamage;
}
/**
* This is called when the snowball hits something.
*
* @param snowball The snowball hitting something.
* @param info Other information about the snowball.
*/
public void hit(Snowball snowball, SnowballInfo info) {
}
@Override
public String toString() {
return getClass().getSimpleName();
}
// Creation
/**
* This method creates a new logic, but does not start it. It chooses the
* logic based on 'hint', which is the stack immediately above the snowball
* being thrown.
*
* @param slice The inventory slice above the snowball in the inventory.
* @return The new logic, not yet started or attached to a snowball, or null
* if the snowball will be illogical.
*/
public static SnowballLogic createLogic(InventorySlice slice) {
ItemStack hint = slice.getBottomItem();
if (hint == null) {
return null;
}
switch (hint.getType()) {
case ARROW:
return new ArrowSnowballLogic(hint);
case COBBLESTONE:
case OBSIDIAN:
case BOOKSHELF:
case BRICK:
case SAND:
case GRAVEL:
return new BlockPlacementSnowballLogic(hint.getType());
//considering adding data values to smooth brick so it randomizes
//including mossy, cracked and even silverfish
case ENDER_PEARL:
return new BlockPlacementSnowballLogic(Material.ENDER_CHEST);
case ANVIL:
return new AnvilSnowballLogic();
case WATCH:
return new WatchSnowballLogic();
case REDSTONE:
return new StartRainLogic();
case CACTUS:
return new StopRainLogic();
case ENDER_STONE:
return new BlockPlacementSnowballLogic(Material.ENDER_PORTAL);
case WATER_BUCKET:
return new BlockPlacementSnowballLogic(Material.WATER);
case LAVA_BUCKET:
return new BlockPlacementSnowballLogic(Material.LAVA);
case QUARTZ:
case COAL:
case COAL_BLOCK:
case SAPLING:
case REDSTONE_BLOCK:
case NETHERRACK:
case LADDER:
case DIAMOND_ORE:
case DIAMOND_BLOCK:
return BlockEmbedSnowballLogic.fromMaterial(hint.getType());
case WOOD_SWORD:
case STONE_SWORD:
case IRON_SWORD:
case GOLD_SWORD:
case DIAMOND_SWORD:
return new SwordSnowballLogic(slice);
case WOOD_PICKAXE:
case STONE_PICKAXE:
case IRON_PICKAXE:
case GOLD_PICKAXE:
case DIAMOND_PICKAXE:
return new PickaxeSnowballLogic(hint.getType());
case STICK:
case BONE:
case BLAZE_ROD:
case FENCE:
case COBBLE_WALL:
case NETHER_FENCE:
case FEATHER:
return KnockbackSnowballLogic.fromMaterial(hint.getType());
case LEAVES:
case STONE:
case SMOOTH_BRICK:
case IRON_FENCE:
case WEB:
return new BoxSnowballLogic(hint.getType());
//all structures that can be broken with any pick, but can be
//large with use of glowstone. Provides a defensive game
case GLASS:
return new BoxSnowballLogic(Material.GLASS, Material.AIR);
case GLASS_BOTTLE:
return new SphereSnowballLogic(Material.GLASS, Material.AIR);
//these two enable a sort of minigame: try not to get encased in glass
//against other players who are trying to encase you
case POTION:
short potionID = hint.getDurability();
switch (potionID) {
case 0: //water bottle gives you water sphere
return new SphereSnowballLogic(Material.GLASS, Material.STATIONARY_WATER);
case 16: //awkward potion made with netherwart gives you TNT
return new BoxSnowballLogic(Material.TNT, Material.AIR);
case 32: //thick potion made with glowstone dust gives you glowstone (potency)
return new SphereSnowballLogic(Material.GLOWSTONE, Material.AIR);
case 64: //mundane potion (extended) made with redstone gives you redstone (duration)
return new SphereSnowballLogic(Material.REDSTONE_BLOCK, Material.AIR);
case 8193: //regen 0:45 gives you a glass sphere to hide in
return new SphereSnowballLogic(Material.GLASS, Material.AIR);
case 8257: //regen 2:00 gives you a glass sphere to hide in
return new SphereSnowballLogic(Material.GLASS, Material.AIR);
case 8225: //regen II gives you a glass box to hide in
return new BoxSnowballLogic(Material.GLASS, Material.AIR);
case 8194: //swiftness 3:00 (sugar)
return new SphereSnowballLogic(Material.REDSTONE_BLOCK, Material.REDSTONE_ORE);
case 8258: //swiftness 8:00 (sugar, redstone)
return new SphereSnowballLogic(Material.REDSTONE_BLOCK, Material.REDSTONE_ORE);
case 8226: //swiftness II (sugar, glowstone)
return new BoxSnowballLogic(Material.REDSTONE_BLOCK, Material.REDSTONE_ORE);
case 8195: //fire resist 3:00 (magma cream) gives you a lava sphere
return new SphereSnowballLogic(Material.GLASS, Material.STATIONARY_LAVA);
case 8259: //fire resist 8:00 (magma cream, redstone) gives you a lava box
return new BoxSnowballLogic(Material.GLASS, Material.STATIONARY_LAVA);
case 8197: //instant health gives you a fish bowl to relax you
return new SphereSnowballLogic(Material.GLASS, Material.STATIONARY_WATER);
case 8229: //instant health II gives you a fish tank to relax you
return new BoxSnowballLogic(Material.GLASS, Material.STATIONARY_WATER);
case 8198: //night vision 3:00 (golden carrot) gives you a obsidian sphere
return new SphereSnowballLogic(Material.OBSIDIAN, Material.AIR);
case 8262: //night vision 8:00 (golden carrot, redstone) gives you a obsidian box
return new BoxSnowballLogic(Material.OBSIDIAN, Material.AIR);
case 8201: //strength 3:00 (blaze powder) gives you a stone fort to carve up
return new SphereSnowballLogic(Material.SMOOTH_BRICK, Material.SMOOTH_BRICK);
case 8265: //strength 8:00 (blaze powder, redstone) gives you armored box
return new BoxSnowballLogic(Material.OBSIDIAN, Material.SMOOTH_BRICK);
case 8233: //strength II (blaze powder, glowstone) gives you the death star!
return new SphereSnowballLogic(Material.OBSIDIAN, Material.SMOOTH_BRICK);
case 8206: //invisibility 3:00 (night vision + spider eye) is a crystal ball
return new SphereSnowballLogic(Material.GLASS, Material.GLASS);
case 8270: //invisibility 8:00 (that plus redstone) is a wood sphere filled with books
return new SphereSnowballLogic(Material.WOOD, Material.BOOKSHELF);
case 8196://poison 0:45 (spider eye) gives you feeeshapocalypse!
return new SphereSnowballLogic(Material.MONSTER_EGG, Material.MONSTER_EGG);
case 8260://poison 2:00 (+redstone) gives you square feeeshapocalypse!
return new BoxSnowballLogic(Material.MONSTER_EGG, Material.MONSTER_EGG);
case 8228://poison II (+glowstone) gives you feeeshapocalypse under glass!!
return new SphereSnowballLogic(Material.MONSTER_EGG, Material.MONSTER_EGG);
case 8200: //weakness 1:30 (strength/regen+fermented spider eye)
return new SphereSnowballLogic(Material.GOLD_BLOCK, Material.GOLD_ORE);
case 8264: //weakness 4:00 (those extended w. redstone + fermented spider eye)
return new SphereSnowballLogic(Material.DIAMOND_BLOCK, Material.DIAMOND_ORE);
case 8202: //slowness 1:30 (swiftness/fireresist+fermented spider eye) makes a web border
return new SphereSnowballLogic(Material.WEB, Material.AIR);
case 8266: //slowness 4:00 makes a web border (spam to encase)
return new BoxSnowballLogic(Material.WEB, Material.AIR);
case 8204: //harming tries to imprison you in bedrock!
return new SphereSnowballLogic(Material.BEDROCK, Material.AIR);
case 8236: //harming II tries to embox you in bedrock!
return new BoxSnowballLogic(Material.BEDROCK, Material.AIR);
default:
}
case BUCKET:
return new BoxSnowballLogic(Material.AIR);
case TORCH:
return new LinkedTrailSnowballLogic(Material.FIRE);
case FENCE_GATE:
return new LinkedTrailSnowballLogic(Material.FENCE);
case CAULDRON_ITEM:
return new LinkedTrailSnowballLogic(Material.STATIONARY_WATER);
case WATER_LILY:
return new LinkedWaterTrailSnowballLogic(Material.WATER_LILY);
case TNT:
return new TNTSnowballLogic(4);
case SULPHUR:
return new TNTSnowballLogic(1);
case FIREWORK:
return new JetpackSnowballLogic();
case FLINT_AND_STEEL:
return new FlintAndSteelSnowballLogic(Material.FIRE);
case SPIDER_EYE:
return new ReversedSnowballLogic();
case FERMENTED_SPIDER_EYE:
return new EchoSnowballLogic(hint.getAmount(), slice.skip(1));
case SUGAR:
return new SpeededSnowballLogic(1.6, slice.skip(1));
case BOW:
return new SpeededSnowballLogic(1.8, slice.skip(1));
case COOKIE:
return new SpeededSnowballLogic(2, slice.skip(1));
case CAKE:
return new SpeededSnowballLogic(3, slice.skip(1));
//the cake is a... lazor!
case BEACON:
return new SpeededSnowballLogic(4, slice.skip(1));
//the beacon is the REAL lazor.
case GLOWSTONE_DUST:
return new PoweredSnowballLogic(1.5, slice.skip(1));
case GLOWSTONE:
return new PoweredSnowballLogic(3, slice.skip(1));
case NETHER_STAR:
return new PoweredSnowballLogic(4, slice.skip(1));
//nuclear option. Beacon/netherstar designed to be insane
//overkill but not that cost-effective, plus more unwieldy.
case SNOW_BALL:
return new MultiplierSnowballLogic(hint.getAmount(), slice.skip(1));
case SLIME_BALL:
return new BouncySnowballLogic(hint.getAmount(), slice.skip(1));
case QUARTZ_BLOCK:
return new KapwingSnowballLogic(hint.getAmount(), slice.skip(1));
case GRASS:
case DIRT:
return new RegenerationSnowballLogic(slice);
case GHAST_TEAR:
return new SpawnSnowballLogic(EntityType.GHAST);
case ROTTEN_FLESH:
return new SpawnSnowballLogic(EntityType.ZOMBIE);
case ENCHANTMENT_TABLE:
return new SpawnSnowballLogic(EntityType.WITCH, EntityType.ENDER_CRYSTAL, 8.0);
case GOLD_NUGGET:
case LEATHER:
case IRON_INGOT:
return new ItemDropSnowballLogic(hint.getType());
//developing ItemDropSnowball to be a randomizer, it won't be
//heavily used so it can be full of special cases
case GOLD_INGOT:
return new SpawnSnowballLogic(EntityType.PIG);
case GOLD_BLOCK:
return new SpawnSnowballLogic(EntityType.PIG, EntityType.PIG_ZOMBIE, 8.0);
case STRING:
return new SpawnSnowballLogic(EntityType.SPIDER, EntityType.CAVE_SPIDER, 8.0);
case EYE_OF_ENDER:
return new SpawnSnowballLogic(EntityType.ENDERMAN);
case DRAGON_EGG:
return new SpawnSnowballLogic(EntityType.CHICKEN, EntityType.ENDER_DRAGON, 8.0);
case MILK_BUCKET:
return new SpawnSnowballLogic(EntityType.COW, EntityType.MUSHROOM_COW, 8.0);
case JACK_O_LANTERN:
return new SpawnSnowballLogic(EntityType.SKELETON, EntityType.WITHER_SKULL, 8.0);
case SKULL_ITEM:
SkullType skullType = SkullType.values()[hint.getDurability()];
return SpawnSnowballLogic.fromSkullType(skullType);
default:
return null;
}
}
// Event Handling
/**
* This method processes a new snowball, executing its launch() method and
* also recording it so the hit() method can be called later.
*
* The shooter may be provided as well; this allows us to launch snowballs
* from places that are not a player, but associated it with a player
* anyway.
*
* @param inventory The inventory slice that determines the logic type.
* @param snowball The snowball to be launched.
* @param info The info record that describes the snowball.
* @return The logic associated with the snowball; may be null.
*/
public static SnowballLogic performLaunch(InventorySlice inventory, Snowball snowball, SnowballInfo info) {
SnowballLogic logic = createLogic(inventory);
if (logic != null) {
performLaunch(logic, snowball, info);
}
return logic;
}
/**
* This overload of performLaunch takes the logic to associate with the
* snowball instead of an inventory.
*
* @param logic The logic to apply to the snowball; can't be null.
* @param snowball The snowball to be launched.
* @param info The info record that describes the snowball.
*/
public static void performLaunch(SnowballLogic logic, Snowball snowball, SnowballInfo info) {
logic.start(snowball, info);
Bukkit.getLogger().info(String.format("Snowball launched: %s [%d]", logic, inFlight.size()));
logic.launch(snowball, info);
}
/**
* This method processes the impact of a snowball, and invokes the hit()
* method on its logic object, if it has one.
*
* @param snowball The impacting snowball.
*/
public static void performHit(Snowball snowball) {
SnowballLogicData data = getData(Preconditions.checkNotNull(snowball));
if (data != null) {
try {
Bukkit.getLogger().info(String.format("Snowball hit: %s [%d]", data.logic, inFlight.size()));
data.logic.hit(snowball, data.info);
} finally {
data.logic.end(snowball);
}
}
}
public static double performDamage(Snowball snowball, Entity target, double damage) {
SnowballLogicData data = getData(Preconditions.checkNotNull(snowball));
if (data != null) {
Bukkit.getLogger().info(String.format("Snowball damage: %s [%d]", data.logic, inFlight.size()));
return data.logic.damage(snowball, data.info, target, damage);
}
return damage;
}
/**
* This method handles a projectile launch; it selects a logic and runs its
* launch method.
*
* @param e The event data.
*/
public static void onProjectileLaunch(SnowballMadness plugin, ProjectileLaunchEvent e) {
Projectile proj = e.getEntity();
LivingEntity shooter = proj.getShooter();
if (proj instanceof Snowball && shooter instanceof Player) {
Snowball snowball = (Snowball) proj;
Player player = (Player) shooter;
PlayerInventory inv = player.getInventory();
int heldSlot = inv.getHeldItemSlot();
ItemStack sourceStack = inv.getItem(heldSlot);
if (sourceStack == null || sourceStack.getType() == Material.SNOW_BALL) {
InventorySlice slice = InventorySlice.fromSlot(player, heldSlot).skip(1);
SnowballLogic logic = performLaunch(slice, snowball, new SnowballInfo(plugin));
if (logic != null && player.getGameMode() != GameMode.CREATIVE) {
replenishSnowball(plugin, inv, heldSlot);
}
}
}
}
/**
* This method calls tick() on each snowball that has any logic.
*/
public static void onTick() {
for (Map.Entry<Snowball, SnowballLogicData> e : inFlight.entrySet()) {
Snowball snowball = e.getKey();
SnowballLogic logic = e.getValue().logic;
SnowballInfo info = e.getValue().info;
logic.tick(snowball, info);
}
}
/**
* This method handles the damage a snowball does on impact, and can adjust
* that damage.
*
* @param e The damage event.
*/
public static void onEntityDamageByEntityEvent(EntityDamageByEntityEvent e) {
Entity damagee = e.getEntity();
Entity damager = e.getDamager();
double damage = e.getDamage();
if (damager instanceof Snowball) {
double newDamage = performDamage((Snowball) damager, damagee, damage);
if (newDamage != damage) {
e.setDamage(newDamage);
}
}
}
/**
* This method increments the number of snowballs in the slot indicated; but
* it does this after a brief delay since changes made during the launch are
* ignored. If the indicated slot contains something that is not a snowball,
* we don't update it. If it is empty, we put one snowball in there.
*
* @param plugin The plugin, used to schedule the update.
* @param inventory The inventory to update.
* @param slotIndex The slot to update.
*/
private static void replenishSnowball(Plugin plugin, final PlayerInventory inventory, final int slotIndex) {
// ugh. We must delay the inventory update or it won't take.
new BukkitRunnable() {
@Override
public void run() {
ItemStack replacing = inventory.getItem(slotIndex);
if (replacing == null) {
inventory.setItem(slotIndex, new ItemStack(Material.SNOW_BALL));
} else if (replacing.getType() == Material.SNOW_BALL) {
int oldCount = replacing.getAmount();
int newCount = Math.min(16, oldCount + 1);
if (oldCount != newCount) {
inventory.setItem(slotIndex, new ItemStack(Material.SNOW_BALL, newCount));
}
}
}
}.runTaskLater(plugin, 1);
}
/**
* This method handles a projectile hit event, and runs the hit method.
*
* @param e The event data.
*/
public static void onProjectileHit(ProjectileHitEvent e) {
Projectile proj = e.getEntity();
if (proj instanceof Snowball) {
performHit((Snowball) proj);
}
}
// Logic Association
private final static WeakHashMap<Snowball, SnowballLogicData> inFlight = new WeakHashMap<Snowball, SnowballLogicData>();
private static int approximateInFlightCount = 0;
private static long inFlightSyncDeadline = 0;
/**
* this class just holds the snowball logic and info for a snowball; the
* snowball itself must not be kept here, as this is the value of a
* weak-hash-map keyed on the snowballs. We don't want to keep them alive.
*/
private final static class SnowballLogicData {
public final SnowballLogic logic;
public final SnowballInfo info;
public SnowballLogicData(SnowballLogic logic, SnowballInfo info) {
this.logic = logic;
this.info = info;
}
}
/**
* This returns the number of snowballs (that have attached logic) that are
* currently in flight. This may count snowballs that have been unloaded or
* otherwise destroyed for a time; it is not exact.
*
* @return The number of in-flight snowballs.
*/
public static int getInFlightCount() {
long now = System.currentTimeMillis();
if (inFlightSyncDeadline <= now) {
inFlightSyncDeadline = now + 1000;
approximateInFlightCount = inFlight.size();
}
return approximateInFlightCount;
}
/**
* This returns the logic and shooter for a snowball that has one.
*
* @param snowball The snowball of interest; can be null.
* @return The logic and info of the snowball, or null if it is an illogical
* snowball or it was null.
*/
private static SnowballLogicData getData(Snowball snowball) {
if (snowball != null) {
return inFlight.get(snowball);
} else {
return null;
}
}
/**
* This method registers the logic so getLogic() can find it. Logics only
* work once started.
*
* @param snowball The snowball being launched.
* @param info Other information about the snowball.
*/
public void start(Snowball snowball, SnowballInfo info) {
inFlight.put(snowball, new SnowballLogicData(this, info));
approximateInFlightCount++;
}
/**
* This method unregisters this logic so it is no longer invoked; this is
* done when snowball hits something.
*
* @param snowball The snowball to deregister.
*/
public void end(Snowball snowball) {
approximateInFlightCount
inFlight.remove(snowball);
}
// Utilitu Methods
/**
* This returns the of the nearest non-air block underneath 'location' that
* is directly over the ground. If 'locaiton' is inside the ground, we'll
* return a new copy of the same location.
*
* @param location The starting location; this is not modified.
* @return A new location describing the place found.
*/
public static Location getGroundUnderneath(Location location) {
Location loc = location.clone();
for (;;) {
// just in case we have a shaft to the void, we need
// to give up before we reach it.
if (loc.getBlockY() <= 0) {
return loc;
}
switch (loc.getBlock().getType()) {
case AIR:
case WATER:
case STATIONARY_WATER:
case LEAVES:
case LONG_GRASS:
case DOUBLE_PLANT:
case LAVA:
case SNOW:
case WATER_LILY:
case RED_ROSE:
case YELLOW_FLOWER:
case DEAD_BUSH:
loc.add(0, -1, 0);
break;
default:
return loc;
}
}
}
} |
package edu.rpi.cct.misc.indexing;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.FilteredQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.store.Directory;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.log4j.Logger;
/** This class implements indexing using Lucene.
* There is an abstract method to create a Lucene Document from an object.
* Also an abstract method to create the Key object.
*/
public abstract class IndexLuceneImpl implements Index {
private boolean debug;
private boolean writeable;
private String basePath;
private String defaultFieldName;
/** We append this to basePath to reach the indexes.
*/
private final static String indexDir = "/indexes";
private boolean updatedIndex;
private boolean isOpen;
private boolean cleanLocks;
private transient Logger log;
/** We try to keep readers and writers open if batchMode is true.
*/
//private boolean batchMode;
IndexReader rdr;
IndexWriter wtr;
Searcher sch;
Analyzer defaultAnalyzer;
QueryParser queryParser;
Hits lastResult;
private String[] stopWords;
/** Simple representation of field options */
public static class FieldInfo {
/** lucene name for field. */
String name;
/** Do w store it? */
boolean store;
/** Do we tokenize it? */
boolean tokenized;
/** boost value for this field */
float boost;
/* Initialised in constructor from store. */
Store howStore;
/* Initialised in constructor from tokenized. */
Field.Index howIndexed;
/** Constructor for unstored, unboosted field
*
* @param name
* @param tokenized
*/
public FieldInfo(String name, boolean tokenized) {
this(name, false, tokenized, 1);
}
/** Constructor for unstored field
*
* @param name
* @param tokenized
* @param boost
*/
public FieldInfo(String name, boolean tokenized, float boost) {
this(name, false, tokenized, boost);
}
/** Constructor allowing full specification
*
* @param name
* @param store
* @param tokenized
* @param boost
*/
public FieldInfo(String name, boolean store,
boolean tokenized, float boost) {
this.name = name;
this.store = store;
this.tokenized = tokenized;
this.boost = boost;
if (store) {
howStore = Store.YES;
} else {
howStore = Store.NO;
}
if (tokenized) {
howIndexed = Field.Index.TOKENIZED;
} else {
howIndexed = Field.Index.UN_TOKENIZED;
}
}
Field makeField(String val) {
Field f = new Field(name, val, howStore, howIndexed);
f.setBoost(boost);
return f;
}
/**
* @return String field name
*/
public String getName() {
return name;
}
}
/** Create an indexer with the default set of stop words.
*
* @param basePath String path to where we should read/write indexes
* @param defaultFieldName default name for searches
* @param writeable true if the caller can update the index
* @param debug true if we want to see what's going on
* @throws IndexException
*/
public IndexLuceneImpl(String basePath,
String defaultFieldName,
boolean writeable,
boolean debug) throws IndexException {
this(basePath, defaultFieldName, writeable, null, debug);
}
/** Create an indexer with the given set of stop words.
*
* @param basePath String path to where we should read/write indexes
* @param defaultFieldName default name for searches
* @param writeable true if the caller can update the index
* @param stopWords set of stop words, null for default.
* @param debug true if we want to see what's going on
* @throws IndexException
*/
public IndexLuceneImpl(String basePath,
String defaultFieldName,
boolean writeable,
String[] stopWords,
boolean debug) throws IndexException {
setDebug(debug);
this.writeable = writeable;
this.basePath = basePath;
this.defaultFieldName = defaultFieldName;
this.stopWords = stopWords;
}
/**
* @return boolean debugging flag
*/
public boolean getDebug() {
return debug;
}
/** Indicate if we should try to clean locks.
*
* @param val
*/
public void setCleanLocks(boolean val) {
cleanLocks = val;
}
/** String appended to basePath
* @return String
*/
public static String getPathSuffix() {
return indexDir;
}
/** Called to make or fill in a Key object.
*
* @param key Possible Index.Key object for reuse
* @param doc The retrieved Document
* @param score The rating for this entry
* @return Index.Key new or reused object
* @throws IndexException
*/
public abstract Index.Key makeKey(Index.Key key,
Document doc,
float score) throws IndexException;
/** Called to make a key term for a record.
*
* @param rec The record
* @return Term Lucene term which uniquely identifies the record
* @throws IndexException
*/
public abstract Term makeKeyTerm(Object rec) throws IndexException;
/** Called to make the primary key name for a record.
*
* @param rec The record
* @return String Name for the field/term
* @throws IndexException
*/
public abstract String makeKeyName(Object rec) throws IndexException;
/** Called to fill in a Document from an object.
*
* @param doc The =Document
* @param rec The record
* @throws IndexException
*/
public abstract void addFields(Document doc,
Object rec) throws IndexException;
/** Called to return an array of valid term names.
*
* @return String[] term names
*/
public abstract String[] getTermNames();
public void setDebug(boolean val) {
debug = val;
}
/** This can be called to open the index in the appropriate manner
* probably determined by information passed to the constructor.
*
* <p>For a first time call a new analyzer will be created.
*/
public void open() throws IndexException {
close();
if (defaultAnalyzer == null) {
if (stopWords == null) {
defaultAnalyzer = new StandardAnalyzer();
} else {
defaultAnalyzer = new StandardAnalyzer(stopWords);
}
queryParser = new QueryParser(defaultFieldName,
defaultAnalyzer);
}
updatedIndex = false;
isOpen = true;
}
/** This can be called to (re)create the index. It will destroy any
* previously existing index.
*/
public void create() throws IndexException {
try {
if (!writeable) {
throw new IndexException(IndexException.noIdxCreateAccess);
}
close();
if (basePath == null) {
throw new IndexException(IndexException.noBasePath);
}
IndexWriter iw = new IndexWriter(basePath + indexDir, defaultAnalyzer, true);
iw.optimize();
iw.close();
iw = null;
open();
} catch (IOException e) {
throw new IndexException(e);
} catch (Throwable t) {
throw new IndexException(t);
}
}
/** See if we need to call open
*/
public boolean getIsOpen() {
return isOpen;
}
/** This gives a single keyword to identify the implementation.
*
* @return String An identifying key.
*/
public String id() {
return "LUCENE";
}
/** This can be called to obtain some information about the index
* implementation. id gives a single keyword whereas this gives a more
* detailed description.
*
* @return String A descrptive string.
*/
public String info() {
return "An implementation of an indexer using jakarta Lucene.";
}
/** Called to index a record
*
* @param rec The record to index
*/
public void indexRec(Object rec) throws IndexException {
unindexRec(rec);
intIndexRec(rec);
closeWtr();
}
/** Called to unindex a record
*
* @param rec The record to unindex
*/
public void unindexRec(Object rec) throws IndexException {
try {
checkOpen();
closeWtr();
intUnindexRec(rec);
} catch (IndexException ie) {
if (ie.getCause() instanceof FileNotFoundException) {
// Assume not indexed yet
throw new IndexException(IndexException.noFiles);
} else {
throw ie;
}
} finally {
closeWtr(); // Just in case
closeRdr();
}
}
/** Called to (re)index a batch of records
*
* @param recs The records to index
*/
public void indexRecs(Object[] recs) throws IndexException {
if (recs == null) {
return;
}
try {
unindexRecs(recs);
for (int i = 0; i < recs.length; i++) {
if (recs[i] != null) {
intIndexRec(recs[i]);
}
}
} finally {
closeWtr();
closeRdr(); // Just in case
}
}
/** Called to index a batch of new records. More efficient way of
* rebuilding the index.
*
* @param recs The records to index
*/
public void indexNewRecs(Object[] recs) throws IndexException {
if (recs == null) {
return;
}
try {
closeRdr(); // Just in case
for (int i = 0; i < recs.length; i++) {
if (recs[i] != null) {
intIndexRec(recs[i]);
}
}
} finally {
closeWtr();
}
}
/** Called to unindex a batch of records
*
* @param recs The records to unindex
*/
public void unindexRecs(Object[] recs) throws IndexException {
if (recs == null) {
return;
}
try {
checkOpen();
closeWtr();
for (int i = 0; i < recs.length; i++) {
if (recs[i] != null) {
intUnindexRec(recs[i]);
}
}
} finally {
closeWtr(); // Just in case
closeRdr();
}
}
/** Called to find entries that match the search string. This string may
* be a simple sequence of keywords or some sort of query the syntax of
* which is determined by the underlying implementation.
*
* @param query Query string
* @return int Number found. 0 means none found,
* -1 means indeterminate
*/
public int search(String query) throws IndexException {
return search(query, null);
}
/** Called to find entries that match the search string. This string may
* be a simple sequence of keywords or some sort of query the syntax of
* which is determined by the underlying implementation.
*
* @param query Query string
* @param filter Filter to apply or null
* @return int Number found. 0 means none found,
* -1 means indeterminate
* @throws IndexException
*/
public int search(String query, Filter filter) throws IndexException {
checkOpen();
try {
if (debug) {
trace("About to search for " + query);
}
Query parsed = queryParser.parse(query);
if (filter != null) {
parsed = new FilteredQuery(parsed, filter);
}
if (debug) {
trace(" with parsed query " + parsed.toString(null));
}
if (sch == null) {
IndexReader rdr = getRdr();
if (rdr != null) {
sch = new IndexSearcher(rdr);
}
}
if (sch == null) {
lastResult = null;
return 0;
}
lastResult = sch.search(parsed);
if (debug) {
trace(" found " + lastResult.length());
}
return lastResult.length();
} catch (ParseException pe) {
throw new IndexException(pe);
} catch (IOException e) {
throw new IndexException(e);
} catch (Throwable t) {
throw new IndexException(t);
}
}
/** Called to retrieve record keys from the result.
*
* @param n Starting index
* @param keys Array for the record keys
* @return int Actual number of records
*/
public int retrieve(int n, Index.Key[] keys) throws IndexException {
checkOpen();
if ((lastResult == null) ||
(keys == null) ||
(n >= lastResult.length())) {
return 0;
}
int i;
for (i = 0; i < keys.length; i++) {
int hi = i + n;
if (hi >= lastResult.length()) {
break;
}
try {
keys[i] = makeKey(keys[i], lastResult.doc(hi), lastResult.score(hi));
} catch (IOException e) {
throw new IndexException(e);
} catch (Throwable t) {
throw new IndexException(t);
}
}
return i;
}
/** Called if we intend to run a batch of updates. endBatch MUST be
* called or manual intervention may be required to remove locks.
*/
public void startBatch() throws IndexException {
//batchMode = true;
}
/** Called at the end of a batch of updates.
*/
public void endBatch() throws IndexException {
//batchMode = false;
close();
}
/** Called to close at the end of a session.
*/
public synchronized void close() throws IndexException {
closeWtr();
closeRdr();
isOpen = false;
}
/** Called if we need to close the writer
*
* @throws IndexException
*/
public synchronized void closeWtr() throws IndexException {
try {
if (wtr != null) {
if (updatedIndex) {
// wtr.optimize();
updatedIndex = false;
}
wtr.close();
wtr = null;
}
} catch (IOException e) {
throw new IndexException(e);
} catch (Throwable t) {
throw new IndexException(t);
}
}
/** Called if we need to close the reader
*
* @throws IndexException
*/
public synchronized void closeRdr() throws IndexException {
try {
if (sch != null) {
try {
sch.close();
} catch (Exception e) {}
sch = null;
}
if (rdr != null) {
rdr.close();
rdr = null;
}
} catch (IOException e) {
throw new IndexException(e);
} catch (Throwable t) {
throw new IndexException(t);
}
}
/** Called to provide some debugging dump info.
*/
public void dump() {
}
/** Called to provide some statistics.
*/
public void stats() {
}
/** Ensure we're open
*
* @throws IndexException
*/
private void checkOpen() throws IndexException {
if (isOpen) {
return;
}
open();
}
/* Called to obtain the current or a new writer.
*
* @return IndexWriter writer to our index
*/
private IndexWriter getWtr() throws IndexException {
if (!writeable) {
throw new IndexException(IndexException.noAccess);
}
String dirPath = basePath + indexDir;
try {
if (wtr == null) {
wtr = new IndexWriter(dirPath, defaultAnalyzer, false);
}
return wtr;
} catch (IOException e) {
if (e instanceof FileNotFoundException) {
// Assume not indexed yet
throw new IndexException(IndexException.noFiles);
}
if (!cleanLocks) {
error(e);
throw new IndexException(e);
}
info("Had exception: " + e.getMessage());
info("Will try to clean lock");
try {
// There should really be a lucene exception for this one
if (IndexReader.isLocked(dirPath)) {
Directory d = getRdr().directory();
IndexReader.unlock(d);
}
wtr = new IndexWriter(dirPath, defaultAnalyzer, false);
info("Clean lock succeeded");
return wtr;
} catch (Throwable t) {
info("Clean lock failed");
throw new IndexException(t);
}
} catch (Throwable t) {
throw new IndexException(t);
}
}
/* Called to obtain the current or a new reader.
*
* @return IndexReader reader of our index
*/
private IndexReader getRdr() throws IndexException {
if (basePath == null) {
throw new IndexException(IndexException.noBasePath);
}
try {
if (rdr == null) {
rdr = IndexReader.open(basePath + indexDir);
}
return rdr;
} catch (IOException e) {
if (e instanceof FileNotFoundException) {
throw new IndexException(IndexException.noFiles);
}
throw new IndexException(e);
} catch (Throwable t) {
throw new IndexException(t);
}
}
/* Called to unindex a record. The reader will be left
* open. The writer must be closed and will stay closed.
*
* @param rec The record to unindex
*/
private boolean intUnindexRec(Object rec) throws IndexException {
try {
Term t = makeKeyTerm(rec);
int numDeleted = getRdr().deleteDocuments(t);
if (numDeleted > 1) {
throw new IndexException(IndexException.dupKey, t.toString());
}
if (debug) {
trace("removed " + numDeleted + " entries for " + t);
}
updatedIndex = true;
return true;
} catch (IndexException ie) {
if (ie.getCause() instanceof FileNotFoundException) {
// ignore
return false;
}
throw ie;
} catch (IOException e) {
throw new IndexException(e);
} catch (Throwable t) {
throw new IndexException(t);
}
}
/* Called to index a record. The writer will be left open and the reader
* must be closed on entry and will stay closed.
*
* @param rec The record to index
*/
private void intIndexRec(Object rec) throws IndexException {
Document doc = new Document();
addFields(doc, rec);
try {
closeRdr();
getWtr().addDocument(doc);
updatedIndex = true;
} catch (IndexException ie) {
throw ie;
} catch (IOException e) {
throw new IndexException(e);
} catch (Throwable t) {
throw new IndexException(t);
}
}
/** Called to add an array of objects to a document
*
* @param doc Document object
* @param fld Field info
* @param os Object array
* @throws IndexException
*/
protected void addField(Document doc, FieldInfo fld, Object[] os)
throws IndexException {
if (os == null) {
return;
}
for (Object o: os) {
if (o != null) {
doc.add(fld.makeField(String.valueOf(o)));
}
}
}
/** Called to add a String val to a document
*
* @param doc The document
* @param fld Field info
* @param val The value
* @throws IndexException
*/
protected void addField(Document doc, FieldInfo fld, Object val)
throws IndexException {
if (val == null) {
return;
}
doc.add(fld.makeField(String.valueOf(val)));
}
protected Logger getLog() {
if (log == null) {
log = Logger.getLogger(this.getClass());
}
return log;
}
protected void error(Throwable e) {
getLog().error(this, e);
}
protected void error(String msg) {
getLog().error(msg);
}
protected void info(String msg) {
getLog().info(msg);
}
protected void trace(String msg) {
getLog().debug(msg);
}
} |
package edu.washington.escience.myria;
import java.io.Serializable;
import java.util.Objects;
import java.util.regex.Pattern;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
/**
* This class holds the key that identifies a relation. The notation is user.program.relation.
*
* @author dhalperi
*/
public final class RelationKey implements Serializable {
/** Required for Java serialization. */
private static final long serialVersionUID = 1L;
/** The user who owns/creates this relation. */
@JsonProperty
private final String userName;
/** The user's program that owns/creates this relation. */
@JsonProperty
private final String programName;
/** The name of the relation. */
@JsonProperty
private final String relationName;
/**
* This is not really unused, it's used automagically by Jackson deserialization.
*/
@SuppressWarnings("unused")
private RelationKey() {
userName = null;
programName = null;
relationName = null;
}
/**
* Static function to create a RelationKey object.
*
* @param userName the user who owns/creates this relation.
* @param programName the user's program that owns/creates this relation.
* @param relationName the name of the relation.
* @return a new RelationKey reference to the specified relation.
*/
public static RelationKey of(final String userName, final String programName, final String relationName) {
return new RelationKey(userName, programName, relationName);
}
/** The regular expression specifying what names are valid. */
public static final String VALID_NAME_REGEX = "^[\\d\\w]+$";
/** The regular expression matcher for {@link #VALID_NAME_REGEX}. */
private static final Pattern VALID_NAME_PATTERN = Pattern.compile(VALID_NAME_REGEX);
private static String checkName(final String name) {
Objects.requireNonNull(name);
Preconditions.checkArgument(VALID_NAME_PATTERN.matcher(name).matches(),
"supplied name %s does not match the valid name regex %s", name, VALID_NAME_REGEX);
return name;
}
/**
* Private constructor to create a RelationKey object.
*
* @param userName the user who owns/creates this relation.
* @param programName the user's program that owns/creates this relation.
* @param relationName the name of the relation.
*/
public RelationKey(final String userName, final String programName, final String relationName) {
checkName(userName);
checkName(programName);
checkName(relationName);
this.userName = userName;
this.programName = programName;
this.relationName = relationName;
}
/**
* @return the name of this relation.
*/
public String getRelationName() {
return relationName;
}
/**
* @return the name of the program containing this relation.
*/
public String getProgramName() {
return programName;
}
/**
* @return the name of the user who owns the program containing this relation.
*/
public String getUserName() {
return userName;
}
@Override
public String toString() {
return toString('[', '
}
/**
* Helper function for computing strings of different types.
*
* @param leftEscape the left escape character, e.g., '['.
* @param separate the separating character, e.g., '#'.
* @param rightEscape the right escape character, e.g., ']'.
* @return [user#program#relation].
*/
private String toString(final char leftEscape, final char separate, final char rightEscape) {
StringBuilder sb = new StringBuilder();
sb.append(leftEscape).append(userName).append(separate).append(programName).append(separate).append(relationName)
.append(rightEscape);
return sb.toString();
}
/**
* Helper function for computing strings of different types.
*
* @param dbms the DBMS, e.g., "mysql".
* @return [user#program#relation].
*/
public String toString(final String dbms) {
switch (dbms) {
case MyriaConstants.STORAGE_SYSTEM_SQLITE:
return toString('[', '
case MyriaConstants.STORAGE_SYSTEM_POSTGRESQL:
case MyriaConstants.STORAGE_SYSTEM_MONETDB:
return toString('\"', ' ', '\"');
case MyriaConstants.STORAGE_SYSTEM_MYSQL:
return toString('`', ' ', '`');
default:
throw new IllegalArgumentException("Unsupported dbms " + dbms);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.