repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
llaith/toolkit
toolkit-core/src/main/java/org/llaith/toolkit/core/pump/impl/BufferSink.java
1784
/******************************************************************************* * Copyright (c) 2005 - 2013 Nos Doughty * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.llaith.toolkit.core.pump.impl; import com.google.common.collect.Iterables; import org.llaith.toolkit.core.pump.Chunk; import org.llaith.toolkit.core.pump.Sink; import org.llaith.toolkit.common.guard.Guard; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Queue; /** * Very simple implementation of a sink buffer. */ public class BufferSink<T> implements Sink<T> { private static final Logger Log = LoggerFactory.getLogger(BufferSink.class); private final Queue<T> queue; public BufferSink(final Queue<T> queue) { this.queue = Guard.notNull(queue); } @Override public void put(final Chunk<T> chunk) { if (chunk != null) Iterables.addAll(this.queue,chunk); // not offer() } @Override public void close() throws RuntimeException { if (!this.queue.isEmpty()) Log.warn( "BufferSink is closing with "+ this.queue.size()+ " elements in the queued."); } }
apache-2.0
hamnis/json-stat.java
src/main/java/net/hamnaberg/jsonstat/Category.java
1899
package net.hamnaberg.jsonstat; import net.hamnaberg.funclite.Optional; import java.util.*; public final class Category implements Iterable<String> { private final Map<String, String> labels = new LinkedHashMap<>(); private final Map<String, Integer> indices = new LinkedHashMap<>(); private final Map<String, List<String>> children = new LinkedHashMap<>(); public Category(Map<String, Integer> indices, Map<String, String> labels, Map<String, List<String>> children) { this.indices.putAll(indices); this.labels.putAll(labels); this.children.putAll(children); } public int getIndex(String id) { Integer integer = indices.get(id); if (integer == null) { return 0; } return integer; } public Optional<String> getLabel(String id) { return Optional.fromNullable(labels.get(id)); } public List<String> getChild(String id) { return children.containsKey(id) ? children.get(id) : Collections.<String>emptyList(); } @Override public Iterator<String> iterator() { if (!indices.isEmpty()) { return indices.keySet().iterator(); } else { return labels.keySet().iterator(); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Category category = (Category) o; if (!children.equals(category.children)) return false; if (!indices.equals(category.indices)) return false; if (!labels.equals(category.labels)) return false; return true; } @Override public int hashCode() { int result = labels.hashCode(); result = 31 * result + indices.hashCode(); result = 31 * result + children.hashCode(); return result; } }
apache-2.0
orfjackal/pommac
src/test/java/net/orfjackal/pommac/util/ZipUtilSpec.java
3286
/* * Copyright © 2008-2009 Esko Luontola, www.orfjackal.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.orfjackal.pommac.util; import jdave.Specification; import jdave.junit4.JDaveRunner; import net.orfjackal.pommac.TestUtil; import org.junit.runner.RunWith; import java.io.*; import java.util.zip.*; /** * @author Esko Luontola * @since 29.2.2008 */ @SuppressWarnings({"FieldCanBeLocal"}) @RunWith(JDaveRunner.class) public class ZipUtilSpec extends Specification<Object> { private File workDir; public void create() { workDir = TestUtil.createWorkDir(); } public void destroy() { TestUtil.deleteWorkDir(); } public class ExtractingFilesFromAZipArchive { private File outputDir; private File archive; private File unpackedEmptyDir; private File unpackedFileA; private File unpackedDir; private File unpackedFileB; public void create() throws IOException { archive = new File(workDir, "archive.zip"); outputDir = new File(workDir, "output"); outputDir.mkdir(); unpackedEmptyDir = new File(outputDir, "emptyDir"); unpackedFileA = new File(outputDir, "fileA.txt"); unpackedDir = new File(outputDir, "dir"); unpackedFileB = new File(unpackedDir, "fileB.txt"); ZipEntry emptyDir = new ZipEntry("emptyDir/foo/"); ZipEntry fileA = new ZipEntry("fileA.txt"); ZipEntry fileB = new ZipEntry("dir/fileB.txt"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archive)); out.putNextEntry(emptyDir); out.putNextEntry(fileA); out.write("alpha".getBytes()); out.putNextEntry(fileB); out.write("beta".getBytes()); out.close(); specify(archive.exists()); specify(outputDir.listFiles(), does.containExactly()); ZipUtil.unzip(archive, outputDir); specify(archive.exists()); } public void willUnpackDirectories() { specify(unpackedEmptyDir.exists()); specify(unpackedEmptyDir.isDirectory()); } public void willUnpackFiles() { specify(unpackedFileA.exists()); specify(unpackedFileA.isFile()); specify(FileUtil.contentsOf(unpackedFileA), does.equal("alpha")); } public void willUnpackFilesInDirectories() { specify(unpackedDir.exists()); specify(unpackedDir.isDirectory()); specify(unpackedFileB.exists()); specify(unpackedFileB.isFile()); specify(FileUtil.contentsOf(unpackedFileB), does.equal("beta")); } } }
apache-2.0
tawja/twj-main
twj-platform/twj-plugins/twj-plugin-database/twj-plugin-database-impl-hsql/src/main/java/org/tawja/platform/plugins/database/hsql/impl/HsqldbDatabaseServer.java
5393
/* * Copyright 2015 Tawja. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tawja.platform.plugins.database.hsql.impl; import java.util.Properties; import org.apache.felix.ipojo.ComponentInstance; import org.apache.felix.ipojo.ConfigurationException; import org.apache.felix.ipojo.Factory; import org.apache.felix.ipojo.MissingHandlerException; import org.apache.felix.ipojo.UnacceptableConfiguration; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Invalidate; import org.apache.felix.ipojo.annotations.Provides; import org.apache.felix.ipojo.annotations.Requires; import org.apache.felix.ipojo.annotations.Updated; import org.apache.felix.ipojo.annotations.Validate; import org.apache.felix.ipojo.whiteboard.Wbp; import org.apache.felix.ipojo.whiteboard.Whiteboards; import org.hsqldb.server.Server; import org.tawja.platform.plugins.database.base.AbstractTwjDatabaseServer; import org.tawja.platform.plugins.database.api.TwjServerStatus; import org.tawja.platform.plugins.database.hsql.HsqldbServiceProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tawja.platform.plugins.database.base.TwjDatabaseUtils; /** * * @author jbennani */ @Component( name = "org.tawja.platform.plugins.database.hsql.server", managedservice = "org.tawja.platform.plugins.database.hsql.server" ) @Provides @Whiteboards( whiteboards = { @Wbp( filter = "(objectclass=org.tawja.platform.plugins.database.hsql.impl.HsqldbDatabase)", onArrival = "onArrivalDatabase", onDeparture = "onDepartureDatabase", onModification = "onModificationDatabase") } ) public class HsqldbDatabaseServer extends AbstractTwjDatabaseServer<Server> { private static final Logger LOG = LoggerFactory.getLogger(HsqldbDatabaseFactory.class); @Requires(filter = "(factory.name=org.tawja.platform.plugins.database.hsql.database)") private Factory databasefactory; public HsqldbDatabaseServer() { super(); setType(HsqldbServiceProperties.SERVER_TYPE_NAME); } public void createInnerServer() { Server hsqldbServer = new Server(); //hsqldbServer.setDatabaseName(0, "default"); //hsqldbServer.setDatabasePath(0, "databases/hsqldb/" + getName() + "/default"); // hsqldbServer.setRestartOnShutdown (true); //hsqldbServer.setAddress(getHost()); hsqldbServer.setPort(getPort()); hsqldbServer.setSilent(false); setInnerServer(hsqldbServer); //return getInnerServer(); } public void createDefaultDatabase() { Properties config = new Properties(); config.put("instance.name", TwjDatabaseUtils.getDatabaseKey("db-" + HsqldbServiceProperties.SERVER_TYPE_NAME, "default", "default")); config.put("name", "default"); config.put("serverName", "default"); config.put("path", HsqldbServiceProperties.CONF_DB_PATH_PREFIX + "/" + getName() + "/default"); config.put("url", HsqldbServiceProperties.CONF_DB_URL_PREFIX + "/" + getHost() + ":" + getPort() + "/" + getName() + "/default"); config.put("user", ""); config.put("password", ""); ComponentInstance instance = null; try { instance = databasefactory.createComponentInstance(config); } catch (UnacceptableConfiguration ucEx) { LOG.error("Unable to create HSQL Database instance : Bad configuration", ucEx); } catch (MissingHandlerException mhEx) { LOG.error("Unable to create HSQL Database instance : Missing handler", mhEx); } catch (ConfigurationException cEx) { LOG.error("Unable to create HSQL Database instance : erron in configuration", cEx); } //TwjDatabaseServer server = ipojoHelper.getServiceObjectByName(TwjDatabaseServer.class, instance.getInstanceName()); } public void destroyInnerServer() { setInnerServer(null); } @Override @Validate public void start() { super.start(); createInnerServer(); getInnerServer().start(); LOG.info("HSQLDB Database Server State : " + getInnerServer().getStateDescriptor()); LOG.info("HSQLDB Database Server Adress : " + getInnerServer().getAddress()); LOG.info("HSQLDB Database Server Port : " + getInnerServer().getPort()); createDefaultDatabase(); LOG.info("HSQLDB Default Database created"); } @Override @Invalidate public void stop() { super.stop(); getInnerServer().stop(); destroyInnerServer(); } @Override @Updated public void update() { super.update(); } @Override public TwjServerStatus getStatus() { return TwjServerStatus.UNKNOWN; } }
apache-2.0
niqo01/monkey
src/internalDebug/java/com/monkeysarmy/fit/ui/debug/HierarchyTreeChangeListener.java
1757
package com.monkeysarmy.fit.ui.debug; import android.view.View; import android.view.ViewGroup; /** * A {@link android.view.ViewGroup.OnHierarchyChangeListener hierarchy change listener} which recursively * monitors an entire tree of views. */ public final class HierarchyTreeChangeListener implements ViewGroup.OnHierarchyChangeListener { /** * Wrap a regular {@link android.view.ViewGroup.OnHierarchyChangeListener hierarchy change listener} with one * that monitors an entire tree of views. */ public static HierarchyTreeChangeListener wrap(ViewGroup.OnHierarchyChangeListener delegate) { return new HierarchyTreeChangeListener(delegate); } private final ViewGroup.OnHierarchyChangeListener delegate; private HierarchyTreeChangeListener(ViewGroup.OnHierarchyChangeListener delegate) { if (delegate == null) { throw new NullPointerException("Delegate must not be null."); } this.delegate = delegate; } @Override public void onChildViewAdded(View parent, View child) { delegate.onChildViewAdded(parent, child); if (child instanceof ViewGroup) { ViewGroup childGroup = (ViewGroup) child; childGroup.setOnHierarchyChangeListener(this); for (int i = 0; i < childGroup.getChildCount(); i++) { onChildViewAdded(childGroup, childGroup.getChildAt(i)); } } } @Override public void onChildViewRemoved(View parent, View child) { if (child instanceof ViewGroup) { ViewGroup childGroup = (ViewGroup) child; for (int i = 0; i < childGroup.getChildCount(); i++) { onChildViewRemoved(childGroup, childGroup.getChildAt(i)); } childGroup.setOnHierarchyChangeListener(null); } delegate.onChildViewRemoved(parent, child); } }
apache-2.0
ArtificerRepo/s-ramp-tck
src/main/java/org/oasis_open/docs/s_ramp/ns/s_ramp_v1/PolicyExpression.java
1851
/* * Copyright 2014 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.12.18 at 03:02:22 PM EST // package org.oasis_open.docs.s_ramp.ns.s_ramp_v1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.io.Serializable; /** * <p>Java class for PolicyExpression complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PolicyExpression"> * &lt;complexContent> * &lt;extension base="{http://docs.oasis-open.org/s-ramp/ns/s-ramp-v1.0}DerivedArtifactType"> * &lt;anyAttribute/> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PolicyExpression") public class PolicyExpression extends DerivedArtifactType implements Serializable { private static final long serialVersionUID = -2660664082872937248L; }
apache-2.0
casid/mazebert-ladder
src/main/java/com/mazebert/error/Error.java
705
package com.mazebert.error; public abstract class Error extends RuntimeException { public Error(String message) { super(message); } public Error(String message, Throwable cause) { super(message, cause); } public abstract int getStatusCode(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Error error = (Error) o; return getMessage() != null ? getMessage().equals(error.getMessage()) : error.getMessage() == null; } @Override public int hashCode() { return getMessage() != null ? getMessage().hashCode() : 0; } }
apache-2.0
OpenChaiSpark/OCspark
tfdma/src/main/java/com/pointr/tensorflow/api/PcieDMAServer.java
2774
package com.pointr.tensorflow.api; import static com.pointr.tensorflow.api.TensorFlowIf.*; public class PcieDMAServer extends DMAServerBase implements TensorFlowIf.DMAServer { public PcieDMAServer() { String parentDir = System.getenv("GITDIR") + "/tfdma"; String ext = System.getProperty("os.name").equals("Mac OS X") ? ".dylib" : ".so"; String libpath = String.format("%s/%s%s",parentDir,"src/main/cpp/dmaserver",ext); Logger.info("Loading DMA native library " + libpath + " .."); try { System.load(libpath); } catch(Exception e) { Logger.error("Unable to load native library %s: %s".format( libpath, e.getMessage()),e); } } @Override public String setupChannel(String setupJson) { super.setupChannel(setupJson); return setupChannelN(setupJson); } @Override public String register(DMACallback callbackIf) { super.register(callbackIf); return registerN(callbackIf); } @Override public String prepareWrite(String configJson) { super.prepareWrite(configJson); return prepareWriteN(configJson); } @Override public DMAStructures.WriteResultStruct write(String configJson, byte[] dataPtr) { super.write(configJson, dataPtr); return writeN(configJson, dataPtr); } @Override public DMAStructures.WriteResultStruct completeWrite(String configJson) { super.completeWrite(configJson); return completeWriteN(configJson); } @Override public String prepareRead(String configJson) { super.prepareRead(configJson); return prepareReadN(configJson); } @Override public DMAStructures.ReadResultStruct read(String configJson) { super.read(configJson); return readN(configJson); } @Override public DMAStructures.ReadResultStruct completeRead(String configJson) { super.completeRead(configJson); return completeReadN(configJson); } @Override public String shutdownChannel(String shutdownJson) { super.shutdownChannel(shutdownJson); return shutdownChannelN(shutdownJson); } @Override public byte[] readLocal(byte[] dataPtr) { super.readLocal(dataPtr); return readLocalN(dataPtr); } native String setupChannelN(String setupJson); native String registerN(DMACallback callbackIf); native String prepareWriteN(String configJson); native DMAStructures.WriteResultStruct writeN(String configJson, byte[] dataPtr); native DMAStructures.WriteResultStruct completeWriteN(String configJson); native String prepareReadN(String configJson); native DMAStructures.ReadResultStruct readN(String configJson); native DMAStructures.ReadResultStruct completeReadN(String configJson); native String shutdownChannelN(String shutdownJson); native byte[] readLocalN(byte[] dataPtr); }
apache-2.0
MarkRunWu/buck
src/com/facebook/buck/cxx/ArchiveScrubberStep.java
5492
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cxx; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.Step; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import java.io.IOException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.ReadOnlyBufferException; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Arrays; /** * Scrub any non-deterministic meta-data from the given archive (e.g. timestamp, UID, GID). */ public class ArchiveScrubberStep implements Step { private static final byte[] FILE_MAGIC = {0x60, 0x0A}; private final Path archive; private final byte[] expectedGlobalHeader; public ArchiveScrubberStep( Path archive, byte[] expectedGlobalHeader) { this.archive = archive; this.expectedGlobalHeader = expectedGlobalHeader; } private byte[] getBytes(ByteBuffer buffer, int len) { byte[] bytes = new byte[len]; buffer.get(bytes); return bytes; } private int getDecimalStringAsInt(ByteBuffer buffer, int len) { byte[] bytes = getBytes(buffer, len); String str = new String(bytes, Charsets.US_ASCII); return Integer.parseInt(str.trim()); } private void putSpaceLeftPaddedString(ByteBuffer buffer, int len, String value) { Preconditions.checkState(value.length() <= len); value = Strings.padStart(value, len, ' '); buffer.put(value.getBytes(Charsets.US_ASCII)); } private void putIntAsOctalString(ByteBuffer buffer, int len, int value) { putSpaceLeftPaddedString(buffer, len, String.format("0%o", value)); } private void putIntAsDecimalString(ByteBuffer buffer, int len, int value) { putSpaceLeftPaddedString(buffer, len, String.format("%d", value)); } private void checkArchive(boolean expression, String msg) throws ArchiveException { if (!expression) { throw new ArchiveException(msg); } } /** * Efficiently modifies the archive backed by the given buffer to remove any non-deterministic * meta-data such as timestamps, UIDs, and GIDs. * @param archive a {@link ByteBuffer} wrapping the contents of the archive. */ @SuppressWarnings("PMD.AvoidUsingOctalValues") private void scrubArchive(ByteBuffer archive) throws ArchiveException { try { // Grab the global header chunk and verify it's accurate. byte[] globalHeader = getBytes(archive, this.expectedGlobalHeader.length); checkArchive( Arrays.equals(this.expectedGlobalHeader, globalHeader), "invalid global header"); // Iterate over all the file meta-data entries, injecting zero's for timestamp, // UID, and GID. while (archive.hasRemaining()) { /* File name */ getBytes(archive, 16); // Inject 0's for the non-deterministic meta-data entries. /* File modification timestamp */ putIntAsDecimalString(archive, 12, 0); /* Owner ID */ putIntAsDecimalString(archive, 6, 0); /* Group ID */ putIntAsDecimalString(archive, 6, 0); /* File mode */ putIntAsOctalString(archive, 8, 0100644); int fileSize = getDecimalStringAsInt(archive, 10); // Lastly, grab the file magic entry and verify it's accurate. byte[] fileMagic = getBytes(archive, 2); checkArchive( Arrays.equals(FILE_MAGIC, fileMagic), "invalid file magic"); // Skip the file data. archive.position(archive.position() + fileSize + fileSize % 2); } // Convert any low-level exceptions to `ArchiveExceptions`s. } catch (BufferUnderflowException | ReadOnlyBufferException e) { throw new ArchiveException(e.getMessage()); } } private FileChannel readWriteChannel(Path path) throws IOException { return FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE); } @Override public int execute(ExecutionContext context) throws InterruptedException { Path archivePath = context.getProjectFilesystem().resolve(archive); try { try (FileChannel channel = readWriteChannel(archivePath)) { MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size()); scrubArchive(map); } } catch (IOException | ArchiveException e) { context.logError(e, "Error scrubbing non-deterministic metadata from %s", archivePath); return 1; } return 0; } @Override public String getShortName() { return "archive-scrub"; } @Override public String getDescription(ExecutionContext context) { return "archive-scrub"; } @SuppressWarnings("serial") public static class ArchiveException extends Exception { public ArchiveException(String msg) { super(msg); } } }
apache-2.0
fabric8io/kubernetes-client
crd-generator/api/src/test/java/io/fabric8/crd/generator/v1/JsonSchemaTest.java
7648
/** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.crd.generator.v1; import com.fasterxml.jackson.databind.JsonNode; import io.fabric8.crd.example.annotated.Annotated; import io.fabric8.crd.example.basic.Basic; import io.fabric8.crd.example.extraction.IncorrectExtraction; import io.fabric8.crd.example.extraction.IncorrectExtraction2; import io.fabric8.crd.example.json.ContainingJson; import io.fabric8.crd.example.extraction.Extraction; import io.fabric8.crd.example.person.Person; import io.fabric8.crd.generator.utils.Types; import io.fabric8.kubernetes.api.model.apiextensions.v1.JSONSchemaProps; import io.sundr.model.TypeDef; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; class JsonSchemaTest { @Test void shouldCreateJsonSchemaFromClass() { TypeDef person = Types.typeDefFrom(Person.class); JSONSchemaProps schema = JsonSchema.from(person); assertNotNull(schema); Map<String, JSONSchemaProps> properties = schema.getProperties(); assertEquals(7, properties.size()); final List<String> personTypes = properties.get("type").getEnum().stream().map(JsonNode::asText) .collect(Collectors.toList()); assertEquals(2, personTypes.size()); assertTrue(personTypes.contains("crazy")); assertTrue(personTypes.contains("crazier")); final Map<String, JSONSchemaProps> addressProperties = properties.get("addresses").getItems() .getSchema().getProperties(); assertEquals(5, addressProperties.size()); final List<String> addressTypes = addressProperties.get("type").getEnum().stream() .map(JsonNode::asText) .collect(Collectors.toList()); assertEquals(2, addressTypes.size()); assertTrue(addressTypes.contains("home")); assertTrue(addressTypes.contains("work")); final TypeDef def = Types.typeDefFrom(Basic.class); schema = JsonSchema.from(def); assertNotNull(schema); properties = schema.getProperties(); assertNotNull(properties); assertEquals(2, properties.size()); Map<String, JSONSchemaProps> spec = properties.get("spec").getProperties(); assertEquals("integer", spec.get("myInt").getType()); assertEquals("integer", spec.get("myLong").getType()); Map<String, JSONSchemaProps> status = properties.get("status").getProperties(); assertEquals("string", status.get("message").getType()); } @Test void shouldAugmentPropertiesSchemaFromAnnotations() { TypeDef annotated = Types.typeDefFrom(Annotated.class); JSONSchemaProps schema = JsonSchema.from(annotated); assertNotNull(schema); Map<String, JSONSchemaProps> properties = schema.getProperties(); assertEquals(2, properties.size()); final JSONSchemaProps specSchema = properties.get("spec"); Map<String, JSONSchemaProps> spec = specSchema.getProperties(); assertEquals(6, spec.size()); // check descriptions are present assertTrue(spec.containsKey("from-field")); JSONSchemaProps prop = spec.get("from-field"); assertEquals("from-field-description", prop.getDescription()); assertTrue(spec.containsKey("from-getter")); prop = spec.get("from-getter"); assertEquals("from-getter-description", prop.getDescription()); // fields without description annotation shouldn't have them assertTrue(spec.containsKey("unnamed")); assertNull(spec.get("unnamed").getDescription()); assertTrue(spec.containsKey("emptySetter")); assertNull(spec.get("emptySetter").getDescription()); assertTrue(spec.containsKey("anEnum")); // check required list, should register properties with their modified name if needed final List<String> required = specSchema.getRequired(); assertEquals(2, required.size()); assertTrue(required.contains("emptySetter")); assertTrue(required.contains("from-getter")); // check the enum values final JSONSchemaProps anEnum = spec.get("anEnum"); final List<JsonNode> enumValues = anEnum.getEnum(); assertEquals(2, enumValues.size()); enumValues.stream().map(JsonNode::textValue).forEach(s -> assertTrue("oui".equals(s) || "non".equals(s))); // check ignored fields assertFalse(spec.containsKey("ignoredFoo")); assertFalse(spec.containsKey("ignoredBar")); } @Test void shouldProduceKubernetesPreserveFields() { TypeDef containingJson = Types.typeDefFrom(ContainingJson.class); JSONSchemaProps schema = JsonSchema.from(containingJson); assertNotNull(schema); Map<String, JSONSchemaProps> properties = schema.getProperties(); assertEquals(2, properties.size()); final JSONSchemaProps specSchema = properties.get("spec"); Map<String, JSONSchemaProps> spec = specSchema.getProperties(); assertEquals(3, spec.size()); // check preserve unknown fields is present assertTrue(spec.containsKey("free")); JSONSchemaProps freeField = spec.get("free"); assertTrue(freeField.getXKubernetesPreserveUnknownFields()); assertTrue(spec.containsKey("field")); JSONSchemaProps field = spec.get("field"); assertNull(field.getXKubernetesPreserveUnknownFields()); assertTrue(spec.containsKey("foo")); JSONSchemaProps fooField = spec.get("foo"); assertTrue(fooField.getXKubernetesPreserveUnknownFields()); } @Test void shouldExtractPropertiesSchemaFromExtractValueAnnotation() { TypeDef extraction = Types.typeDefFrom(Extraction.class); JSONSchemaProps schema = JsonSchema.from(extraction); assertNotNull(schema); Map<String, JSONSchemaProps> properties = schema.getProperties(); assertEquals(2, properties.size()); final JSONSchemaProps specSchema = properties.get("spec"); Map<String, JSONSchemaProps> spec = specSchema.getProperties(); assertEquals(2, spec.size()); // check typed SchemaFrom JSONSchemaProps foo = spec.get("foo"); Map<String, JSONSchemaProps> fooProps = foo.getProperties(); assertNotNull(fooProps); // you can change everything assertEquals("integer", fooProps.get("BAZ").getType()); assertTrue(foo.getRequired().contains("BAZ")); // you can exclude fields assertNull(fooProps.get("baz")); // check typed SchemaSwap JSONSchemaProps bar = spec.get("bar"); Map<String, JSONSchemaProps> barProps = bar.getProperties(); assertNotNull(barProps); // you can change everything assertEquals("integer", barProps.get("BAZ").getType()); assertTrue(bar.getRequired().contains("BAZ")); // you can exclude fields assertNull(barProps.get("baz")); } @Test void shouldThrowIfSchemaSwapHasUnmatchedField() { TypeDef incorrectExtraction = Types.typeDefFrom(IncorrectExtraction.class); assertThrows(IllegalArgumentException.class, () -> JsonSchema.from(incorrectExtraction)); } @Test void shouldThrowIfSchemaSwapHasUnmatchedClass() { TypeDef incorrectExtraction2 = Types.typeDefFrom(IncorrectExtraction2.class); assertThrows(IllegalArgumentException.class, () -> JsonSchema.from(incorrectExtraction2)); } }
apache-2.0
YoungDigitalPlanet/empiria.player
src/main/java/eu/ydp/empiria/player/client/module/identification/IdentificationModule.java
7707
/* * Copyright 2017 Young Digital Planet S.A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.ydp.empiria.player.client.module.identification; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.json.client.JSONArray; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.xml.client.Element; import com.google.gwt.xml.client.Node; import com.google.inject.Inject; import eu.ydp.empiria.player.client.controller.body.InlineBodyGeneratorSocket; import eu.ydp.empiria.player.client.controller.variables.objects.response.CorrectAnswers; import eu.ydp.empiria.player.client.gin.factory.IdentificationModuleFactory; import eu.ydp.empiria.player.client.module.core.base.InteractionModuleBase; import eu.ydp.empiria.player.client.module.ModuleJsSocketFactory; import eu.ydp.empiria.player.client.module.identification.presenter.SelectableChoicePresenter; import eu.ydp.gwtutil.client.event.factory.Command; import eu.ydp.gwtutil.client.event.factory.EventHandlerProxy; import eu.ydp.gwtutil.client.event.factory.UserInteractionHandlerFactory; import eu.ydp.gwtutil.client.xml.XMLUtils; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class IdentificationModule extends InteractionModuleBase { private int maxSelections; private boolean locked = false; private boolean showingCorrectAnswers = false; @Inject private UserInteractionHandlerFactory interactionHandlerFactory; @Inject private IdentificationModuleFactory identificationModuleFactory; @Inject private IdentificationChoicesManager choicesManager; private final List<Element> multiViewElements = new ArrayList<>(); @Override public void addElement(Element element) { multiViewElements.add(element); } @Override public void installViews(List<HasWidgets> placeholders) { setResponseFromElement(multiViewElements.get(0)); maxSelections = XMLUtils.getAttributeAsInt(multiViewElements.get(0), "maxSelections"); for (int i = 0; i < multiViewElements.size(); i++) { Element element = multiViewElements.get(i); SelectableChoicePresenter selectableChoice = createSelectableChoiceFromElement(element); addClickHandler(selectableChoice); HasWidgets currPlaceholder = placeholders.get(i); currPlaceholder.add(selectableChoice.getView()); choicesManager.addChoice(selectableChoice); } } private SelectableChoicePresenter createSelectableChoiceFromElement(Element element) { Node simpleChoice = element.getElementsByTagName("simpleChoice").item(0); SelectableChoicePresenter selectableChoice = createSelectableChoice((Element) simpleChoice); return selectableChoice; } private SelectableChoicePresenter createSelectableChoice(Element item) { String identifier = XMLUtils.getAttributeAsString(item, "identifier"); InlineBodyGeneratorSocket inlineBodyGeneratorSocket = getModuleSocket().getInlineBodyGeneratorSocket(); Widget contentWidget = inlineBodyGeneratorSocket.generateInlineBody(item); SelectableChoicePresenter selectableChoice = identificationModuleFactory.createSelectableChoice(contentWidget, identifier); return selectableChoice; } private void addClickHandler(final SelectableChoicePresenter selectableChoice) { Command clickCommand = createClickCommand(selectableChoice); EventHandlerProxy userClickHandler = interactionHandlerFactory.createUserClickHandler(clickCommand); userClickHandler.apply(selectableChoice.getView()); } private Command createClickCommand(final SelectableChoicePresenter selectableChoice) { return new Command() { @Override public void execute(NativeEvent event) { onChoiceClick(selectableChoice); } }; } @Override public void lock(boolean locked) { this.locked = locked; if (locked) { choicesManager.lockAll(); } else { choicesManager.unlockAll(); } } @Override public void markAnswers(boolean mark) { CorrectAnswers correctAnswers = getResponse().correctAnswers; choicesManager.markAnswers(mark, correctAnswers); } @Override public void reset() { super.reset(); markAnswers(false); lock(false); choicesManager.clearSelections(); updateResponse(false, true); } @Override public void showCorrectAnswers(boolean show) { if (show) { CorrectAnswers correctAnswers = getResponse().correctAnswers; choicesManager.selectCorrectAnswers(correctAnswers); } else { List<String> values = getResponse().values; choicesManager.restoreView(values); } showingCorrectAnswers = show; } @Override public JavaScriptObject getJsSocket() { return ModuleJsSocketFactory.createSocketObject(this); } @Override public JSONArray getState() { return choicesManager.getState(); } @Override public void setState(JSONArray newState) { choicesManager.setState(newState); updateResponse(false); } private void onChoiceClick(SelectableChoicePresenter selectableChoice) { if (!locked) { selectableChoice.setSelected(!selectableChoice.isSelected()); Collection<SelectableChoicePresenter> selectedOptions = choicesManager.getSelectedChoices(); int currSelectionsCount = selectedOptions.size(); if (currSelectionsCount > maxSelections) { for (SelectableChoicePresenter choice : selectedOptions) { if (selectableChoice != choice) { choice.setSelected(false); break; } } } updateResponse(true); } } private void updateResponse(boolean userInteract) { updateResponse(userInteract, false); } private void updateResponse(boolean userInteract, boolean isReset) { if (!showingCorrectAnswers) { List<String> currResponseValues = choicesManager.getIdentifiersSelectedChoices(); if (!getResponse().compare(currResponseValues) || !getResponse().isInitialized()) { getResponse().set(currResponseValues); fireStateChanged(userInteract, isReset); } } } @Override public void onBodyLoad() { } @Override public void onBodyUnload() { } @Override public void onSetUp() { updateResponse(false); } @Override public void onStart() { } @Override public void onClose() { } }
apache-2.0
ctripcorp/apollo
apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/v1/controller/ItemController.java
7531
/* * Copyright 2021 Apollo Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.ctrip.framework.apollo.openapi.v1.controller; import com.ctrip.framework.apollo.common.dto.ItemDTO; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.common.utils.RequestPrecondition; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO; import com.ctrip.framework.apollo.openapi.util.OpenApiBeanUtils; import com.ctrip.framework.apollo.portal.service.ItemService; import com.ctrip.framework.apollo.portal.spi.UserService; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpStatusCodeException; import javax.servlet.http.HttpServletRequest; @RestController("openapiItemController") @RequestMapping("/openapi/v1/envs/{env}") public class ItemController { private final ItemService itemService; private final UserService userService; public ItemController(final ItemService itemService, final UserService userService) { this.itemService = itemService; this.userService = userService; } @GetMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}") public OpenItemDTO getItem(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String key) { ItemDTO itemDTO = itemService.loadItem(Env.valueOf(env), appId, clusterName, namespaceName, key); return itemDTO == null ? null : OpenApiBeanUtils.transformFromItemDTO(itemDTO); } @PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)") @PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items") public OpenItemDTO createItem(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @RequestBody OpenItemDTO item, HttpServletRequest request) { RequestPrecondition.checkArguments( !StringUtils.isContainEmpty(item.getKey(), item.getDataChangeCreatedBy()), "key and dataChangeCreatedBy should not be null or empty"); if (userService.findByUserId(item.getDataChangeCreatedBy()) == null) { throw new BadRequestException("User " + item.getDataChangeCreatedBy() + " doesn't exist!"); } if(!StringUtils.isEmpty(item.getComment()) && item.getComment().length() > 256){ throw new BadRequestException("Comment length should not exceed 256 characters"); } ItemDTO toCreate = OpenApiBeanUtils.transformToItemDTO(item); //protect toCreate.setLineNum(0); toCreate.setId(0); toCreate.setDataChangeLastModifiedBy(toCreate.getDataChangeCreatedBy()); toCreate.setDataChangeLastModifiedTime(null); toCreate.setDataChangeCreatedTime(null); ItemDTO createdItem = itemService.createItem(appId, Env.valueOf(env), clusterName, namespaceName, toCreate); return OpenApiBeanUtils.transformFromItemDTO(createdItem); } @PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)") @PutMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}") public void updateItem(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String key, @RequestBody OpenItemDTO item, @RequestParam(defaultValue = "false") boolean createIfNotExists, HttpServletRequest request) { RequestPrecondition.checkArguments(item != null, "item payload can not be empty"); RequestPrecondition.checkArguments( !StringUtils.isContainEmpty(item.getKey(), item.getDataChangeLastModifiedBy()), "key and dataChangeLastModifiedBy can not be empty"); RequestPrecondition.checkArguments(item.getKey().equals(key), "Key in path and payload is not consistent"); if (userService.findByUserId(item.getDataChangeLastModifiedBy()) == null) { throw new BadRequestException("user(dataChangeLastModifiedBy) not exists"); } if(!StringUtils.isEmpty(item.getComment()) && item.getComment().length() > 256){ throw new BadRequestException("Comment length should not exceed 256 characters"); } try { ItemDTO toUpdateItem = itemService .loadItem(Env.valueOf(env), appId, clusterName, namespaceName, item.getKey()); //protect. only value,comment,lastModifiedBy can be modified toUpdateItem.setComment(item.getComment()); toUpdateItem.setValue(item.getValue()); toUpdateItem.setDataChangeLastModifiedBy(item.getDataChangeLastModifiedBy()); itemService.updateItem(appId, Env.valueOf(env), clusterName, namespaceName, toUpdateItem); } catch (Throwable ex) { if (ex instanceof HttpStatusCodeException) { // check createIfNotExists if (((HttpStatusCodeException) ex).getStatusCode().equals(HttpStatus.NOT_FOUND) && createIfNotExists) { createItem(appId, env, clusterName, namespaceName, item, request); return; } } throw ex; } } @PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)") @DeleteMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}") public void deleteItem(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @PathVariable String key, @RequestParam String operator, HttpServletRequest request) { if (userService.findByUserId(operator) == null) { throw new BadRequestException("user(operator) not exists"); } ItemDTO toDeleteItem = itemService.loadItem(Env.valueOf(env), appId, clusterName, namespaceName, key); if (toDeleteItem == null){ throw new BadRequestException("item not exists"); } itemService.deleteItem(Env.valueOf(env), toDeleteItem.getId(), operator); } }
apache-2.0
wangxujin/json-rpc
src/main/java/com/felix/unbiz/json/rpc/util/CollectionUtils.java
666
package com.felix.unbiz.json.rpc.util; import java.util.Collection; /** * ClassName: CollectionUtils <br> * Function: 集合工具类 * * @author wangxujin */ public final class CollectionUtils { private CollectionUtils() { } /** * 判断集合是否为空 * * @param coll 集合对象 * * @return */ public static boolean isEmpty(Collection coll) { return coll == null || coll.isEmpty(); } /** * 判断集合对象不为空 * * @param coll 集合对象 * * @return */ public static boolean isNotEmpty(Collection coll) { return !isEmpty(coll); } }
apache-2.0
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/BaseRateError.java
1565
package com.google.api.ads.dfp.jaxws.v201405; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * An error having to do with {@link BaseRate}. * * * <p>Java class for BaseRateError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="BaseRateError"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201405}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://www.google.com/apis/ads/publisher/v201405}BaseRateError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BaseRateError", propOrder = { "reason" }) public class BaseRateError extends ApiError { protected BaseRateErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link BaseRateErrorReason } * */ public BaseRateErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link BaseRateErrorReason } * */ public void setReason(BaseRateErrorReason value) { this.reason = value; } }
apache-2.0
christophersmith/summer-mqtt
summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/util/MqttClientEventPublisher.java
8095
/******************************************************************************* * Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.github.christophersmith.summer.mqtt.core.util; import org.springframework.context.ApplicationEventPublisher; import org.springframework.messaging.MessagingException; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectedEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectionFailureEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectionLostEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttClientDisconnectedEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttMessageDeliveredEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttMessagePublishFailureEvent; import com.github.christophersmith.summer.mqtt.core.event.MqttMessagePublishedEvent; /** * This is a convenience class that facilitates the publishing of Events to an * {@link ApplicationEventPublisher} instance. * <p> * This class in only used internally. */ public final class MqttClientEventPublisher { /** * Publishes a {@link MqttClientConnectedEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param serverUri the Server URI the MQTT Client is connected to * @param subscribedTopics the Topic Filters the MQTT Client is subscribed to * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } /** * Publishes a {@link MqttClientConnectionFailureEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param autoReconnect whether the MQTT Client will automatically reconnect * @param throwable the originating {@link Throwable} * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } /** * Publishes a {@link MqttClientConnectionLostEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param autoReconnect whether the MQTT Client will automatically reconnect * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } /** * Publishes a {@link MqttClientDisconnectedEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } /** * Publishes a {@link MqttMessageDeliveredEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param messageIdentifier the Message Identifier * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } /** * Publishes a {@link MqttMessagePublishedEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param messageIdentifier the Message Identifier * @param correlationId the Correlation ID * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } /** * Publishes a {@link MqttMessagePublishFailureEvent} message to the * {@link ApplicationEventPublisher}. * <p> * If the {@link ApplicationEventPublisher} instance is null, no event message will be * published. * * @param clientId the Client ID value * @param exception the {@link MessagingException} for this event * @param applicationEventPublisher the {@link ApplicationEventPublisher} value * @param source the source that sent this event */ public void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessagePublishFailureEvent(clientId, exception, source)); } } }
apache-2.0
estatio/estatio
estatioapp/app/src/main/java/org/incode/module/document/dom/impl/docs/minio/Document_downloadExternalUrlAsBlob.java
1351
package org.incode.module.document.dom.impl.docs.minio; import javax.inject.Inject; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Mixin; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.value.Blob; import org.incode.module.document.DocumentModule; import org.incode.module.document.dom.impl.docs.Document; import org.incode.module.document.dom.impl.docs.DocumentSort; import org.incode.module.document.spi.minio.ExternalUrlDownloadService; @Mixin(method="act") public class Document_downloadExternalUrlAsBlob { private final Document document; public Document_downloadExternalUrlAsBlob(final Document document) { this.document = document; } public static class ActionDomainEvent extends DocumentModule.ActionDomainEvent<Document_downloadExternalUrlAsBlob> { } @Action( semantics = SemanticsOf.SAFE, domainEvent = ActionDomainEvent.class ) @ActionLayout(named = "Download") public Blob act() { return externalUrlDownloadService.downloadAsBlob(document); } public boolean hideAct() { return document.getSort() != DocumentSort.EXTERNAL_BLOB; } @Inject ExternalUrlDownloadService externalUrlDownloadService; }
apache-2.0
toulezu/play
sendEmail/test/dataparser/TestReadDate.java
1071
package dataparser; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class TestReadDate { public static void main(String[] args) { String file = "D:\\工作积累\\CSDN-中文IT社区-600万\\www.csdn.net.sql"; int cache = 10000; int dbcache = 1000; try { List<DataBean> list = new ArrayList<DataBean>(); DataBean bean = null; String[] data = null; String temp = null; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); while ((temp = br.readLine()) != null) { data = temp.split("#"); bean = new DataBean(); bean.setName(null); bean.setPassword(null); bean.setEmail(data[2].trim()); if (list.size() < cache) { list.add(bean); } else { DBHelper.insertData(list, dbcache); list.clear(); } } if (list.size() > 0) { DBHelper.insertData(list, dbcache); list.clear(); } } catch (Exception e) { e.printStackTrace(); } } }
artistic-2.0
GcsSloop/SUtils
library/src/main/java/com/sloop/adapter/utils/CommonAdapter.java
2424
package com.sloop.adapter.utils; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import java.util.ArrayList; import java.util.List; /** * ListView 的通用适配器 * Author: Sloop * Version: v1.1 * Date: 2015/11/17 * <ul type="disc"> * <li><a href="http://www.sloop.icoc.cc" target="_blank">作者网站</a> </li> * <li><a href="http://weibo.com/5459430586" target="_blank">作者微博</a> </li> * <li><a href="https://github.com/GcsSloop" target="_blank">作者GitHub</a> </li> * </ul> */ public abstract class CommonAdapter<T> extends BaseAdapter { private LayoutInflater mInflater; private Context mContext; private List<T> mDatas = new ArrayList<>(); private int mLayoutId; /** * @param context 上下文 * @param datas 数据集 * @param layoutId 布局ID */ public CommonAdapter(@NonNull Context context, List<T> datas, @NonNull int layoutId) { mInflater = LayoutInflater.from(context); this.mContext = context; this.mLayoutId = layoutId; if(datas!=null){ this.mDatas = datas; } } public void addDatas(List<T> datas){ this.mDatas.addAll(datas); notifyDataSetChanged(); } public void clearDatas(){ this.mDatas.clear(); notifyDataSetChanged(); } public T getDataById(int position){ return mDatas.get(position); } @Override public int getCount() { return mDatas.size(); } @Override public T getItem(int position) { return mDatas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //实例化一个ViewHolder ViewHolder holder = ViewHolder.getInstance(mContext, convertView, parent, mLayoutId, position); //需要自定义的部分 convert(position, holder, getItem(position)); return holder.getConvertView(); } /** * 需要处理的部分,在这里给View设置值 * * @param holder ViewHolder * @param bean 数据集 */ public abstract void convert(int position, ViewHolder holder, T bean); }
artistic-2.0
ColaMachine/MyBlock
src/main/java/com/dozenx/game/engine/item/parser/ItemEquipParser.java
3844
package com.dozenx.game.engine.item.parser; import cola.machine.game.myblocks.engine.Constants; import cola.machine.game.myblocks.engine.modes.GamingState; import cola.machine.game.myblocks.manager.TextureManager; import cola.machine.game.myblocks.model.base.BaseBlock; import com.dozenx.game.engine.command.EquipPartType; import com.dozenx.game.engine.command.ItemMainType; import com.dozenx.game.engine.element.model.BoxModel; import com.dozenx.game.engine.element.model.CakeModel; import com.dozenx.game.engine.element.model.IconModel; import com.dozenx.game.engine.item.bean.ItemDefinition; import com.dozenx.game.engine.item.bean.ItemWearProperties; import core.log.LogUtil; import java.util.Map; /** * Created by dozen.zhang on 2017/5/9. */ public class ItemEquipParser { public static void parse(ItemDefinition item,Map map){ //item.setType(Constants.ICON_TYPE_WEAR); ItemWearProperties properties = new ItemWearProperties(); item.itemTypeProperties = properties; if (map.get("spirit") != null) { int spirit = (int) map.get("spirit"); item.setSpirit(spirit); properties.spirit = spirit; } if (map.get("agile") != null) { int agile = (int) map.get("agile"); item.setAgile(agile); properties.agile = agile; } if (map.get("intelli") != null) { int intelli = (int) map.get("intelli"); item.setIntelli(intelli); properties.intel = intelli; } if (map.get("strenth") != null) { int strenth = (int) map.get("strenth"); item.setStrenth(strenth); properties.strength = strenth; } String position = (String) map.get("position"); if (position != null) { if (position.equals("head")) { item.setPosition(Constants.WEAR_POSI_HEAD); properties.part = EquipPartType.HEAD; } else if (position.equals("body")) { item.setPosition(Constants.WEAR_POSI_BODY); properties.part = EquipPartType.BODY; } else if (position.equals("leg")) { item.setPosition(Constants.WEAR_POSI_LEG); properties.part = EquipPartType.LEG; } else if (position.equals("foot")) { item.setPosition(Constants.WEAR_POSI_FOOT); properties.part = EquipPartType.FOOT; } else if (position.equals("hand")) { item.setPosition(Constants.WEAR_POSI_HAND); properties.part = EquipPartType.HAND; } } item.setType(ItemMainType.WEAR); if (GamingState.player != null) {//区分服务器版本和客户端版本 // String shapeName = (String) map.get("shape"); /*if(icon.equals("fur_helmet")){ LogUtil.println("123"); }*/ item.getItemModel().setIcon(item.itemModel.getIcon()); BaseBlock shape = TextureManager.getShape(item.getName()); if (shape == null) {//如果没有shape 说明还没有用到该物体 还没有定义shape LogUtil.println("hello"); item.getItemModel().init(); } else { item.setShape(shape); item.itemModel.wearModel = new BoxModel(shape); item.itemModel.handModel = new CakeModel(item.itemModel.getIcon()); item.itemModel.outdoorModel = new IconModel(item.itemModel.getIcon()); item.itemModel.placeModel = null; } } // return null; } public void renderHand(){ } public void renderBody(){ } public void renderTerrain(){ } public void renderDrop(){ } }
bsd-2-clause
dobrakmato/jge
src/main/java/eu/matejkormuth/jge/exceptions/gl/ProgramLinkException.java
1761
/** * anothergltry - Another GL try * Copyright (c) 2015, Matej Kormuth <http://www.github.com/dobrakmato> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package eu.matejkormuth.jge.exceptions.gl; import org.lwjgl.opengl.OpenGLException; /** * Thrown when there was error while linking a program. */ public class ProgramLinkException extends OpenGLException { public ProgramLinkException() { } public ProgramLinkException(String msg) { super(msg); } }
bsd-2-clause
myking520/gamefm
gamefm-net/src/main/java/com/myking520/github/client/IClientManager.java
232
package com.myking520.github.client; import org.apache.mina.core.session.IoSession; /** * 客户端管理 */ public interface IClientManager { public IClient create(IoSession session); public void remove(IoSession session); }
bsd-2-clause
manorrock/json
convert/src/main/java/com/manorrock/json/convert/JsonStringStringConverter.java
2078
/* * Copyright (c) 2002-2017, Manorrock.com. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.manorrock.json.convert; import com.manorrock.convert.Converter; import com.manorrock.convert.ConverterContext; import com.manorrock.json.JsonString; /** * A JSON string to String converter. * * @author Manfred Riem (mriem@manorrock.com) */ public class JsonStringStringConverter implements Converter<JsonString, String> { /** * Convert a JSON string to a string. * * @param context the context. * @param string the JSON string. * @return the string. */ @Override public String convert(ConverterContext context, JsonString string) { return string != null ? string.getString() : null; } }
bsd-2-clause
ONatalia/Masterarbeit
src/demo/inpro/system/pento/nlu/PentoRMRSResolver.java
12477
package demo.inpro.system.pento.nlu; import inpro.incremental.processor.RMRSComposer.Resolver; import inpro.irmrsc.rmrs.Formula; import inpro.irmrsc.rmrs.SimpleAssertion; import inpro.irmrsc.rmrs.SimpleAssertion.Type; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.JFrame; import javax.xml.bind.JAXBException; import work.inpro.gui.pentomino.january.GameCanvas; import work.inpro.system.pentomino.Column; import work.inpro.system.pentomino.Field; import work.inpro.system.pentomino.PentoObject; import work.inpro.system.pentomino.Piece; import work.inpro.system.pentomino.Row; import work.inpro.system.pentomino.Setting; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4Boolean; import edu.cmu.sphinx.util.props.S4String; public class PentoRMRSResolver implements Resolver { /** the pento setting to work with */ private Setting setting; /** config for creating setting from XML */ @S4String(defaultValue = "") public final static String PROP_SETTING_XML = "settingXML"; /** a list of lemmata to ignore when resolving */ private List<String> skipList = new ArrayList<String>(); /** a mapping of rmrs lemmata to pento attributes */ Map<String,String> mappedAttributeLemmata = new HashMap<String,String>(); /** a canvas to display current setting */ private GameCanvas gameCanvas; /** a frame for display the setting's canvas */ private static JFrame gameFrame = new JFrame("Pento Setting"); /** boolean for determining whether to show the setting */ @S4Boolean(defaultValue = true) public final static String PROP_SHOW_SETTING = "showSetting"; private boolean showSetting; private boolean updateSetting = true; // Change to suppress changes to the GUI @Override public void newProperties(PropertySheet ps) throws PropertyException { showSetting = ps.getBoolean(PROP_SHOW_SETTING); try { setting = Setting.createFromXML(new URL(ps.getString(PROP_SETTING_XML)).openStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // FIXME: load this from somewhere else... skipList.add("def"); skipList.add("nehmen"); skipList.add("legen"); skipList.add("löschen"); skipList.add("drehen"); skipList.add("spiegeln"); skipList.add("addressee"); mappedAttributeLemmata.put("rot","red"); mappedAttributeLemmata.put("gelb","yellow"); mappedAttributeLemmata.put("grün","green"); mappedAttributeLemmata.put("blau","blue"); mappedAttributeLemmata.put("grau","gray"); mappedAttributeLemmata.put("kreuz","X"); mappedAttributeLemmata.put("gewehr","N"); mappedAttributeLemmata.put("schlange","Z"); mappedAttributeLemmata.put("treppe","W"); mappedAttributeLemmata.put("brücke","U"); mappedAttributeLemmata.put("handy","P"); mappedAttributeLemmata.put("krücke","Y"); mappedAttributeLemmata.put("balken","I"); mappedAttributeLemmata.put("winkel","V"); //mappedAttributeLemmata.put("ecke","V"); Grrrrr, piece and location have the same lemma mappedAttributeLemmata.put("mast","T"); mappedAttributeLemmata.put("pistole","F"); mappedAttributeLemmata.put("sieben","L"); // Build the gui if (showSetting) { this.updateCanvas(); this.drawScene(); } } public Setting getSetting() { return setting; } @SuppressWarnings("unchecked") @Override public Map<Integer, List<?>> resolvesObjects(Formula f) { Map<Integer, List<?>> matches = new HashMap<Integer, List<?>>(); List<SimpleAssertion> transitives = new ArrayList<SimpleAssertion>(); List<SimpleAssertion> ditransitives = new ArrayList<SimpleAssertion>(); // Sort assertions, since we want to do transitives before ditransitives // Also initialize a map for each predicate argument to all world objects (these lists will be reduced below) for (SimpleAssertion sa : f.getNominalAssertions()) { if (skipList.contains(sa.getPredicateName())) { continue; } else if (sa.getType() == Type.TRANSITIVE) { transitives.add(sa); matches.put(sa.getArguments().get(0), this.setting.getPentoObjects()); } else if (sa.getType() == Type.DITRANSITIVE) { ditransitives.add(sa); matches.put(sa.getArguments().get(0), this.setting.getPentoObjects()); matches.put(sa.getArguments().get(1), this.setting.getPentoObjects()); } } //logger.warn("New Formula - Trans: " + transitives.toString() + " Ditrans: " + ditransitives.toString()); // Reduce the number of objects that resolve for each transitive argument for (SimpleAssertion sa : transitives) { List<PentoObject> newMatches = new ArrayList<PentoObject>(); for (PentoObject po : (List<PentoObject>) matches.get(sa.getArguments().get(0))) { if (transitivePredicateResolvesObject(po, sa.getPredicateName())) { newMatches.add(po); } } matches.put(sa.getArguments().get(0), newMatches); } // Reduce the number of objects that resolve for each ditransitive argument for (SimpleAssertion dsa : ditransitives) { List<PentoObject> firstObjectMatches = new ArrayList<PentoObject>(); List<PentoObject> secondObjectMatches = new ArrayList<PentoObject>(); for (PentoObject firstObject : (List<PentoObject>) matches.get(dsa.getArguments().get(0)) ) { for (PentoObject secondObject : (List<PentoObject>) matches.get(dsa.getArguments().get(1)) ) { if (this.ditransitivePredicateResolvesObjects(firstObject, secondObject, dsa.getPredicateName())) { if (!firstObjectMatches.contains(firstObject)) firstObjectMatches.add(firstObject); if (!secondObjectMatches.contains(secondObject)) secondObjectMatches.add(secondObject); } } } matches.put(dsa.getArguments().get(0), firstObjectMatches); matches.put(dsa.getArguments().get(1), secondObjectMatches); } if (this.showSetting) { for (Integer id : matches.keySet()) { for (Piece piece : this.setting.getPieces()) { piece.setSelect(false); for (PentoObject po : (List<PentoObject>) matches.get(id)) { if (po instanceof Piece) { System.out.println(po); ((Piece) po).setSelect(true); } } } } if (this.updateSetting) this.updateCanvas(); } return matches; } @Override public int resolves(Formula f) { Map<Integer, List<?>> matches = this.resolvesObjects(f); if (matches.keySet().isEmpty()) { return 0; } boolean allUnique = true; boolean piecesUnique = true; for (Integer id : matches.keySet()) { if (matches.get(id).isEmpty()) { //logger.warn("Nothing resolved for predicate argument " + id); // else any empties? -> -1 return -1; } else if (matches.get(id).size() > 1) { allUnique = false; if (matches.get(id).get(0) instanceof Piece) { piecesUnique = false; } } } if (allUnique || piecesUnique) { // all uniques or only pieces are uniques -> 1 return 1; } else { return 0; } } @SuppressWarnings("unchecked") @Override public int resolvesObject(Formula f, String tileId) { int ret = -1; // nothing matched yet Map<Integer, List<?>> matches = this.resolvesObjects(f); for (Integer id : matches.keySet()) { for (PentoObject po : (List<PentoObject>) matches.get(id)) { if (po instanceof Piece && po.getID().equals(tileId)) { if (matches.get(id).size() == 1) { return 1; // one object was a match and it was in a singleton list } else if (matches.get(id).size() == 2) { // if two, then they have to be in two different grids. if (!((PentoObject) matches.get(id).get(0)).getField().getGrid().equals(((PentoObject) matches.get(id).get(1)).getField().getGrid())) { return 1; } else { ret = 0; } } else { ret = 0; // continue, but at least we had a match in a longer list } } } } return ret; } public void updateSetting(Setting newsetting) { setting = newsetting; drawScene(); } public void setPerformDomainAction(boolean performActions) { updateSetting = performActions; } /** * Method for checking if a PentoObject matches attributes. * @param po the PentoObject to check * @param predicate the attribute (lemmatized) * @return true if po matched attribute */ private boolean transitivePredicateResolvesObject(PentoObject po, String predicate) { boolean resolved = false; if (mappedAttributeLemmata.containsKey(predicate)) { if (po instanceof Piece) { resolved = (Character.toString(((Piece) po).getType()).equals(mappedAttributeLemmata.get(predicate)) || po.hasColor(mappedAttributeLemmata.get(predicate)) || po.hasLabel(predicate)); } else if (po instanceof Field) { resolved = (po.hasColor(mappedAttributeLemmata.get(predicate)) || po.hasLabel(predicate)); } } else if (predicate.equals("oben")) { resolved = po.isTop(); } else if (predicate.equals("unten")) { resolved = po.isBottom(); } else if (predicate.equals("links")) { resolved = po.isLeft(); } else if (predicate.equals("rechts")) { resolved = po.isRight(); } else if (predicate.equals("ecke")) { resolved = po.isCorner(); } else if (predicate.equals("mitte")) { resolved = po.isCentre(); } else if (predicate.equals("teil") || predicate.toLowerCase().equals("pper")) { // lower casing because robust ppers are PPERs resolved = po instanceof Piece; } else if (predicate.equals("feld")) { resolved = po instanceof Field; } else if (predicate.equals("erste")) { resolved = po.isFirst(); } else if (predicate.equals("zweite")) { resolved = po.isSecond(); } else if (predicate.equals("dritte")) { resolved = po.isThird(); } else if (predicate.equals("spalte")) { resolved = po instanceof Column; } else if (predicate.equals("zeile")) { resolved = po instanceof Row; } else if (predicate.equals("horizontal")) { resolved = false; } else if (predicate.equals("vertikal")) { resolved = false; } return resolved; } /** * Method for checking if two PentoObject resolve with a given predicate. * For instance, in(x,y) is true if x is in y and x is a piece and y a tile... * @param firstObject the first object * @param secondObject the second object * @param predicate the predicate to check the two objects with */ private boolean ditransitivePredicateResolvesObjects(PentoObject firstObject, PentoObject secondObject, String predicate) { boolean resolves = false; if (predicate.equals("in") || predicate.equals("aus")) { resolves = firstObject.isIn(secondObject); // Use this instead if you only want pieces to be in things, not fields // resolves = firstObject.isIn(secondObject) && // firstObject instanceof Piece && // !(secondObject instanceof Piece); } else if (predicate.equals("auf") || predicate.equals("über")) { resolves = firstObject.isAbove(secondObject) && firstObject instanceof Piece && secondObject instanceof Piece; } else if (predicate.equals("neben")) { resolves = firstObject.isNextTo(secondObject) && firstObject instanceof Piece && secondObject instanceof Piece; } else if (predicate.equals("unter")) { resolves = firstObject.isBelow(secondObject) && firstObject instanceof Piece && secondObject instanceof Piece; } return resolves; } /** must be called to update the gameCanvas to reflect the current setting */ private synchronized void updateCanvas() { gameCanvas = new GameCanvas(setting); gameCanvas.hideCursor(); gameCanvas.setVisible(true); gameFrame.setContentPane(gameCanvas); gameFrame.validate(); gameFrame.repaint(); } /** * Sets up the scene from local variable for setting XML. */ private void drawScene() { try { gameCanvas = new GameCanvas(setting); gameCanvas.hideCursor(); resetGUI(this.setting, "Pento Canvas", this.gameCanvas); } catch (Exception e) { e.printStackTrace(); } } /** * Resets GUI */ protected static void resetGUI(Setting setting, String frameName, GameCanvas c) { gameFrame.setName(frameName); gameFrame.setContentPane(c); gameFrame.pack(); gameFrame.setSize(setting.getGrids().get(0).getNumColumns()*115, setting.getGrids().get(0).getNumRows()*120); gameFrame.setVisible(true); } }
bsd-2-clause
cemartins/RichTextFX
richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/XMLEditor.java
5270
package org.fxmisc.richtext.demo; import java.util.Collection; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.CodeArea; import org.fxmisc.richtext.LineNumberFactory; import org.fxmisc.richtext.model.StyleSpans; import org.fxmisc.richtext.model.StyleSpansBuilder; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class XMLEditor extends Application { private static final Pattern XML_TAG = Pattern.compile("(?<ELEMENT>(</?\\h*)(\\w+)([^<>]*)(\\h*/?>))" +"|(?<COMMENT><!--[^<>]+-->)"); private static final Pattern ATTRIBUTES = Pattern.compile("(\\w+\\h*)(=)(\\h*\"[^\"]+\")"); private static final int GROUP_OPEN_BRACKET = 2; private static final int GROUP_ELEMENT_NAME = 3; private static final int GROUP_ATTRIBUTES_SECTION = 4; private static final int GROUP_CLOSE_BRACKET = 5; private static final int GROUP_ATTRIBUTE_NAME = 1; private static final int GROUP_EQUAL_SYMBOL = 2; private static final int GROUP_ATTRIBUTE_VALUE = 3; private static final String sampleCode = String.join("\n", new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", "<!-- Sample XML -->", "< orders >", " <Order number=\"1\" table=\"center\">", " <items>", " <Item>", " <type>ESPRESSO</type>", " <shots>2</shots>", " <iced>false</iced>", " <orderNumber>1</orderNumber>", " </Item>", " <Item>", " <type>CAPPUCCINO</type>", " <shots>1</shots>", " <iced>false</iced>", " <orderNumber>1</orderNumber>", " </Item>", " <Item>", " <type>LATTE</type>", " <shots>2</shots>", " <iced>false</iced>", " <orderNumber>1</orderNumber>", " </Item>", " <Item>", " <type>MOCHA</type>", " <shots>3</shots>", " <iced>true</iced>", " <orderNumber>1</orderNumber>", " </Item>", " </items>", " </Order>", "</orders>" }); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { CodeArea codeArea = new CodeArea(); codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea)); codeArea.textProperty().addListener((obs, oldText, newText) -> { codeArea.setStyleSpans(0, computeHighlighting(newText)); }); codeArea.replaceText(0, 0, sampleCode); Scene scene = new Scene(new StackPane(new VirtualizedScrollPane<>(codeArea)), 600, 400); scene.getStylesheets().add(JavaKeywordsAsync.class.getResource("xml-highlighting.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.setTitle("XML Editor Demo"); primaryStage.show(); } private static StyleSpans<Collection<String>> computeHighlighting(String text) { Matcher matcher = XML_TAG.matcher(text); int lastKwEnd = 0; StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>(); while(matcher.find()) { spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd); if(matcher.group("COMMENT") != null) { spansBuilder.add(Collections.singleton("comment"), matcher.end() - matcher.start()); } else { if(matcher.group("ELEMENT") != null) { String attributesText = matcher.group(GROUP_ATTRIBUTES_SECTION); spansBuilder.add(Collections.singleton("tagmark"), matcher.end(GROUP_OPEN_BRACKET) - matcher.start(GROUP_OPEN_BRACKET)); spansBuilder.add(Collections.singleton("anytag"), matcher.end(GROUP_ELEMENT_NAME) - matcher.end(GROUP_OPEN_BRACKET)); if(!attributesText.isEmpty()) { lastKwEnd = 0; Matcher amatcher = ATTRIBUTES.matcher(attributesText); while(amatcher.find()) { spansBuilder.add(Collections.emptyList(), amatcher.start() - lastKwEnd); spansBuilder.add(Collections.singleton("attribute"), amatcher.end(GROUP_ATTRIBUTE_NAME) - amatcher.start(GROUP_ATTRIBUTE_NAME)); spansBuilder.add(Collections.singleton("tagmark"), amatcher.end(GROUP_EQUAL_SYMBOL) - amatcher.end(GROUP_ATTRIBUTE_NAME)); spansBuilder.add(Collections.singleton("avalue"), amatcher.end(GROUP_ATTRIBUTE_VALUE) - amatcher.end(GROUP_EQUAL_SYMBOL)); lastKwEnd = amatcher.end(); } if(attributesText.length() > lastKwEnd) spansBuilder.add(Collections.emptyList(), attributesText.length() - lastKwEnd); } lastKwEnd = matcher.end(GROUP_ATTRIBUTES_SECTION); spansBuilder.add(Collections.singleton("tagmark"), matcher.end(GROUP_CLOSE_BRACKET) - lastKwEnd); } } lastKwEnd = matcher.end(); } spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd); return spansBuilder.create(); } }
bsd-2-clause
bonej-org/BoneJ2
Modern/wrapperPlugins/src/main/java/org/bonej/wrapperPlugins/wrapperUtils/ResultUtils.java
6867
/*- * #%L * High-level BoneJ2 commands. * %% * Copyright (C) 2015 - 2020 Michael Doube, BoneJ developers * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ /* BSD 2-Clause License Copyright (c) 2018, Michael Doube, Richard Domander, Alessandro Felder All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.bonej.wrapperPlugins.wrapperUtils; import ij.ImagePlus; import java.util.Optional; import java.util.stream.Stream; import net.imagej.axis.Axes; import net.imagej.axis.AxisType; import net.imagej.axis.CalibratedAxis; import net.imagej.axis.TypedAxis; import net.imagej.space.AnnotatedSpace; import net.imagej.units.UnitService; import org.bonej.utilities.AxisUtils; import org.scijava.util.StringUtils; /** * Static utility methods that help display results to the user * * @author Richard Domander */ public final class ResultUtils { private ResultUtils() {} /** * Returns the exponent character of the elements in this space, e.g. '³' for * a spatial 3D space. * * @param space an N-dimensional space. * @param <S> type of the space. * @param <A> type of the axes. * @return the exponent character if the space has 2 - 9 spatial dimensions. * An empty character otherwise. */ public static <S extends AnnotatedSpace<A>, A extends TypedAxis> char getExponent(final S space) { final long dimensions = AxisUtils.countSpatialDimensions(space); if (dimensions == 2) { return '\u00B2'; } if (dimensions == 3) { return '\u00B3'; } if (dimensions == 4) { return '\u2074'; } if (dimensions == 5) { return '\u2075'; } if (dimensions == 6) { return '\u2076'; } if (dimensions == 7) { return '\u2077'; } if (dimensions == 8) { return '\u2078'; } if (dimensions == 9) { return '\u2079'; } // Return an "empty" character return '\u0000'; } /** * Returns a verbal description of the size of the elements in the given * space, e.g. "A" for 2D images and "V" for 3D images. * * @param space an N-dimensional space. * @param <S> type of the space. * @param <A> type of the axes. * @return the noun for the size of the elements. */ public static <S extends AnnotatedSpace<A>, A extends TypedAxis> String getSizeDescription(final S space) { final long dimensions = AxisUtils.countSpatialDimensions(space); if (dimensions == 2) { return "A"; } if (dimensions == 3) { return "V"; } return "Size"; } /** * Returns the common unit string, e.g. "mm<sup>3</sup>" that describes the * elements in the space. * <p> * The common unit is the unit of the first spatial axis if it can be * converted to the units of the other axes. * </p> * * @param space an N-dimensional space. * @param <S> type of the space. * @param unitService an {@link UnitService} to convert axis calibrations. * @param exponent an exponent to be added to the unit, e.g. '³'. * @return the unit string with the exponent. */ public static <S extends AnnotatedSpace<CalibratedAxis>> String getUnitHeader( final S space, final UnitService unitService, final String exponent) { final Optional<String> unit = AxisUtils.getSpatialUnit(space, unitService); if (!unit.isPresent()) { return ""; } final String unitHeader = unit.get(); if (unitHeader.isEmpty()) { // Don't show default units return ""; } return "(" + unitHeader + exponent + ")"; } /** * Gets the unit of the image calibration, which can be displayed to the user. * * @param imagePlus a ImageJ1 style {@link ImagePlus}. * @return calibration unit, or empty string if there's no unit. */ public static String getUnitHeader(final ImagePlus imagePlus) { final String unit = imagePlus.getCalibration().getUnit(); if (StringUtils.isNullOrEmpty(unit)) { return ""; } return "(" + unit + ")"; } /** * If needed, converts the given index to the ImageJ1 convention where Z, * Channel and Time axes start from 1. * * @param type type of the axis's dimension. * @param index the index in the axis. * @return index + 1 if type is Z, Channel or Time. Index otherwise. */ public static long toConventionalIndex(final AxisType type, final long index) { final Stream<AxisType> oneAxes = Stream.of(Axes.Z, Axes.CHANNEL, Axes.TIME); if (oneAxes.anyMatch(t -> t.equals(type))) { return index + 1; } return index; } }
bsd-2-clause
chototsu/MikuMikuStudio
engine/src/jogl2/com/jme3/glhelper/Helper.java
1955
package com.jme3.glhelper; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import com.jme3.math.ColorRGBA; import com.jme3.shader.Shader; /** * OpenGL helper that does not rely on a specific binding. Its main purpose is to allow * to move the binding-agnostic OpenGL logic from the source code of the both renderers * to a single abstract renderer in order to ease the maintenance * * @author Julien Gouesse * */ public interface Helper { public static final int TEXTURE0 = 33984; //TODO: add Array, Format, TargetBuffer, TextureType, ShaderType, ShadeModel, BlendMode, CullFace, FillMode, DepthFunc, AlphaFunc public enum MatrixMode{ MODELVIEW(0x1700),PROJECTION(0x1701); private final int glConstant; private MatrixMode(int glConstant){ this.glConstant = glConstant; } public final int getGLConstant(){ return glConstant; } }; public enum BufferBit{ COLOR_BUFFER(16384),DEPTH_BUFFER(256),STENCIL_BUFFER(1024),ACCUM_BUFFER(512); private final int glConstant; private BufferBit(int glConstant){ this.glConstant = glConstant; } public final int getGLConstant(){ return glConstant; } } public enum Filter{ NEAREST(9728),LINEAR(9729); private final int glConstant; private Filter(int glConstant){ this.glConstant = glConstant; } public final int getGLConstant(){ return glConstant; } } public void useProgram(int program); public void setMatrixMode(MatrixMode matrixMode); public void loadMatrixf(FloatBuffer m); public void multMatrixf(FloatBuffer m); public void setViewPort(int x, int y, int width, int height); public void setBackgroundColor(ColorRGBA color); public void clear(BufferBit bufferBit); public void setDepthRange(float start, float end); public void setScissor(int x, int y, int width, int height); public int getUniformLocation(Shader shader,String name,ByteBuffer nameBuffer); }
bsd-2-clause
jinterval/jinterval
jinterval-expression/src/main/java/net/java/jinterval/expression/example/FireRisk.java
12563
/* * Copyright (c) 2016, JInterval Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package net.java.jinterval.expression.example; import net.java.jinterval.expression.CodeList; import net.java.jinterval.expression.Expression; import net.java.jinterval.expression.OptimizationProblem; /** * Формулы из Количественная оценка неопределённости пожарного риска. Сценарий * аварии "Пожар пролива ЛВЖ" Проблемы анализа риска, том 11, 2014Б ном. 4 */ public class FireRisk { /** * Enum to choose input variable */ public enum From { tpac_T_uw_d, L_d_theta, a_b_theta }; /** * Enum to choose objective function. */ public enum To { F, Fv, Fh, Fsqr } /** * Create optimization problem minimizing Fv on (l,d,theta) inputs. * * @return OptimizationProblem */ public static OptimizationProblem createOptimizationProblemLdMinFv() { return createOptimizationProblem(From.L_d_theta, To.Fv, false); } /** * Create optimization problem maximizing Fv on (tpac,T,uw,d) inputs. * * @return OptimizationProblem */ public static OptimizationProblem createOptimizationProblemTempMaxFv() { return createOptimizationProblem(From.tpac_T_uw_d, To.Fv, true); } /** * Create optimization problem * * @param from choose input variables * @param to choose objective function * @param neg true to negate objective function * @return OptimizationProblem */ public static OptimizationProblem createOptimizationProblem(From from, To to, boolean neg) { String[] box; switch (from) { case tpac_T_uw_d: box = new String[]{ "[50.0,170.0]", // tpac "[254.0,299.0]", // T "[2.3,9.0]", // uw "[15.2,34.8]" // d }; break; case L_d_theta: box = new String[]{ "[19.1,55.2]", // L "[15.2,34.8]", // d "[0,1.18]" // theta }; break; case a_b_theta: box = new String[]{ "[382/348,1104/152]", // a = 2*L/d "[2000/348,2000/152]", // b = 2*X/d "[0,1.18]" // theta }; break; default: throw new AssertionError(); } return new OptimizationProblem(createObjective(from, to, neg), box); } /** * Create objective function * * @param from choose input variables * @param to choose objective function * @param neg true to negate objective function * @return objective function */ public static Expression createObjective(From from, To to, boolean neg) { Subclass fr = new Subclass(from); Expression objective; switch (to) { case F: objective = fr.F; break; case Fv: objective = fr.Fv(); break; case Fh: objective = fr.Fh(); break; case Fsqr: objective = fr.Fsqr(); break; default: throw new AssertionError(); } return neg ? objective.neg().name("neg_" + objective.name()) : objective; } final CodeList cl; final From from; FireRisk(From from) { this.from = from; switch (from) { case tpac_T_uw_d: cl = CodeList.create("tpac", "T", "uw", "d"); break; case L_d_theta: cl = CodeList.create("L", "d", "theta"); break; case a_b_theta: cl = CodeList.create("a", "b", "theta"); break; default: throw new AssertionError(); } } boolean from(From from) { return this.from.ordinal() <= from.ordinal(); } Expression n(String literal) { return cl.lit(literal); } public static class Subclass extends FireRisk { Subclass(From from) { super(from); } // Constants public Expression m_prime = n("0.06").name("m_prime"); public Expression g = n("9.81").name("g"); public Expression Tnom = n("288.15").name("Tnom"); public Expression ro_v_nom = n("1.225").name("ro_v_nom"); public Expression X = n("100").name("X"); public Expression V_mu = n("22.413").name("V_mu"); public Expression k_factor = n("1.216").div(n("0.67668")).name("k_factor"); public Expression c1Pi = cl.pi().recip().name("c1Pi"); public Expression tpac = from(From.tpac_T_uw_d) ? cl.getInp(0) : null; public Expression T = from(From.tpac_T_uw_d) ? cl.getInp(1) : null; public Expression uw = from(From.tpac_T_uw_d) ? cl.getInp(2) : null; public Expression d = from(From.tpac_T_uw_d) ? cl.getInp(3) : from(From.L_d_theta) ? cl.getInp(1) : null; /*0*/ public Expression k = from(From.tpac_T_uw_d) ? k_factor.mul(tpac.rootn(3)).name("k") : null; public Expression mu0 = from(From.tpac_T_uw_d) ? n("7").mul(k).sub(n("21.5")).name("mu0") : null; public Expression mu1 = from(From.tpac_T_uw_d) ? n("0.76").sub(n("0.04").mul(k)).name("mu1") : null; public Expression mu2 = from(From.tpac_T_uw_d) ? n("0.0003").mul(k).sub(n("0.00245")).name("mu2") : null; /*1*/ public Expression mu = from(From.tpac_T_uw_d) ? mu0.add(mu1.mul(tpac)).add(mu2.mul(tpac.sqr())).name("mu") : null; /*2*/ public Expression ro_p = from(From.tpac_T_uw_d) ? mu.div(V_mu.mul(n("1").add(n("0.00367").mul(tpac)))).name("ro_p") : null; public Expression u_star_arg = from(From.tpac_T_uw_d) ? ro_p.div(m_prime.mul(g).mul(d)) : null; /*3*/ public Expression u_star = from(From.tpac_T_uw_d) ? uw.mul(u_star_arg.rootn(3)).max(n("1")).name("u_star") : null; /*4*/ public Expression ro_v = from(From.tpac_T_uw_d) ? Tnom.mul(ro_v_nom).div(T).name("ro_v") : null; /*5*/ public Expression L = from(From.tpac_T_uw_d) ? n("55") .mul(m_prime.pow(n("0.67"))) .div(g.pow(n("0.335"))) .mul(d.pow(n("0.665"))) .mul(u_star.pow(n("0.21"))) .div(ro_v.pow(n("0.67"))) .name("L") : from(From.L_d_theta) ? cl.getInp(0) : null; /*6*/ public Expression theta = from(From.tpac_T_uw_d) ? u_star.sqrt().recip().acos().name("theta") : from(From.L_d_theta) ? cl.getInp(2) : from(From.a_b_theta) ? cl.getInp(2) : null; /*7*/ public Expression a = from(From.L_d_theta) ? L.mul(n("2")).div(d).name("a") : from(From.a_b_theta) ? cl.getInp(0) : null; /*8*/ public Expression b = from(From.L_d_theta) ? n("2").mul(X).div(d).name("b") : from(From.a_b_theta) ? cl.getInp(1) : null; public Expression bp1 = b.add(n("1")).name("bp1"); public Expression bm1 = b.sub(n("1")).name("bm1"); public Expression sinth = theta.sin().name("sinth"); public Expression costh = theta.cos().name("costh"); public Expression A_arg = a.sqr() .add(bp1.sqr()) .sub(n("2").mul(a.mul(bp1).mul(sinth))) .name("A_arg"); /*9*/ public Expression A = A_arg.sqrt().name("A"); public Expression B_arg = a.sqr() .add(bm1.sqr()) .sub(n("2").mul(a.mul(bm1).mul(sinth))) .name("B_arg"); /*10*/ public Expression B = B_arg.sqrt().name("B"); public Expression C_arg = n("1").add((b.sqr().sub(n("1"))).mul(costh.sqr())).name("C_arg"); /*11*/ public Expression C = C_arg.sqrt().name("C"); public Expression D_arg = from(From.L_d_theta) ? n("2").mul(X).sub(d) .div(n("2").mul(X).add(d)) .name("D_arg") : from(From.a_b_theta) ? bm1.div(bp1).sqrt() : null; /*12*/ public Expression D = D_arg.sqrt().name("D"); /*13*/ public Expression E = from(From.L_d_theta) ? L.mul(costh) .div(X.sub(L.mul(sinth))) .name("E") : from(From.a_b_theta) ? a.mul(costh).div(b.sub(a.mul(sinth))) : null; /*14*/ public Expression F_arg = b.sqr().sub(n("1")).name("F_arg"); public Expression F = F_arg.sqrt().name("F"); public Expression ab = a.mul(b).name("ab"); public Expression AB = A.mul(B).name("AB"); public Expression S1arg = ab.sub(F.sqr().mul(sinth)) .div(F.mul(C)).name("S1arg"); public Expression S1 = S1arg.atan().name("S1"); public Expression S2arg = F.mul(sinth).div(C).name("S2arg"); public Expression S2 = S2arg.atan().name("S2"); public Expression S = S1.add(S2).name("S"); public Expression ADB = A.mul(D).div(B).name("ADB"); public Expression atanADB = ADB.atan().name("atanADB"); public Expression Fv() { Expression abFv = a.sqr() .add(b.add(n("1")).sqr()) .sub(n("2").mul(b).mul(n("1").add(a.mul(sinth)))) .name("abFv"); Expression Fv1 = E.neg().mul(D.atan()).name("Fv1"); Expression Fv2 = E.mul(abFv).div(AB).mul(atanADB).name("Fv2"); Expression Fv3 = costh.div(C).mul(S).name("Fv3"); Expression Fv = cl.pi().recip().mul(Fv1.add(Fv2.add(Fv3))).name("Fv"); return Fv; } public Expression Fh() { Expression abFh = a.sqr() .add(b.add(n("1")).sqr()) .sub(n("2").mul(b.add(n("1")).add(ab.mul(sinth)))) .name("abFh"); Expression Fh1 = D.recip().atan().name("Fh1"); Expression Fh2 = sinth.div(C).mul(S).name("Fh2"); Expression Fh3 = abFh.div(AB).mul(atanADB).name("Fh3"); Expression Fh = c1Pi.mul(Fh1.add(Fh2).sub(Fh3)).name("Fh"); return Fh; } public Expression Fsqr() { return Fv().sqr() .add(Fh().sqr()) .name("Fsqr"); } } }
bsd-2-clause
catree1988/CardFantasy-master
workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/feature/WeakenAllFeature.java
1173
package cfvbaibai.cardfantasy.engine.feature; import java.util.List; import cfvbaibai.cardfantasy.CardFantasyRuntimeException; import cfvbaibai.cardfantasy.data.Feature; import cfvbaibai.cardfantasy.engine.CardInfo; import cfvbaibai.cardfantasy.engine.EntityInfo; import cfvbaibai.cardfantasy.engine.FeatureInfo; import cfvbaibai.cardfantasy.engine.FeatureResolver; import cfvbaibai.cardfantasy.engine.HeroDieSignal; import cfvbaibai.cardfantasy.engine.Player; public final class WeakenAllFeature { public static void apply(FeatureResolver resolver, FeatureInfo featureInfo, EntityInfo attacker, Player defenderPlayer) throws HeroDieSignal { if (defenderPlayer == null) { throw new CardFantasyRuntimeException("defenderPlayer is null"); } if (attacker == null) { return; } Feature feature = featureInfo.getFeature(); List<CardInfo> defenders = defenderPlayer.getField().getAliveCards(); resolver.getStage().getUI().useSkill(attacker, defenders, feature, true); WeakenFeature.weakenCard(resolver, featureInfo, featureInfo.getFeature().getImpact(), attacker, defenders); } }
bsd-2-clause
oGZo/zjgsu-abroadStu-web
backend/zjgsu-abroadStu/abroadStu-model/src/main/java/com/zjgsu/abroadStu/model/Admin.java
1355
package com.zjgsu.abroadStu.model; import java.io.Serializable; /** * Created by JIADONG on 16/4/29. */ public class Admin implements Serializable { private Integer id; private String account; private String password; private String token; private String lastLoginIp; public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastLoginIp() { return lastLoginIp; } public void setLastLoginIp(String lastLoginIp) { this.lastLoginIp = lastLoginIp; } @Override public String toString() { return "Admin{" + "id=" + id + ", account='" + account + '\'' + ", password='" + password + '\'' + ", token='" + token + '\'' + ", lastLoginIp='" + lastLoginIp + '\'' + '}'; } }
bsd-2-clause
wingerjc/ChanteySongs
source/java/ChanteySongs/Data/DataUtil.java
2472
package ChanteySongs.Data; import java.io.*; import java.util.*; import java.text.*; import com.thoughtworks.xstream.*; public class DataUtil { public static final DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); public static String getData(Scanner in, PrintWriter out, String name) { String tmp; out.print(name + ": "); out.flush(); tmp = in.nextLine(); return (tmp.length() == 0) ? null : tmp; } public static String getDataMultiLine(Scanner in, PrintWriter out, String name) { String tmp = ""; String ret = ""; out.print(name + ": "); out.flush(); while(!tmp.equalsIgnoreCase("end")) { ret += tmp + "\n"; tmp = in.nextLine(); } return (ret.replaceAll("\\s","").length() == 0) ? null : ret; } public static int getDataInt(Scanner in, PrintWriter out, String name) { String tmp; out.print(name + ": "); out.flush(); tmp = in.nextLine(); try { return (tmp.length() == 0) ? -1 : Integer.parseInt(tmp); }catch(NumberFormatException nfe) { System.err.println("Not an integer value for " + name + ": " + tmp); return -1; } } public static Date getDataDate(Scanner in, PrintWriter out, String name) { String tmp; out.print(name + ": "); out.flush(); tmp = in.nextLine(); try { return (tmp.length() == 0) ? null : formatter.parse(tmp); }catch(ParseException pe) { System.err.println("Could not parse date for " + name + ": " + tmp); return null; } } public static Set<String> getDataSet(Scanner in, PrintWriter out, String name) { Set<String> ret = new HashSet<String>(); String tmp; do { tmp = getData(in, out, name); if(tmp != null) { ret.add(tmp); } }while(tmp != null); return (ret.size() == 0)? null : ret; } public static void prepare(XStream xstream) { xstream.alias("Person", Person.class); xstream.alias("Index", Index.class); xstream.alias("Collection", SongCollection.class); xstream.alias("Song", Song.class); } }
bsd-2-clause
clementval/claw-compiler
driver/src/clawfc/depscan/FortranFileProgramUnitInfoDeserializer.java
1597
/* * This file is released under terms of BSD license * See LICENSE file for more information * @author Mikhail Zhigun */ package clawfc.depscan; import java.io.InputStream; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import clawfc.Configuration; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.Unmarshaller; public class FortranFileProgramUnitInfoDeserializer { final Unmarshaller _unmarshaller; final String SCHEMA_FILE = "/clawfc/depscan/serial/file_unit_info.xsd"; public FortranFileProgramUnitInfoDeserializer(boolean validate) throws Exception { JAXBContext contextObj = JAXBContext.newInstance(clawfc.depscan.serial.FortranFileProgramUnitInfo.class); _unmarshaller = contextObj.createUnmarshaller(); if (validate) { Schema schema; try (InputStream schemaStream = Configuration.class.getResourceAsStream(SCHEMA_FILE)) { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schema = sf.newSchema(new StreamSource(schemaStream)); } _unmarshaller.setSchema(schema); } } public clawfc.depscan.FortranFileProgramUnitInfo deserialize(InputStream in) throws Exception { FortranFileProgramUnitInfo deObj = new FortranFileProgramUnitInfo( (clawfc.depscan.serial.FortranFileProgramUnitInfo) _unmarshaller.unmarshal(in)); return deObj; } }
bsd-2-clause
belteshazzar/oors
oors/src/org/oors/Base.java
12619
package org.oors; import java.util.Date; import javax.persistence.TypedQuery; import javax.swing.text.html.HTMLDocument; public abstract class Base extends OorsEventGenerator { private static final String NULL_ATTRIBUTE = "Null attribute parameter"; private static final String INVALID_VALUE_TYPE = "Attribute value type incorrect"; private static final String INVALID_FOR_TYPE = "Attribute for type incorrect"; private static final String NULL_VALUE = "Null value passed"; abstract long getId(); abstract ProjectBranch getProjectBranch(); public boolean getBooleanValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.BOOLEAN ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeBooleanValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeBooleanValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeBooleanValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeBooleanValue asv = new AttributeBooleanValue(attribute,this.getId(),false); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setBooleanValue( Attribute attribute, boolean value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.BOOLEAN ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeBooleanValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeBooleanValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeBooleanValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeBooleanValue asv = new AttributeBooleanValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public Date getDateValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.DATE ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeDateValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeDateValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeDateValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeDateValue asv = new AttributeDateValue(attribute,this.getId(),new Date()); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setDateValue( Attribute attribute, Date value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.DATE ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeDateValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeDateValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeDateValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeDateValue asv = new AttributeDateValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public String getStringValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.STRING ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeStringValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeStringValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeStringValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeStringValue asv = new AttributeStringValue(attribute,this.getId(),"Default"); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setStringValue( Attribute attribute, String value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.STRING ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); if ( value==null ) throw new AttributeException(NULL_VALUE); TypedQuery<AttributeStringValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeStringValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeStringValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeStringValue asv = new AttributeStringValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public javax.swing.text.html.HTMLDocument getHTMLValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.HTML ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeHTMLValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeHTMLValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeHTMLValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeHTMLValue asv = new AttributeHTMLValue(attribute,this.getId(),new javax.swing.text.html.HTMLDocument()); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setHTMLValue( Attribute attribute, javax.swing.text.html.HTMLDocument value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.HTML ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeHTMLValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeHTMLValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeHTMLValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeHTMLValue asv = new AttributeHTMLValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public double getNumberValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.NUMBER ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeNumberValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeNumberValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeNumberValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { return q.getSingleResult().getValue(); } catch ( Exception ex ) { AttributeNumberValue asv = new AttributeNumberValue(attribute,this.getId(),0.0); DataSource.getInstance().persist(asv); return asv.getValue(); } } public void setNumberValue( Attribute attribute, double value ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( attribute.valueType!=AttributeType.NUMBER ) throw new AttributeException(INVALID_VALUE_TYPE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); TypedQuery<AttributeNumberValue> q = DataSource .getInstance() .entityManager .createQuery("FROM AttributeNumberValue v WHERE v.projectBranchId = :pb AND v.attributeId = :aid AND v.valueForId = :id",AttributeNumberValue.class); q.setParameter("pb", this.getProjectBranch().id); q.setParameter("aid", attribute.id); q.setParameter("id", this.getId()); try { q.getSingleResult().setValue(value); } catch ( Exception ex ) { AttributeNumberValue asv = new AttributeNumberValue(attribute,this.getId(),value); DataSource.getInstance().persist(asv); asv.setValue(value); } } public Object getValue( Attribute attribute ) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE+", Expected: " +attribute.getForType()+", Found: "+this.getClass()); switch ( attribute.valueType ) { case BOOLEAN: return this.getBooleanValue(attribute); case DATE: return this.getDateValue(attribute); case HTML: return this.getHTMLValue(attribute); case NUMBER: return this.getNumberValue(attribute); case STRING: return this.getStringValue(attribute); //case USER: return this.getUserValue(attribute); //case USERGROUP: return this.getUserGroupValue(attribute); default: return null; } } public void setValue(Attribute attribute, Object value) throws AttributeException { if ( attribute==null ) throw new AttributeException(NULL_ATTRIBUTE); if ( this.getClass().hashCode()!=attribute.getForType().getHash() ) throw new AttributeException(INVALID_FOR_TYPE); try { switch ( attribute.valueType ) { case BOOLEAN: this.setBooleanValue(attribute,(Boolean)value); case DATE: this.setDateValue(attribute,(Date)value); case HTML: this.setHTMLValue(attribute,(HTMLDocument)value); case NUMBER: this.setNumberValue(attribute,(Double)value); case STRING: this.setStringValue(attribute,(String)value); //case USER: this.getUserValue(attribute,value); //case USERGROUP: this.getUserGroupValue(attribute,value); } } catch ( ClassCastException ccex ) { throw new AttributeException(ccex.getMessage()); } } }
bsd-2-clause
xyz327/studyResource
study-design-pattern/src/main/java/cn/xz/study/design/pattern/singleton/LazySingleton.java
601
package cn.xz.study.design.pattern.singleton; public class LazySingleton { /** * volatile 确保线程改变了变量的值时 会立刻同步改变量的值 以保证改变量的值是最新的 */ private volatile static LazySingleton singleton = null; private LazySingleton(){ } public static LazySingleton getInstance(){ if(singleton == null){ synchronized (LazySingleton.class){ singleton = new LazySingleton(); } } return singleton; } private int count = 0; public synchronized int add(){ return count++; } public int getCount() { return count; } }
bsd-2-clause
javafunk/matchbox
src/test/java/org/javafunk/matchbox/implementations/BetweenMatcherTest.java
2115
package org.javafunk.matchbox.implementations; import org.hamcrest.Description; import org.hamcrest.StringDescription; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.javafunk.matchbox.Matchers.successfullyMatches; import static org.javafunk.matchbox.Matchers.mismatchesSampleWithMessage; public class BetweenMatcherTest { @Test public void shouldMatchIfComparableValueBetweenSuppliedValues() throws Exception { assertThat(betweenMatcher(5, 10), successfullyMatches(7)); } @Test public void shouldMatchIfComparableValueEqualToLowerBound() throws Exception { assertThat(betweenMatcher(5, 10), successfullyMatches(5)); } @Test public void shouldMatchIfComparableValueEqualToUpperBound() throws Exception { assertThat(betweenMatcher(5, 10), successfullyMatches(10)); } @Test public void shouldNotMatchIfComparableValueLessThanLowerBound() throws Exception { assertThat(betweenMatcher(5, 10), mismatchesSampleWithMessage(3, "was <3>")); } @Test public void shouldNotMatchIfComparableValueGreaterThanUpperBound() throws Exception { assertThat(betweenMatcher(5, 10), mismatchesSampleWithMessage(13, "was <13>")); } @Test public void shouldDescribeExpectedToSuppliedDescription() throws Exception { // Given Description actual = new StringDescription(); BetweenMatcher<Integer> betweenMatcher = new BetweenMatcher<Integer>(5, 10); Description expected = new StringDescription(); expected.appendText("value between ") .appendValue(5) .appendText(" and ") .appendValue(10) .appendText(" inclusive."); // When betweenMatcher.describeTo(actual); // Then assertThat(actual.toString(), is(expected.toString())); } private static BetweenMatcher<Integer> betweenMatcher(int lowerBound, int upperBound) { return new BetweenMatcher<Integer>(lowerBound, upperBound); } }
bsd-2-clause
markovmodel/stallone
src/stallone/mc/pcca/PCCA.java
11313
package stallone.mc.pcca; import static stallone.api.API.*; import stallone.api.IAlgorithm; import stallone.api.algebra.Algebra; import stallone.api.algebra.IEigenvalueDecomposition; import stallone.api.cluster.IClustering; import stallone.api.doubles.Doubles; import stallone.api.doubles.IDoubleArray; import stallone.api.ints.IIntArray; import stallone.api.ints.Ints; import stallone.ints.PrimitiveIntArray; /** * A java implementation of the Inner Simplex Algorithm (ISA) from Marcus Weber. For details refer to:<br> * <i>Marcus Weber: Improved Perron Cluster Analysis, ZIB-Report 03-04.<br> * Marcus Weber and Tobias Galliat: Charakterization of Transition States in Conformational Dynamics using Fuzzy States, * ZIB-Report 02-12.</i><br> * See <tt><A HREF="www.zib.de/bib/pub/index.en.html"><CODE>www.zib.de/bib/pub/index.en.html</CODE></A></tt>. * * <p>A typical application is the computation of meta stable sets of a Markov chain represented by a given reversible * transition matrix. This requires the following steps:<br> * 1) Compute a reversible transition matrix, say <b>P</b>.<br> * 2) Determine the number of meta stable sets, for instance via the size of the Perron Cluster, say <i>k</i>.<br> * 3) Compute the <i>k</i> eigenvectors belonging to the <i>k</i> eigenvalues closest to 1.<br> * 4) Use the eigenvectors as input data to the cluster algorithm.<br> * 5) With {@link #getClusters} you get an array containing the allocation of each indices to a cluster, which is a * number between 0,...,k-1.<br> * 6) Use {@link #getPermutationArray} to obtain a permutation array. With this array you can permute the state space of * <b>P</b>, such that states belonging to the same cluster are neighbours.</p> * * @author meerbach@math.fu-berlin.de */ public final class PCCA implements IAlgorithm { /** * The condition of the transformation matrix. The transformation matrix transforms a given dataset with * simplex-like structure to a dataset with standard simplex-like structure. Large condition indicates an ill * conditioned cluster problem. */ //public double COND_TRANS; /** * An indikator for the deviation of the data-points from simplex structure. Is this indikator negative, than there * are data points outside the computed simplex, so this indikator should be close to zero. */ public double INDIKATOR; private int[] CLUSTER; private int[] SORTARRAY; private int[] CLUSTER_SIZE; private IDoubleArray FUZZY; private IDoubleArray eigenvectors; /** * Creates a new instance of ClusterByIsa and computes a clustering of a data set with the Isa-algorithm. The * created instance will be immutable. The results will be:<br> * <i>Cluster allocation</i>: An integer array containing the allocation of the given data points to the clusters: * <code>CLUSTER[i]</code> is the cluster of data point <i>i</i>.<br> * <i>Fuzzy allocations</i>: A (number of data points times number of clusters) -matrix containing the fuzzy * allocation for each data point.<br> * <i>Simplex indikator</i>: An indikator for the deviation of the shape of the set of data-points from a simplex * structure.<br> * <i>Condition indikator</i>: Large condition indicates an ill conditioned cluster problem.<br> * Use the {@link #allData()} method to display all results and the {@link #getClusters()}, resp. {@link #getFuzzy} * method to achieve them. The simplex and the condition indikator are public fields. * * @param dataSet the data points in a <code>DoubleMatrix2D</code>. <code>dataSet.rows()</code> is the number of * data points, while <code>dataSet.columns()</code> is the number of cluster. * * @throws IllegalArgumentException if there are more clusters than data points. */ public PCCA() { } public void setEigenvectors(IDoubleArray dataSet) { this.eigenvectors = dataSet; } public void perform() { if (eigenvectors == null) { throw new RuntimeException("No eigenvectors set. Aborting."); } /* initialisation */ int noOfClusters = eigenvectors.columns(); int noOfPoints = eigenvectors.rows(); IDoubleArray fuzzyAllocation; IDoubleArray transMatrix; double condTrans; double indikator = 0; int[] clusterAllocation = new int[noOfPoints]; int[] counter; /* Special cases: */ /* a) less than two clusters. */ if (noOfClusters < 2) { fuzzyAllocation = Doubles.create.matrix(noOfPoints, 1, 1); transMatrix = Doubles.create.matrix(1, 1, 1 / eigenvectors.get(0, 0)); condTrans = 0; for (int i = 0; i < noOfPoints; i++) { clusterAllocation[i] = 0; } counter = new int[2]; counter[0] = 0; counter[1] = noOfPoints; } /* b) more cluster than states. */ else if (noOfClusters > noOfPoints) { throw new IllegalArgumentException("There are more clusters than points given!"); } else if (noOfClusters == noOfPoints) { fuzzyAllocation = Doubles.create.array(noOfPoints,noOfPoints); for (int i=0; i<fuzzyAllocation.rows(); i++) fuzzyAllocation.set(i,i,1); transMatrix = Algebra.util.inverse(eigenvectors); // currently, we do not calculate the condition number because we lack the method //condTrans = A.cond(transMatrix); counter = new int[noOfPoints + 1]; for (int i = 0; i < noOfPoints; i++) { clusterAllocation[i] = i; counter[i + 1] = 1; } } /* Start of the Isa-algorithm. */ else { double skalar = 0; double maxDist = 0; double comp = 0; double entry = 0; int[] index = new int[noOfClusters]; int[] indexAll = Ints.create.arrayRange(0, noOfClusters).getArray(); IDoubleArray orthoSys = eigenvectors.copy(); IDoubleArray dummy; /* Compute the two data-points with the largest distance *(quantified by the 2-norm)*/ for (int i = 0; i < noOfPoints; i++) { for (int j = i + 1; j < noOfPoints; j++) { double dij = Algebra.util.distance(eigenvectors.viewRow(i), eigenvectors.viewRow(j)); if (dij > maxDist) { maxDist = dij; index[0] = i; index[1] = j; } } } /* compute the other representatives by modified gram-schmidt * (i.e. the data points with the *largest distance to them computed before).*/ for (int i = 0; i < noOfPoints; i++) { for (int j=0; j<orthoSys.columns(); j++) orthoSys.set(i, j, orthoSys.get(i,j)-eigenvectors.get(0, j)); } // divide by norm of index 1. double d = Algebra.util.norm(orthoSys.viewRow(index[1])); Algebra.util.scale(1.0/d, orthoSys); // ?? for (int i = 2; i < noOfClusters; i++) { maxDist = 0; dummy = orthoSys.viewRow(index[i - 1]).copy(); for (int j = 0; j < noOfPoints; j++) { skalar = Algebra.util.dot(dummy, orthoSys.viewRow(j)); for (int k = 0; k<dummy.size(); k++) { orthoSys.set(j, k, orthoSys.get(j,k) - (dummy.get(k) * skalar)); } comp = Algebra.util.norm(orthoSys.viewRow(j)); if (comp > maxDist) { maxDist = comp; index[i] = j; } } double normi = Algebra.util.norm(orthoSys.viewRow(index[i])); Algebra.util.scale(1.0/normi, orthoSys); } /* Use the index-array with the representatives to compute the * transformation matrix, i.e., the matrix that maps the * representative to the edges of the standard simplex.*/ transMatrix = Algebra.util.inverse(eigenvectors.view(index, indexAll)); // currently cannot compute condition number //condTrans = A.cond(transMatrix); /* Transform the data set to a (hopefully) nearly standard simplex * structure, by mapping all data points with the computed * transformation matrix. */ fuzzyAllocation = Doubles.create.matrix(Algebra.util.product(eigenvectors, transMatrix).getTable()); /* Extract from soft (fuzzy) allocation the sharp allocation vektor.*/ counter = new int[noOfClusters + 1]; for (int i = 0; i < noOfPoints; i++) { comp = 0; for (int j = 0; j < noOfClusters; j++) { entry = fuzzyAllocation.get(i, j); if (entry < indikator) { indikator = entry; } if (entry > comp) { clusterAllocation[i] = j; comp = entry; } } counter[clusterAllocation[i] + 1]++; } } // end if-else /* Compute a sorting array and an array with the number of data points *in each cluster*/ int[] counter2 = new int[noOfClusters]; int[] sortarray = new int[noOfPoints]; for (int i = 1; i < counter.length; i++) { counter[i] += counter[i - 1]; } for (int i = 0; i < sortarray.length; i++) { sortarray[counter[clusterAllocation[i]] + counter2[clusterAllocation[i]]] = i; counter2[clusterAllocation[i]]++; } /* define fields */ INDIKATOR = indikator; FUZZY = fuzzyAllocation; //COND_TRANS = condTrans; CLUSTER = clusterAllocation; SORTARRAY = sortarray; CLUSTER_SIZE = counter2; } /** * Returns an array with cluster allocations. <code>int[i]</code> is the cluster to which data point i was * allocated. */ public IIntArray getClusters() { return(new PrimitiveIntArray(CLUSTER)); } /** * Returns an array containing the number of data points in each cluster. */ public IIntArray getClusterSize() { return(new PrimitiveIntArray(CLUSTER_SIZE)); } public IDoubleArray getFuzzy() { return(FUZZY); } /** * Returns the permutation which is needed to arrange the data points according to their cluster. */ public IIntArray getPermutationArray() { return(new PrimitiveIntArray(SORTARRAY)); } }
bsd-2-clause
warriordog/BlazeLoader
src/com/blazeloader/api/recipe/ApiCrafting.java
12203
package com.blazeloader.api.recipe; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; import java.util.*; public class ApiCrafting { private static final Map<Integer, BLCraftingManager> instances = new HashMap<Integer, BLCraftingManager>(); private static int nextId = 1; static { instances.put(0, new BLCraftingManager(0, CraftingManager.getInstance().getRecipeList())); } /** * Gets a wrapped instance of the normal CraftingManager. * @return Manager instance of CraftingManager */ public static BLCraftingManager getVanillaCraftingManager() { return instances.get(0); } /** * Intended for compatibility with mods that implemement their * own CraftingManageers based off of the vanilla one. * * Will parse a vanilla minecraft CraftingManager to a Blazeloader apis compatible Manager. * * It is not recommened to use this method often. Rather start off with a Manager * or keep a reference to the converted result for later use. * * @param manager CraftingManager to convert * * @return Manager corresponding to the given CraftingManager */ public static BLCraftingManager toManager(CraftingManager manager) { for (BLCraftingManager i : instances.values()) { if (i.equals(manager)) return i; } return createCraftingManager((ArrayList<IRecipe>)manager.getRecipeList()); } /** * Gets a CraftingManager from the pool by it's unique id. * * @param id integer id of the manager you'd like to find. * * @return Manager or null if not found. */ public static BLCraftingManager getManagerFromId(int id) { return instances.containsKey(id) ? instances.get(id) : null; } /** * Creates a brand spanking **new** Crafting Manager. */ public static BLCraftingManager createCraftingManager() { return createCraftingManager(new ArrayList<IRecipe>()); } private static BLCraftingManager createCraftingManager(ArrayList<IRecipe> startingRecipes) { int id = nextId++; instances.put(id, new BLCraftingManager(id, startingRecipes)); return instances.get(id); } /** * Custom implementation of the CraftingManager. * Supports additional functionality such as reverse crafting, * crafting areas greater than 3x3 and methods for removing recipes. * */ public static final class BLCraftingManager implements Comparable<BLCraftingManager> { private final int id; private final List<IRecipe> recipes; private BLCraftingManager(int n, List<IRecipe> recipes) { id = n; this.recipes = recipes; } /** * Gets the unique integer id for this CraftingManager. * Can be used to retrieve this manager again from the pool of CraftingManagers. * * @return integer id */ public int getId() { return id; } /** * Returns an unmodifieable list of recipes registered to this CraftingManager. * * @return List of Recipes */ public List<IRecipe> getRecipeList() { return Collections.unmodifiableList(recipes); } /** * Adds a shaped recipe to this CraftingManager. * * @param output ItemStack output for this recipe * @param input Strings of recipe pattern followed by chars mapped to Items/Blocks/ItemStacks */ public ShapedRecipe addRecipe(ItemStack output, Object... input) { ShapedRecipe result = createShaped(output, false, input); recipes.add(result); return result; } /** * Adds a shapeless crafting recipe to this CraftingManager. * * @param output ItemStack output for this recipe * @param input An array of ItemStack's Item's and Block's that make up the recipe. */ public ShapelessRecipe addShapelessRecipe(ItemStack output, Object... input) { ShapelessRecipe result = createShapeless(output, false, input); recipes.add(result); return result; } /** * Adds a shaped recipe to this CraftingManager. * * @param output ItemStack output for this recipe * @param input Strings of recipe pattern followed by chars mapped to Items/Blocks/ItemStacks */ public ReversibleShapedRecipe addReverseRecipe(ItemStack output, Object... input) { ShapedRecipe result = createShaped(output, true, input); recipes.add(result); return (ReversibleShapedRecipe)result; } /** * Adds a shapeless crafting recipe to this CraftingManager. * * @param output ItemStack output for this recipe * @param input An array of ItemStack's Item's and Block's that make up the recipe. */ public ReversibleShapelessRecipe addReverseShapelessRecipe(ItemStack output, Object... input) { ShapelessRecipe result = createShapeless(output, true, input); recipes.add(result); return (ReversibleShapelessRecipe)result; } /** * Adds an IRecipe to this RecipeManager. * * @param recipe A recipe that will be added to the recipe list. */ public void addRecipe(ShapelessRecipe recipe) { recipes.add(recipe); } /** * Adds an IRecipe to this RecipeManager. * * @param recipe A recipe that will be added to the recipe list. */ public void addRecipe(ShapedRecipe recipe) { recipes.add(recipe); } /** * Adds an IRecipe to this RecipeManager. * * @param recipe A recipe that will be added to the recipe list. */ public void addRecipe(IReversibleRecipe recipe) { recipes.add(recipe); } /** * Removes the given recipe * * @param recipe recipe to be removed * * @return true if the recipe was removed, false otherwise */ public boolean removeRecipe(IRecipe recipe) { int index = recipes.indexOf(recipe); if (index >= 0) { recipes.remove(index); return true; } return false; } /** * Removes recipes for the given item * * @param result ItemStack result of the recipe to be removed * * @return total number of successful removals */ public int removeRecipe(ItemStack result) { return removeRecipe(result, -1); } /** * Removes recipes for the given item * * @param result ItemStack result of the recipe to be removed * @param maxRemovals Maximum number of removals * * @return total number of successful removals */ public int removeRecipe(ItemStack result, int maxRemovals) { int count = 0; for (int i = 0; i < recipes.size(); i++) { if (recipes.get(i).getRecipeOutput() == result) { count++; recipes.remove(i); if (maxRemovals > 0 && count >= maxRemovals) return count; } } return count; } private ShapedRecipe createShaped(ItemStack output, boolean reverse, Object... input) { String recipe = ""; int index = 0; int width = 0; int height = 0; if (input[index] instanceof String[]) { for (String i : (String[])input[index++]) { ++height; width = i.length(); recipe += i; } } else { while (input[index] instanceof String) { String line = (String)input[index++]; ++height; width = line.length(); recipe += line; } } HashMap<Character, ItemStack> stackmap = new HashMap<Character, ItemStack>(); while (index < input.length) { char var13 = (Character) input[index]; ItemStack var15 = null; if (input[index + 1] instanceof Item) { var15 = new ItemStack((Item)input[index + 1]); } else if (input[index + 1] instanceof Block) { var15 = new ItemStack((Block)input[index + 1], 1, 32767); } else if (input[index + 1] instanceof ItemStack) { var15 = (ItemStack)input[index + 1]; } stackmap.put(var13, var15); index += 2; } ItemStack[] stacks = new ItemStack[width * height]; for (int i = 0; i < width * height; i++) { char key = recipe.charAt(i); if (stackmap.containsKey(key)) { stacks[i] = stackmap.get(key).copy(); } else { stacks[i] = null; } } if (reverse) return new ReversibleShapedRecipe(width, height, stacks, output); return new ShapedRecipe(width, height, stacks, output); } private ShapelessRecipe createShapeless(ItemStack output, boolean reverse, Object ... input) { ArrayList itemStacks = Lists.newArrayList(); for (Object obj : input) { if (obj instanceof ItemStack) { itemStacks.add(((ItemStack) obj).copy()); } else if (obj instanceof Item) { itemStacks.add(new ItemStack((Item) obj)); } else { if (!(obj instanceof Block)) throw new IllegalArgumentException("Invalid shapeless recipe: unknown type " + obj.getClass().getName() + "!"); itemStacks.add(new ItemStack((Block) obj)); } } if (reverse) return new ReversibleShapelessRecipe(output, itemStacks); return new ShapelessRecipe(output, itemStacks); } /** * Retrieves the result of a matched recipe in this RecipeManager. * * @param inventory inventory containing the crafting materials * @param world the world that the crafting is being done in (usually the world of the player) * * @return ItemStack result or null if none match */ public ItemStack findMatchingRecipe(InventoryCrafting inventory, World world) { for (IRecipe i : recipes) { if (i.matches(inventory, world)) return i.getCraftingResult(inventory); } return null; } /** * Retrieves the input required to craft the given item. * * @param recipeOutput ItemStack you wish to uncraft * @param width width of crafting table * @param height height of crafting table * * @return ItemStack[] array of inventory contents needed */ public ItemStack[] findRecipeInput(ItemStack recipeOutput, int width, int height) { for (IRecipe i : recipes) { if (i instanceof IReversibleRecipe) { IReversibleRecipe recipe = ((IReversibleRecipe)i); if (recipe.matchReverse(recipeOutput, width, height)) return recipe.getRecipeInput(); } } return null; } /** * Gets the remaining contents for the inventory after performing a craft. * * @param inventory inventory containing the crafting materials * @param world the world that the crafting is being done in (usually the world of the player) * * @return ItemStack[] array or remaining items */ public ItemStack[] getUnmatchedInventory(InventoryCrafting inventory, World world) { for (IRecipe i : recipes) { if (i.matches(inventory, world)) return i.getRemainingItems(inventory); } ItemStack[] newInventory = new ItemStack[inventory.getSizeInventory()]; for (int i = 0; i < newInventory.length; i++) { newInventory[i] = inventory.getStackInSlot(i); } return newInventory; } public boolean equals(Object obj) { if (obj instanceof BLCraftingManager) { return ((BLCraftingManager) obj).id == id; } if (obj instanceof CraftingManager) { return recipes.equals(((CraftingManager)obj).getRecipeList()); } if (obj instanceof List<?>) { return obj.equals(recipes); } return super.equals(obj); } public int compareTo(BLCraftingManager o) { return o.id - id; } } }
bsd-2-clause
igorbotian/rsskit
src/main/java/com/rhcloud/igorbotian/rsskit/rest/RestEndpoint.java
479
package com.rhcloud.igorbotian.rsskit.rest; import com.fasterxml.jackson.databind.JsonNode; import org.apache.http.NameValuePair; import java.io.IOException; import java.util.Set; /** * @author Igor Botian <igor.botian@gmail.com> */ public interface RestEndpoint { JsonNode makeRequest(String endpoint, Set<NameValuePair> params) throws IOException; JsonNode makeRequest(String endpoint, Set<NameValuePair> params, Set<NameValuePair> headers) throws IOException; }
bsd-2-clause
bednar/components
src/main/java/com/github/bednar/components/inject/service/CoffeeCompilerCfg.java
608
package com.github.bednar.components.inject.service; import javax.annotation.Nonnull; /** * @author Jakub Bednář (07/01/2014 20:59) */ public final class CoffeeCompilerCfg { private Boolean bare = false; private CoffeeCompilerCfg() { } @Nonnull public static CoffeeCompilerCfg build() { return new CoffeeCompilerCfg(); } @Nonnull public Boolean getBare() { return bare; } @Nonnull public CoffeeCompilerCfg setBare(@Nonnull final Boolean bare) { this.bare = Boolean.TRUE.equals(bare); return this; } }
bsd-2-clause
steven-maasch/spotsome
de.bht.ebus.spotsome/src/main/java/de/bht/ebus/spotsome/model/Spot.java
3630
package de.bht.ebus.spotsome.model; import java.util.Objects; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import org.springframework.data.domain.Persistable; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; import de.bht.ebus.spotsome.util.JsonViews; @Entity @Table(name = "spot") @Access(AccessType.FIELD) @JsonAutoDetect(fieldVisibility=Visibility.ANY, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE) public class Spot implements Persistable<Long> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "spot_id") @JsonView({JsonViews.OnlyId.class, JsonViews.Public.class}) @JsonProperty("spot_id") private Long spotId; @Column(nullable = false) @JsonView(JsonViews.Public.class) private String name; /** * The radius around the location in meters */ @Column(nullable = false) @JsonView(JsonViews.Public.class) private double radius; @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinColumn(name = "location_id", nullable = false) @JsonView(JsonViews.Public.class) private Location location; @OneToOne @JoinColumn(name = "user_fk", nullable = false, updatable = false) @JsonIgnore private User owner; public Spot(String name, double radius, Location location, User owner) { setName(name); setRadius(radius); setLocation(location); this.owner = Objects.requireNonNull(owner); } protected Spot() { } public Long getId() { return spotId; } public String getName() { return name; } public void setName(String name) { this.name = Objects.requireNonNull(name); } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = Objects.requireNonNull(location); } public User getOwner() { return owner; } @Override public boolean isNew() { return spotId == null && location.getLocationId() == null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((spotId == null) ? 0 : spotId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Spot other = (Spot) obj; if (spotId == null) { if (other.spotId != null) return false; } else if (!spotId.equals(other.spotId)) return false; return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Spot [spotId="); builder.append(spotId); builder.append(", name="); builder.append(name); builder.append(", radius="); builder.append(radius); builder.append(", location="); builder.append(location); builder.append(", owner="); builder.append(owner); builder.append("]"); return builder.toString(); } }
bsd-2-clause
iron-io/iron_worker_java
src/main/java/io/iron/ironworker/client/builders/ScheduleOptionsObject.java
1705
package io.iron.ironworker.client.builders; import java.util.Date; import java.util.HashMap; import java.util.Map; public class ScheduleOptionsObject { private Map<String, Object> options; public ScheduleOptionsObject() { options = new HashMap<String, Object>(); } public ScheduleOptionsObject priority(int priority) { options.put("priority", priority); return this; } public ScheduleOptionsObject startAt(Date startAt) { options.put("start_at", startAt); return this; } public ScheduleOptionsObject endAt(Date endAt) { options.put("end_at", endAt); return this; } public ScheduleOptionsObject delay(int delay) { options.put("delay", delay); return this; } public ScheduleOptionsObject runEvery(int runEvery) { options.put("run_every", runEvery); return this; } public ScheduleOptionsObject runTimes(int runTimes) { options.put("run_times", runTimes); return this; } public ScheduleOptionsObject cluster(String cluster) { options.put("cluster", cluster); return this; } public ScheduleOptionsObject label(String label) { options.put("label", label); return this; } public ScheduleOptionsObject encryptionKey(String encryptionKey) { options.put("encryptionKey", encryptionKey); return this; } public ScheduleOptionsObject encryptionKeyFile(String encryptionKeyFile) { options.put("encryptionKeyFile", encryptionKeyFile); return this; } public Map<String, Object> create() { return options; } }
bsd-2-clause
wenerme/Lizzy
src/java/christophedelory/playlist/wpl/Body.java
2760
/* * Copyright (c) 2008, Christophe Delory * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY CHRISTOPHE DELORY ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CHRISTOPHE DELORY BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package christophedelory.playlist.wpl; /** * Contains the elements that define the contents of a playlist. * The contents of a playlist are organized within a seq element that is contained within the body element. * Typically there is either one seq element that defines a static set of media items and contains media elements, * or there is one that defines a dynamic set of media items and contains a smartPlaylist element. * <br> * Windows Media Player 9 Series or later. * @version $Revision: 92 $ * @author Christophe Delory * @castor.class xml="body" */ public class Body { /** * The body sequence. */ private Seq _seq = new Seq(); /** * Returns the body sequence. * @return a sequence. Shall not be <code>null</code>. * @see #setSeq * @castor.field * get-method="getSeq" * set-method="setSeq" * required="true" * @castor.field-xml * name="seq" * node="element" */ public Seq getSeq() { return _seq; } /** * Initializes the body sequence. * @param seq a sequence. Shall not be <code>null</code>. * @throws NullPointerException if <code>seq</code> is <code>null</code>. * @see #getSeq */ public void setSeq(final Seq seq) { if (seq == null) { throw new NullPointerException("No body sequence"); } _seq = seq; } }
bsd-2-clause
buptwufengjiao/weibo4j
src/com/jungstudy/VertexMenuListener.java
660
/* * VertexMenuListener.java * * Created on March 21, 2007, 1:50 PM; Updated May 29, 2007 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.jungstudy; import edu.uci.ics.jung.visualization.VisualizationViewer; /** * Used to indicate that this class wishes to be told of a selected vertex * along with its visualization component context. Note that the VisualizationViewer * has full access to the graph and layout. * @author Dr. Greg M. Bernstein */ public interface VertexMenuListener<V> { void setVertexAndView(V v, VisualizationViewer visView); }
bsd-3-clause
fabricebouye/gw2-sab
gw2-sab/src/com/bouye/gw2/sab/scene/account/AccountInfoPaneController.java
11512
/* * Copyright (C) 2016-2017 Fabrice Bouyé * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ package com.bouye.gw2.sab.scene.account; import api.web.gw2.mapping.v1.guilddetails.GuildDetails; import api.web.gw2.mapping.v2.account.Account; import api.web.gw2.mapping.v2.account.AccountAccessType; import api.web.gw2.mapping.v2.tokeninfo.TokenInfo; import api.web.gw2.mapping.v2.worlds.World; import com.bouye.gw2.sab.SABConstants; import com.bouye.gw2.sab.scene.SABControllerBase; import com.bouye.gw2.sab.session.Session; import com.bouye.gw2.sab.query.WebQuery; import com.bouye.gw2.sab.text.LabelUtils; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.css.PseudoClass; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.Labeled; import javafx.scene.layout.FlowPane; import javafx.scene.text.TextFlow; /** * FXML Controller class * @author Fabrice Bouyé */ public final class AccountInfoPaneController extends SABControllerBase<AccountInfoPane> { @FXML private Label accountIconLabel; @FXML private Label accountNameLabel; @FXML private Label accessLabel; @FXML private Hyperlink worldLink; @FXML private CheckBox commanderCheck; @FXML private TextFlow guildsTextFlow; @FXML private Label dailyApLabel; @FXML private Label monthlyApLabel; @FXML private Label wvwRankLabel; @FXML private FlowPane permissionsFlowPane; /** * Creates a new instance. */ public AccountInfoPaneController() { } @Override public void initialize(final URL url, final ResourceBundle rb) { } @Override public void dispose() { try { if (infoService != null) { infoService.cancel(); } } finally { super.dispose(); } } /** * Called whenever observed values are invalidated. */ private final InvalidationListener valueInvalidationListener = observable -> updateUI(); /** * Monitors the session validity. */ private BooleanBinding validBinding; @Override protected void uninstallNode(final AccountInfoPane parent) { parent.sessionProperty().removeListener(valueInvalidationListener); validBinding.removeListener(valueInvalidationListener); validBinding.dispose(); validBinding = null; clearOldStyle(parent); } @Override protected void installNode(final AccountInfoPane parent) { parent.sessionProperty().addListener(valueInvalidationListener); validBinding = Bindings.selectBoolean(parent.sessionProperty(), "valid"); // NOI18N. validBinding.addListener(valueInvalidationListener); } @Override protected void updateUI() { if (infoService != null) { infoService.cancel(); } final Optional<AccountInfoPane> parent = parentNode(); final Session session = parent.isPresent() ? parent.get().getSession() : null; parent.ifPresent(this::clearOldStyle); if (session == null || !session.isValid()) { // Other. accountNameLabel.setText(null); accessLabel.setText(null); commanderCheck.setSelected(false); dailyApLabel.setText(null); monthlyApLabel.setText(null); wvwRankLabel.setText(null); guildsTextFlow.getChildren().clear(); // Permissions. permissionsFlowPane.getChildren().clear(); } else { final Account account = session.getAccount(); final TokenInfo tokenInfo = session.getTokenInfo(); // Name. accountNameLabel.setText(account.getName()); final String accessText = account.getAccess() .stream() .map(LabelUtils.INSTANCE::toLabel) .collect(Collectors.joining(", ", "[", "]")); // NOI18N. accessLabel.setText(accessText); // final int worldId = account.getWorld(); worldLink.setUserData(worldId); worldLink.setOnAction(actionEvent -> displayWorldDetails(worldId)); worldLink.setText(String.valueOf(worldId)); // commanderCheck.setSelected(account.isCommander()); dailyApLabel.setText(String.valueOf(account.getDailyAp())); monthlyApLabel.setText(String.valueOf(account.getMonthlyAp())); wvwRankLabel.setText(String.valueOf(account.getWvwRank())); // final List<Labeled> guildLinks = account.getGuilds() .stream() .map(guildId -> { final Hyperlink guildLink = new Hyperlink(String.valueOf(guildId)); guildLink.setUserData(guildId); guildLink.setOnAction(actionEvent -> displayGuildDetails(guildId)); return guildLink; }) .collect(Collectors.toList()); guildsTextFlow.getChildren().setAll(guildLinks); // Permissions. final List<Label> permissionLabels = tokenInfo.getPermissions() .stream() .map(permission -> { final Label icon = new Label(SABConstants.I18N.getString("icon.fa.gear")); // NOI18N. icon.getStyleClass().addAll("awesome-icon", "permission-icon"); // NOI18N. final Label label = new Label(); label.getStyleClass().add("permission-label"); // NOI18N. final String text = LabelUtils.INSTANCE.toLabel(permission); label.setText(text); label.setGraphic(icon); return label; }) .collect(Collectors.toList()); permissionsFlowPane.getChildren().setAll(permissionLabels); updateOtherValuesAsync(session, worldLink, guildLinks); parent.ifPresent(this::installNewStyle); } } /** * Clear old style from given parent. * @param parent The parent, never {@code null}. */ private void clearOldStyle(final AccountInfoPane parent) { Arrays.stream(AccountAccessType.values()).forEach(accessType -> { final PseudoClass pseudoClass = LabelUtils.INSTANCE.toPseudoClass(accessType); parent.pseudoClassStateChanged(pseudoClass, false); }); } /** * Apply new style to given parent. * @param parent The parent, never {@code null}. */ private void installNewStyle(final AccountInfoPane parent) { final Session session = parent.getSession(); if (session != null && session.isValid()) { final Account account = session.getAccount(); final Set<AccountAccessType> access = account.getAccess(); final PseudoClass pseudoClass = LabelUtils.INSTANCE.toPseudoClass(access.stream() .findFirst() .orElse(AccountAccessType.NONE)); parent.pseudoClassStateChanged(pseudoClass, true); } } /** * Invoked when the user clicks on the world hyperlink. * @param worldId The id of the world to inspect. */ private void displayWorldDetails(final int worldId) { final Optional<AccountInfoPane> parent = Optional.ofNullable(getNode()); parent.ifPresent(p -> { final Optional<BiConsumer<Session, Integer>> onWorldDetails = Optional.ofNullable(p.getOnWorldDetails()); onWorldDetails.ifPresent(c -> c.accept(p.getSession(), worldId)); }); } /** * Invoked when the user clicks on one of the guild hyperlinks. * @param guildId The id of the guild to inspect. */ private void displayGuildDetails(final String guildId) { final Optional<AccountInfoPane> parent = Optional.ofNullable(getNode()); parent.ifPresent(p -> { final Optional<BiConsumer<Session, String>> onGuildDetails = Optional.ofNullable(p.getOnGuildDetails()); onGuildDetails.ifPresent(c -> c.accept(p.getSession(), guildId)); }); } private Service<Void> infoService; private void updateOtherValuesAsync(final Session session, final Labeled worldLabel, final List<Labeled> guildLinks) { if (infoService == null) { infoService = new Service<Void>() { @Override protected Task<Void> createTask() { return new AccountInfoUpdateTaks(session, worldLabel, guildLinks); } }; } addAndStartService(infoService, "AccountInfoPaneController::updateOtherValuesAsync"); } /** * Update info associated to an account (ie: server name, guilds' names, etc.). * @author Fabrice Bouyé */ private class AccountInfoUpdateTaks extends Task<Void> { private final Session session; private final Labeled worldLabel; private final List<Labeled> guildLinks; public AccountInfoUpdateTaks(final Session session, final Labeled worldLabel, final List<Labeled> guildLinks) { this.session = session; this.worldLabel = worldLabel; this.guildLinks = guildLinks; } @Override protected Void call() throws Exception { // World. final int worldId = (Integer) worldLabel.getUserData(); final List<World> worlds = WebQuery.INSTANCE.queryWorlds(worldId); if (!worlds.isEmpty()) { final World world = worlds.get(0); // Update on JavaFX application thread. Platform.runLater(() -> worldLabel.setText(world.getName())); } // Guild. final String[] guildIds = guildLinks.stream() .map(hyperlink -> (String) hyperlink.getUserData()) .toArray(size -> new String[size]); final Map<String, GuildDetails> guilds = WebQuery.INSTANCE.queryGuildDetails(guildIds) .stream() .collect(Collectors.toMap(guildDetails -> guildDetails.getGuildId(), Function.identity())); // Update on JavaFX application thread. Platform.runLater(() -> { guildLinks.stream().forEach(guildLink -> { final String guildId = (String) guildLink.getUserData(); final GuildDetails guildDetails = guilds.get(guildId); final String label = String.format("%s [%s]", guildDetails.getGuildName(), guildDetails.getTag()); guildLink.setText(label); }); }); return null; } } }
bsd-3-clause
bertleft/jmonkeyengine
jme3-bullet/src/main/java/com/jme3/bullet/joints/PhysicsJoint.java
5286
/* * Copyright (c) 2009-2012, 2016 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.bullet.joints; import com.jme3.bullet.objects.PhysicsRigidBody; import com.jme3.export.*; import com.jme3.math.Vector3f; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * <p> * PhysicsJoint - Basic Phyiscs Joint * </p> * * @author normenhansen */ public abstract class PhysicsJoint implements Savable { protected long objectId = 0; protected PhysicsRigidBody nodeA; protected PhysicsRigidBody nodeB; protected Vector3f pivotA; protected Vector3f pivotB; protected boolean collisionBetweenLinkedBodys = true; public PhysicsJoint() { } /** * @param nodeA first node of the joint * @param nodeB second node of the joint * @param pivotA local translation of the joint connection point in node A * @param pivotB local translation of the joint connection point in node B */ public PhysicsJoint(PhysicsRigidBody nodeA, PhysicsRigidBody nodeB, Vector3f pivotA, Vector3f pivotB) { this.nodeA = nodeA; this.nodeB = nodeB; this.pivotA = pivotA; this.pivotB = pivotB; nodeA.addJoint(this); nodeB.addJoint(this); } public float getAppliedImpulse() { return getAppliedImpulse(objectId); } private native float getAppliedImpulse(long objectId); /** * @return the constraint */ public long getObjectId() { return objectId; } /** * @return the collisionBetweenLinkedBodys */ public boolean isCollisionBetweenLinkedBodys() { return collisionBetweenLinkedBodys; } /** * toggles collisions between linked bodys<br> * joint has to be removed from and added to PhyiscsSpace to apply this. * * @param collisionBetweenLinkedBodys set to false to have no collisions * between linked bodys */ public void setCollisionBetweenLinkedBodys(boolean collisionBetweenLinkedBodys) { this.collisionBetweenLinkedBodys = collisionBetweenLinkedBodys; } public PhysicsRigidBody getBodyA() { return nodeA; } public PhysicsRigidBody getBodyB() { return nodeB; } public Vector3f getPivotA() { return pivotA; } public Vector3f getPivotB() { return pivotB; } /** * destroys this joint and removes it from its connected PhysicsRigidBodys * joint lists */ public void destroy() { getBodyA().removeJoint(this); getBodyB().removeJoint(this); } @Override public void write(JmeExporter ex) throws IOException { OutputCapsule capsule = ex.getCapsule(this); capsule.write(nodeA, "nodeA", null); capsule.write(nodeB, "nodeB", null); capsule.write(pivotA, "pivotA", null); capsule.write(pivotB, "pivotB", null); } @Override public void read(JmeImporter im) throws IOException { InputCapsule capsule = im.getCapsule(this); this.nodeA = ((PhysicsRigidBody) capsule.readSavable("nodeA", new PhysicsRigidBody())); this.nodeB = (PhysicsRigidBody) capsule.readSavable("nodeB", new PhysicsRigidBody()); this.pivotA = (Vector3f) capsule.readSavable("pivotA", new Vector3f()); this.pivotB = (Vector3f) capsule.readSavable("pivotB", new Vector3f()); } @Override protected void finalize() throws Throwable { try { Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Finalizing Joint {0}", Long.toHexString(objectId)); finalizeNative(objectId); } finally { super.finalize(); } } protected native void finalizeNative(long objectId); }
bsd-3-clause
gurkerl83/millipede-xtreemfs
java/servers/test/org/xtreemfs/test/common/libxtreemfs/ClientTest.java
8942
/* * Copyright (c) 2008-2011 by Paul Seiferth, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.test.common.libxtreemfs; import java.io.IOException; import java.net.InetSocketAddress; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.xtreemfs.common.libxtreemfs.Client; import org.xtreemfs.common.libxtreemfs.FileHandle; import org.xtreemfs.common.libxtreemfs.Options; import org.xtreemfs.common.libxtreemfs.UUIDIterator; import org.xtreemfs.common.libxtreemfs.Volume; import org.xtreemfs.dir.DIRClient; import org.xtreemfs.dir.DIRConfig; import org.xtreemfs.dir.DIRRequestDispatcher; import org.xtreemfs.foundation.buffer.ReusableBuffer; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.Auth; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials; import org.xtreemfs.foundation.util.FSUtils; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceSet; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.Stat; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.Volumes; import org.xtreemfs.pbrpc.generatedinterfaces.DIRServiceClient; import org.xtreemfs.test.SetupUtils; import org.xtreemfs.test.TestEnvironment; /** * * <br> * Sep 3, 2011 */ public class ClientTest extends TestCase { private DIRRequestDispatcher dir; private TestEnvironment testEnv; private DIRConfig dirConfig; private UserCredentials userCredentials; private Auth auth = RPCAuthentication.authNone; private DIRClient dirClient; /** * */ public ClientTest() throws IOException { dirConfig = SetupUtils.createDIRConfig(); Logging.start(Logging.LEVEL_DEBUG); } @Before public void setUp() throws Exception { System.out.println("TEST: " + getClass().getSimpleName()); FSUtils.delTree(new java.io.File(SetupUtils.TEST_DIR)); dir = new DIRRequestDispatcher(dirConfig, SetupUtils.createDIRdbsConfig()); dir.startup(); dir.waitForStartup(); testEnv = new TestEnvironment(new TestEnvironment.Services[] { TestEnvironment.Services.DIR_CLIENT, TestEnvironment.Services.TIME_SYNC, TestEnvironment.Services.RPC_CLIENT, TestEnvironment.Services.MRC, TestEnvironment.Services.OSD }); testEnv.start(); userCredentials = UserCredentials.newBuilder().setUsername("test").addGroups("test").build(); dirClient = new DIRClient(new DIRServiceClient(testEnv.getRpcClient(), null), new InetSocketAddress[] { testEnv.getDIRAddress() }, 3, 1000); } @After public void tearDown() throws Exception { testEnv.shutdown(); dir.shutdown(); dir.waitForShutdown(); } // public void testCreateOpenRemoveListVolume() throws Exception { // // final String VOLUME_NAME_1 = "foobar"; // // // TODO: Create pseudo commandline and parse it. // Options options = new Options(5000, 10000, 4, 2); // // String dirAddress = testEnv.getDIRAddress().getHostName() + ":" + testEnv.getDIRAddress().getPort(); // // Client client = Client.createClient(dirAddress, userCredentials, null, options); // client.start(); // // String mrcAddress = testEnv.getMRCAddress().getHostName() + ":" + testEnv.getMRCAddress().getPort(); // // // Create volume // client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME_1); // // ServiceSet sSet = null; // sSet = dirClient.xtreemfs_service_get_by_name(testEnv.getDIRAddress(), auth, userCredentials, // VOLUME_NAME_1); // // assertEquals(1, sSet.getServicesCount()); // assertEquals(VOLUME_NAME_1, sSet.getServices(0).getName()); // // // List volumes // Volumes volumes = client.listVolumes(mrcAddress); // assertEquals(1, volumes.getVolumesCount()); // assertEquals(VOLUME_NAME_1, volumes.getVolumes(0).getName()); // // // Delete volume // client.deleteVolume(mrcAddress, auth, userCredentials, VOLUME_NAME_1); // // sSet = null; // // sSet = dirClient.xtreemfs_service_get_by_name(testEnv.getDIRAddress(), auth, userCredentials, // VOLUME_NAME_1); // // assertEquals(0, sSet.getServicesCount()); // // // List volumes // volumes = client.listVolumes(mrcAddress); // assertEquals(0, volumes.getVolumesCount()); // // // shutdown the client // client.shutdown(); // } // // public void testUUIDResolver() throws Exception { // final String VOLUME_NAME_1 = "foobar"; // final String VOLUME_NAME_2 = "barfoo"; // // // TODO: Create pseudo commandline and parse it. // Options options = new Options(5000, 10000, 4, 2); // // String dirAddress = testEnv.getDIRAddress().getHostName() + ":" + testEnv.getDIRAddress().getPort(); // // Client client = Client.createClient(dirAddress, userCredentials, null, options); // client.start(); // // String mrcAddress = testEnv.getMRCAddress().getHostName() + ":" + testEnv.getMRCAddress().getPort(); // // // Create volumes // client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME_1); // client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME_2); // // // // get and MRC UUID for the volume. Should be that from the only MRC. // String uuidString = client.volumeNameToMRCUUID(VOLUME_NAME_1); // assertEquals(SetupUtils.getMRC1UUID().toString(), uuidString); // // // same for the second volume // uuidString = client.volumeNameToMRCUUID(VOLUME_NAME_2); // assertEquals(SetupUtils.getMRC1UUID().toString(), uuidString); // // // this should work if we use UUIDIterator, too. // UUIDIterator uuidIterator = new UUIDIterator(); // client.volumeNameToMRCUUID(VOLUME_NAME_1, uuidIterator); // assertEquals(SetupUtils.getMRC1UUID().toString(), uuidIterator.getUUID()); // // // resolve MRC UUID // String address = client.uuidToAddress(SetupUtils.getMRC1UUID().toString()); // assertEquals(testEnv.getMRCAddress().getHostName()+":"+testEnv.getMRCAddress().getPort(), address); // // // resolve OSD UUID // address = client.uuidToAddress(SetupUtils.createMultipleOSDConfigs(1)[0].getUUID().toString()); // assertEquals(testEnv.getOSDAddress().getHostName()+":"+testEnv.getOSDAddress().getPort(), address); // // // shutdown the client // client.shutdown(); // } @Test public void testMinimalExample() throws Exception { final String VOLUME_NAME_1 = "foobar"; Options options = new Options(5000, 10000, 4, 2); String dirAddress = testEnv.getDIRAddress().getHostName() + ":" + testEnv.getDIRAddress().getPort(); String mrcAddress = testEnv.getMRCAddress().getHostName() + ":" + testEnv.getMRCAddress().getPort(); Client client = Client.createClient(dirAddress, userCredentials, null, options); client.start(); //Open a volume named "foobar". client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME_1); Volume volume = client.openVolume(VOLUME_NAME_1, null, options); // Open a file. FileHandle fileHandle = volume.openFile(userCredentials, "/bla.tzt", SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()); // Get file attributes Stat stat = volume.getAttr(userCredentials, "/bla.tzt"); assertEquals(0, stat.getSize()); // Write to file. String data = "Need a testfile? Why not (\\|)(+,,,+)(|/)?"; ReusableBuffer buf = ReusableBuffer.wrap(data.getBytes()); fileHandle.write(userCredentials, buf, buf.capacity(), 0); // fileHandle.close(); //TODO: Check how to get fileSize stat = volume.getAttr(userCredentials, "/bla.tzt"); // assertEquals(data.length(), stat.getSize()); // Read from file. byte[] readData = new byte[data.length()]; ReusableBuffer readBuf = ReusableBuffer.wrap(readData); int readCount = fileHandle.read(userCredentials, readBuf, data.length(), 0); assertEquals(data.length(), readCount); for (int i = 0; i < data.length(); i++) { assertEquals(readData[i], data.getBytes()[i]); } fileHandle.close(); //TODO: join of renewal thread don't work. fix it. //client.shutdown(); } }
bsd-3-clause
al3xandru/testng-jmock
core/src/org/jmock/core/stub/ThrowStub.java
1847
/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.core.stub; import org.jmock.core.Invocation; import org.jmock.core.Stub; import org.jmock.util.Assert; public class ThrowStub extends Assert implements Stub { private Throwable throwable; public ThrowStub(Throwable throwable) { this.throwable = throwable; } public Object invoke(Invocation invocation) throws Throwable { if (isThrowingCheckedException()) { checkTypeCompatiblity(invocation.invokedMethod.getExceptionTypes()); } throwable.fillInStackTrace(); throw throwable; } public StringBuffer describeTo(StringBuffer buffer) { return buffer.append("throws <").append(throwable).append(">"); } private void checkTypeCompatiblity(Class[] allowedExceptionTypes) { for (int i = 0; i < allowedExceptionTypes.length; i++) { if (allowedExceptionTypes[i].isInstance(throwable)) return; } reportIncompatibleCheckedException(allowedExceptionTypes); } private void reportIncompatibleCheckedException(Class[] allowedTypes) { StringBuffer message = new StringBuffer(); message.append("tried to throw a "); message.append(throwable.getClass().getName()); message.append(" from a method that throws "); if (allowedTypes.length == 0) { message.append("no exceptions"); } else { for (int i = 0; i < allowedTypes.length; i++) { if (i > 0) message.append(","); message.append(allowedTypes[i].getName()); } } fail(message.toString()); } private boolean isThrowingCheckedException() { return !(throwable instanceof RuntimeException || throwable instanceof Error); } }
bsd-3-clause
zzuegg/jmonkeyengine
jme3-vr/src/main/java/com/jme3/input/vr/oculus/OculusVR.java
20261
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jme3.input.vr.oculus; import com.jme3.app.VREnvironment; import com.jme3.input.vr.HmdType; import com.jme3.input.vr.VRAPI; import com.jme3.math.*; import com.jme3.renderer.Camera; import com.jme3.texture.*; import org.lwjgl.*; import org.lwjgl.ovr.*; import java.nio.IntBuffer; import java.util.logging.Logger; import static org.lwjgl.BufferUtils.createPointerBuffer; import static org.lwjgl.ovr.OVR.*; import static org.lwjgl.ovr.OVRErrorCode.ovrSuccess; import static org.lwjgl.ovr.OVRUtil.ovr_Detect; import static org.lwjgl.system.MemoryUtil.*; /** * Oculus VR (LibOVR 1.3.0) Native support. * <p> * A few notes about the Oculus coordinate system: * <ul> * <li>Matrices should be transposed</li> * <li>Quaternions should be inverted<li/> * <li>Vectors should have their X and Z axes flipped, but apparently not Y.</li> * </ul> * * @author Campbell Suter (znix@znix.xyz) */ public class OculusVR implements VRAPI { private static final Logger LOGGER = Logger.getLogger(OculusVR.class.getName()); private final VREnvironment environment; private boolean initialized; /** * Pointer to the HMD object */ private long session; /** * Information about the VR session (should the app quit, is * it visible or is the universal menu open, etc) */ private OVRSessionStatus sessionStatus; /** * HMD information, such as product name and manufacturer. */ private OVRHmdDesc hmdDesc; /** * The horizontal resolution of the HMD */ private int resolutionW; /** * The vertical resolution of the HMD */ private int resolutionH; /** * Field-of-view data for each eye (how many degrees from the * center can the user see). */ private final OVRFovPort fovPorts[] = new OVRFovPort[2]; /** * Data about each eye to be rendered - in particular, the * offset from the center of the HMD to the eye. */ private final OVREyeRenderDesc eyeRenderDesc[] = new OVREyeRenderDesc[2]; /** * Store the projections for each eye, so we don't have to malloc * and recalculate them each frame. */ private final OVRMatrix4f[] projections = new OVRMatrix4f[2]; /** * Store the poses for each eye, relative to the HMD. * * @see #getHMDMatrixPoseLeftEye() */ private final Matrix4f[] hmdRelativeEyePoses = new Matrix4f[2]; /** * Store the positions for each eye, relative to the HMD. * * @see #getHMDVectorPoseLeftEye() */ private final Vector3f[] hmdRelativeEyePositions = new Vector3f[2]; /** * The current state of the tracked components (HMD, touch) */ private OVRTrackingState trackingState; /** * The position and orientation of the user's head. */ private OVRPosef headPose; /** * The state of the Touch controllers. */ private OculusVRInput input; // The size of the texture drawn onto the HMD private int textureW; private int textureH; // Layers to render into private PointerBuffer layers; private OVRLayerEyeFov layer0; /** * Chain texture set thing. */ private long chains[]; /** * Frame buffers we can draw into. */ private FrameBuffer framebuffers[][]; public OculusVR(VREnvironment environment) { this.environment = environment; } @Override public OculusVRInput getVRinput() { return input; } @Override public String getName() { return "OVR"; } @Override public int getDisplayFrequency() { // TODO find correct frequency. I'm not sure // if LibOVR has a way to do that, though. return 60; } @Override public boolean initialize() { // Check to make sure the HMD is connected OVRDetectResult detect = OVRDetectResult.calloc(); ovr_Detect(0, detect); boolean connected = detect.IsOculusHMDConnected(); LOGGER.config("OVRDetectResult.IsOculusHMDConnected = " + connected); LOGGER.config("OVRDetectResult.IsOculusServiceRunning = " + detect.IsOculusServiceRunning()); detect.free(); if (!connected) { LOGGER.info("Oculus Rift not connected"); return false; } initialized = true; // Set up the HMD OVRLogCallback callback = new OVRLogCallback() { @Override public void invoke(long userData, int level, long message) { LOGGER.fine("LibOVR [" + userData + "] [" + level + "] " + memASCII(message)); } }; OVRInitParams initParams = OVRInitParams.calloc(); initParams.LogCallback(callback); if (ovr_Initialize(initParams) != ovrSuccess) { LOGGER.severe("LibOVR Init Failed"); return false; // TODO fix memory leak - destroy() is not called } LOGGER.config("LibOVR Version " + ovr_GetVersionString()); initParams.free(); // Get access to the HMD LOGGER.info("Initialize HMD Session"); PointerBuffer pHmd = memAllocPointer(1); OVRGraphicsLuid luid = OVRGraphicsLuid.calloc(); if (ovr_Create(pHmd, luid) != ovrSuccess) { LOGGER.severe("Failed to create HMD"); return false; // TODO fix memory leak - destroy() is not called } session = pHmd.get(0); memFree(pHmd); luid.free(); sessionStatus = OVRSessionStatus.calloc(); // Get the information about the HMD LOGGER.fine("Get HMD properties"); hmdDesc = OVRHmdDesc.malloc(); ovr_GetHmdDesc(session, hmdDesc); if (hmdDesc.Type() == ovrHmd_None) { LOGGER.warning("No HMD connected"); return false; // TODO fix memory leak - destroy() is not called } resolutionW = hmdDesc.Resolution().w(); resolutionH = hmdDesc.Resolution().h(); LOGGER.config("HMD Properties: " + "\t Manufacturer: " + hmdDesc.ManufacturerString() + "\t Product: " + hmdDesc.ProductNameString() + "\t Serial: <hidden>" // + hmdDesc.SerialNumberString() // Hidden for privacy reasons + "\t Type: " + hmdDesc.Type() + "\t Resolution (total): " + resolutionW + "," + resolutionH); if (resolutionW == 0) { LOGGER.severe("HMD witdth=0 : aborting"); return false; // TODO fix memory leak - destroy() is not called } // Find the FOV for each eye for (int eye = 0; eye < 2; eye++) { fovPorts[eye] = hmdDesc.DefaultEyeFov(eye); } // Get the pose for each eye, and cache it for later. for (int eye = 0; eye < 2; eye++) { // Create the projection objects projections[eye] = OVRMatrix4f.malloc(); hmdRelativeEyePoses[eye] = new Matrix4f(); hmdRelativeEyePositions[eye] = new Vector3f(); // Find the eye render information - we use this in the // view manager for giving LibOVR its timewarp information. eyeRenderDesc[eye] = OVREyeRenderDesc.malloc(); ovr_GetRenderDesc(session, eye, fovPorts[eye], eyeRenderDesc[eye]); // Get the pose of the eye OVRPosef pose = eyeRenderDesc[eye].HmdToEyePose(); // Get the position and rotation of the eye vecO2J(pose.Position(), hmdRelativeEyePositions[eye]); Quaternion rotation = quatO2J(pose.Orientation(), new Quaternion()); // Put it into a matrix for the get eye pose functions hmdRelativeEyePoses[eye].loadIdentity(); hmdRelativeEyePoses[eye].setTranslation(hmdRelativeEyePositions[eye]); hmdRelativeEyePoses[eye].setRotationQuaternion(rotation); } // Recenter the HMD. The game itself should do this too, but just in case / before they do. reset(); // Do this so others relying on our texture size (the GUI in particular) get it correct. findHMDTextureSize(); // Allocate the memory for the tracking state - we actually // set it up later, but Input uses it so calloc it now. trackingState = OVRTrackingState.calloc(); // Set up the input input = new OculusVRInput(this, session, sessionStatus, trackingState); // TODO find some way to get in ovrTrackingOrigin_FloorLevel // throw new UnsupportedOperationException("Not yet implemented!"); return true; } @Override public void updatePose() { double ftiming = ovr_GetPredictedDisplayTime(session, 0); ovr_GetTrackingState(session, ftiming, true, trackingState); ovr_GetSessionStatus(session, sessionStatus); input.updateControllerStates(); headPose = trackingState.HeadPose().ThePose(); } @Override public boolean isInitialized() { return initialized; } @Override public void destroy() { // fovPorts: contents are managed by LibOVR, no need to do anything. // Clean up the input input.dispose(); // Check if we've set up rendering - if so, clean that up. if (chains != null) { // Destroy our set of huge buffer images. for (long chain : chains) { ovr_DestroyTextureSwapChain(session, chain); } // Free up the layer layer0.free(); // The layers array apparently takes care of itself (and crashes if we try to free it) } for (OVREyeRenderDesc eye : eyeRenderDesc) { eye.free(); } for (OVRMatrix4f projection : projections) { projection.free(); } hmdDesc.free(); trackingState.free(); sessionStatus.free(); // Wrap everything up ovr_Destroy(session); ovr_Shutdown(); } @Override public void reset() { // Reset the coordinate system - where the user's head is now is facing forwards from [0,0,0] ovr_RecenterTrackingOrigin(session); } @Override public void getRenderSize(Vector2f store) { if (!isInitialized()) { throw new IllegalStateException("Cannot call getRenderSize() before initialized!"); } store.x = textureW; store.y = textureH; } @Override public float getInterpupillaryDistance() { return 0.065f; // TODO } @Override public Quaternion getOrientation() { return quatO2J(headPose.Orientation(), new Quaternion()); } @Override public Vector3f getPosition() { return vecO2J(headPose.Position(), new Vector3f()); } @Override public void getPositionAndOrientation(Vector3f storePos, Quaternion storeRot) { storePos.set(getPosition()); storeRot.set(getOrientation()); } private Matrix4f calculateProjection(int eye, Camera cam) { Matrix4f mat = new Matrix4f(); // Get LibOVR to find the correct projection OVRUtil.ovrMatrix4f_Projection(fovPorts[eye], cam.getFrustumNear(), cam.getFrustumFar(), OVRUtil.ovrProjection_None, projections[eye]); matrixO2J(projections[eye], mat); return mat; } @Override public Matrix4f getHMDMatrixProjectionLeftEye(Camera cam) { return calculateProjection(ovrEye_Left, cam); } @Override public Matrix4f getHMDMatrixProjectionRightEye(Camera cam) { return calculateProjection(ovrEye_Right, cam); } @Override public Vector3f getHMDVectorPoseLeftEye() { return hmdRelativeEyePositions[ovrEye_Left]; } @Override public Vector3f getHMDVectorPoseRightEye() { return hmdRelativeEyePositions[ovrEye_Right]; } @Override public Vector3f getSeatedToAbsolutePosition() { throw new UnsupportedOperationException(); } @Override public Matrix4f getHMDMatrixPoseLeftEye() { return hmdRelativeEyePoses[ovrEye_Left]; } @Override public Matrix4f getHMDMatrixPoseRightEye() { return hmdRelativeEyePoses[ovrEye_Left]; } @Override public HmdType getType() { return HmdType.OCULUS_RIFT; } @Override public boolean initVRCompositor(boolean set) { if (!set) { throw new UnsupportedOperationException("Cannot use LibOVR without compositor!"); } setupLayers(); framebuffers = new FrameBuffer[2][]; for (int eye = 0; eye < 2; eye++) setupFramebuffers(eye); // TODO move initialization code here from VRViewManagerOculus return true; } @Override public void printLatencyInfoToConsole(boolean set) { throw new UnsupportedOperationException("Not yet implemented!"); } @Override public void setFlipEyes(boolean set) { throw new UnsupportedOperationException("Not yet implemented!"); } @Override public Void getCompositor() { throw new UnsupportedOperationException("Not yet implemented!"); } @Override public Void getVRSystem() { throw new UnsupportedOperationException("Not yet implemented!"); } // Rendering-type stuff public void findHMDTextureSize() { // Texture sizes float pixelScaling = 1.0f; // pixelsPerDisplayPixel OVRSizei leftTextureSize = OVRSizei.malloc(); ovr_GetFovTextureSize(session, ovrEye_Left, fovPorts[ovrEye_Left], pixelScaling, leftTextureSize); OVRSizei rightTextureSize = OVRSizei.malloc(); ovr_GetFovTextureSize(session, ovrEye_Right, fovPorts[ovrEye_Right], pixelScaling, rightTextureSize); if (leftTextureSize.w() != rightTextureSize.w()) { throw new IllegalStateException("Texture sizes do not match [horizontal]"); } if (leftTextureSize.h() != rightTextureSize.h()) { throw new IllegalStateException("Texture sizes do not match [vertical]"); } textureW = leftTextureSize.w(); textureH = leftTextureSize.h(); leftTextureSize.free(); rightTextureSize.free(); } private long setupTextureChain() { // Set up the information for the texture buffer chain thing OVRTextureSwapChainDesc swapChainDesc = OVRTextureSwapChainDesc.calloc() .Type(ovrTexture_2D) .ArraySize(1) .Format(OVR_FORMAT_R8G8B8A8_UNORM_SRGB) .Width(textureW) .Height(textureH) .MipLevels(1) .SampleCount(1) .StaticImage(false); // ovrFalse // Create the chain PointerBuffer textureSetPB = createPointerBuffer(1); if (OVRGL.ovr_CreateTextureSwapChainGL(session, swapChainDesc, textureSetPB) != ovrSuccess) { throw new RuntimeException("Failed to create Swap Texture Set"); } swapChainDesc.free(); return textureSetPB.get(); // TODO is this a memory leak? } public void setupLayers() { //Layers layer0 = OVRLayerEyeFov.calloc(); layer0.Header().Type(ovrLayerType_EyeFov); layer0.Header().Flags(ovrLayerFlag_TextureOriginAtBottomLeft); chains = new long[2]; for (int eye = 0; eye < 2; eye++) { long eyeChain = setupTextureChain(); chains[eye] = eyeChain; OVRRecti viewport = OVRRecti.calloc(); viewport.Pos().x(0); viewport.Pos().y(0); viewport.Size().w(textureW); viewport.Size().h(textureH); layer0.ColorTexture(eye, eyeChain); layer0.Viewport(eye, viewport); layer0.Fov(eye, fovPorts[eye]); viewport.free(); // we update pose only when we have it in the render loop } layers = createPointerBuffer(1); layers.put(0, layer0); } /** * Create a framebuffer for an eye. */ public void setupFramebuffers(int eye) { // Find the chain length IntBuffer length = BufferUtils.createIntBuffer(1); ovr_GetTextureSwapChainLength(session, chains[eye], length); int chainLength = length.get(); LOGGER.fine("HMD Eye #" + eye + " texture chain length: " + chainLength); // Create the frame buffers framebuffers[eye] = new FrameBuffer[chainLength]; for (int i = 0; i < chainLength; i++) { // find the GL texture ID for this texture IntBuffer textureIdB = BufferUtils.createIntBuffer(1); OVRGL.ovr_GetTextureSwapChainBufferGL(session, chains[eye], i, textureIdB); int textureId = textureIdB.get(); // TODO less hacky way of getting our texture into JMonkeyEngine Image img = new Image(); img.setId(textureId); img.setFormat(Image.Format.RGBA8); img.setWidth(textureW); img.setHeight(textureH); Texture2D tex = new Texture2D(img); FrameBuffer buffer = new FrameBuffer(textureW, textureH, 1); buffer.setDepthBuffer(Image.Format.Depth); buffer.setColorTexture(tex); framebuffers[eye][i] = buffer; } } // UTILITIES // TODO move to helper class /** * Copy the values from a LibOVR matrix into a jMonkeyEngine matrix. * * @param from The matrix to copy from. * @param to The matrix to copy to. * @return The {@code to} argument. */ public static Matrix4f matrixO2J(OVRMatrix4f from, Matrix4f to) { to.loadIdentity(); // For the additional columns (unless I'm badly misunderstanding matricies) for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) { float val = from.M(x + y * 4); // TODO verify this to.set(x, y, val); } } to.transposeLocal(); // jME vs LibOVR coordinate spaces - Yay! return to; } /** * Copy the values from a LibOVR quaternion into a jMonkeyEngine quaternion. * * @param from The quaternion to copy from. * @param to The quaternion to copy to. * @return The {@code to} argument. */ public static Quaternion quatO2J(OVRQuatf from, Quaternion to) { // jME and LibOVR do their coordinate spaces differently for rotations, so flip Y and W (thanks, jMonkeyVR). to.set( from.x(), -from.y(), from.z(), -from.w() ); to.normalizeLocal(); return to; } /** * Copy the values from a LibOVR vector into a jMonkeyEngine vector. * * @param from The vector to copy from. * @param to The vector to copy to. * @return The {@code to} argument. */ public static Vector3f vecO2J(OVRVector3f from, Vector3f to) { // jME and LibOVR disagree on which way X and Z are, too. to.set( -from.x(), from.y(), -from.z() ); return to; } // Getters, intended for VRViewManager. public long getSessionPointer() { return session; } public long getChain(int eye) { return chains[eye]; } public FrameBuffer[] getFramebuffers(int eye) { return framebuffers[eye]; } public PointerBuffer getLayers() { return layers; } public OVRLayerEyeFov getLayer0() { return layer0; } public OVRFovPort getFovPort() { return fovPorts[ovrEye_Left]; // TODO checking the left and right eyes match } public OVRPosef getHeadPose() { return headPose; } public OVRPosef getEyePose(int eye) { return eyeRenderDesc[eye].HmdToEyePose(); } public VREnvironment getEnvironment() { return environment; } } /* vim: set ts=4 softtabstop=0 sw=4 expandtab: */
bsd-3-clause
linyufly/QLearningMP
AutoTest/Code/Machine Problem 1 (Part 1)_gazdzia2_attempt_2014-09-22-20-19-36_QLearningAgent.java
2454
/* Author: Robert Gazdziak (gazdzia2) */ /* Collaborated with: Thomas Lesniak (tlesnia2) */ import java.util.Random; import java.util.ArrayList; public class QLearningAgent implements Agent { public QLearningAgent() { this.rand = new Random(); } public void initialize(int numOfStates, int numOfActions) { this.q = new double[numOfStates][numOfActions]; this.numOfStates = numOfStates; this.numOfActions = numOfActions; } //Returns best possible action (or random action of multiple best actions) private int bestUtility(int state) { double max = q[state][0]; //Array list that holds best actions ArrayList<Integer> bestActions = new ArrayList<Integer>(); bestActions.add(0); for(int i = 1; i<numOfActions; i++) { //if greater than max, clear list and put this action on if(q[state][i] > max) { max = q[state][i]; bestActions.clear(); bestActions.add(i); } //If equal, add on to the list else if(q[state][i] == max) { bestActions.add(i); } } //Choose random action from list of best actions int action = rand.nextInt(bestActions.size()); return bestActions.get(action); } //Returns best possible action or random action depending on epsilon public int chooseAction(int state) { //Random double for epsilon-greedy double greedy = rand.nextDouble(); int action = 0; //if smaller, choose (one of the possible) best option(s) if(greedy < (1.0-epsilon)) action = bestUtility(state); //If equal or larger choose random action else action = rand.nextInt(numOfActions); return action; } //update the policy of oldState+action public void updatePolicy(double reward, int action, int oldState, int newState) { q[oldState][action] = q[oldState][action] + rate*(reward+discount*(q[newState][chooseAction(newState)]-q[oldState][action])); } //Returns best policy for every state public Policy getPolicy() { int[] actions = new int[numOfStates]; //run through all states for(int i = 0; i<numOfStates; i++) { //for each state pick the best action actions[i] = bestUtility(i); } return new Policy(actions); } private static final double discount = 0.9; private static final double rate = 0.1; private static final double epsilon = 0.00; private Random rand; private int numOfStates; private int numOfActions; private double[][] q; }
bsd-3-clause
sergv/jscheme
src/jscheme/JScheme.java
23965
package jscheme; import java.io.PrintWriter; import jsint.Evaluator; import jsint.InputPort; import jsint.Pair; import jsint.Scheme; import jsint.Symbol; import jsint.U; /** JScheme - a simple interface to JScheme. <p> This class provides methods to perform common Scheme operations from java. Each instance of <code>JScheme</code> is an isolated Scheme environment. <p>For example, you can: <ul> <li> Create a new Scheme environment: <pre> JScheme js = new JScheme(); </pre> <li> Initialize an application by loading Scheme expressions from a file: <pre> js.load(new java.io.File("app.init")); </pre> <li> Run the Scheme procedure <tt>(describe)</tt> to describe the current object like this: <pre> js.call("describe", this); </pre> If you need to call a procedure with more than twenty arguments use apply(). <li>Evalute a string as an expression: <pre> String query = "(+ (expt (Math.sin 2.0) 2) (expt (Math.cos 2.0) 2))"; System.out.println(query + " = " + js.eval(query)); </pre> </ul> <p> Unit test: <pre> (import "jscheme.JScheme") (load "elf/util.scm") (define js (JScheme.forCurrentEvaluator)) (assert (equal? (+ 2 3) (.eval js '(+ 2 3)))) (assert (= (+ 2 3) (.eval js "(+ 2 3)"))) (assert (= (+ 2 3) (.call js "+" 2 3))) (assert (= (+ 2 3) (.call js + 2 3))) (assert (= (+ 2 3) (.apply js "+" (JScheme.list 2 3)))) (.load js "(define (f x) (+ x (g x))) (define (g x) (* x 3))") (assert (= (f 3) 12)) </pre> **/ public class JScheme implements java.io.Serializable { private Evaluator evaluator; /** * Creates a new, isolated Scheme environment. */ public JScheme() { evaluator = new Evaluator(); } /** * Creates a Scheme environment that shares an evaluation enironment. * Top-level bindings will be shared. */ public JScheme(Evaluator e) { evaluator = e; } /** * Returns the Scheme environment that is currently executing Scheme. Only * call this from Scheme (or from Java called from Scheme). */ public static JScheme forCurrentEvaluator() { return new JScheme(Scheme.currentEvaluator()); } /** * Returns this Scheme environment's evaluator. */ public Evaluator getEvaluator() { return evaluator; } /** * Enters this instance's evaluator. */ private void enter() { Scheme.pushEvaluator((Evaluator)evaluator); } /** * Exits an evaluator. This must be called for every call to * <code>enter</code>. */ private void exit() { Scheme.popEvaluator(); } /** Does the Symbol named s have a global value? **/ public boolean isDefined(String s) { enter(); try { return Symbol.intern(s).isDefined();} finally { exit(); } } /** Get the value of the global variable named s. **/ public Object getGlobalValue(String s) { enter(); try { return Symbol.intern(s).getGlobalValue(); } finally { exit(); } } /** Set the value of the global variable named s to v. **/ public void setGlobalValue(String s, Object v) { enter(); try { Symbol.intern(s).setGlobalValue(v); } finally { exit(); } } /** Returns the global procedure named s. **/ public SchemeProcedure getGlobalSchemeProcedure(String s) { enter(); try { return U.toProc(getGlobalValue(s)); } finally { exit(); } } /** Load Scheme expressions from a Reader, or String. **/ public Object load(java.io.Reader in) { enter(); try { return Scheme.load(new InputPort(in)); } finally { exit(); } } public Object load(String in) { return load(new java.io.StringReader(in)); } /** Eval or load a string. This is useful for handling command line arguments. If it starts with "(", it is evaled. If it doesn't start with "-", it is loaded. **/ public void evalOrLoad(String it) { if (it.startsWith("(")) { load(new java.io.StringReader(it)); } else if (! it.startsWith("-")) { enter(); try { Scheme.load(it); } finally { exit(); } } } /** Call a procedure with 0 to 20 arguments **/ public Object call(SchemeProcedure p) { enter(); try { return p.apply(list()); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1) { enter(); try { return p.apply(list(a1)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2) { enter(); try { return p.apply(list(a1, a2)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3) { enter(); try { return p.apply(list(a1, a2, a3)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4) { enter(); try { return p.apply(list(a1, a2, a3, a4)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19, Object a20) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)); } finally { exit(); } } /** Apply a procedure to a list of arguments. **/ public Object apply(SchemeProcedure p, SchemePair as) { enter(); try { return p.apply(as); } finally { exit(); } } public Object apply(SchemeProcedure p, Object[] args) { enter(); try { return p.apply(args); } finally { exit(); } } /** Call a procedure named p with from 0 to 20 arguments. **/ public Object call(String p) { enter(); try { return getGlobalSchemeProcedure(p).apply(list()); } finally { exit(); } } public Object call(String p, Object a1) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1)); } finally { exit(); } } public Object call(String p, Object a1, Object a2) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19, Object a20) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)); } finally { exit(); } } /** Apply a procedure named p to a list of arguments. **/ public Object apply(String p, SchemePair as) { enter(); try { return getGlobalSchemeProcedure(p).apply(as); } finally { exit(); } } /** Evaluate the contents of a string as a Scheme expression. **/ public Object eval(String s) { Object it = read(s); return it == InputPort.EOF ? it : eval(it); } /** Evaluate an expression Object **/ public Object eval(Object it) { enter(); try { return Scheme.evalToplevel(it, jsint.Scheme.getInteractionEnvironment()); } finally { exit(); } } /** Read an expression from a String. **/ public Object read(String s) { enter(); try { return (new InputPort(new java.io.StringReader(s))).read(); } finally { exit(); } } /** Lists of length 0 to 20. **/ public static SchemePair list() { return Pair.EMPTY; } public static SchemePair list(Object a0) { return new Pair(a0, list()); } public static SchemePair list(Object a0, Object a1) { return new Pair(a0, list(a1)); } public static SchemePair list(Object a0, Object a1, Object a2) { return new Pair(a0, list(a1, a2)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3) { return new Pair(a0, list(a1, a2, a3)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4) { return new Pair(a0, list(a1, a2, a3, a4)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return new Pair(a0, list(a1, a2, a3, a4, a5)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19, Object a20) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)); } public void write(Object x, PrintWriter port, boolean quoted) { enter(); try { U.write(x, port, quoted); } finally { exit(); } } public void write(Object x, PrintWriter port) { enter(); try { U.write(x, port, true); } finally { exit(); } } public void display(Object x, PrintWriter port) { enter(); try { U.write(x, port, false); } finally { exit(); } } public void readEvalPrintLoop() { enter(); try { Scheme.readEvalWriteLoop(">"); } finally { exit(); } } /** Convert from an Object to a primitive type. **/ public static boolean booleanValue(Object o) { return o != Boolean.FALSE; } public static byte byteValue(Object o) { return ((Number) o).byteValue(); } public static char charValue(Object o) { return (o instanceof Number) ? ((char)((Number) o).shortValue()) : ((Character) o).charValue(); } public static short shortValue(Object o) { return ((Number) o).shortValue(); } public static int intValue(Object o) { return ((Number) o).intValue(); } public static long longValue(Object o) { return ((Number) o).longValue(); } public static float floatValue(Object o) { return ((Number) o).floatValue(); } public static double doubleValue(Object o) { return ((Number) o).doubleValue(); } /** Convert from primitive type to Object. **/ public static Boolean toObject(boolean x) { return x ? Boolean.TRUE : Boolean.FALSE; } public static Object toObject(byte x) { return new Byte(x); } public static Object toObject(char x) { return new Character(x); } public static Object toObject(short x) { return new Short(x); } public static Object toObject(int x) { return U.toNum(x); } public static Object toObject(long x) { return new Long(x); } public static Object toObject(float x) { return new Float(x); } public static Object toObject(double x) { return new Double(x); } public static Object toObject(Object x) { return x; } // Completeness. }
bsd-3-clause
yuripourre/etyllica-physics
src/main/java/org/dyn4j/collision/broadphase/BroadphaseDetector.java
7243
/* * Copyright (c) 2010-2013 William Bittle http://www.dyn4j.org/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of dyn4j nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dyn4j.collision.broadphase; import java.util.List; import org.dyn4j.collision.Collidable; import org.dyn4j.collision.narrowphase.NarrowphaseDetector; import org.dyn4j.geometry.AABB; import org.dyn4j.geometry.Convex; import org.dyn4j.geometry.Ray; import org.dyn4j.geometry.Shape; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Vector2; /** * Represents a broad-phase collision detection algorithm. * <p> * A {@link BroadphaseDetector} should quickly determine the pairs of {@link Collidable}s that * possibly intersect. These algorithms are used to filter out collision pairs in the interest * of sending less pairs to the {@link NarrowphaseDetector}. * <p> * {@link BroadphaseDetector}s require that the collidables are updated via the {@link #update(Collidable)} * method when the collidables move, rotate, or are changed in anyway that changes their AABB. * <p> * {@link BroadphaseDetector}s use a expansion value to expand the AABB of a collidable. The {@link #getAABB(Collidable)} * returns the expanded {@link AABB}. This expansion is used to reduce the number of updates to the * broadphase. See the {@link #setAABBExpansion(double)} for more details on this value. * <p> * The {@link #detect()}, {@link #detect(AABB)}, {@link #raycast(Ray, double)} methods use the current state of * all the collidables that have been added. Make sure that all changes have been reflected to the broadphase * using the {@link #update(Collidable)} method before calling these methods. * <p> * The {@link #detect(Collidable, Collidable)} and {@link #detect(Convex, Transform, Convex, Transform)} methods do not * use the current state of the broadphase. * @author William Bittle * @version 3.1.0 * @since 1.0.0 * @param <E> the {@link Collidable} type */ public interface BroadphaseDetector<E extends Collidable> { /** The default {@link AABB} expansion value */ public static final double DEFAULT_AABB_EXPANSION = 0.2; /** * Adds a new {@link Collidable} to the broadphase. * @param collidable the {@link Collidable} * @since 3.0.0 */ public void add(E collidable); /** * Removes the given {@link Collidable} from the broadphase. * @param collidable the {@link Collidable} * @since 3.0.0 */ public void remove(E collidable); /** * Updates the given {@link Collidable}. * <p> * Used when the collidable has moved or rotated. * @param collidable the {@link Collidable} * @since 3.0.0 */ public void update(E collidable); /** * Clears all {@link Collidable}s from the broadphase. * @since 3.0.0 */ public void clear(); /** * Returns the expanded {@link AABB} for a given {@link Collidable}. * <p> * Returns null if the collidable has not been added to this * broadphase detector. * @param collidable the {@link Collidable} * @return {@link AABB} the {@link AABB} for the given {@link Collidable} */ public AABB getAABB(E collidable); /** * Performs collision detection on all {@link Collidable}s that have been added to * this {@link BroadphaseDetector}. * @return List&lt;{@link BroadphasePair}&gt; * @since 3.0.0 */ public List<BroadphasePair<E>> detect(); /** * Performs a broadphase collision test using the given {@link AABB}. * @param aabb the {@link AABB} to test * @return List list of all {@link AABB}s that overlap with the given {@link AABB} * @since 3.0.0 */ public List<E> detect(AABB aabb); /** * Performs a preliminary raycast over all the collidables in the broadphase to improve performance of the * narrowphase raycasts. * @param ray the {@link Ray} * @param length the length of the ray; 0.0 for infinite length * @return List the filtered list of possible collidables * @since 3.0.0 */ public abstract List<E> raycast(Ray ray, double length); /** * Performs a broadphase collision test on the given {@link Collidable}s and * returns true if they could possibly intersect. * @param a the first {@link Collidable} * @param b the second {@link Collidable} * @return boolean */ public abstract boolean detect(E a, E b); /** * Performs a broadphase collision test on the given {@link Convex} {@link Shape}s and * returns true if they could possibly intersect. * <p> * This method does not use the expansion value. * @param convex1 the first {@link Convex} {@link Shape} * @param transform1 the first {@link Convex} {@link Shape}'s {@link Transform} * @param convex2 the second {@link Convex} {@link Shape} * @param transform2 the second {@link Convex} {@link Shape}'s {@link Transform} * @return boolean */ public abstract boolean detect(Convex convex1, Transform transform1, Convex convex2, Transform transform2); /** * Returns the {@link AABB} expansion value used to improve performance of broadphase updates. * @return double */ public abstract double getAABBExpansion(); /** * Sets the {@link AABB} expansion value used to improve performance of broadphase updates. * <p> * Increasing this value will cause less updates to the broadphase but will cause more pairs * to be sent to the narrowphase. * @param expansion the expansion */ public abstract void setAABBExpansion(double expansion); /** * Translates all {@link Collidable} proxies to match the given coordinate shift. * @param shift the amount to shift along the x and y axes * @since 3.1.0 */ public abstract void shiftCoordinates(Vector2 shift); }
bsd-3-clause
groupon/monsoon
intf/src/main/java/com/groupon/lex/metrics/SynchronousGroupGenerator.java
853
package com.groupon.lex.metrics; import java.util.Collection; import static java.util.Collections.singleton; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; public abstract class SynchronousGroupGenerator implements GroupGenerator { protected abstract Collection<? extends MetricGroup> getGroups(CompletableFuture<TimeoutObject> timeout); @Override public final Collection<CompletableFuture<? extends Collection<? extends MetricGroup>>> getGroups(Executor threadpool, CompletableFuture<TimeoutObject> timeout) throws Exception { CompletableFuture<Collection<? extends MetricGroup>> result = CompletableFuture.supplyAsync(() -> getGroups(timeout), threadpool); timeout.thenAccept(timeoutObject -> { result.cancel(true); }); return singleton(result); } }
bsd-3-clause
lottie-c/spl_tests_new
src/java/cz/cuni/mff/spl/utils/ssh/SshReconnectingSession.java
7212
/* * Copyright (c) 2012, František Haas, Martin Lacina, Jaroslav Kotrč, Jiří Daniel * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package cz.cuni.mff.spl.utils.ssh; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import cz.cuni.mff.spl.utils.logging.SplLog; import cz.cuni.mff.spl.utils.logging.SplLogger; import cz.cuni.mff.spl.utils.ssh.exception.SshException; /** * <p> * This class provides auto reconnecting session for JSch library. * * @author Frantisek Haas * */ public class SshReconnectingSession implements ISshSession { private static final SplLog logger = SplLogger.getLogger(SshReconnectingSession.class); private static final int KEEP_ALIVE_INTERVAL_MS = 10000; private final SshDetails details; /** If session is initialized connecting and auto reconnecting is enabled. */ private boolean initialized = false; private JSch jsch = null; private Session session = null; private ChannelSftp sftpChannel = null; /** To log reconnecting only once per lost connection. */ private boolean logReconnecting = true; /** * <p> * Creates the session. Does not open any connections. To start the session * working call {@link #connect}. Even if it fails further calls to * {@link #connect()}, {@link #getSession()} and {@link #getSftpChannel()} * will try to open the connection. The {@link #close()} closes the * connection. * * @param details */ public SshReconnectingSession(SshDetails details) { this.details = details; } /** * @return * Returns connection details. */ public SshDetails getDetails() { return details; } /** * <p> * Initializes the session and tries to open the connection. * * @throws SshException * <p> * If connection fails. But later calls to {@link #connect()}, * {@link #getSession()} and {@link #getSftpChannel()} will try * to open the connection again. */ @Override public void connect() throws SshException { if (initialized && logReconnecting) { logger.info("Connection lost ... reconnecting."); } if (!initialized) { jsch = SshUtils.createJsch(details); initialized = true; } try { if (!isConnected()) { innerClose(); try { session = SshUtils.createSession(jsch, details); session.setServerAliveInterval(KEEP_ALIVE_INTERVAL_MS); sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.connect(); logger.trace("Successfully connected session."); } catch (SshException e) { innerClose(); logger.trace("Failed to connect session."); throw e; } catch (JSchException e) { innerClose(); logger.trace("Failed to connect session."); throw new SshException(e); } } } finally { logReconnecting = isConnected(); } } /** * <p> * Initializes the session and tries to open the connection. * * @return * <p> * True if connected. False If connection fails. But later calls to * {@link #connect()}, {@link #getSession()} and * {@link #getSftpChannel()} will try to open the connection again. * */ @Override public boolean silentConnect() { try { connect(); return true; } catch (SshException e) { return false; } } /** * Checks if connection is established. Tries to send keep alive message. * * @return */ @Override public boolean isConnected() { if (session == null || !session.isConnected() || sftpChannel == null || !sftpChannel.isConnected()) { return false; } else { return true; } } /** * <p> * If there's a valid connected session it's returned. If there's not the * function tries to connect one and return it. * * @return * Session if it's valid and connected. Otherwise {@code null}. */ @Override public Session getSession() { if (!initialized) { return null; } if (!isConnected()) { silentConnect(); } return session; } /** * <p> * If there's a valid connected session it's returned. If there's not the * function tries to connect one and return it. * * @return * Session if it's valid and connected. Otherwise {@code null}. */ @Override public ChannelSftp getSftpChannel() { if (!initialized) { return null; } if (!isConnected()) { silentConnect(); } return sftpChannel; } public void innerClose() { if (sftpChannel != null) { sftpChannel.disconnect(); sftpChannel = null; } if (session != null) { session.disconnect(); session = null; } } @Override public void close() { initialized = false; innerClose(); } }
bsd-3-clause
pparkkin/eta
rts/src/eta/runtime/thunk/ApV.java
347
package eta.runtime.thunk; import eta.runtime.stg.Closure; import eta.runtime.stg.StgContext; public class ApV extends UpdatableThunk { public Closure p; public ApV(final Closure p) { super(); this.p = p; } @Override public Closure thunkEnter(StgContext context) { return p.applyV(context); } }
bsd-3-clause
ndexbio/ndex-rest
src/main/java/org/ndexbio/task/NdexTaskProcessor.java
2543
/** * Copyright (c) 2013, 2016, The Regents of the University of California, The Cytoscape Consortium * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.ndexbio.task; import java.io.IOException; import java.sql.SQLException; import java.util.UUID; import org.ndexbio.common.models.dao.postgresql.TaskDAO; import org.ndexbio.model.exceptions.NdexException; import org.ndexbio.model.object.Status; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; public abstract class NdexTaskProcessor implements Runnable { protected boolean shutdown; public NdexTaskProcessor () { shutdown = false; } public void shutdown() { shutdown = true; } protected static void saveTaskStatus (UUID taskID, Status status, String message, String stackTrace) throws NdexException, SQLException, JsonParseException, JsonMappingException, IOException { try (TaskDAO dao = new TaskDAO ()) { dao.updateTaskStatus(taskID, status, message,stackTrace); dao.commit(); } } }
bsd-3-clause
groupon/monsoon
exporter/src/main/java/com/groupon/lex/metrics/json/JsonTags.java
903
package com.groupon.lex.metrics.json; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.groupon.lex.metrics.Tags; import static com.groupon.lex.metrics.json.Json.extractMetricValue; import java.util.HashMap; import java.util.function.Function; import java.util.stream.Collectors; class JsonTags extends HashMap<String, Object> { private static final Function<Tags, JsonTags> TAGS_CACHE = CacheBuilder.newBuilder() .softValues() .build(CacheLoader.from((Tags in) -> new JsonTags(in)))::getUnchecked; public JsonTags() {} private JsonTags(Tags tags) { super(tags.stream() .collect(Collectors.toMap(tag_entry -> tag_entry.getKey(), tag_entry -> extractMetricValue(tag_entry.getValue())))); } public static JsonTags valueOf(Tags tags) { return TAGS_CACHE.apply(tags); } }
bsd-3-clause
NCIP/c3pr
codebase/projects/core/test/src/java/edu/duke/cabig/c3pr/MayoSpecificRegistryUseCaseTest.java
44705
/******************************************************************************* * Copyright Duke Comprehensive Cancer Center and SemanticBits * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/c3pr/LICENSE.txt for details. ******************************************************************************/ package edu.duke.cabig.c3pr; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import edu.duke.cabig.c3pr.constants.ConsentingMethod; import edu.duke.cabig.c3pr.constants.CoordinatingCenterStudyStatus; import edu.duke.cabig.c3pr.constants.OrganizationIdentifierTypeEnum; import edu.duke.cabig.c3pr.constants.StudyDataEntryStatus; import edu.duke.cabig.c3pr.dao.HealthcareSiteDao; import edu.duke.cabig.c3pr.dao.ParticipantDao; import edu.duke.cabig.c3pr.dao.ReasonDao; import edu.duke.cabig.c3pr.dao.RegistryStatusDao; import edu.duke.cabig.c3pr.dao.StudyDao; import edu.duke.cabig.c3pr.dao.StudySubjectDao; import edu.duke.cabig.c3pr.domain.Address; import edu.duke.cabig.c3pr.domain.Consent; import edu.duke.cabig.c3pr.domain.ConsentQuestion; import edu.duke.cabig.c3pr.domain.HealthcareSite; import edu.duke.cabig.c3pr.domain.LocalHealthcareSite; import edu.duke.cabig.c3pr.domain.LocalStudy; import edu.duke.cabig.c3pr.domain.OrganizationAssignedIdentifier; import edu.duke.cabig.c3pr.domain.Participant; import edu.duke.cabig.c3pr.domain.PermissibleStudySubjectRegistryStatus; import edu.duke.cabig.c3pr.domain.RegistryStatus; import edu.duke.cabig.c3pr.domain.RegistryStatusReason; import edu.duke.cabig.c3pr.domain.Study; import edu.duke.cabig.c3pr.domain.StudyCoordinatingCenter; import edu.duke.cabig.c3pr.domain.StudySite; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.domain.StudySubjectConsentVersion; import edu.duke.cabig.c3pr.utils.DaoTestCase; /** * JUnit Tests for ParticipantDao * * @author Priyatam * @testType unit */ public class MayoSpecificRegistryUseCaseTest extends DaoTestCase { /** The dao. */ private StudyDao studyDao; /** The healthcare sitedao. */ private HealthcareSiteDao healthcareSitedao; private RegistryStatusDao registryStatusDao; private ReasonDao reasonDao; private ParticipantDao participantDao; private StudySubjectDao studySubjectDao; private StudySubject studySubject; private Study study; private Consent consent1; private Consent consent2; private RegistryStatusReason registryStatusReason1; private RegistryStatusReason registryStatusReason2; private RegistryStatusReason registryStatusReason3; private RegistryStatusReason registryStatusReason4; /* (non-Javadoc) * @see edu.duke.cabig.c3pr.utils.DaoTestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); studyDao = (StudyDao) getApplicationContext().getBean("studyDao"); healthcareSitedao = (HealthcareSiteDao) getApplicationContext() .getBean("healthcareSiteDao"); registryStatusDao = (RegistryStatusDao) getApplicationContext() .getBean("registryStatusDao"); reasonDao = (ReasonDao) getApplicationContext() .getBean("reasonDao"); participantDao = (ParticipantDao) getApplicationContext().getBean("participantDao"); studySubjectDao = (StudySubjectDao) getApplicationContext().getBean("studySubjectDao"); } private Study createStudyForRegistry() { study = new LocalStudy(); study.setPrecisText("New study"); study.setShortTitleText("ShortTitleText"); study.setLongTitleText("LongTitleText"); study.setPhaseCode("PhaseCode"); study.setCoordinatingCenterStudyStatus(CoordinatingCenterStudyStatus.OPEN); study.setDataEntryStatus(StudyDataEntryStatus.COMPLETE); study.setTargetAccrualNumber(150); study.setType("Type"); study.setMultiInstitutionIndicator(Boolean.TRUE); study.setOriginalIndicator(true); //add consents consent1 = study.getStudyVersion().getConsents().get(0); consent1.setConsentingMethods(Arrays.asList(new ConsentingMethod[]{ConsentingMethod.VERBAL, ConsentingMethod.WRITTEN})); consent1.setName("general1"); consent1.setVersion(1); consent1.addQuestion(new ConsentQuestion("code1","question1")); consent1.addQuestion(new ConsentQuestion("code2","question2")); consent2 = study.getStudyVersion().getConsents().get(1); consent2.setConsentingMethods(Arrays.asList(new ConsentingMethod[]{ConsentingMethod.VERBAL, ConsentingMethod.WRITTEN})); consent2.setName("general2"); consent2.setVersion(1); //add mayo as cocenter and study site HealthcareSite healthcaresite = new LocalHealthcareSite(); Address address = new Address(); address.setCity("Reston"); address.setCountryCode("USA"); address.setPostalCode("20191"); address.setStateCode("VA"); address.setStreetAddress("12359 Sunrise Valley Dr"); healthcaresite.setAddress(address); healthcaresite.setName("MAYO"); healthcaresite.setDescriptionText("MAYO"); healthcaresite.setCtepCode("MN026"); healthcareSitedao.save(healthcaresite); // Cocenter StudyCoordinatingCenter studyCoCenter = new StudyCoordinatingCenter(); study.addStudyOrganization(studyCoCenter); studyCoCenter.setHealthcareSite(healthcaresite); // Study Site StudySite studySite = new StudySite(); study.addStudySite(studySite); studySite.setHealthcareSite(healthcaresite); studySite.setIrbApprovalDate(new Date()); // Identifiers OrganizationAssignedIdentifier id = new OrganizationAssignedIdentifier(); id.setPrimaryIndicator(true); id.setHealthcareSite(healthcaresite); id.setValue("MAYO-1"); id.setType(OrganizationIdentifierTypeEnum.COORDINATING_CENTER_IDENTIFIER); study.getIdentifiers().add(id); study.setCoordinatingCenterStudyStatus(CoordinatingCenterStudyStatus.OPEN); study.setDataEntryStatus(StudyDataEntryStatus.COMPLETE); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus1 = study.getPermissibleStudySubjectRegistryStatuses().get(0); permissibleStudySubjectRegistryStatus1.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Pre-Enrolled")); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus2 = study.getPermissibleStudySubjectRegistryStatuses().get(1); permissibleStudySubjectRegistryStatus2.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Enrolled")); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus3 = study.getPermissibleStudySubjectRegistryStatuses().get(2); permissibleStudySubjectRegistryStatus3.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Screen Failed")); registryStatusReason1 = new RegistryStatusReason("lab1","lab out of range1", reasonDao.getReasonByCode("FAILED INCLUSION"), false); registryStatusReason2 = new RegistryStatusReason("lab2","lab out of range2", reasonDao.getReasonByCode("FAILED EXCLUSION"), false); permissibleStudySubjectRegistryStatus3.setSecondaryReasons(Arrays.asList(new RegistryStatusReason[]{registryStatusReason1, registryStatusReason2})); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus4 = study.getPermissibleStudySubjectRegistryStatuses().get(3); permissibleStudySubjectRegistryStatus4.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Accrued")); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus5 = study.getPermissibleStudySubjectRegistryStatuses().get(4); permissibleStudySubjectRegistryStatus5.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Withdrawn")); registryStatusReason3 = new RegistryStatusReason("distance","distance", reasonDao.getReasonByCode("UNWILLING"), false); registryStatusReason4 = new RegistryStatusReason("schedule","schedule", reasonDao.getReasonByCode("UNWILLING"), false); permissibleStudySubjectRegistryStatus5.setSecondaryReasons(Arrays.asList(new RegistryStatusReason[]{registryStatusReason3, registryStatusReason4})); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus6 = study.getPermissibleStudySubjectRegistryStatuses().get(5); permissibleStudySubjectRegistryStatus6.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Active Intervention")); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus7 = study.getPermissibleStudySubjectRegistryStatuses().get(6); permissibleStudySubjectRegistryStatus7.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Long-Term Followup")); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus8 = study.getPermissibleStudySubjectRegistryStatuses().get(7); permissibleStudySubjectRegistryStatus8.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Observation")); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus9 = study.getPermissibleStudySubjectRegistryStatuses().get(8); permissibleStudySubjectRegistryStatus9.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Declined Consent")); PermissibleStudySubjectRegistryStatus permissibleStudySubjectRegistryStatus10 = study.getPermissibleStudySubjectRegistryStatuses().get(9); permissibleStudySubjectRegistryStatus10.setRegistryStatus(registryStatusDao.getRegistryStatusByCode("Completed")); studyDao.save(study); return study; } private void createStudySubject(){ studySubject = new StudySubject(); Participant participant = participantDao.getById(1001); studySubject.setStudySubjectDemographics(participant.createStudySubjectDemographics()); Study study = createStudyForRegistry(); studySubject.setStudySite(study.getStudySites().get(0)); } public void testScreenFailed(){ createStudySubject(); // Pre-Enrolled //add consent delivery date StudySubjectConsentVersion studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(0); studySubjectConsentVersion.setConsent(consent1); studySubjectConsentVersion.setConsentDeliveryDate(new GregorianCalendar(2006, 02,20).getTime()); studySubjectConsentVersion.setConsentPresenter("me"); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Pre-Enrolled", new GregorianCalendar(2006, 01, 31).getTime(), "some comment", null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("some comment", studySubject.getStudySubjectRegistryStatus().getCommentText()); assertEquals(1, studySubject.getLatestConsents().size()); assertEquals("general1", studySubject.getLatestConsents().get(0).getConsent().getName()); assertEquals(new GregorianCalendar(2006, 02,20).getTime(), studySubject.getLatestConsents().get(0).getConsentDeliveryDate()); assertEquals("me", studySubject.getLatestConsents().get(0).getConsentPresenter()); assertEquals(new GregorianCalendar(2006, 01,31).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); //Enrolled interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); //add consent signed studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(0); studySubjectConsentVersion.setInformedConsentSignedDate(new GregorianCalendar(2006, 03,20).getTime()); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Enrolled", new GregorianCalendar(2006, 03,20).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 03,20).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(2, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 01,31).getTime(), studySubject.getStudySubjectRegistryStatusHistory().get(1).getEffectiveDate()); assertEquals(new GregorianCalendar(2006, 03,20).getTime(), studySubject.getLatestConsents().get(0).getInformedConsentSignedDate()); //Screen Failed interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); //build screen failure reasons List<RegistryStatusReason> reasons = new ArrayList<RegistryStatusReason>(); RegistryStatus registryStatus = registryStatusDao.getRegistryStatusByCode("Screen Failed"); reasons.add(registryStatus.getPrimaryReason("FAILED INCLUSION")); reasons.add(registryStatus.getPrimaryReason("FAILED EXCLUSION")); reasons.add(registryStatusReason1); reasons.add(registryStatusReason2); studySubject.updateRegistryStatus("Screen Failed", new GregorianCalendar(2006, 05,12).getTime(), null, reasons); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Screen Failed", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 05,12).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(3, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(4, studySubject.getStudySubjectRegistryStatus().getReasons().size()); } public void testCompleted(){ createStudySubject(); // Pre-Enrolled //add consent delivery date StudySubjectConsentVersion studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(0); studySubjectConsentVersion.setConsent(consent1); studySubjectConsentVersion.setConsentDeliveryDate(new GregorianCalendar(2006, 02,20).getTime()); studySubjectConsentVersion.setConsentPresenter("me"); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Pre-Enrolled", new GregorianCalendar(2006, 01, 31).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(1, studySubject.getLatestConsents().size()); assertEquals("general1", studySubject.getLatestConsents().get(0).getConsent().getName()); assertEquals(new GregorianCalendar(2006, 02,20).getTime(), studySubject.getLatestConsents().get(0).getConsentDeliveryDate()); assertEquals("me", studySubject.getLatestConsents().get(0).getConsentPresenter()); assertEquals(new GregorianCalendar(2006, 01,31).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); //Enrolled interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); //add consent signed studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(0); studySubjectConsentVersion.setInformedConsentSignedDate(new GregorianCalendar(2006, 03,20).getTime()); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Enrolled", new GregorianCalendar(2006, 03,20).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 03,20).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(2, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 01,31).getTime(), studySubject.getStudySubjectRegistryStatusHistory().get(1).getEffectiveDate()); assertEquals(new GregorianCalendar(2006, 03,20).getTime(), studySubject.getLatestConsents().get(0).getInformedConsentSignedDate()); //Accrued interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Accrued", new GregorianCalendar(2006, 04,26).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 04,26).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(3, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); // Active Intervention //add new consent delivery date studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(1); studySubjectConsentVersion.setConsent(consent2); studySubjectConsentVersion.setConsentDeliveryDate(new GregorianCalendar(2006, 05,01).getTime()); studySubjectConsentVersion.setConsentPresenter("me"); studySubjectConsentVersion.setInformedConsentSignedDate(new GregorianCalendar(2006, 05,10).getTime()); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Active Intervention", new GregorianCalendar(2006, 05,10).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Active Intervention", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 05,10).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(4, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(2, studySubject.getLatestConsents().size()); //Observation interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Observation", new GregorianCalendar(2007, 01,05).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Observation", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2007, 01,05).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(5, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Active Intervention", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(4).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); //Long-Term Followup interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Long-Term Followup", new GregorianCalendar(2009, 03,13).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Long-Term Followup", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2009, 03,13).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(6, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Observation", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Active Intervention", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(4).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(5).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); //Completed interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); //build screen failure reasons List<RegistryStatusReason> reasons = new ArrayList<RegistryStatusReason>(); RegistryStatus registryStatus = registryStatusDao.getRegistryStatusByCode("Completed"); reasons.add(registryStatus.getPrimaryReason("DIED")); studySubject.updateRegistryStatus("Completed", new GregorianCalendar(2010, 07,22).getTime(), null, reasons); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Completed", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2010, 07,22).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(7, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Long-Term Followup", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Observation", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Active Intervention", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(4).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(5).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(6).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(1, studySubject.getStudySubjectRegistryStatus().getReasons().size()); } public void testWithdrawn(){ createStudySubject(); // Pre-Enrolled //add consent delivery date StudySubjectConsentVersion studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(0); studySubjectConsentVersion.setConsent(consent1); studySubjectConsentVersion.setConsentDeliveryDate(new GregorianCalendar(2006, 02,20).getTime()); studySubjectConsentVersion.setConsentPresenter("me"); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Pre-Enrolled", new GregorianCalendar(2006, 01, 31).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(1, studySubject.getLatestConsents().size()); assertEquals("general1", studySubject.getLatestConsents().get(0).getConsent().getName()); assertEquals(new GregorianCalendar(2006, 02,20).getTime(), studySubject.getLatestConsents().get(0).getConsentDeliveryDate()); assertEquals("me", studySubject.getLatestConsents().get(0).getConsentPresenter()); assertEquals(new GregorianCalendar(2006, 01,31).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); //Enrolled interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); //add consent signed studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(0); studySubjectConsentVersion.setInformedConsentSignedDate(new GregorianCalendar(2006, 03,20).getTime()); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Enrolled", new GregorianCalendar(2006, 03,20).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 03,20).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(2, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 01,31).getTime(), studySubject.getStudySubjectRegistryStatusHistory().get(1).getEffectiveDate()); assertEquals(new GregorianCalendar(2006, 03,20).getTime(), studySubject.getLatestConsents().get(0).getInformedConsentSignedDate()); //Accrued interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Accrued", new GregorianCalendar(2006, 04,26).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 04,26).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(3, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); // Active Intervention //add new consent delivery date studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(1); studySubjectConsentVersion.setConsent(consent2); studySubjectConsentVersion.setConsentDeliveryDate(new GregorianCalendar(2006, 05,01).getTime()); studySubjectConsentVersion.setConsentPresenter("me"); studySubjectConsentVersion.setInformedConsentSignedDate(new GregorianCalendar(2006, 05,10).getTime()); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Active Intervention", new GregorianCalendar(2006, 05,10).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Active Intervention", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 05,10).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(4, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(2, studySubject.getLatestConsents().size()); //Observation interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Observation", new GregorianCalendar(2007, 01,05).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Observation", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2007, 01,05).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(5, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Active Intervention", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(4).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); //Long-Term Followup interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Long-Term Followup", new GregorianCalendar(2009, 03,13).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Long-Term Followup", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2009, 03,13).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(6, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Observation", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Active Intervention", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(4).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(5).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); //Withdrawn interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); //build screen failure reasons List<RegistryStatusReason> reasons = new ArrayList<RegistryStatusReason>(); RegistryStatus registryStatus = registryStatusDao.getRegistryStatusByCode("Withdrawn"); reasons.add(registryStatus.getPrimaryReason("UNWILLING")); reasons.add(registryStatusReason3); reasons.add(registryStatusReason4); studySubject.updateRegistryStatus("Withdrawn", new GregorianCalendar(2010, 07,22).getTime(), null, reasons); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Withdrawn", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2010, 07,22).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(7, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Long-Term Followup", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Observation", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Active Intervention", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(4).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(5).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(6).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(3, studySubject.getStudySubjectRegistryStatus().getReasons().size()); } public void testDeclinedConsent(){ createStudySubject(); // Pre-Enrolled //add consent delivery date StudySubjectConsentVersion studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(0); studySubjectConsentVersion.setConsent(consent1); studySubjectConsentVersion.setConsentDeliveryDate(new GregorianCalendar(2006, 02,20).getTime()); studySubjectConsentVersion.setConsentPresenter("me"); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Pre-Enrolled", new GregorianCalendar(2006, 01, 31).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(1, studySubject.getLatestConsents().size()); assertEquals("general1", studySubject.getLatestConsents().get(0).getConsent().getName()); assertEquals(new GregorianCalendar(2006, 02,20).getTime(), studySubject.getLatestConsents().get(0).getConsentDeliveryDate()); assertEquals("me", studySubject.getLatestConsents().get(0).getConsentPresenter()); assertEquals(new GregorianCalendar(2006, 01,31).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); //Enrolled interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); //add consent signed studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(0); studySubjectConsentVersion.setInformedConsentSignedDate(new GregorianCalendar(2006, 03,20).getTime()); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Enrolled", new GregorianCalendar(2006, 03,20).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 03,20).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(2, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 01,31).getTime(), studySubject.getStudySubjectRegistryStatusHistory().get(1).getEffectiveDate()); assertEquals(new GregorianCalendar(2006, 03,20).getTime(), studySubject.getLatestConsents().get(0).getInformedConsentSignedDate()); //Accrued interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Accrued", new GregorianCalendar(2006, 04,26).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 04,26).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(3, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); // Declined Consent //add new consent delivery date studySubjectConsentVersion = studySubject.getStudySubjectStudyVersion().getStudySubjectConsentVersions().get(1); studySubjectConsentVersion.setConsent(consent2); studySubjectConsentVersion.setConsentDeliveryDate(new GregorianCalendar(2006, 05,01).getTime()); studySubjectConsentVersion.setConsentPresenter("me"); studySubjectDao.save(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); studySubject.updateRegistryStatus("Declined Consent", new GregorianCalendar(2006, 05,10).getTime(), null, null); studySubject = studySubjectDao.merge(studySubject); interruptSession(); studySubject = studySubjectDao.getById(studySubject.getId()); assertEquals("Declined Consent", studySubject.getStudySubjectRegistryStatus().getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(new GregorianCalendar(2006, 05,10).getTime(), studySubject.getStudySubjectRegistryStatus().getEffectiveDate()); assertEquals(4, studySubject.getStudySubjectRegistryStatusHistory().size()); assertEquals("Accrued", studySubject.getStudySubjectRegistryStatusHistory().get(1).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(2).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals("Pre-Enrolled", studySubject.getStudySubjectRegistryStatusHistory().get(3).getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode()); assertEquals(2, studySubject.getLatestConsents().size()); } }
bsd-3-clause
NUBIC/psc-mirror
domain/src/test/java/edu/northwestern/bioinformatics/studycalendar/domain/tools/hibernate/ScheduledActivityStateTypeTest.java
6590
package edu.northwestern.bioinformatics.studycalendar.domain.tools.hibernate; import edu.northwestern.bioinformatics.studycalendar.domain.DomainTestCase; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivityMode; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivityState; import gov.nih.nci.cabig.ctms.lang.DateTools; import java.sql.*; import java.util.Calendar; import java.util.Date; import static edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivityMode.*; import static org.easymock.classextension.EasyMock.expect; /** * @author Rhett Sutphin */ public class ScheduledActivityStateTypeTest extends DomainTestCase { private static final Date DATE = DateTools.createDate(2003, Calendar.APRIL, 6); private static final String REASON = "reason"; private static final String[] COLUMN_NAMES = new String[] { "current_state_mode_id", "current_state_reason", "current_state_date", "current_state_with_time" }; private static final Boolean WITH_TIME = false; private ScheduledActivityStateType type = new ScheduledActivityStateType(); private ResultSet rs; private PreparedStatement st; @Override protected void setUp() throws Exception { super.setUp(); rs = registerMockFor(ResultSet.class); st = registerMockFor(PreparedStatement.class); } public void testDeepCopy() throws Exception { ScheduledActivityState state = ScheduledActivityMode.SCHEDULED. createStateInstance(DateTools.createDate(2004, Calendar.JANUARY, 4), "Because"); Object copy = type.deepCopy(state); assertNotSame(state, copy); assertTrue(copy instanceof ScheduledActivityState); ScheduledActivityState copyState = (ScheduledActivityState) copy; assertEquals(state.getMode(), copyState.getMode()); assertEquals(state.getDate(), copyState.getDate()); assertEquals(state.getReason(), copyState.getReason()); assertEquals(state.getWithTime(), copyState.getWithTime()); } public void testNullSafeGetScheduled() throws Exception { expectGetStateFields(SCHEDULED, true); ScheduledActivityState state = doNullSafeGet(); assertScheduledActivityState(SCHEDULED, REASON, DATE, state, WITH_TIME); } public void testNullSafeGetOccurred() throws Exception { expectGetStateFields(OCCURRED, true); ScheduledActivityState state = doNullSafeGet(); assertScheduledActivityState(OCCURRED, REASON, DATE, state, WITH_TIME); } public void testNullSafeGetCanceled() throws Exception { expectGetStateFields(CANCELED, true); ScheduledActivityState state = doNullSafeGet(); assertScheduledActivityState(CANCELED, REASON, DATE, state, WITH_TIME); } public void testNullSafeGetConditional() throws Exception { expectGetStateFields(CONDITIONAL, true); ScheduledActivityState state = doNullSafeGet(); assertScheduledActivityState(CONDITIONAL, REASON, DATE, state, WITH_TIME); } public void testNullSafeGetNotAvailable() throws Exception { expectGetStateFields(NOT_APPLICABLE, true); ScheduledActivityState state = doNullSafeGet(); assertScheduledActivityState(NOT_APPLICABLE, REASON, DATE, state, WITH_TIME); } // TODO (requires changes to ControlledVocabularyObjectType) // public void testNullSafeGetNull() throws Exception { // expect(rs.getInt(COLUMN_NAMES[0])).andReturn(null); // assertNull(doNullSafeGet()); // } private ScheduledActivityState doNullSafeGet() throws SQLException { replayMocks(); ScheduledActivityState state = (ScheduledActivityState) type.nullSafeGet(rs, COLUMN_NAMES, null, null); verifyMocks(); return state; } private void expectGetStateFields(ScheduledActivityMode expectedMode, boolean expectDate) throws SQLException { if (expectDate) expect(rs.getTimestamp(COLUMN_NAMES[2])).andReturn(new Timestamp(DATE.getTime())); expect(rs.getString(COLUMN_NAMES[1])).andReturn(REASON); expect(rs.getInt(COLUMN_NAMES[0])).andReturn(expectedMode.getId()); expect(rs.getBoolean(COLUMN_NAMES[3])).andReturn(WITH_TIME); } private void assertScheduledActivityState(ScheduledActivityMode expectedMode, String expectedReason, Date expectedDate, ScheduledActivityState actual, Boolean expectedWithTime) { assertEquals("Wrong type", expectedMode, actual.getMode()); assertEquals("Wrong reason", expectedReason, actual.getReason()); if (expectedDate != null) { assertEquals("Wrong date", expectedDate, actual.getDate()); } assertEquals("Wrong withTime", expectedWithTime, actual.getWithTime()); } public void testNullSafeSetScheduled() throws Exception { expectSetStateFields(SCHEDULED, 4, true, WITH_TIME); doNullSafeSet(ScheduledActivityMode.SCHEDULED.createStateInstance(DATE, REASON), 4); } public void testNullSafeSetOccurred() throws Exception { expectSetStateFields(OCCURRED, 2, true, WITH_TIME); doNullSafeSet(ScheduledActivityMode.OCCURRED.createStateInstance(DATE, REASON), 2); } public void testNullSafeSetCanceled() throws Exception { expectSetStateFields(CANCELED, 7, true, WITH_TIME); doNullSafeSet(ScheduledActivityMode.CANCELED.createStateInstance(DATE, REASON), 7); } public void testNullSafeSetConditional() throws Exception { expectSetStateFields(CONDITIONAL, 5, true, WITH_TIME); doNullSafeSet(ScheduledActivityMode.CONDITIONAL.createStateInstance(DATE, REASON), 5); } public void testNullSafeSetNotAvailable() throws Exception { expectSetStateFields(NOT_APPLICABLE, 6, true, WITH_TIME); doNullSafeSet(ScheduledActivityMode.NOT_APPLICABLE.createStateInstance(DATE, REASON), 6); } private void doNullSafeSet(ScheduledActivityState expectedState, int index) throws SQLException { replayMocks(); type.nullSafeSet(st, expectedState, index, null); verifyMocks(); } private void expectSetStateFields(ScheduledActivityMode expectedMode, int index, boolean expectDate, boolean withTime) throws SQLException { st.setObject(index , expectedMode.getId(), Types.INTEGER); st.setString(index + 1, REASON); st.setTimestamp(index + 2, expectDate ? new Timestamp(DATE.getTime()) : null); st.setBoolean(index + 3, withTime); } }
bsd-3-clause
ffurkanhas/dungeon
src/main/java/org/mafagafogigante/dungeon/game/LocationPreset.java
2633
package org.mafagafogigante.dungeon.game; import org.mafagafogigante.dungeon.util.Percentage; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * The LocationPreset class that serves as a recipe for Locations. */ public final class LocationPreset { private final Id id; private final Type type; private final Name name; private final BlockedEntrances blockedEntrances = new BlockedEntrances(); private final List<SpawnerPreset> spawners = new ArrayList<>(); private final Map<Id, Percentage> items = new HashMap<>(); private Percentage lightPermittivity; private int blobSize; private LocationDescription description; LocationPreset(Id id, Type type, Name name) { this.id = id; this.type = type; this.name = name; } public Id getId() { return id; } public Type getType() { return type; } public Name getName() { return name; } public LocationDescription getDescription() { return description; } public void setDescription(LocationDescription description) { this.description = description; } public List<SpawnerPreset> getSpawners() { return spawners; } /** * Adds a Spawner to this Location based on a SpawnerPreset. * * @param preset the SpawnerPreset */ public void addSpawner(SpawnerPreset preset) { this.spawners.add(preset); } public Set<Entry<Id, Percentage>> getItems() { return items.entrySet(); } /** * Adds an Item to this Location based on an ItemFrequencyPair. * * @param id the ID string of the item * @param probability the probability of the item appearing */ public void addItem(String id, Double probability) { items.put(new Id(id), new Percentage(probability)); } public BlockedEntrances getBlockedEntrances() { return new BlockedEntrances(blockedEntrances); } /** * Blocks exiting and entering into the location by a given direction. * * @param direction a Direction to be blocked. */ public void block(Direction direction) { blockedEntrances.block(direction); } public Percentage getLightPermittivity() { return lightPermittivity; } public void setLightPermittivity(double lightPermittivity) { this.lightPermittivity = new Percentage(lightPermittivity); } public int getBlobSize() { return blobSize; } public void setBlobSize(int blobSize) { this.blobSize = blobSize; } public enum Type {HOME, RIVER, BRIDGE, DUNGEON_ENTRANCE, DUNGEON_STAIRWAY, DUNGEON_ROOM, DUNGEON_CORRIDOR, LAND} }
bsd-3-clause
Flash3388/FlashLib
flashlib.vision.core/src/main/java/com/flash3388/flashlib/vision/SourcePoller.java
788
package com.flash3388.flashlib.vision; import com.castle.util.throwables.ThrowableHandler; public class SourcePoller<T> implements Runnable { private final Source<? extends T> mSource; private final Pipeline<? super T> mPipeline; private final ThrowableHandler mThrowableHandler; public SourcePoller(Source<? extends T> source, Pipeline<? super T> pipeline, ThrowableHandler throwableHandler) { mSource = source; mPipeline = pipeline; mThrowableHandler = throwableHandler; } @Override public void run() { try { T data = mSource.get(); mPipeline.process(data); } catch (Throwable t) { mThrowableHandler.handle(t); } } }
bsd-3-clause
emabrey/SleekSlick2D
slick/src/main/java/org/newdawn/slick/SavedState.java
5505
package org.newdawn.slick; import org.newdawn.slick.muffin.FileMuffin; import org.newdawn.slick.muffin.Muffin; import org.newdawn.slick.muffin.WebstartMuffin; import org.newdawn.slick.util.Log; import javax.jnlp.ServiceManager; import java.io.IOException; import java.util.HashMap; /** * A utility to allow game setup/state to be stored locally. This utility will adapt to the current enviornment * (webstart or file based). Note that this will not currently work in an applet. * <p/> * * @author kappaOne */ public class SavedState { /** * file name of where the scores will be saved */ private String fileName; /** * Type of Muffin to use */ private Muffin muffin; /** * hash map where int data will be stored */ private HashMap numericData = new HashMap(); /** * hash map where string data will be stored */ private HashMap stringData = new HashMap(); /** * Create and Test to see if the app is running as webstart or local app and select the appropriate muffin type * <p/> * * @param fileName name of muffin where data will be saved * <p/> * * @throws SlickException Indicates a failure to load the stored state */ public SavedState(String fileName) throws SlickException { this.fileName = fileName; if (isWebstartAvailable()) { muffin = new WebstartMuffin(); } else { muffin = new FileMuffin(); } try { load(); } catch (IOException e) { throw new SlickException("Failed to load state on startup", e); } } /** * Get number stored at given location * <p/> * * @param nameOfField The name of the number to retrieve * <p/> * * @return The number saved at this location */ public double getNumber(String nameOfField) { return getNumber(nameOfField, 0); } /** * Get number stored at given location * <p/> * * @param nameOfField The name of the number to retrieve * @param defaultValue The value to return if the specified value hasn't been set * <p/> * * @return The number saved at this location */ public double getNumber(String nameOfField, double defaultValue) { Double value = ((Double) numericData.get(nameOfField)); if (value == null) { return defaultValue; } return value.doubleValue(); } /** * Save the given value at the given location will overwrite any previous value at this location * <p/> * * @param nameOfField The name to store the value against * @param value The value to store */ public void setNumber(String nameOfField, double value) { numericData.put(nameOfField, new Double(value)); } /** * Get the String at the given location * <p/> * * @param nameOfField location of string * <p/> * * @return String stored at the location given */ public String getString(String nameOfField) { return getString(nameOfField, null); } /** * Get the String at the given location * <p/> * * @param nameOfField location of string * @param defaultValue The value to return if the specified value hasn't been set * <p/> * * @return String stored at the location given */ public String getString(String nameOfField, String defaultValue) { String value = (String) stringData.get(nameOfField); if (value == null) { return defaultValue; } return value; } /** * Save the given value at the given location will overwrite any previous value at this location * <p/> * * @param nameOfField location to store int * @param value The value to store */ public void setString(String nameOfField, String value) { stringData.put(nameOfField, value); } /** * Save the stored data to file/muffin * <p/> * * @throws IOException Indicates it wasn't possible to store the state */ public void save() throws IOException { muffin.saveFile(numericData, fileName + "_Number"); muffin.saveFile(stringData, fileName + "_String"); } /** * Load the data from file/muffin * <p/> * * @throws IOException Indicates it wasn't possible to load the state */ public void load() throws IOException { numericData = muffin.loadFile(fileName + "_Number"); stringData = muffin.loadFile(fileName + "_String"); } /** * Will delete all current data held in Score */ public void clear() { numericData.clear(); stringData.clear(); } /** * Quick test to see if running through Java webstart * <p/> * * @return True if jws running */ private boolean isWebstartAvailable() { try { Class.forName("javax.jnlp.ServiceManager"); // this causes to go and see if the service is available ServiceManager.lookup("javax.jnlp.PersistenceService"); Log.info("Webstart detected using Muffins"); } catch (Exception e) { Log.info("Using Local File System"); return false; } return true; } }
bsd-3-clause
erwin1/gluon-samples
spring-motd/client/src/main/java/com/gluonhq/spring/motd/client/service/Service.java
2745
/** * Copyright (c) 2017, Gluon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Gluon, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL GLUON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.gluonhq.spring.motd.client.service; import com.gluonhq.cloudlink.client.data.DataClient; import com.gluonhq.cloudlink.client.data.DataClientBuilder; import com.gluonhq.cloudlink.client.data.OperationMode; import com.gluonhq.cloudlink.client.data.SyncFlag; import com.gluonhq.connect.GluonObservableObject; import com.gluonhq.connect.provider.DataProvider; import javax.annotation.PostConstruct; public class Service { private static final String MOTD = "spring-motd-v1"; private DataClient dataClient; @PostConstruct public void postConstruct() { dataClient = DataClientBuilder.create() .operationMode(OperationMode.CLOUD_FIRST) .build(); } public GluonObservableObject<String> retrieveMOTD() { GluonObservableObject<String> motd = DataProvider .retrieveObject(dataClient.createObjectDataReader(MOTD, String.class, SyncFlag.OBJECT_READ_THROUGH)); motd.initializedProperty().addListener((obs, ov, nv) -> { if (nv && motd.get() == null) { motd.set("This is the first Message of the Day!"); } }); return motd; } }
bsd-3-clause
intarsys/runtime
src/de/intarsys/tools/locator/ZipFileLocator.java
3058
package de.intarsys.tools.locator; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.stream.StreamTools; /** * ! not yet functional ! * * An {@link ILocator} into a zip file. * */ public class ZipFileLocator extends CommonLocator { static class ZipFile { final private ILocator zipLocator; private List<ZipEntry> entries; public ZipFile(ILocator zipLocator) { super(); this.zipLocator = zipLocator; } protected List<ZipEntry> createEntries() throws IOException { List<ZipEntry> tempEntries = new ArrayList<ZipEntry>(); InputStream is = zipLocator.getInputStream(); try { ZipInputStream zis = new ZipInputStream(is); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { tempEntries.add(entry); } } finally { StreamTools.close(is); } return tempEntries; } synchronized protected List<ZipEntry> getEntries() throws IOException { if (entries == null) { entries = createEntries(); } return entries; } } final private ZipFile zipFile; final private String path; public ZipFileLocator(ILocator zipLocator, String path) { super(); this.zipFile = new ZipFile(zipLocator); this.path = path; } protected ZipFileLocator(ZipFile zipFile, String path) { super(); this.zipFile = zipFile; this.path = path; } public boolean exists() { return false; } protected ZipEntry findEntry(String tempPath) throws IOException { for (ZipEntry entry : zipFile.getEntries()) { if (entry.getName().equals(path)) { return entry; } } return null; } public ILocator getChild(String name) { String tempPath = path + "/" + name; return new ZipFileLocator(this, tempPath); } public String getFullName() { return null; } public InputStream getInputStream() throws IOException { return null; } public String getLocalName() { return null; } public OutputStream getOutputStream() throws IOException { return null; } public ILocator getParent() { return null; } public IRandomAccess getRandomAccess() throws IOException { return null; } public Reader getReader() throws IOException { return null; } public Reader getReader(String encoding) throws IOException { return null; } public String getType() { return null; } public String getTypedName() { return null; } public Writer getWriter() throws IOException { return null; } public Writer getWriter(String encoding) throws IOException { return null; } public boolean isDirectory() { return false; } public boolean isOutOfSynch() { return false; } public ILocator[] listLocators(ILocatorNameFilter filter) throws IOException { return null; } public void synch() { } public URL toURL() { return null; } }
bsd-3-clause
vanadium/intellij-vdl-plugin
gen/io/v/vdl/psi/impl/VdlTagImpl.java
933
// This is a generated file. Not intended for manual editing. package io.v.vdl.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static io.v.vdl.psi.VdlTypes.*; import io.v.vdl.psi.VdlCompositeElementImpl; import io.v.vdl.psi.*; public class VdlTagImpl extends VdlCompositeElementImpl implements VdlTag { public VdlTagImpl(ASTNode node) { super(node); } public void accept(@NotNull VdlVisitor visitor) { visitor.visitTag(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof VdlVisitor) accept((VdlVisitor)visitor); else super.accept(visitor); } @Override @NotNull public VdlStringLiteral getStringLiteral() { return findNotNullChildByClass(VdlStringLiteral.class); } }
bsd-3-clause
Team319/BobBAE2013
src/org/usfirst/frc319/BobBAE2013/commands/TrapdoorRetract.java
1650
// RobotBuilder Version: 0.0.2 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc319.BobBAE2013.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc319.BobBAE2013.Robot; /** * */ public class TrapdoorRetract extends Command { public TrapdoorRetract() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.dumper); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES setTimeout(1); } // Called just before this Command runs the first time protected void initialize() { Robot.dumper.TrapdoorRetract(); } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return isTimedOut(); } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
bsd-3-clause
smaccm/smaccm
fm-workbench/trusted-build/edu.umn.cs.crisys.tb/src/edu/umn/cs/crisys/topsort/TopologicalSort.java
2087
package edu.umn.cs.crisys.topsort; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; // TODO: currently only sorts the elements in the initial list, // even if the dependencies contain other elements; this matches // my current purpose, but may not do what you want! public class TopologicalSort { public static <T2 extends DependsOn<T2>> void topoSortElement(T2 elem, Map<T2, Color> assoc, List<T2> sorted) throws CyclicException { Color c = assoc.get(elem); if (c == null) { assoc.put(elem, Color.GRAY); if (elem.dependencies() != null) { for (T2 dep : elem.dependencies()) { // Don't consider elements outside of the initial set to sort. topoSortElement(dep, assoc, sorted); } } assoc.put(elem, Color.BLACK); sorted.add(elem); } else if (c == Color.GRAY) { throw new CyclicException("Cycle detected during topological sort."); } }; public static <T2 extends DependsOn<T2>> List<T2> performTopologicalSort(Collection<T2> elements) throws CyclicException { Map<T2, Color> colorAssoc = new HashMap<T2, Color>(); List<T2> sorted = new ArrayList<T2>(elements.size()); for (T2 e : elements) { topoSortElement(e, colorAssoc, sorted); } return sorted; } public static <T2 extends DependsOn<T2>> List<T2> performElementsOnlyTopologicalSort(Collection<T2> elements) throws CyclicException { // start from the set under consideration. final Set<T2> elemSet = new HashSet<T2>(elements); final List<T2> allTypesSorted = performTopologicalSort(elements); List<T2> elementsSorted = new ArrayList<T2>(); for (T2 e : allTypesSorted) { if (elemSet.contains(e)) { elementsSorted.add(e); } } return elementsSorted; } }; // check for duplicates...this is currently inefficient! /* boolean found = false; for (T2 other: sorted) { if (other.equals(elem)) { found = true; } } if (!found) { sorted.add(elem); } */
bsd-3-clause
GameRevision/GWLP-R
protocol/src/main/java/gwlpr/protocol/gameserver/outbound/P455_InformationChat.java
655
package gwlpr.protocol.gameserver.outbound; import gwlpr.protocol.serialization.GWMessage; /** * Auto-generated by PacketCodeGen. * Will display text of hard coded string IDs in the * chat box * */ public final class P455_InformationChat extends GWMessage { private short text; @Override public short getHeader() { return 455; } public void setText(short text) { this.text = text; } @Override public String toString() { StringBuilder sb = new StringBuilder("P455_InformationChat["); sb.append("text=").append(this.text).append("]"); return sb.toString(); } }
bsd-3-clause
vanadium/intellij-vdl-plugin
gen/io/v/vdl/psi/impl/VdlFunctionLitImpl.java
1102
// This is a generated file. Not intended for manual editing. package io.v.vdl.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static io.v.vdl.psi.VdlTypes.*; import io.v.vdl.psi.*; public class VdlFunctionLitImpl extends VdlExpressionImpl implements VdlFunctionLit { public VdlFunctionLitImpl(ASTNode node) { super(node); } public void accept(@NotNull VdlVisitor visitor) { visitor.visitFunctionLit(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof VdlVisitor) accept((VdlVisitor)visitor); else super.accept(visitor); } @Override @Nullable public VdlBlock getBlock() { return findChildByClass(VdlBlock.class); } @Override @Nullable public VdlSignature getSignature() { return findChildByClass(VdlSignature.class); } @Override @NotNull public PsiElement getFunc() { return findNotNullChildByType(FUNC); } }
bsd-3-clause
hyperverse/mini2Dx
core/src/main/java/org/mini2Dx/core/graphics/ShapeTextureCache.java
6063
/** * Copyright (c) 2015 See AUTHORS file * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mini2Dx.core.graphics; import java.util.HashMap; import java.util.Map; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; /** * Implements a cache of textures for shapes */ public class ShapeTextureCache { private Map<Integer, Texture> filledRectangleTextures; private Map<String, Texture> rectangleTextures; private Map<String, Texture> circleTextures; private Map<String, Texture> filledCircleTextures; /** * Constructor */ public ShapeTextureCache() { rectangleTextures = new HashMap<String, Texture>(); filledRectangleTextures = new HashMap<Integer, Texture>(); circleTextures = new HashMap<String, Texture>(); filledCircleTextures = new HashMap<String, Texture>(); } /** * Returns a filled rectangular texture for the provided {@link Color} * * @param color * The {@link Color} to fetch a texture of * @return A new {@link Texture} if this is first time it has been * requested, otherwise it will return a cached instance of the * {@link Texture} for the given {@link Color} */ public Texture getFilledRectangleTexture(Color color) { int bits = color.toIntBits(); if (!filledRectangleTextures.containsKey(bits)) { Pixmap pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888); pixmap.setColor(color); pixmap.fillRectangle(0, 0, 1, 1); filledRectangleTextures.put(bits, new Texture(pixmap)); pixmap.dispose(); } return filledRectangleTextures.get(bits); } /** * Returns a rectangular texture for the provided {@link Color} * * @param color * The {@link Color} to fetch a texture of * @param width * The width of the rectangle * @param height * The height of the rectangle * @param lineHeight * The line height of the rectangle * @return A new {@link Texture} if this is first time it has been * requested, otherwise it will return a cached instance of the * {@link Texture} for the given {@link Color} */ public Texture getRectangleTexture(Color color, int width, int height, int lineHeight) { int bits = color.toIntBits(); String key = "" + bits + "," + width + "," + height + "," + lineHeight; if (!rectangleTextures.containsKey(key)) { Pixmap pixmap = new Pixmap(width + 1, height + 1, Pixmap.Format.RGBA8888); pixmap.setColor(color); for (int i = 0; i < lineHeight; i++) { pixmap.drawRectangle(i, i, width - (i * 2), height - (i * 2)); } rectangleTextures.put(key, new Texture(pixmap)); pixmap.dispose(); } return rectangleTextures.get(key); } /** * Returns a circle texture for the provided {@link Color} * * @param color * The {@link Color} to fetch a texture of * @param radius * The radius of the circle * @param lineHeight * The line height of the circle * @return A new {@link Texture} if this is first time it has been * requested, otherwise it will return a cached instance of the * {@link Texture} for the given {@link Color} */ public Texture getCircleTexture(Color color, int radius, int lineHeight) { int bits = color.toIntBits(); String key = "" + bits + "," + radius + "," + lineHeight; if (!circleTextures.containsKey(key)) { Pixmap pixmap = new Pixmap((radius * 2) + 1, (radius * 2) + 1, Pixmap.Format.RGBA8888); pixmap.setColor(color); for (int i = 0; i < lineHeight; i++) { pixmap.drawCircle(radius, radius, radius - i); } circleTextures.put(key, new Texture(pixmap)); pixmap.dispose(); } return circleTextures.get(key); } /** * Returns a filled circular texture for the provided {@link Color} * * @param color * The {@link Color} to fetch a texture of * @param radius * The radius of the circle * @return A new {@link Texture} if this is first time it has been * requested, otherwise it will return a cached instance of the * {@link Texture} for the given {@link Color} */ public Texture getFilledCircleTexture(Color color, int radius) { int bits = color.toIntBits(); String key = "" + bits + "," + radius; if (!filledCircleTextures.containsKey(key)) { Pixmap pixmap = new Pixmap((radius * 2) + 1, (radius * 2) + 1, Pixmap.Format.RGBA8888); pixmap.setColor(color); pixmap.fillCircle(radius, radius, radius); filledCircleTextures.put(key, new Texture(pixmap)); pixmap.dispose(); } return filledCircleTextures.get(key); } }
bsd-3-clause
ekoontz/pgjdbc
org/postgresql/jdbc2/EscapedFunctions.java
25872
/*------------------------------------------------------------------------- * * Copyright (c) 2004-2014, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.jdbc2; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.HashMap; import java.util.Locale; import java.util.List; import java.util.Map; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; /** * this class stores supported escaped function * @author Xavier Poinsard */ public class EscapedFunctions { // numeric functions names public final static String ABS="abs"; public final static String ACOS="acos"; public final static String ASIN="asin"; public final static String ATAN="atan"; public final static String ATAN2="atan2"; public final static String CEILING="ceiling"; public final static String COS="cos"; public final static String COT="cot"; public final static String DEGREES="degrees"; public final static String EXP="exp"; public final static String FLOOR="floor"; public final static String LOG="log"; public final static String LOG10="log10"; public final static String MOD="mod"; public final static String PI="pi"; public final static String POWER="power"; public final static String RADIANS="radians"; public final static String ROUND="round"; public final static String SIGN="sign"; public final static String SIN="sin"; public final static String SQRT="sqrt"; public final static String TAN="tan"; public final static String TRUNCATE="truncate"; // string function names public final static String ASCII="ascii"; public final static String CHAR="char"; public final static String CONCAT="concat"; public final static String INSERT="insert"; // change arguments order public final static String LCASE="lcase"; public final static String LEFT="left"; public final static String LENGTH="length"; public final static String LOCATE="locate"; // the 3 args version duplicate args public final static String LTRIM="ltrim"; public final static String REPEAT="repeat"; public final static String REPLACE="replace"; public final static String RIGHT="right"; // duplicate args public final static String RTRIM="rtrim"; public final static String SPACE="space"; public final static String SUBSTRING="substring"; public final static String UCASE="ucase"; // soundex is implemented on the server side by // the contrib/fuzzystrmatch module. We provide a translation // for this in the driver, but since we don't want to bother with run // time detection of this module's installation we don't report this // method as supported in DatabaseMetaData. // difference is currently unsupported entirely. // date time function names public final static String CURDATE="curdate"; public final static String CURTIME="curtime"; public final static String DAYNAME="dayname"; public final static String DAYOFMONTH="dayofmonth"; public final static String DAYOFWEEK="dayofweek"; public final static String DAYOFYEAR="dayofyear"; public final static String HOUR="hour"; public final static String MINUTE="minute"; public final static String MONTH="month"; public final static String MONTHNAME="monthname"; public final static String NOW="now"; public final static String QUARTER="quarter"; public final static String SECOND="second"; public final static String WEEK="week"; public final static String YEAR="year"; // for timestampadd and timestampdiff the fractional part of second is not supported // by the backend // timestampdiff is very partially supported public final static String TIMESTAMPADD="timestampadd"; public final static String TIMESTAMPDIFF="timestampdiff"; // constants for timestampadd and timestampdiff public final static String SQL_TSI_ROOT="SQL_TSI_"; public final static String SQL_TSI_DAY="DAY"; public final static String SQL_TSI_FRAC_SECOND="FRAC_SECOND"; public final static String SQL_TSI_HOUR="HOUR"; public final static String SQL_TSI_MINUTE="MINUTE"; public final static String SQL_TSI_MONTH="MONTH"; public final static String SQL_TSI_QUARTER="QUARTER"; public final static String SQL_TSI_SECOND="SECOND"; public final static String SQL_TSI_WEEK="WEEK"; public final static String SQL_TSI_YEAR="YEAR"; // system functions public final static String DATABASE="database"; public final static String IFNULL="ifnull"; public final static String USER="user"; /** storage for functions implementations */ private static Map functionMap = createFunctionMap(); private static Map createFunctionMap() { Method[] arrayMeths = EscapedFunctions.class.getDeclaredMethods(); Map functionMap = new HashMap(arrayMeths.length*2); for (int i=0;i<arrayMeths.length;i++){ Method meth = arrayMeths[i]; if (meth.getName().startsWith("sql")) functionMap.put(meth.getName().toLowerCase(Locale.US),meth); } return functionMap; } /** * get Method object implementing the given function * @param functionName name of the searched function * @return a Method object or null if not found */ public static Method getFunction(String functionName){ return (Method) functionMap.get("sql"+functionName.toLowerCase(Locale.US)); } // ** numeric functions translations ** /** ceiling to ceil translation */ public static String sqlceiling(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("ceil("); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","ceiling"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** log to ln translation */ public static String sqllog(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("ln("); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","log"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** log10 to log translation */ public static String sqllog10(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("log("); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","log10"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** power to pow translation */ public static String sqlpower(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("pow("); if (parsedArgs.size()!=2){ throw new PSQLException(GT.tr("{0} function takes two and only two arguments.","power"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)).append(',').append(parsedArgs.get(1)); return buf.append(')').toString(); } /** truncate to trunc translation */ public static String sqltruncate(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("trunc("); if (parsedArgs.size()!=2){ throw new PSQLException(GT.tr("{0} function takes two and only two arguments.","truncate"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)).append(',').append(parsedArgs.get(1)); return buf.append(')').toString(); } // ** string functions translations ** /** char to chr translation */ public static String sqlchar(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("chr("); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","char"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** concat translation */ public static String sqlconcat(List parsedArgs){ StringBuilder buf = new StringBuilder(); buf.append('('); for (int iArg = 0;iArg<parsedArgs.size();iArg++){ buf.append(parsedArgs.get(iArg)); if (iArg!=(parsedArgs.size()-1)) buf.append(" || "); } return buf.append(')').toString(); } /** insert to overlay translation */ public static String sqlinsert(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("overlay("); if (parsedArgs.size()!=4){ throw new PSQLException(GT.tr("{0} function takes four and only four argument.","insert"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)).append(" placing ").append(parsedArgs.get(3)); buf.append(" from ").append(parsedArgs.get(1)).append(" for ").append(parsedArgs.get(2)); return buf.append(')').toString(); } /** lcase to lower translation */ public static String sqllcase(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("lower("); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","lcase"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** left to substring translation */ public static String sqlleft(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("substring("); if (parsedArgs.size()!=2){ throw new PSQLException(GT.tr("{0} function takes two and only two arguments.","left"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)).append(" for ").append(parsedArgs.get(1)); return buf.append(')').toString(); } /** length translation */ public static String sqllength(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("length(trim(trailing from "); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","length"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append("))").toString(); } /** locate translation */ public static String sqllocate(List parsedArgs) throws SQLException{ if (parsedArgs.size()==2){ return "position("+parsedArgs.get(0)+" in "+parsedArgs.get(1)+")"; }else if (parsedArgs.size()==3){ String tmp = "position("+parsedArgs.get(0)+" in substring("+parsedArgs.get(1)+" from "+parsedArgs.get(2)+"))"; return "("+parsedArgs.get(2)+"*sign("+tmp+")+"+tmp+")"; }else{ throw new PSQLException(GT.tr("{0} function takes two or three arguments.","locate"), PSQLState.SYNTAX_ERROR); } } /** ltrim translation */ public static String sqlltrim(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("trim(leading from "); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","ltrim"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** right to substring translation */ public static String sqlright(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("substring("); if (parsedArgs.size()!=2){ throw new PSQLException(GT.tr("{0} function takes two and only two arguments.","right"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)).append(" from (length(").append(parsedArgs.get(0)).append(")+1-").append(parsedArgs.get(1)); return buf.append("))").toString(); } /** rtrim translation */ public static String sqlrtrim(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("trim(trailing from "); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","rtrim"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** space translation */ public static String sqlspace(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("repeat(' ',"); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","space"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** substring to substr translation */ public static String sqlsubstring(List parsedArgs) throws SQLException{ if (parsedArgs.size()==2){ return "substr("+parsedArgs.get(0)+","+parsedArgs.get(1)+")"; }else if (parsedArgs.size()==3){ return "substr("+parsedArgs.get(0)+","+parsedArgs.get(1)+","+parsedArgs.get(2)+")"; }else{ throw new PSQLException(GT.tr("{0} function takes two or three arguments.","substring"), PSQLState.SYNTAX_ERROR); } } /** ucase to upper translation */ public static String sqlucase(List parsedArgs) throws SQLException{ StringBuilder buf = new StringBuilder(); buf.append("upper("); if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","ucase"), PSQLState.SYNTAX_ERROR); } buf.append(parsedArgs.get(0)); return buf.append(')').toString(); } /** curdate to current_date translation */ public static String sqlcurdate(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=0){ throw new PSQLException(GT.tr("{0} function doesn''t take any argument.","curdate"), PSQLState.SYNTAX_ERROR); } return "current_date"; } /** curtime to current_time translation */ public static String sqlcurtime(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=0){ throw new PSQLException(GT.tr("{0} function doesn''t take any argument.","curtime"), PSQLState.SYNTAX_ERROR); } return "current_time"; } /** dayname translation */ public static String sqldayname(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","dayname"), PSQLState.SYNTAX_ERROR); } return "to_char("+parsedArgs.get(0)+",'Day')"; } /** dayofmonth translation */ public static String sqldayofmonth(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","dayofmonth"), PSQLState.SYNTAX_ERROR); } return "extract(day from "+parsedArgs.get(0)+")"; } /** dayofweek translation * adding 1 to postgresql function since we expect values from 1 to 7 */ public static String sqldayofweek(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","dayofweek"), PSQLState.SYNTAX_ERROR); } return "extract(dow from "+parsedArgs.get(0)+")+1"; } /** dayofyear translation */ public static String sqldayofyear(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","dayofyear"), PSQLState.SYNTAX_ERROR); } return "extract(doy from "+parsedArgs.get(0)+")"; } /** hour translation */ public static String sqlhour(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","hour"), PSQLState.SYNTAX_ERROR); } return "extract(hour from "+parsedArgs.get(0)+")"; } /** minute translation */ public static String sqlminute(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","minute"), PSQLState.SYNTAX_ERROR); } return "extract(minute from "+parsedArgs.get(0)+")"; } /** month translation */ public static String sqlmonth(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","month"), PSQLState.SYNTAX_ERROR); } return "extract(month from "+parsedArgs.get(0)+")"; } /** monthname translation */ public static String sqlmonthname(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","monthname"), PSQLState.SYNTAX_ERROR); } return "to_char("+parsedArgs.get(0)+",'Month')"; } /** quarter translation */ public static String sqlquarter(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","quarter"), PSQLState.SYNTAX_ERROR); } return "extract(quarter from "+parsedArgs.get(0)+")"; } /** second translation */ public static String sqlsecond(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","second"), PSQLState.SYNTAX_ERROR); } return "extract(second from "+parsedArgs.get(0)+")"; } /** week translation */ public static String sqlweek(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","week"), PSQLState.SYNTAX_ERROR); } return "extract(week from "+parsedArgs.get(0)+")"; } /** year translation */ public static String sqlyear(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=1){ throw new PSQLException(GT.tr("{0} function takes one and only one argument.","year"), PSQLState.SYNTAX_ERROR); } return "extract(year from "+parsedArgs.get(0)+")"; } /** time stamp add */ public static String sqltimestampadd(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=3){ throw new PSQLException(GT.tr("{0} function takes three and only three arguments.","timestampadd"), PSQLState.SYNTAX_ERROR); } String interval = EscapedFunctions.constantToInterval(parsedArgs.get(0).toString(),parsedArgs.get(1).toString()); StringBuilder buf = new StringBuilder(); buf.append("(").append(interval).append("+"); buf.append(parsedArgs.get(2)).append(")"); return buf.toString(); } private final static String constantToInterval(String type,String value)throws SQLException{ if (!type.startsWith(SQL_TSI_ROOT)) throw new PSQLException(GT.tr("Interval {0} not yet implemented",type), PSQLState.SYNTAX_ERROR); String shortType = type.substring(SQL_TSI_ROOT.length()); if (SQL_TSI_DAY.equalsIgnoreCase(shortType)) return "CAST(" + value + " || ' day' as interval)"; else if (SQL_TSI_SECOND.equalsIgnoreCase(shortType)) return "CAST(" + value + " || ' second' as interval)"; else if (SQL_TSI_HOUR.equalsIgnoreCase(shortType)) return "CAST(" + value + " || ' hour' as interval)"; else if (SQL_TSI_MINUTE.equalsIgnoreCase(shortType)) return "CAST(" + value + " || ' minute' as interval)"; else if (SQL_TSI_MONTH.equalsIgnoreCase(shortType)) return "CAST(" + value + " || ' month' as interval)"; else if (SQL_TSI_QUARTER.equalsIgnoreCase(shortType)) return "CAST((" + value + "::int * 3) || ' month' as interval)"; else if (SQL_TSI_WEEK.equalsIgnoreCase(shortType)) return "CAST(" + value + " || ' week' as interval)"; else if (SQL_TSI_YEAR.equalsIgnoreCase(shortType)) return "CAST(" + value + " || ' year' as interval)"; else if (SQL_TSI_FRAC_SECOND.equalsIgnoreCase(shortType)) throw new PSQLException(GT.tr("Interval {0} not yet implemented","SQL_TSI_FRAC_SECOND"), PSQLState.SYNTAX_ERROR); else throw new PSQLException(GT.tr("Interval {0} not yet implemented",type), PSQLState.SYNTAX_ERROR); } /** time stamp diff */ public static String sqltimestampdiff(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=3){ throw new PSQLException(GT.tr("{0} function takes three and only three arguments.","timestampdiff"), PSQLState.SYNTAX_ERROR); } String datePart = EscapedFunctions.constantToDatePart(parsedArgs.get(0).toString()); StringBuilder buf = new StringBuilder(); buf.append("extract( ").append(datePart) .append(" from (").append(parsedArgs.get(2)).append("-").append(parsedArgs.get(1)).append("))"); return buf.toString(); } private final static String constantToDatePart(String type)throws SQLException{ if (!type.startsWith(SQL_TSI_ROOT)) throw new PSQLException(GT.tr("Interval {0} not yet implemented",type), PSQLState.SYNTAX_ERROR); String shortType = type.substring(SQL_TSI_ROOT.length()); if (SQL_TSI_DAY.equalsIgnoreCase(shortType)) return "day"; else if (SQL_TSI_SECOND.equalsIgnoreCase(shortType)) return "second"; else if (SQL_TSI_HOUR.equalsIgnoreCase(shortType)) return "hour"; else if (SQL_TSI_MINUTE.equalsIgnoreCase(shortType)) return "minute"; // See http://archives.postgresql.org/pgsql-jdbc/2006-03/msg00096.php /*else if (SQL_TSI_MONTH.equalsIgnoreCase(shortType)) return "month"; else if (SQL_TSI_QUARTER.equalsIgnoreCase(shortType)) return "quarter"; else if (SQL_TSI_WEEK.equalsIgnoreCase(shortType)) return "week"; else if (SQL_TSI_YEAR.equalsIgnoreCase(shortType)) return "year";*/ else if (SQL_TSI_FRAC_SECOND.equalsIgnoreCase(shortType)) throw new PSQLException(GT.tr("Interval {0} not yet implemented","SQL_TSI_FRAC_SECOND"), PSQLState.SYNTAX_ERROR); else throw new PSQLException(GT.tr("Interval {0} not yet implemented",type), PSQLState.SYNTAX_ERROR); } /** database translation */ public static String sqldatabase(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=0){ throw new PSQLException(GT.tr("{0} function doesn''t take any argument.","database"), PSQLState.SYNTAX_ERROR); } return "current_database()"; } /** ifnull translation */ public static String sqlifnull(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=2){ throw new PSQLException(GT.tr("{0} function takes two and only two arguments.","ifnull"), PSQLState.SYNTAX_ERROR); } return "coalesce("+parsedArgs.get(0)+","+parsedArgs.get(1)+")"; } /** user translation */ public static String sqluser(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=0){ throw new PSQLException(GT.tr("{0} function doesn''t take any argument.","user"), PSQLState.SYNTAX_ERROR); } return "user"; } }
bsd-3-clause
jjfiv/coop
src/main/java/edu/umass/cs/jfoley/coop/conll/classifier/SparseFloatFeatures.java
712
package edu.umass.cs.jfoley.coop.conll.classifier; import ciir.jfoley.chai.collections.Pair; import gnu.trove.map.hash.TIntFloatHashMap; import java.util.Iterator; /** * @author jfoley. */ public class SparseFloatFeatures implements FeatureVector { TIntFloatHashMap features; @Override public Iterator<Pair<Integer, Float>> iterator() { final int[] keys = features.keys(); return new Iterator<Pair<Integer, Float>>() { int pos = 0; @Override public boolean hasNext() { return pos < keys.length; } @Override public Pair<Integer, Float> next() { float val = features.get(keys[pos]); return Pair.of(pos++, val); } }; } }
bsd-3-clause
Nelspike/UniversityStuff
Spam ID3/src/Row.java
760
import java.util.*; public class Row<T> { private HashMap<String, T> rowValues; private int nColumns; public Row(int c) { nColumns = c; rowValues = new HashMap<String, T>(nColumns); } public HashMap<String, T> getRowValues() { return rowValues; } public void setRowValues(HashMap<String, T> rowValues) { this.rowValues = rowValues; } public void insert(String columnName, T value) { rowValues.put(columnName, value); } public T getFromRow(String columnName) { return rowValues.get(columnName); } public String toString() { Iterator<String> iterator = rowValues.keySet().iterator(); String s = "Row Info "; while(iterator.hasNext()) { s += rowValues.get(iterator.next()) + " | "; } return s; } }
bsd-3-clause
luttero/Maud
src/gov/noaa/pmel/sgt/PlotMark.java
7985
/* * $Id: PlotMark.java,v 1.1 2004/12/27 16:15:20 luca Exp $ * * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ package gov.noaa.pmel.sgt; import java.awt.Component; import java.awt.Graphics; import java.awt.BorderLayout; import java.awt.FontMetrics; import java.awt.Font; import java.awt.Color; import javax.swing.*; import gov.noaa.pmel.util.Dimension2D; /** * Support class used to draw a PlotMark. Plot mark codes are defined * in the following table. <br> * * <P ALIGN="CENTER"><IMG SRC="plotmarkcodes.gif" ALIGN="BOTTOM" BORDER="0"> * * @author Donald Denbo * @version $Revision: 1.1 $, $Date: 2004/12/27 16:15:20 $ * @since 2.0 * @see PointCartesianRenderer * @see gov.noaa.pmel.sgt.swing.PlotMarkIcon */ public class PlotMark { protected int mark_; protected int tableSize_ = 51; protected int firstPoint_; protected int lastPoint_; protected double markHeight_; protected int fillMark_ = 44; protected boolean fill_ = false; protected boolean circle_ = false; protected static final int[][] markTable = {{ 5, 9}, { 11, 15}, { 14, 15}, { 11, 12}, // 0 { 26, 31}, { 32, 37}, { 38, 43}, { 44, 49}, // 4 { 1, 5}, { 64, 67}, { 5, 15}, { 50, 54}, // 8 { 1, 9}, { 55, 63}, { 15, 19}, { 21, 25}, // 12 { 50, 53}, { 51, 54}, { 72, 77}, { 84, 98}, // 16 { 18, 22}, { 11, 19}, { 64, 66}, { 68, 71}, // 20 { 68, 70}, { 78, 83}, {102, 106}, {113, 118}, // 24 {119, 124}, {125, 130}, {131, 136}, {105, 110}, // 28 {107, 112}, {137, 139}, { 99, 106}, {103, 108}, // 32 {140, 144}, {140, 147}, {156, 163}, {148, 155}, // 36 {170, 183}, {184, 189}, {188, 193}, {164, 169}, // 40 { 1, 5}, { 64, 67}, { 55, 63}, { 15, 19}, // 44 { 68, 71}, {164, 169}, {164, 169}}; // 48 protected static final int[] table = { 9, 41, 45, 13, 9, 45, 0, 13, 41, 0, // 0 25, 29, 0, 11, 43, 29, 11, 25, 43, 11, // 10 25, 29, 11, 43, 29, 18, 27, 34, 0, 27, // 20 24, 20, 27, 36, 0, 27, 30, 20, 27, 18, // 30 0, 3, 27, 36, 27, 34, 0, 27, 51, 41, // 40 13, 45, 9, 41, 4, 2, 16, 32, 50, 52, // 50 38, 22, 4, 9, 29, 41, 9, 13, 25, 45, // 60 13, 13, 27, 31, 0, 27, 45, 9, 27, 29, // 70 0, 27, 41, 13, 20, 18, 9, 0, 18, 34, // 80 0, 20, 36, 0, 45, 36, 34, 41, 19, 35, // 90 0, 21, 17, 33, 37, 21, 19, 35, 33, 17, // 100 21, 37, 20, 29, 25, 0, 17, 33, 21, 37, // 110 35, 19, 17, 33, 21, 37, 19, 35, 33, 17, // 120 21, 19, 43, 0, 37, 33, 21, 37, 25, 12, // 130 44, 0, 42, 10, 0, 17, 37, 26, 30, 0, // 140 12, 44, 0, 8, 40, 13, 45, 0, 43, 11, // 150 0, 9, 41, 4, 41, 30, 9, 52, 4, 12, // 160 20, 21, 13, 12, 0, 9, 45, 0, 33, 41, // 170 42, 34, 33, 14, 44, 10, 0, 9, 41, 0, // 180 42, 12, 46, 0, 0, 0, 0, 0, 0, 0}; // 190 /** * Construct a <code>PlotMark</code> using the code and height from the * <code>LineAttribute</code>. */ public PlotMark(LineAttribute attr) { setLineAttribute(attr); } /** * Construct a <code>PlotMark</code> using the code and height from the * <code>PointAttribute</code>. */ public PlotMark(PointAttribute attr) { setPointAttribute(attr); } /** * Construct a <code>PlotMark</code> using the code from the * mark code. Default height = 0.08. */ public PlotMark(int mark) { setMark(mark); markHeight_ = 0.08; } /** * Set the mark and height from the <code>PointAttribute</code>. */ public void setPointAttribute(PointAttribute attr) { int mark = attr.getMark(); setMark(mark); markHeight_ = attr.getMarkHeightP()/8.0; } /** * Set the mark and height from the <code>LineAttribute</code>. */ public void setLineAttribute(LineAttribute attr) { int mark = attr.getMark(); setMark(mark); markHeight_ = attr.getMarkHeightP()/8.0; } /** * Set the mark. */ public void setMark(int mark) { if(mark <= 0) mark = 0; fill_ = mark > fillMark_; circle_ = mark >= 50; if(circle_) fill_ = mark == 51; if(mark > tableSize_) mark = tableSize_; firstPoint_ = markTable[mark-1][0]-1; lastPoint_ = markTable[mark-1][1]; mark_ = mark; } /** * Get the mark code. */ public int getMark() { return mark_; } /** * Set the mark height. */ public void setMarkHeightP(double mHeight) { markHeight_ = mHeight/8.0; } /** * Get the mark height */ public double getMarkHeightP() { return markHeight_*8.0; } /** * Used internally by sgt. */ public void paintMark(Graphics g, Layer ly, int xp, int yp) { int count, ib; int xdOld = 0, ydOld = 0; int movex, movey; int xt, yt; double xscl = ly.getXSlope()*markHeight_; double yscl = ly.getYSlope()*markHeight_; if(circle_) { xt = (int)(xscl*-2) + xp; yt = (int)(xscl*-2) + yp; int w = (int)(xscl*4.0) - 1; if(fill_) { g.fillOval(xt, yt, w, w); } else { g.drawOval(xt, yt, w, w); } return; } int[] xl = new int[lastPoint_-firstPoint_]; int[] yl = new int[lastPoint_-firstPoint_]; boolean penf = false; int i=0; for(count = firstPoint_; count < lastPoint_; count++) { ib = table[count]; if(ib == 0) { penf = false; } else { movex = (ib>>3) - 3; movey = -((ib&7) - 3); xt = (int)(xscl*(double)movex) + xp; yt = (int)(yscl*(double)movey) + yp; if(penf) { if(fill_) { xl[i] = xt; yl[i] = yt; i++; } else { g.drawLine(xdOld, ydOld, xt, yt); } } penf = true; xdOld = xt; ydOld = yt; } if(fill_) g.fillPolygon(xl, yl, i); } } public static void main(String[] args) { /** * hack code to create a "list" of plot marks. */ JFrame frame = new JFrame("Plot Marks"); frame.getContentPane().setLayout(new BorderLayout()); frame.setSize(500, 700); JPane pane = new JPane("Plot Mark Pane", frame.getSize()); Layer layer = new Layer("Plot Mark Layer", new Dimension2D(5.0, 7.0)); pane.setBatch(true); pane.setLayout(new StackedLayout()); frame.getContentPane().add(pane, BorderLayout.CENTER); pane.add(layer); frame.setVisible(true); pane.setBatch(false); PlotMark pm = new PlotMark(1); Graphics g = pane.getGraphics(); g.setFont(new Font("Helvetica", Font.PLAIN, 18)); pm.setMarkHeightP(0.32); int w = pane.getSize().width; int h = pane.getSize().height; g.setColor(Color.white); g.fillRect(0, 0, w, h); g.setColor(Color.black); FontMetrics fm = g.getFontMetrics(); int hgt = fm.getAscent()/2; String label; int xt = 100; int yt = 400; int wid = 0; int mark = 1; for(int j=0; j < 13; j++) { yt = 45*j + 100; for(int i=0; i < 4; i++) { xt = 120*i + 75; label = mark + ":"; wid = fm.stringWidth(label) + 20; g.setColor(Color.blue.brighter()); g.drawString(label, xt - wid, yt); pm.setMark(mark); g.setColor(Color.black); pm.paintMark(g, layer, xt, yt - hgt); mark++; if(mark > 51) break; } } } public String toString() { return "PlotMark: " + mark_; } }
bsd-3-clause
oracle-adf/PaaS-SaaS_UIAccelerator
OSCProxyClient/src/com/oracle/ptsdemo/oscproxyclient/types/ProcessOpportunityResponse.java
1912
package com.oracle.ptsdemo.oscproxyclient.types; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="result" type="{http://xmlns.oracle.com/apps/sales/opptyMgmt/opportunities/opportunityService/}Opportunity" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "result" }) @XmlRootElement(name = "processOpportunityResponse") public class ProcessOpportunityResponse { protected List<Opportunity> result; /** * Gets the value of the result property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the result property. * * <p> * For example, to add a new item, do as follows: * <pre> * getResult().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Opportunity } * * */ public List<Opportunity> getResult() { if (result == null) { result = new ArrayList<Opportunity>(); } return this.result; } }
bsd-3-clause
fresskarma/tinyos-1.x
tools/java/net/tinyos/message/ByteArray.java
2317
// $Id: ByteArray.java,v 1.2 2003/10/07 21:45:57 idgay Exp $ /* tab:4 * "Copyright (c) 2000-2003 The Regents of the University of California. * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice, the following * two paragraphs and the author appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * * Copyright (c) 2002-2003 Intel Corporation * All rights reserved. * * This file is distributed under the terms in the attached INTEL-LICENSE * file. If you do not find these files, copies can be found by writing to * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, * 94704. Attention: Intel License Inquiry. */ /* Authors: David Gay <dgay@intel-research.net> * Intel Research Berkeley Lab * */ /** * ByteArray class. A simple abstract, read-only byte array class. * * ByteArrays is the "interface" (in class form) expected by the * dataSet method of net.tinyos.message.Message. Users should extend * ByteArray and implement an appropriate get method. Example: * received.dataSet * (new ByteArray() { * public byte get(int index) { return msg.getData(index);} }); * @author David Gay <dgay@intel-research.net> * @author Intel Research Berkeley Lab */ package net.tinyos.message; abstract public class ByteArray { /** * Get the index'th byte of this array * @param index: index of byte to fetch */ public abstract byte get(int index); }
bsd-3-clause
jeanlazarou/straight
src/com/ap/straight/unsupported/AbstractStatement.java
1965
package com.ap.straight.unsupported; import java.sql.*; import java.sql.ResultSet; public abstract class AbstractStatement implements Statement { public int getResultSetHoldability() throws SQLException { throw new UnsupportedOperationException(); } public boolean getMoreResults(int current) throws SQLException { throw new UnsupportedOperationException(); } public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { throw new UnsupportedOperationException(); } public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { throw new UnsupportedOperationException(); } public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { throw new UnsupportedOperationException(); } public boolean execute(String sql, int[] columnIndexes) throws SQLException { throw new UnsupportedOperationException(); } public java.sql.ResultSet getGeneratedKeys() throws SQLException { throw new UnsupportedOperationException(); } public int executeUpdate(String sql, String[] columnNames) throws SQLException { throw new UnsupportedOperationException(); } public boolean execute(String sql, String[] columnNames) throws SQLException { throw new UnsupportedOperationException(); } public boolean isClosed() throws SQLException { throw new UnsupportedOperationException(); } public void setPoolable(boolean poolable) throws SQLException { throw new UnsupportedOperationException(); } public boolean isPoolable() throws SQLException { throw new UnsupportedOperationException(); } public void closeOnCompletion() throws SQLException { throw new UnsupportedOperationException(); } public boolean isCloseOnCompletion() throws SQLException { throw new UnsupportedOperationException(); } }
bsd-3-clause
NCIP/calims
calims2-model/src/java/gov/nih/nci/calims2/domain/inventory/l10n/ContainerQuantityBundle.java
789
/*L * Copyright Moxie Informatics. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/calims/LICENSE.txt for details. */ package gov.nih.nci.calims2.domain.inventory.l10n; import java.util.ListResourceBundle; import gov.nih.nci.calims2.domain.inventory.enumeration.ContainerQuantity; /** * @author connollym@moxieinformatics.com * */ public class ContainerQuantityBundle extends ListResourceBundle { private static final Object[][] CONTENTS = { {ContainerQuantity.MAXIMUMCAPACITY.name(), "Maximum Capacity"}, {ContainerQuantity.CURRENTQUANTITY.name(), "Current Quantity"}, {ContainerQuantity.MINIMUMCAPACITY.name(), "Minimum Capacity"}}; /** * {@inheritDoc} */ protected Object[][] getContents() { return CONTENTS; } }
bsd-3-clause
jolting/cs263
project/src/main/java/project/GetPCD.java
8756
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * Copyright (c) 2014, Hunter Laux * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ package project; import java.io.IOException; import java.util.List; import java.util.logging.Level; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.blobstore.BlobInfo; import com.google.appengine.api.blobstore.BlobInfoFactory; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.Query.Filter; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; // The Worker servlet should be mapped to the "/worker" URL. public class GetPCD extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ /* skip the first key / */ String keyStr =request.getPathInfo().substring(1); /* This allows /$key/filename.pcd where filename can be whatever */ keyStr = keyStr.split("/")[0]; DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key pclKey = KeyFactory.createKey("PointCloud2", keyStr); Query query = new Query(pclKey); try{ Entity pointCloud2 = datastore.prepare(query).asSingleEntity(); if(pointCloud2 == null) { ServletOutputStream out = response.getOutputStream(); out.print("Can't find point cloud "+ keyStr + "\n"); out.flush(); return; } PointCloud2 cloud = new PointCloud2(); cloud.width = Integer.valueOf(((Long) pointCloud2.getProperty("width")).intValue()); cloud.height = Integer.valueOf(((Long) pointCloud2.getProperty("height")).intValue()); cloud.is_bigendian = (Boolean) pointCloud2.getProperty("is_bigendian"); cloud.row_step = Integer.valueOf(((Long) pointCloud2.getProperty("row_step")).intValue()); cloud.is_dense = (Boolean) pointCloud2.getProperty("is_dense"); Filter filter = new FilterPredicate("cloud", FilterOperator.EQUAL, keyStr); Query fieldQuery = new Query("PointField").setFilter(filter); PreparedQuery fields = datastore.prepare(fieldQuery); List<Entity>lFields = fields.asList(FetchOptions.Builder.withDefaults()); cloud.fields = new PointField[lFields.size()]; int i; for(i = 0; i < lFields.size(); i++){ int idx = ((Long) lFields.get(i).getProperty("idx")).intValue(); cloud.fields[idx] = new PointField(); cloud.fields[idx].count = Integer.valueOf(((Long) lFields.get(i).getProperty("count")).intValue()); cloud.fields[idx].offset = Integer.valueOf(((Long) lFields.get(i).getProperty("offset")).intValue()); cloud.fields[idx].datatype = Byte.valueOf(((Long) lFields.get(i).getProperty("datatype")).byteValue()); cloud.fields[idx].name = (String) lFields.get(i).getProperty("name"); } BlobKey blobKey =(BlobKey) pointCloud2.getProperty("data"); ServletOutputStream out = response.getOutputStream(); out.print("# .PCD v0.7 - Point Cloud Data file format\n"); out.print("VERSION 0.7\n"); out.print(getFieldstr(cloud)+"\n"); out.print(getSizeStr(cloud)+"\n"); out.print(getTypeStr(cloud)+"\n"); out.print(getCountStr(cloud)+"\n"); out.print("WIDTH " + cloud.width+"\n" ); out.print("HEIGHT " + cloud.height+"\n"); out.print("VIEWPOINT 0 0 0 1 0 0 0\n"); out.print("POINTS " + cloud.width * cloud.height + "\n"); out.print("DATA binary\n"); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey); if( blobInfo == null ) return; if( blobInfo.getSize() > Integer.MAX_VALUE ) throw new RuntimeException("This method can only process blobs up to " + Integer.MAX_VALUE + " bytes"); int blobSize = (int)blobInfo.getSize(); int chunks = (int)Math.ceil(((double)blobSize / BlobstoreService.MAX_BLOB_FETCH_SIZE)); int startPointer = 0; int endPointer; for(i = 0; i < chunks; i++ ){ endPointer = Math.min(blobSize - 1, startPointer + BlobstoreService.MAX_BLOB_FETCH_SIZE - 1); byte[] bytes = blobstoreService.fetchData(blobKey, startPointer, endPointer); out.write(bytes); startPointer = endPointer + 1; } // out.write(cloud.data.getBytes()); out.flush(); } catch(IndexOutOfBoundsException e) { ServletOutputStream out = response.getOutputStream(); out.println("can't fetch pointcloud "+ keyStr); out.flush(); } } private String getTypeStr(PointCloud2 cloud) { String typeStr = new String("TYPE"); for(PointField field: cloud.fields){ switch(field.datatype){ case(1): case(3): case(5): typeStr = typeStr + " I"; break; case(2): case(4): case(6): typeStr = typeStr + " U"; break; case(7): case(8): typeStr = typeStr + " F"; break; } } return typeStr; } private String getCountStr(PointCloud2 cloud) { String countStr = new String("COUNT"); for(PointField field: cloud.fields){ countStr = countStr + " " + field.count; } return countStr; } private String getSizeStr(PointCloud2 cloud) { String typeStr = new String("SIZE"); for(PointField field: cloud.fields){ switch(field.datatype){ case(1): case(2): typeStr = typeStr + " 1"; break; case(3): case(4): typeStr = typeStr + " 2"; break; case(5): case(6): case(7): case(8): typeStr = typeStr + " 4"; break; } } return typeStr; } private String getFieldstr(PointCloud2 cloud) { String fieldStr = new String("FIELDS"); for(PointField field: cloud.fields){ fieldStr = fieldStr + " " + field.name; } return fieldStr; } }
bsd-3-clause
vivo-project/Vitro
api/src/main/java/edu/cornell/mannlib/vitro/webapp/modelaccess/impl/keys/OntModelKey.java
1164
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.vitro.webapp.modelaccess.impl.keys; import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.LanguageOption; import edu.cornell.mannlib.vitro.webapp.utils.logging.ToString; /** * An immutable key for storing and retrieving OntModels. * * In addition to the usual options, it has a name, which adds to the * uniqueness. */ public final class OntModelKey extends ModelAccessKey { private final String name; private final int hashCode; public OntModelKey(String name, LanguageOption... options) { super(findLanguageOption(options)); this.name = name; this.hashCode = super.hashCode() ^ name.hashCode(); } public String getName() { return name; } @Override public LanguageOption getLanguageOption() { return super.getLanguageOption(); } @Override public boolean equals(Object obj) { return super.equals(obj) && ((OntModelKey) obj).name.equals(this.name); } @Override public int hashCode() { return hashCode; } @Override public String toString() { return super.toString() + " " + ToString.modelName(name); } }
bsd-3-clause
pohh-mell/BeerHousePOS
src/ee/ut/math/tvt/salessystem/service/HibernateDataService.java
1610
package ee.ut.math.tvt.salessystem.service; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import org.apache.log4j.Logger; import org.hibernate.Session; import ee.ut.math.tvt.salessystem.domain.data.Order; import ee.ut.math.tvt.salessystem.domain.data.SoldItem; import ee.ut.math.tvt.salessystem.domain.data.StockItem; import ee.ut.math.tvt.salessystem.util.HibernateUtil; @SuppressWarnings("unchecked") public class HibernateDataService { private static final Logger log = Logger .getLogger(HibernateDataService.class); private Session session = HibernateUtil.currentSession(); public List<SoldItem> getSoldItems() { List<SoldItem> result = new ArrayList<SoldItem>(); try { result = session.createQuery("from SOLDITEM").list(); } catch (Throwable ex) { log.error("No database connection!"); JOptionPane.showMessageDialog(null, "Unable to connect to the database!"); } return result; } public List<StockItem> getStockItems() { List<StockItem> result = new ArrayList<StockItem>(); try { result = session.createQuery("from STOCKITEM").list(); } catch (Throwable ex) { log.error("No database connection!"); JOptionPane.showMessageDialog(null, "Unable to connect to the database!"); } return result; } public List<Order> getOrders() { List<Order> result = new ArrayList<Order>(); try { result = session.createQuery("from ORDER").list(); } catch (Throwable ex) { log.error("No database connection!"); JOptionPane.showMessageDialog(null, "Unable to connect to the database!"); } return result; } }
bsd-3-clause
NCIP/caintegrator
caintegrator-war/src/gov/nih/nci/caintegrator/application/query/GenomicQueryHandler.java
17653
/** * Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caintegrator/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.application.query; import gov.nih.nci.caintegrator.application.arraydata.ArrayDataService; import gov.nih.nci.caintegrator.application.arraydata.ArrayDataValueType; import gov.nih.nci.caintegrator.application.arraydata.ArrayDataValues; import gov.nih.nci.caintegrator.application.arraydata.DataRetrievalRequest; import gov.nih.nci.caintegrator.common.HibernateUtil; import gov.nih.nci.caintegrator.common.QueryUtil; import gov.nih.nci.caintegrator.data.CaIntegrator2Dao; import gov.nih.nci.caintegrator.domain.application.EntityTypeEnum; import gov.nih.nci.caintegrator.domain.application.GenomicDataQueryResult; import gov.nih.nci.caintegrator.domain.application.GenomicDataResultColumn; import gov.nih.nci.caintegrator.domain.application.GenomicDataResultRow; import gov.nih.nci.caintegrator.domain.application.GenomicDataResultValue; import gov.nih.nci.caintegrator.domain.application.Query; import gov.nih.nci.caintegrator.domain.application.ResultRow; import gov.nih.nci.caintegrator.domain.application.ResultTypeEnum; import gov.nih.nci.caintegrator.domain.application.SegmentDataResultValue; import gov.nih.nci.caintegrator.domain.genomic.AbstractReporter; import gov.nih.nci.caintegrator.domain.genomic.ArrayData; import gov.nih.nci.caintegrator.domain.genomic.GenomeBuildVersionEnum; import gov.nih.nci.caintegrator.domain.genomic.Platform; import gov.nih.nci.caintegrator.domain.genomic.ReporterList; import gov.nih.nci.caintegrator.domain.genomic.ReporterTypeEnum; import gov.nih.nci.caintegrator.domain.genomic.SegmentData; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.google.common.collect.Maps; /** * Runs queries that return <code>GenomicDataQueryResults</code>. */ class GenomicQueryHandler { private static final float DECIMAL_100 = 100.0f; private final Query query; private final CaIntegrator2Dao dao; private final ArrayDataService arrayDataService; GenomicQueryHandler(Query query, CaIntegrator2Dao dao, ArrayDataService arrayDataService) { this.query = query; this.dao = dao; this.arrayDataService = arrayDataService; } GenomicDataQueryResult execute() throws InvalidCriterionException { if (ResultTypeEnum.COPY_NUMBER.equals(query.getResultType())) { return createCopyNumberResult(); } ArrayDataValues values = getDataValues(); return createGeneExpressionResult(values); } Collection<SegmentData> retrieveSegmentDataQuery() throws InvalidCriterionException { Collection<ArrayData> arrayDatas = getMatchingArrayDatas(); return getMatchingSegmentDatas(arrayDatas); } private GenomicDataQueryResult createGeneExpressionResult(ArrayDataValues values) { GenomicDataQueryResult result = new GenomicDataQueryResult(); createGeneExpressionResultRows(result, values); Map<Long, GenomicDataResultRow> reporterIdToRowMap = createReporterIdToRowMap(result); for (ArrayData arrayData : values.getArrayDatas()) { addToGeneExpressionResult(values, result, reporterIdToRowMap, arrayData); } result.setQuery(query); return result; } private GenomicDataQueryResult createCopyNumberResult() throws InvalidCriterionException { GenomicDataQueryResult result = new GenomicDataQueryResult(); Collection<ArrayData> arrayDatas = getMatchingArrayDatas(); Collection<SegmentData> segmentDatas = getMatchingSegmentDatas(arrayDatas); Map<SegmentData, GenomicDataResultRow> segmentDataToRowMap = createCopyNumberResultRows(result, arrayDatas, segmentDatas); CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); result.setHasCriterionSpecifiedValues(criterionHandler.hasCriterionSpecifiedSegmentValues()); for (ArrayData arrayData : arrayDatas) { addToCopyNumberResult(result, segmentDataToRowMap, arrayData, criterionHandler); } result.setQuery(query); return result; } private void addToCopyNumberResult(GenomicDataQueryResult result, Map<SegmentData, GenomicDataResultRow> segmentDataToRowMap, ArrayData arrayData, CompoundCriterionHandler criterionHandler) { GenomicDataResultColumn column = result.addColumn(); //Just take the 1st sample aquisition column.setSampleAcquisition(arrayData.getSample().getSampleAcquisitions().iterator().next()); for (SegmentData segmentData : segmentDataToRowMap.keySet()) { if (segmentData.getArrayData().equals(arrayData)) { GenomicDataResultRow row = segmentDataToRowMap.get(segmentData); GenomicDataResultValue value = new GenomicDataResultValue(); value.setColumn(column); value.setValue(twoDecimalPoint(segmentData.getSegmentValue())); value.setCallsValue(segmentData.getCallsValue()); value.setProbabilityAmplification(twoDecimalPoint(segmentData.getProbabilityAmplification())); value.setProbabilityGain(twoDecimalPoint(segmentData.getProbabilityGain())); value.setProbabilityLoss(twoDecimalPoint(segmentData.getProbabilityLoss())); value.setProbabilityNormal(twoDecimalPoint(segmentData.getProbabilityNormal())); checkMeetsCopyNumberCriterion(result, criterionHandler, row, value); row.getValues().add(value); } } } private float twoDecimalPoint(float floatValue) { return Math.round(floatValue * DECIMAL_100) / DECIMAL_100; } private Map<SegmentData, GenomicDataResultRow> createCopyNumberResultRows( GenomicDataQueryResult result, Collection<ArrayData> arrayDatas, Collection<SegmentData> segmentDatas) { Map<Integer, Map<Integer, GenomicDataResultRow>> startEndPositionResultRowMap = new HashMap<Integer, Map<Integer, GenomicDataResultRow>>(); Map<SegmentData, GenomicDataResultRow> segmentDataToRowMap = new HashMap<SegmentData, GenomicDataResultRow>(); GenomeBuildVersionEnum genomeVersion = query.getCopyNumberPlatform().getGenomeVersion(); boolean isGenomeVersionMapped = dao.isGenomeVersionMapped(genomeVersion); for (SegmentData segmentData : segmentDatas) { if (arrayDatas.contains(segmentData.getArrayData())) { int startPosition = segmentData.getLocation().getStartPosition(); int endPosition = segmentData.getLocation().getEndPosition(); if (!startEndPositionResultRowMap.containsKey(startPosition)) { startEndPositionResultRowMap.put(startPosition, new HashMap<Integer, GenomicDataResultRow>()); } if (!startEndPositionResultRowMap.get(startPosition).containsKey(endPosition)) { GenomicDataResultRow row = new GenomicDataResultRow(); addSegmentDataToRow(segmentData, row, isGenomeVersionMapped, genomeVersion); startEndPositionResultRowMap.get(startPosition).put(endPosition, row); result.getRowCollection().add(row); } segmentDataToRowMap.put(segmentData, startEndPositionResultRowMap.get(startPosition).get(endPosition)); } } return segmentDataToRowMap; } private void addSegmentDataToRow(SegmentData segmentData, GenomicDataResultRow row, boolean isGenomeVersionMapped, GenomeBuildVersionEnum genomeVersion) { row.setSegmentDataResultValue(new SegmentDataResultValue()); row.getSegmentDataResultValue().setChromosomalLocation(segmentData.getLocation()); if (isGenomeVersionMapped) { row.getSegmentDataResultValue().getGenes().addAll( dao.findGenesByLocation(segmentData.getLocation().getChromosome(), segmentData.getLocation() .getStartPosition(), segmentData.getLocation().getEndPosition(), genomeVersion)); } } private void addToGeneExpressionResult(ArrayDataValues values, GenomicDataQueryResult result, Map<Long, GenomicDataResultRow> reporterIdToRowMap, ArrayData arrayData) { CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); result.setHasCriterionSpecifiedValues(criterionHandler.hasCriterionSpecifiedReporterValues()); GenomicDataResultColumn column = result.addColumn(); //Take the 1st sample acquisition column.setSampleAcquisition(arrayData.getSample().getSampleAcquisitions().iterator().next()); for (AbstractReporter reporter : values.getReporters()) { if (query.isNeedsGenomicHighlighting()) { HibernateUtil.loadCollection(reporter.getGenes()); HibernateUtil.loadCollection(reporter.getSamplesHighVariance()); } GenomicDataResultRow row = reporterIdToRowMap.get(reporter.getId()); GenomicDataResultValue value = new GenomicDataResultValue(); value.setColumn(column); float floatValue = values.getFloatValue(arrayData, reporter, ArrayDataValueType.EXPRESSION_SIGNAL); value.setValue(twoDecimalPoint(floatValue)); if (query.isNeedsGenomicHighlighting()) { checkMeetsGeneExpressionCriterion(result, criterionHandler, reporter, row, value); checkHighVariance(result, arrayData, reporter, value); } row.getValues().add(value); } } private void checkMeetsGeneExpressionCriterion(GenomicDataQueryResult result, CompoundCriterionHandler criterionHandler, AbstractReporter reporter, GenomicDataResultRow row, GenomicDataResultValue value) { if (result.isHasCriterionSpecifiedValues()) { value.setCriteriaMatchType(criterionHandler. getGenomicValueMatchCriterionType(reporter.getGenes(), value.getValue())); row.setHasMatchingValues(row.isHasMatchingValues() || value.isMeetsCriterion()); } } private void checkMeetsCopyNumberCriterion(GenomicDataQueryResult result, CompoundCriterionHandler criterionHandler, GenomicDataResultRow row, GenomicDataResultValue value) { if (result.isHasCriterionSpecifiedValues()) { if (criterionHandler.hasCriterionSpecifiedSegmentValues() && !criterionHandler.hasCriterionSpecifiedSegmentCallsValues()) { value.setCriteriaMatchType(criterionHandler.getSegmentValueMatchCriterionType(value.getValue())); } else { value.setCriteriaMatchType(criterionHandler. getSegmentCallsValueMatchCriterionType(value.getCallsValue())); } row.setHasMatchingValues(row.isHasMatchingValues() || value.isMeetsCriterion()); } } private void checkHighVariance(GenomicDataQueryResult result, ArrayData arrayData, AbstractReporter reporter, GenomicDataResultValue value) { if (reporter.getSamplesHighVariance().contains(arrayData.getSample())) { value.setHighVariance(true); result.setHasHighVarianceValues(true); } } private Map<Long, GenomicDataResultRow> createReporterIdToRowMap(GenomicDataQueryResult result) { Map<Long, GenomicDataResultRow> rowMap = Maps.newHashMapWithExpectedSize(result.getRowCollection().size()); for (GenomicDataResultRow row : result.getRowCollection()) { rowMap.put(row.getReporter().getId(), row); } return rowMap; } private void createGeneExpressionResultRows(GenomicDataQueryResult result, ArrayDataValues values) { for (AbstractReporter reporter : values.getReporters()) { GenomicDataResultRow row = new GenomicDataResultRow(); row.setReporter(reporter); result.getRowCollection().add(row); } } private ArrayDataValues getDataValues() throws InvalidCriterionException { Collection<ArrayData> arrayDatas = getMatchingArrayDatas(); Collection<AbstractReporter> reporters = getMatchingReporters(arrayDatas); return getDataValues(arrayDatas, reporters); } private ArrayDataValues getDataValues(Collection<ArrayData> arrayDatas, Collection<AbstractReporter> reporters) { DataRetrievalRequest request = new DataRetrievalRequest(); request.addReporters(reporters); request.addArrayDatas(arrayDatas); request.addType(ArrayDataValueType.EXPRESSION_SIGNAL); if (QueryUtil.isFoldChangeQuery(query) && !query.isAllGenomicDataQuery()) { return arrayDataService.getFoldChangeValues(request, query); } else { return arrayDataService.getData(request); } } private Collection<ArrayData> getMatchingArrayDatas() throws InvalidCriterionException { CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); Set<EntityTypeEnum> samplesOnly = new HashSet<EntityTypeEnum>(); samplesOnly.add(EntityTypeEnum.SAMPLE); Set<ResultRow> rows = criterionHandler.getMatches(dao, arrayDataService, query, samplesOnly); return getArrayDatas(rows); } private void addMatchesFromArrayDatas(Set<ArrayData> matchingArrayDatas, Collection<ArrayData> candidateArrayDatas) { Platform platform = query.getGeneExpressionPlatform(); ReporterTypeEnum reporterTypeToUse = query.getReporterType(); if (ResultTypeEnum.COPY_NUMBER == query.getResultType()) { platform = query.getCopyNumberPlatform(); reporterTypeToUse = ReporterTypeEnum.DNA_ANALYSIS_REPORTER; } for (ArrayData arrayData : candidateArrayDatas) { for (ReporterList reporterList : arrayData.getReporterLists()) { if (isMatchingArrayData(platform, reporterTypeToUse, arrayData, reporterList)) { matchingArrayDatas.add(arrayData); } } } } private boolean isMatchingArrayData(Platform platform, ReporterTypeEnum reporterType, ArrayData arrayData, ReporterList reporterList) { return reporterType == reporterList.getReporterType() && platform.equals(arrayData.getArray().getPlatform()); } private Set<ArrayData> getArrayDatas(Set<ResultRow> rows) { Set<ArrayData> arrayDatas = new HashSet<ArrayData>(); for (ResultRow row : rows) { if (row.getSampleAcquisition() != null) { Collection<ArrayData> candidateArrayDatas = row.getSampleAcquisition().getSample().getArrayDataCollection(); addMatchesFromArrayDatas(arrayDatas, candidateArrayDatas); } } return arrayDatas; } private Collection<AbstractReporter> getMatchingReporters(Collection<ArrayData> arrayDatas) { CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); if (arrayDatas.isEmpty()) { return Collections.emptySet(); } else if (criterionHandler.hasReporterCriterion() && !query.isAllGenomicDataQuery()) { return criterionHandler.getReporterMatches(dao, query.getSubscription().getStudy(), query.getReporterType(), query.getGeneExpressionPlatform()); } else { return getAllReporters(arrayDatas); } } private Collection<AbstractReporter> getAllReporters(Collection<ArrayData> arrayDatas) { HashSet<AbstractReporter> reporters = new HashSet<AbstractReporter>(); for (ArrayData arrayData : arrayDatas) { arrayData = dao.get(arrayData.getId(), ArrayData.class); reporters.addAll(arrayData.getReporters()); } return reporters; } private Collection<SegmentData> getMatchingSegmentDatas(Collection<ArrayData> arrayDatas) throws InvalidCriterionException { CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); if (arrayDatas.isEmpty()) { return Collections.emptySet(); } else if (criterionHandler.hasSegmentDataCriterion() && !query.isAllGenomicDataQuery()) { return criterionHandler.getSegmentDataMatches(dao, query.getSubscription().getStudy(), query.getCopyNumberPlatform()); } else { return getAllSegmentDatas(arrayDatas); } } private Collection<SegmentData> getAllSegmentDatas(Collection<ArrayData> arrayDatas) { HashSet<SegmentData> segmentDatas = new HashSet<SegmentData>(); for (ArrayData arrayData : arrayDatas) { arrayData = dao.get(arrayData.getId(), ArrayData.class); segmentDatas.addAll(arrayData.getSegmentDatas()); } return segmentDatas; } }
bsd-3-clause
dougqh/JAK
net.dougqh.jak.core/src/net/dougqh/jak/TypeDescriptor.java
1479
package net.dougqh.jak; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; public final class TypeDescriptor { private final int flags; private final String name; private final TypeVariable<?>[] typeVars; private final Type parentType; private final Type[] interfaceTypes; TypeDescriptor( final int flags, final String name, final TypeVariable<?>[] typeVars, final Type parentType, final Type[] interfaceTypes ) { this.flags = flags; this.name = name; this.typeVars = typeVars; this.parentType = parentType; this.interfaceTypes = interfaceTypes; } public final JavaVersion version() { return JavaVersion.getDefault(); } public final int flags() { return this.flags; } public final String name() { return this.name; } public final Type parentType() { return this.parentType; } public final Type[] interfaceTypes() { return this.interfaceTypes; } public final TypeVariable<?>[] typeVars() { return this.typeVars; } public final TypeDescriptor qualify( final String packageName ) { return new TypeDescriptor( this.flags, packageName + '.' + this.name, this.typeVars, this.parentType, this.interfaceTypes ); } public final TypeDescriptor innerType( final String className, final int additionalFlags ) { return new TypeDescriptor( this.flags | additionalFlags, className + '$' + this.name, this.typeVars, this.parentType, this.interfaceTypes ); } }
bsd-3-clause
dimitarp/basex
basex-core/src/main/java/org/basex/query/util/pkg/PkgComponent.java
445
package org.basex.query.util.pkg; import java.io.*; /** * Package component. * * @author BaseX Team 2005-20, BSD License * @author Rositsa Shadura */ final class PkgComponent { /** Namespace URI. */ String uri; /** Component file. */ String file; /** * Extracts the component file name from the component path. * @return name */ String name() { return file.substring(file.lastIndexOf(File.separator) + 1); } }
bsd-3-clause
kstreee/infer
infer/tests/endtoend/objc/BlockCaptureCXXRefTest.java
1797
/* * Copyright (c) 2016 - present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package endtoend.objc; import static org.hamcrest.MatcherAssert.assertThat; import static utils.matchers.ResultContainsExactly.containsExactly; import com.google.common.collect.ImmutableList; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.io.IOException; import utils.DebuggableTemporaryFolder; import utils.InferException; import utils.InferResults; import utils.InferRunner; public class BlockCaptureCXXRefTest { public static final String FILE = "infer/tests/codetoanalyze/objcpp/errors/blocks/block.mm"; private static ImmutableList<String> inferCmd; public static final String REFERENCE_CAPTURED = "CXX_REFERENCE_CAPTURED_IN_OBJC_BLOCK"; @ClassRule public static DebuggableTemporaryFolder folder = new DebuggableTemporaryFolder(); @BeforeClass public static void runInfer() throws InterruptedException, IOException { inferCmd = InferRunner.createObjCPPInferCommand(folder, FILE); } @Test public void whenInferRunsOnNavigateToURLInBackgroundThenNPEIsFound() throws InterruptedException, IOException, InferException { InferResults inferResults = InferRunner.runInferObjC(inferCmd); String[] procedures = { "foo:", "foo3:param2:" }; assertThat( "Results should contain the expected C++ reference captured in block", inferResults, containsExactly( REFERENCE_CAPTURED, FILE, procedures ) ); } }
bsd-3-clause
Caleydo/caleydo
org.caleydo.ui/src/org/caleydo/core/view/opengl/picking/IPickingLabelProvider.java
691
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license ******************************************************************************/ package org.caleydo.core.view.opengl.picking; /** * Provides a label that depends on a {@link Pick}. * * @author Christian Partl * */ public interface IPickingLabelProvider { /** * Returns a label depending on the provided {@link Pick}. * * @param pick * @return */ public String getLabel(Pick pick); }
bsd-3-clause
NCIP/cagrid-core
integration-tests/projects/sdk42StyleTests/src/org/cagrid/tests/data/styles/cacore42/story/SDK42DataServiceSystemTests.java
4639
/** *============================================================================ * Copyright The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, and * Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-core/LICENSE.txt for details. *============================================================================ **/ package org.cagrid.tests.data.styles.cacore42.story; import gov.nih.nci.cagrid.common.Utils; import java.io.File; import junit.framework.TestResult; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class SDK42DataServiceSystemTests { private static Log LOG = LogFactory.getLog(SDK42DataServiceSystemTests.class); private static File tempApplicationDir; @BeforeClass public static void setUp() throws Throwable { // create a temporary directory for the SDK application to package things in tempApplicationDir = File.createTempFile("SdkExample", "temp"); tempApplicationDir.delete(); tempApplicationDir.mkdirs(); LOG.debug("Created temp application base dir: " + tempApplicationDir.getAbsolutePath()); // throw out the ivy cache dirs used by the SDK LOG.debug("Destroying SDK ivy cache"); NukeIvyCacheStory nukeStory = new NukeIvyCacheStory(); nukeStory.runBare(); // create the caCORE SDK example project LOG.debug("Running caCORE SDK example project creation story"); CreateExampleProjectStory createExampleStory = new CreateExampleProjectStory(tempApplicationDir, false); createExampleStory.runBare(); } @Test public void localSDKApiTests() throws Throwable { // create and run a caGrid Data Service using the SDK's local API LOG.debug("Running data service using local API story"); SDK42StyleLocalApiStory localApiStory = new SDK42StyleLocalApiStory(false, false); localApiStory.runBare(); } @Test public void secureLocalSDKApiTests() throws Throwable { // create and run a secure caGrid Data Service using the SDK's local API LOG.debug("Running secure data service using local API story"); SDK42StyleLocalApiStory secureLocalApiStory = new SDK42StyleLocalApiStory(true, false); secureLocalApiStory.runBare(); } @Test public void remoteSDKApiTests() throws Throwable { // create and run a caGrid Data Service using the SDK's remote API LOG.debug("Running data service using remote API story"); SDK42StyleRemoteApiStory remoteApiStory = new SDK42StyleRemoteApiStory(false); remoteApiStory.runBare(); } @Test public void secureRemoteSDKApiTests() throws Throwable { // create and run a secure caGrid Data Service using the SDK's remote API LOG.debug("Running secure data service using remote API story"); SDK42StyleRemoteApiStory secureRemoteApiStory = new SDK42StyleRemoteApiStory(true); secureRemoteApiStory.runBare(); } @Test public void localSDKApiWithCsmTests() throws Throwable { LOG.debug("Running caCORE SDK example project with CSM creation story"); CreateExampleProjectStory createExampleWithCsmStory = new CreateExampleProjectStory(tempApplicationDir, true); createExampleWithCsmStory.runBare(); // create and run a caGrid Data Service using the SDK's local API LOG.debug("Running secure data service using local API and CSM story"); SDK42StyleLocalApiStory localApiWithCsmStory = new SDK42StyleLocalApiStory(true, true); localApiWithCsmStory.runBare(); } @AfterClass public static void cleanUp() { LOG.debug("Cleaning up after tests"); // throw away the temp sdk dir LOG.debug("Deleting temp application base dir: " + tempApplicationDir.getAbsolutePath()); Utils.deleteDir(tempApplicationDir); } public static void main(String[] args) { TestRunner runner = new TestRunner(); TestResult result = runner.doRun(new TestSuite(SDK42DataServiceSystemTests.class)); System.exit(result.errorCount() + result.failureCount()); } }
bsd-3-clause
endlessm/chromium-browser
chrome/android/javatests/src/org/chromium/chrome/browser/SafeBrowsingTest.java
4607
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser; import android.support.test.InstrumentationRegistry; import android.support.test.filters.MediumTest; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.components.safe_browsing.SafeBrowsingApiBridge; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.test.util.Criteria; import org.chromium.content_public.browser.test.util.CriteriaHelper; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.net.test.EmbeddedTestServer; import org.chromium.ui.base.PageTransition; import java.util.concurrent.Callable; /** * Test integration with the SafeBrowsingApiHandler. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public final class SafeBrowsingTest { @Rule public ChromeActivityTestRule<ChromeActivity> mActivityTestRule = new ChromeActivityTestRule<>(ChromeActivity.class); private EmbeddedTestServer mTestServer; /** * Wait for an interstitial (or lack thereof) to be shown. * Disclaimer: when |shouldBeShown| is false, it isn't clear that the interstitial would never * be shown at some point in the near future. There isn't currently a way to wait for some event * that would indicate this, unfortunately. */ private void waitForInterstitial(final boolean shouldBeShown) { CriteriaHelper.pollUiThread(Criteria.equals(shouldBeShown, new Callable<Boolean>() { @Override public Boolean call() { // TODO(carlosil): For now, we check the presence of an interstitial through the // title since isShowingInterstitialPage does not work with committed interstitials. // Once we fully migrate to committed interstitials, this should be changed to a // more robust check. return getWebContents().getTitle().equals("Security error"); } })); } private WebContents getWebContents() { return mActivityTestRule.getActivity().getCurrentWebContents(); } /* * Loads a URL in the current tab without waiting for the load to finish. * This is necessary because pages with interstitials do not finish loading. */ private void loadUrlNonBlocking(String url) { Tab tab = mActivityTestRule.getActivity().getActivityTab(); TestThreadUtils.runOnUiThreadBlocking( (Runnable) () -> tab.loadUrl(new LoadUrlParams(url, PageTransition.TYPED))); } @Before public void setUp() { // Create a new temporary instance to ensure the Class is loaded. Otherwise we will get a // ClassNotFoundException when trying to instantiate during startup. SafeBrowsingApiBridge.setSafeBrowsingHandlerType( new MockSafeBrowsingApiHandler().getClass()); } @After public void tearDown() { if (mTestServer != null) { mTestServer.stopAndDestroyServer(); } MockSafeBrowsingApiHandler.clearMockResponses(); } @Test @MediumTest public void noInterstitialPage() throws Exception { mTestServer = EmbeddedTestServer.createAndStartServer(InstrumentationRegistry.getContext()); mActivityTestRule.startMainActivityOnBlankPage(); String url = mTestServer.getURL("/chrome/test/data/android/about.html"); mActivityTestRule.loadUrl(url); waitForInterstitial(false); } @Test @MediumTest public void interstitialPage() throws Exception { mTestServer = EmbeddedTestServer.createAndStartServer(InstrumentationRegistry.getContext()); String url = mTestServer.getURL("/chrome/test/data/android/about.html"); MockSafeBrowsingApiHandler.addMockResponse(url, "{\"matches\":[{\"threat_type\":\"5\"}]}"); mActivityTestRule.startMainActivityOnBlankPage(); loadUrlNonBlocking(url); waitForInterstitial(true); } }
bsd-3-clause
tarchan/NanikaKit
src/com/mac/tarchan/nanika/shell/NanikaCanvas.java
4436
/* * Copyright (c) 2009 tarchan. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY TARCHAN ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL TARCHAN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of tarchan. */ package com.mac.tarchan.nanika.shell; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JPanel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * NanikaScope * * @author tarchan */ public class NanikaCanvas extends JPanel { /** シリアルバージョンID */ private static final long serialVersionUID = -8122309255321836447L; /** ログ */ private static final Log log = LogFactory.getLog(NanikaCanvas.class); /** シェル */ protected NanikaShell shell; /** サーフェス */ protected NanikaSurface surface; /** * シェルを設定します。 * * @param shell シェル */ public void setShell(NanikaShell shell) { this.shell = shell; } /** * 指定された ID のサーフェスに切り替えます。 * * @param id サーフェス ID */ public void setSurface(String id) { log.debug("id=" + id); surface = shell.getSurface(id); if (surface != null) { setSize(surface.getSize()); // if (surface.isAnimations()) // for (SerikoAnimation animation : surface.getAnimations()) // { //// new SerikoTimer(90, new ActionListener() // new SerikoTimer(animation, new ActionListener() // { // @Override // public void actionPerformed(ActionEvent e) // { // if (log.isTraceEnabled()) log.debug("repaint=" + surface.getID()); // repaint(); // } // }).start(); // } } } /** * @see javax.swing.JComponent#getPreferredSize() */ @Override public Dimension getPreferredSize() { return surface != null ? surface.getSize() : null; } /** * @see javax.swing.JComponent#getMaximumSize() */ @Override public Dimension getMaximumSize() { return getPreferredSize(); } /** * @see javax.swing.JComponent#getMinimumSize() */ @Override public Dimension getMinimumSize() { return getPreferredSize(); } /** * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) */ @Override protected void paintComponent(Graphics g) // public void paint(Graphics g) { if (surface == null) return; // g.clearRect(0, 0, getWidth(), getHeight()); if (surface != null) surface.draw((Graphics2D)g); // new Thread(new Runnable() // { // @Override // public void run() // { // try // { // if (log.isTraceEnabled()) log.debug("sleep"); // Thread.sleep(90); // if (log.isTraceEnabled()) log.debug("wakeup"); //// repaint(90); //// invalidate(); //// validate(); // repaint(); // } // catch (InterruptedException x) // { // // 何もしない // } // } // }).start(); } /** {@inheritDoc} */ @Override public String toString() { StringBuilder buf = new StringBuilder(super.toString()); buf.append("["); buf.append("surface="); buf.append(surface); buf.append("]"); return buf.toString(); } }
bsd-3-clause
xiGUAwanOU/Ingwer
src/test/java/net/xiguawanou/ingwer/TestUtility.java
381
package net.xiguawanou.ingwer; import org.junit.Assert; public class TestUtility { public static void assertAnimationEquals(Animation animation, int startFrame, int endFrame, float fps) { Assert.assertEquals(startFrame, animation.getStartFrame()); Assert.assertEquals(endFrame, animation.getEndFrame()); Assert.assertEquals(fps, animation.getFrameRate(), 0.001f); } }
bsd-3-clause
OBHITA/Consent2Share
ThirdParty/logback-audit/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditorAction.java
1850
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.audit.client.joran.action; import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.ActionException; import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.util.StatusPrinter; public class AuditorAction extends Action { static final String INTERNAL_DEBUG_ATTR = "debug"; boolean debugMode = false; public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { String debugAttrib = attributes.getValue(INTERNAL_DEBUG_ATTR); if ((debugAttrib == null) || debugAttrib.equals("") || debugAttrib.equals("false") || debugAttrib.equals("null")) { addInfo("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); } else { debugMode = true; } // if ((nameAttrib == null) || nameAttrib.equals("")) { // String errMsg = "Empty " + NAME_ATTRIBUTE + " attribute."; // addError(errMsg); // throw new ActionException(ActionException.SKIP_CHILDREN); // } // the context is appender attachable, so it is pushed on top of the stack ec.pushObject(getContext()); } public void end(InterpretationContext ec, String name) { if (debugMode) { addInfo("End of configuration."); StatusPrinter.print(context); } ec.popObject(); } }
bsd-3-clause
NCIP/calims
calims2-util/test/unit/java/gov/nih/nci/calims2/util/enumeration/I18nTestEnumeration.java
777
/*L * Copyright Moxie Informatics. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/calims/LICENSE.txt for details. */ /** * */ package gov.nih.nci.calims2.util.enumeration; import java.util.Locale; /** * @author viseem * */ public enum I18nTestEnumeration implements I18nEnumeration { /** Test value 1. */ VALUE1, /** Test value 2. */ VALUE2, /** Test value 3. */ VALUE3, /** Test value 4. */ VALUE4, /** Test value 5. */ VALUE5; /** * {@inheritDoc} */ public String getLocalizedValue(Locale locale) { return I18nEnumerationHelper.getLocalizedValue(I18nTestEnumerationBundle.class, locale, this); } /** * {@inheritDoc} */ public String getName() { return name(); } }
bsd-3-clause
cyclus/cyclist2
cyclist/src/edu/utexas/cycic/ConnectorLine.java
2469
package edu.utexas.cycic; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.text.Font; import javafx.scene.text.Text; public class ConnectorLine extends Line { { setStroke(Color.BLACK); } Line right = new Line(){ { setStrokeWidth(2); setStroke(Color.BLACK); } }; Line left = new Line(){ { setStrokeWidth(2); setStroke(Color.BLACK); } }; Line right1 = new Line(){ { setStrokeWidth(2); setStroke(Color.BLACK); } }; Line left1 = new Line(){ { setStrokeWidth(2); setStroke(Color.BLACK); } }; Text text = new Text(){ { setFill(Color.BLACK); setFont(new Font(20)); } }; public void updatePosition(){ double x1 = getEndX(); double y1 = getEndY(); double x2 = getStartX(); double y2 = getStartY(); right1.setStartX(x1 + (x2-x1)*0.33); right1.setStartY(y1 + (y2-y1)*0.33); right1.setEndX((x1 + (x2-x1)*0.38)+5.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); right1.setEndY((y1 + (y2-y1)*0.38)-5.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); left1.setStartX(x1 + (x2-x1)*0.33); left1.setStartY(y1 + (y2-y1)*0.33); left1.setEndX((x1 + (x2-x1)*0.38)-5.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); left1.setEndY((y1 + (y2-y1)*0.38)+5.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); right.setStartX(x1 + (x2-x1)*0.66); right.setStartY(y1 + (y2-y1)*0.66); right.setEndX((x1 + (x2-x1)*0.71)+5.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); right.setEndY((y1 + (y2-y1)*0.71)-5.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); left.setStartX(x1 + (x2-x1)*0.66); left.setStartY(y1 + (y2-y1)*0.66); left.setEndX((x1 + (x2-x1)*0.71)-5.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); left.setEndY((y1 + (y2-y1)*0.71)+5.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); text.setX(x1 + (x2-x1)*0.55+10.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); text.setY(y1 + (y2-y1)*0.55+10.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2))); } public void updateColor(Color color){ this.setStroke(color); right1.setStroke(color); right.setStroke(color); left1.setStroke(color); left.setStroke(color); text.setFill(color); } public void hideText(){ Cycic.pane.getChildren().remove(text); } public void showText(){ Cycic.pane.getChildren().add(text); } }
bsd-3-clause
Team2168/FRC2014_Main_Robot
src/org/team2168/commands/intake/IntakeSingleBall.java
688
package org.team2168.commands.intake; import org.team2168.RobotMap; import org.team2168.commands.winch.WaitUntilBallNotPresent; import org.team2168.commands.winch.WaitUntilBallPresent; import edu.wpi.first.wpilibj.command.CommandGroup; public class IntakeSingleBall extends CommandGroup { public IntakeSingleBall() { //Drive the motors to acquire ball addParallel(new IntakeDriveMotor( -RobotMap.intakeWheelVoltage.getDouble())); //wait until you see a ball addSequential(new WaitUntilBallPresent()); //wait until you don't see a ball addSequential(new WaitUntilBallNotPresent()); //stop intake motors addSequential(new IntakeDriveMotor(0.0), 0.1); } }
bsd-3-clause
sebastiangraf/treetank
interfacemodules/jax-rx/src/test/java/org/treetank/service/jaxrx/util/DOMHelper.java
3354
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * */ package org.treetank.service.jaxrx.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.testng.annotations.Guice; import org.treetank.testutil.ModuleFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * This class gets a stream and builds of it a Document object to perform tests * for an expected streaming result. * * @author Lukas Lewandowski, University of Konstanz * */ @Guice(moduleFactory = ModuleFactory.class) public final class DOMHelper { /** * private contructor. */ private DOMHelper() { // private no instantiation } /** * This method gets an output stream from the streaming output and converts * it to a Document type to perform test cases. * * @param output * The output stream that has to be packed into the document. * @return The parsed document. * @throws ParserConfigurationException * The error occurred. * @throws SAXException * XML parsing exception. * @throws IOException * An exception occurred. */ public static Document buildDocument(final ByteArrayOutputStream output) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final ByteArrayInputStream bais = new ByteArrayInputStream(output.toByteArray()); final Document document = docBuilder.parse(bais); return document; } }
bsd-3-clause
mikem2005/vijava
src/com/vmware/vim25/VmConfigInfo.java
3563
/*================================================================================ Copyright (c) 2009 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** @author Steve Jin (sjin@vmware.com) */ public class VmConfigInfo extends DynamicData { public VAppProductInfo[] product; public VAppPropertyInfo[] property; public VAppIPAssignmentInfo ipAssignment; public String[] eula; public VAppOvfSectionInfo[] ovfSection; public String[] ovfEnvironmentTransport; public boolean installBootRequired; public int installBootStopDelay; public VAppProductInfo[] getProduct() { return this.product; } public VAppPropertyInfo[] getProperty() { return this.property; } public VAppIPAssignmentInfo getIpAssignment() { return this.ipAssignment; } public String[] getEula() { return this.eula; } public VAppOvfSectionInfo[] getOvfSection() { return this.ovfSection; } public String[] getOvfEnvironmentTransport() { return this.ovfEnvironmentTransport; } public boolean isInstallBootRequired() { return this.installBootRequired; } public int getInstallBootStopDelay() { return this.installBootStopDelay; } public void setProduct(VAppProductInfo[] product) { this.product=product; } public void setProperty(VAppPropertyInfo[] property) { this.property=property; } public void setIpAssignment(VAppIPAssignmentInfo ipAssignment) { this.ipAssignment=ipAssignment; } public void setEula(String[] eula) { this.eula=eula; } public void setOvfSection(VAppOvfSectionInfo[] ovfSection) { this.ovfSection=ovfSection; } public void setOvfEnvironmentTransport(String[] ovfEnvironmentTransport) { this.ovfEnvironmentTransport=ovfEnvironmentTransport; } public void setInstallBootRequired(boolean installBootRequired) { this.installBootRequired=installBootRequired; } public void setInstallBootStopDelay(int installBootStopDelay) { this.installBootStopDelay=installBootStopDelay; } }
bsd-3-clause
Kendanware/onegui
onegui-core/src/main/java/com/kendanware/onegui/core/Validation.java
3116
/* * Copyright (c) 2015 Kendanware * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of onegui, Kendanware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.kendanware.onegui.core; import java.util.List; /** * Contains various validation methods. * * @author Daniel Johansson, Kendanware * @author Kenny Colliander Nordin, Kendanware * * @since 0.0.1 */ public class Validation { /** * Check that the id is unique. Scan the tree of components for the id * * @param id * the id to check * @throws IllegalArgumentException * if the id is invalid */ public static void checkId(final Component component, final String id) { if ((id == null) || id.trim().isEmpty()) { throw new IllegalArgumentException("Invalid id: " + id); } if (component == null) { return; } Component parent = component; while (parent.getParent() != null) { parent = parent.getParent(); } Validation.checkIdTraverse(parent, id); } protected static void checkIdTraverse(final Component component, final String id) { if (id.equals(component.getId())) { throw new IllegalArgumentException("Invalid id; already in use: " + id); } if (component instanceof Container) { final Container container = (Container) component; final List<Component> list = container.getChildren(); for (final Component child : list) { Validation.checkIdTraverse(child, id); } } } }
bsd-3-clause
NUBIC/psc-mirror
web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/accesscontrol/PscAuthorizedCommand.java
783
package edu.northwestern.bioinformatics.studycalendar.web.accesscontrol; import org.springframework.validation.Errors; import java.util.Collection; /** * @author Rhett Sutphin */ public interface PscAuthorizedCommand { /** * Return the set of authorizations describing a user which could have * access to the action described by this command. * <p> * The command is not guaranteed to be in a consistent state when this * method is called -- if there are binding problems, there could be * missing field values. This method should provide a best-effort * set of authorizations in that case. * * @see PscAuthorizedHandler * @param bindErrors */ Collection<ResourceAuthorization> authorizations(Errors bindErrors); }
bsd-3-clause
martijnvermaat/network-programming
assignment-3/Room.java
840
public class Room { private RoomType roomType; private boolean available; private String guest; public RoomType getRoomType() { return this.roomType; } public String getGuest() throws NotBookedException { if (isAvailable()) { throw new NotBookedException(); } return this.guest; } public boolean isAvailable() { return this.available; } synchronized public void book(String guest) throws NotAvailableException { if (!isAvailable()) { throw new NotAvailableException("This room is not available"); } this.available = false; this.guest = guest; } public Room (RoomType roomType) { this.roomType = roomType; this.available = true; this.guest = null; } }
bsd-3-clause
Parrot-Developers/libARDiscovery
JNI/java/com/parrot/arsdk/ardiscovery/ARDiscoveryDeviceService.java
8864
/* Copyright (C) 2014 Parrot SA Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Parrot nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * ARDiscoveryService.java * * Created on: * Author: */ package com.parrot.arsdk.ardiscovery; import android.os.Parcel; import android.os.Parcelable; import com.parrot.arsdk.arsal.ARSALPrint; public class ARDiscoveryDeviceService implements Parcelable { /** * */ private static String TAG = "ARDiscoveryDevice"; private String name; /**< Name of the device */ private int productID; /**< Specific product ID */ private ARDISCOVERY_NETWORK_TYPE_ENUM networkType; private Object device; /**< can by ARDiscoveryDeviceNetService or ARDiscoveryDeviceBLEService or ARDiscoveryDeviceUsbService*/ public static final Parcelable.Creator<ARDiscoveryDeviceService> CREATOR = new Parcelable.Creator<ARDiscoveryDeviceService>() { @Override public ARDiscoveryDeviceService createFromParcel(Parcel source) { return new ARDiscoveryDeviceService(source); } @Override public ARDiscoveryDeviceService[] newArray(int size) { return new ARDiscoveryDeviceService[size]; } }; public ARDiscoveryDeviceService () { name = ""; setDevice(null); productID = 0; networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_UNKNOWN; } public ARDiscoveryDeviceService (String name, Object device, int productID) { this.name = name; this.setDevice(device); this.productID = productID; } // Parcelling part public ARDiscoveryDeviceService(Parcel in) { this.name = in.readString(); this.productID = in.readInt(); this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.getFromValue(in.readInt()); switch(this.networkType) { case ARDISCOVERY_NETWORK_TYPE_NET: this.device = in.readParcelable(ARDiscoveryDeviceNetService.class.getClassLoader()); break; case ARDISCOVERY_NETWORK_TYPE_BLE: this.device = in.readParcelable(ARDiscoveryDeviceBLEService.class.getClassLoader()); break; case ARDISCOVERY_NETWORK_TYPE_USBMUX: this.device = in.readParcelable(ARDiscoveryDeviceUsbService.class.getClassLoader()); break; case ARDISCOVERY_NETWORK_TYPE_UNKNOWN: default: this.device = null; break; } } @Override public boolean equals(Object other) { boolean isEqual = true; if ( (other == null) || !(other instanceof ARDiscoveryDeviceService) ) { isEqual = false; } else if (other == this) { isEqual = true; } else { /* check */ ARDiscoveryDeviceService otherDevice = (ARDiscoveryDeviceService) other; if (this.getDevice() != otherDevice.getDevice()) { if((this.getDevice() != null) && (otherDevice.getDevice() != null)) { /* check if the devices are of same class */ if (this.networkType == otherDevice.networkType) { switch (this.networkType) { case ARDISCOVERY_NETWORK_TYPE_NET: /* if it is a NetDevice */ ARDiscoveryDeviceNetService deviceNetService = (ARDiscoveryDeviceNetService) this.getDevice(); ARDiscoveryDeviceNetService otherDeviceNetService = (ARDiscoveryDeviceNetService) otherDevice.getDevice(); if (!deviceNetService.equals(otherDeviceNetService)) { isEqual = false; } break; case ARDISCOVERY_NETWORK_TYPE_BLE: /* if it is a BLEDevice */ ARDiscoveryDeviceBLEService deviceBLEService = (ARDiscoveryDeviceBLEService) this.getDevice(); ARDiscoveryDeviceBLEService otherDeviceBLEService = (ARDiscoveryDeviceBLEService) otherDevice.getDevice(); if (!deviceBLEService.equals(otherDeviceBLEService)) { isEqual = false; } break; case ARDISCOVERY_NETWORK_TYPE_USBMUX: /* if it is a BLEDevice */ ARDiscoveryDeviceUsbService deviceUsbService = (ARDiscoveryDeviceUsbService) this.getDevice(); ARDiscoveryDeviceUsbService otherDeviceUsbService = (ARDiscoveryDeviceUsbService) otherDevice.getDevice(); if (!deviceUsbService.equals(otherDeviceUsbService)) { isEqual = false; } break; } } else { isEqual = false; } } else { isEqual = false; } } else { isEqual = false; } } return isEqual; } public String getName () { return name; } public void setName (String name) { this.name = name; } public Object getDevice () { return device; } public void setDevice (Object device) { this.device = device; if (device instanceof ARDiscoveryDeviceNetService) { this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_NET; } else if (device instanceof ARDiscoveryDeviceBLEService) { this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_BLE; } else if (device instanceof ARDiscoveryDeviceUsbService) { this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_USBMUX; } else { this.networkType = ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_UNKNOWN; } } public ARDISCOVERY_NETWORK_TYPE_ENUM getNetworkType() { return networkType; } public int getProductID () { return productID; } public void setProductID (int productID) { this.productID = productID; } @Override public int describeContents() { return 0; } @Override public String toString() { return "name="+name+", productID="+productID+", networkType="+networkType; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); dest.writeInt(this.productID); dest.writeInt(this.networkType.getValue()); if(this.networkType != ARDISCOVERY_NETWORK_TYPE_ENUM.ARDISCOVERY_NETWORK_TYPE_UNKNOWN) { dest.writeParcelable((Parcelable) this.device, flags); } } };
bsd-3-clause
magicDGS/gatk
src/test/java/org/broadinstitute/hellbender/tools/funcotator/dataSources/gencode/GencodeFuncotationUnitTest.java
18552
package org.broadinstitute.hellbender.tools.funcotator.dataSources.gencode; import org.broadinstitute.hellbender.GATKBaseTest; import org.broadinstitute.hellbender.exceptions.GATKException; import org.broadinstitute.hellbender.tools.funcotator.vcfOutput.VcfOutputRenderer; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; /** * * Unit test class for the {@link GencodeFuncotation} class. * Created by jonn on 9/1/17. */ public class GencodeFuncotationUnitTest extends GATKBaseTest { //================================================================================================================== // Helper Methods: private static GencodeFuncotation createGencodeFuncotation(final String hugoSymbol, final String ncbiBuild, final String chromosome, final int start, final int end, final GencodeFuncotation.VariantClassification variantClassification, final GencodeFuncotation.VariantClassification secondaryVariantClassification, final GencodeFuncotation.VariantType variantType, final String refAllele, final String tumorSeqAllele2, final String genomeChange, final String annotationTranscript, final String transcriptStrand, final Integer transcriptExon, final Integer transcriptPos, final String cDnaChange, final String codonChange, final String proteinChange, final Double gcContent, final String referenceContext, final List<String> otherTranscripts) { final GencodeFuncotation gencodeFuncotation = new GencodeFuncotation(); gencodeFuncotation.setVersion("TEST_VERSION"); gencodeFuncotation.setDataSourceName(GencodeFuncotationFactory.DEFAULT_NAME); gencodeFuncotation.setHugoSymbol( hugoSymbol ); gencodeFuncotation.setNcbiBuild( ncbiBuild ); gencodeFuncotation.setChromosome( chromosome ); gencodeFuncotation.setStart( start ); gencodeFuncotation.setEnd( end ); gencodeFuncotation.setVariantClassification( variantClassification ); gencodeFuncotation.setSecondaryVariantClassification(secondaryVariantClassification); gencodeFuncotation.setVariantType( variantType ); gencodeFuncotation.setRefAllele( refAllele ); gencodeFuncotation.setTumorSeqAllele2( tumorSeqAllele2 ); gencodeFuncotation.setGenomeChange( genomeChange ); gencodeFuncotation.setAnnotationTranscript( annotationTranscript ); gencodeFuncotation.setTranscriptStrand( transcriptStrand ); gencodeFuncotation.setTranscriptExonNumber( transcriptExon ); gencodeFuncotation.setTranscriptPos( transcriptPos ); gencodeFuncotation.setcDnaChange( cDnaChange ); gencodeFuncotation.setCodonChange( codonChange ); gencodeFuncotation.setProteinChange( proteinChange ); gencodeFuncotation.setGcContent( gcContent ); gencodeFuncotation.setReferenceContext( referenceContext ); gencodeFuncotation.setOtherTranscripts( otherTranscripts ); return gencodeFuncotation; } private static GencodeFuncotation setFuncotationFieldOverride( final GencodeFuncotation gencodeFuncotation, final String field, final String overrideValue) { final GencodeFuncotation otherGencodeFuncotation = new GencodeFuncotation(gencodeFuncotation); otherGencodeFuncotation.setFieldSerializationOverrideValue( field, overrideValue ); return otherGencodeFuncotation; } //================================================================================================================== // Data Providers: @DataProvider Object[][] provideForTestGetFieldNames() { //final GencodeFuncotation gencodeFuncotation, final LinkedHashSet<String> expected return new Object[][] { { createGencodeFuncotation("TESTGENE", "BUILD1", "chr1", 1, 100, GencodeFuncotation.VariantClassification.NONSENSE, GencodeFuncotation.VariantClassification.INTRON, GencodeFuncotation.VariantType.SNP, "A", "T", "big_%20_changes", "T1", "3'", 1, 1, "A", "ATC", "Lys", 1.0, null, Arrays.asList("ONE", "TWO", "THREE")), new LinkedHashSet<>( Arrays.asList("Gencode_TEST_VERSION_hugoSymbol", "Gencode_TEST_VERSION_ncbiBuild", "Gencode_TEST_VERSION_chromosome", "Gencode_TEST_VERSION_start", "Gencode_TEST_VERSION_end", "Gencode_TEST_VERSION_variantClassification", "Gencode_TEST_VERSION_secondaryVariantClassification", "Gencode_TEST_VERSION_variantType", "Gencode_TEST_VERSION_refAllele", "Gencode_TEST_VERSION_tumorSeqAllele1", "Gencode_TEST_VERSION_tumorSeqAllele2", "Gencode_TEST_VERSION_genomeChange", "Gencode_TEST_VERSION_annotationTranscript", "Gencode_TEST_VERSION_transcriptStrand", "Gencode_TEST_VERSION_transcriptExon", "Gencode_TEST_VERSION_transcriptPos", "Gencode_TEST_VERSION_cDnaChange", "Gencode_TEST_VERSION_codonChange", "Gencode_TEST_VERSION_proteinChange", "Gencode_TEST_VERSION_gcContent", "Gencode_TEST_VERSION_referenceContext", "Gencode_TEST_VERSION_otherTranscripts") ) }, }; } @DataProvider Object[][] provideForTestGetField() { //final GencodeFuncotation gencodeFuncotation, final String fieldName, final String expected final GencodeFuncotation gencodeFuncotation = createGencodeFuncotation("TESTGENE", "BUILD1", "chr1", 1, 100, GencodeFuncotation.VariantClassification.NONSENSE, GencodeFuncotation.VariantClassification.INTRON, GencodeFuncotation.VariantType.SNP, "A", "T", "big_%20_changes", "T1", "3'", 1, 1, "A", "ATC", "Lys", 1.0, "ATGCGCAT", Arrays.asList("ONE", "TWO", "THREE")); return new Object[][] { { gencodeFuncotation, "Gencode_TEST_VERSION_hugoSymbol", "TESTGENE" }, { gencodeFuncotation, "hugoSymbol", "TESTGENE" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_hugoSymbol", "GARBAGEDAY"), "hugoSymbol", "GARBAGEDAY" }, { gencodeFuncotation, "ncbiBuild", "BUILD1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_ncbiBuild", "OVERRIDE"), "ncbiBuild", "OVERRIDE" }, { gencodeFuncotation, "chromosome", "chr1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_chromosome", "OVERRIDE"), "chromosome", "OVERRIDE" }, { gencodeFuncotation, "start", "1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_start", "OVERRIDE"), "start", "OVERRIDE" }, { gencodeFuncotation, "end", "100" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_end", "OVERRIDE"), "end", "OVERRIDE" }, { gencodeFuncotation, "variantClassification", GencodeFuncotation.VariantClassification.NONSENSE.toString() }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_variantClassification", "OVERRIDE"), "variantClassification", "OVERRIDE" }, { gencodeFuncotation, "secondaryVariantClassification", GencodeFuncotation.VariantClassification.INTRON.toString() }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_secondaryVariantClassification", "OVERRIDE"), "secondaryVariantClassification", "OVERRIDE" }, { gencodeFuncotation, "variantType", GencodeFuncotation.VariantType.SNP.toString() }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_variantType", "OVERRIDE"), "variantType", "OVERRIDE" }, { gencodeFuncotation, "refAllele", "A" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_refAllele", "OVERRIDE"), "refAllele", "OVERRIDE" }, { gencodeFuncotation, "tumorSeqAllele1", "A" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_tumorSeqAllele1", "OVERRIDE"), "tumorSeqAllele1", "OVERRIDE" }, { gencodeFuncotation, "tumorSeqAllele2", "T" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_tumorSeqAllele2", "OVERRIDE"), "tumorSeqAllele2", "OVERRIDE" }, { gencodeFuncotation, "genomeChange", "big_%20_changes" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_genomeChange", "OVERRIDE"), "genomeChange", "OVERRIDE" }, { gencodeFuncotation, "annotationTranscript", "T1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_annotationTranscript", "OVERRIDE"), "annotationTranscript", "OVERRIDE" }, { gencodeFuncotation, "transcriptStrand", "3'" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_transcriptStrand", "OVERRIDE"), "transcriptStrand", "OVERRIDE" }, { gencodeFuncotation, "transcriptExon", "1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_transcriptExon", "OVERRIDE"), "transcriptExon", "OVERRIDE" }, { gencodeFuncotation, "transcriptPos", "1" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_transcriptPos", "OVERRIDE"), "transcriptPos", "OVERRIDE" }, { gencodeFuncotation, "cDnaChange", "A" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_cDnaChange", "OVERRIDE"), "cDnaChange", "OVERRIDE" }, { gencodeFuncotation, "codonChange", "ATC" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_codonChange", "OVERRIDE"), "codonChange", "OVERRIDE" }, { gencodeFuncotation, "proteinChange", "Lys" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_proteinChange", "OVERRIDE"), "proteinChange", "OVERRIDE" }, { gencodeFuncotation, "gcContent", "1.0" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_gcContent", "OVERRIDE"), "gcContent", "OVERRIDE" }, { gencodeFuncotation, "referenceContext", "ATGCGCAT" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_referenceContext", "OVERRIDE"), "referenceContext", "OVERRIDE" }, { gencodeFuncotation, "otherTranscripts", "ONE" + VcfOutputRenderer.OTHER_TRANSCRIPT_DELIMITER + "TWO" + VcfOutputRenderer.OTHER_TRANSCRIPT_DELIMITER + "THREE" }, { setFuncotationFieldOverride(gencodeFuncotation, "Gencode_TEST_VERSION_otherTranscripts", "OVERRIDE"), "otherTranscripts", "OVERRIDE" } }; } @DataProvider Object[][] provideForTestGetFieldFail() { //final GencodeFuncotation gencodeFuncotation, final String fieldName, final String expected final GencodeFuncotation gencodeFuncotation = createGencodeFuncotation("TESTGENE", "BUILD1", "chr1", 1, 100, GencodeFuncotation.VariantClassification.NONSENSE, GencodeFuncotation.VariantClassification.INTRON, GencodeFuncotation.VariantType.SNP, "A", "T", "big_%20_changes", "T1", "3'", 1, 1, "A", "ATC", "Lys", 1.0, "ATGCGCAT", Arrays.asList("ONE", "TWO", "THREE")); return new Object[][] { { gencodeFuncotation, "TESTFIELD_OMICRON" }, { gencodeFuncotation, "hugoSymmbol" }, { gencodeFuncotation, "GENCODE_hugoSymbol" }, }; } //================================================================================================================== // Tests: @Test(dataProvider = "provideForTestGetFieldNames") public void testGetFieldNames(final GencodeFuncotation gencodeFuncotation, final LinkedHashSet<String> expected) { Assert.assertEquals(gencodeFuncotation.getFieldNames(), expected); } @Test(dataProvider = "provideForTestGetField") public void testGetField(final GencodeFuncotation gencodeFuncotation, final String fieldName, final String expected) { Assert.assertEquals(gencodeFuncotation.getField(fieldName), expected); } @Test(dataProvider = "provideForTestGetFieldFail", expectedExceptions = GATKException.class) public void testGetFieldFail(final GencodeFuncotation gencodeFuncotation, final String fieldName) { gencodeFuncotation.getField(fieldName); } }
bsd-3-clause
daejunpark/jsaf
third_party/pmd/src/main/java/net/sourceforge/pmd/lang/java/rule/design/AccessorClassGenerationRule.java
12208
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression; import net.sourceforge.pmd.lang.java.ast.ASTArguments; import net.sourceforge.pmd.lang.java.ast.ASTArrayDimsAndInits; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; /** * 1. Note all private constructors. * 2. Note all instantiations from outside of the class by way of the private * constructor. * 3. Flag instantiations. * <p/> * <p/> * Parameter types can not be matched because they can come as exposed members * of classes. In this case we have no way to know what the type is. We can * make a best effort though which can filter some? * * @author CL Gilbert (dnoyeb@users.sourceforge.net) * @author David Konecny (david.konecny@) * @author Romain PELISSE, belaran@gmail.com, patch bug#1807370 */ public class AccessorClassGenerationRule extends AbstractJavaRule { private List<ClassData> classDataList = new ArrayList<ClassData>(); private int classID = -1; private String packageName; public Object visit(ASTEnumDeclaration node, Object data) { return data; // just skip Enums } public Object visit(ASTCompilationUnit node, Object data) { classDataList.clear(); packageName = node.getScope().getEnclosingSourceFileScope().getPackageName(); return super.visit(node, data); } private static class ClassData { private String className; private List<ASTConstructorDeclaration> privateConstructors; private List<AllocData> instantiations; /** * List of outer class names that exist above this class */ private List<String> classQualifyingNames; public ClassData(String className) { this.className = className; this.privateConstructors = new ArrayList<ASTConstructorDeclaration>(); this.instantiations = new ArrayList<AllocData>(); this.classQualifyingNames = new ArrayList<String>(); } public void addInstantiation(AllocData ad) { instantiations.add(ad); } public Iterator<AllocData> getInstantiationIterator() { return instantiations.iterator(); } public void addConstructor(ASTConstructorDeclaration cd) { privateConstructors.add(cd); } public Iterator<ASTConstructorDeclaration> getPrivateConstructorIterator() { return privateConstructors.iterator(); } public String getClassName() { return className; } public void addClassQualifyingName(String name) { classQualifyingNames.add(name); } public List<String> getClassQualifyingNamesList() { return classQualifyingNames; } } private static class AllocData { private String name; private int argumentCount; private ASTAllocationExpression allocationExpression; private boolean isArray; public AllocData(ASTAllocationExpression node, String aPackageName, List<String> classQualifyingNames) { if (node.jjtGetChild(1) instanceof ASTArguments) { ASTArguments aa = (ASTArguments) node.jjtGetChild(1); argumentCount = aa.getArgumentCount(); //Get name and strip off all superfluous data //strip off package name if it is current package if (!(node.jjtGetChild(0) instanceof ASTClassOrInterfaceType)) { throw new RuntimeException("BUG: Expected a ASTClassOrInterfaceType, got a " + node.jjtGetChild(0).getClass()); } ASTClassOrInterfaceType an = (ASTClassOrInterfaceType) node.jjtGetChild(0); name = stripString(aPackageName + '.', an.getImage()); //strip off outer class names //try OuterClass, then try OuterClass.InnerClass, then try OuterClass.InnerClass.InnerClass2, etc... String findName = ""; for (ListIterator<String> li = classQualifyingNames.listIterator(classQualifyingNames.size()); li.hasPrevious();) { String aName = li.previous(); findName = aName + '.' + findName; if (name.startsWith(findName)) { //strip off name and exit name = name.substring(findName.length()); break; } } } else if (node.jjtGetChild(1) instanceof ASTArrayDimsAndInits) { //this is incomplete because I dont need it. // child 0 could be primitive or object (ASTName or ASTPrimitiveType) isArray = true; } allocationExpression = node; } public String getName() { return name; } public int getArgumentCount() { return argumentCount; } public ASTAllocationExpression getASTAllocationExpression() { return allocationExpression; } public boolean isArray() { return isArray; } } /** * Outer interface visitation */ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isInterface()) { if (!(node.jjtGetParent().jjtGetParent() instanceof ASTCompilationUnit)) { // not a top level interface String interfaceName = node.getImage(); int formerID = getClassID(); setClassID(classDataList.size()); ClassData newClassData = new ClassData(interfaceName); //store the names of any outer classes of this class in the classQualifyingName List ClassData formerClassData = classDataList.get(formerID); newClassData.addClassQualifyingName(formerClassData.getClassName()); classDataList.add(getClassID(), newClassData); Object o = super.visit(node, data); setClassID(formerID); return o; } else { String interfaceName = node.getImage(); classDataList.clear(); setClassID(0); classDataList.add(getClassID(), new ClassData(interfaceName)); Object o = super.visit(node, data); if (o != null) { processRule(o); } else { processRule(data); } setClassID(-1); return o; } } else if (!(node.jjtGetParent().jjtGetParent() instanceof ASTCompilationUnit)) { // not a top level class String className = node.getImage(); int formerID = getClassID(); setClassID(classDataList.size()); ClassData newClassData = new ClassData(className); // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (formerID == -1 || formerID >= classDataList.size()) { return null; } //store the names of any outer classes of this class in the classQualifyingName List ClassData formerClassData = classDataList.get(formerID); newClassData.addClassQualifyingName(formerClassData.getClassName()); classDataList.add(getClassID(), newClassData); Object o = super.visit(node, data); setClassID(formerID); return o; } // outer classes if ( ! node.isStatic() ) { // See bug# 1807370 String className = node.getImage(); classDataList.clear(); setClassID(0);//first class classDataList.add(getClassID(), new ClassData(className)); } Object o = super.visit(node, data); if (o != null && ! node.isStatic() ) { // See bug# 1807370 processRule(o); } else { processRule(data); } setClassID(-1); return o; } /** * Store all target constructors */ public Object visit(ASTConstructorDeclaration node, Object data) { if (node.isPrivate()) { getCurrentClassData().addConstructor(node); } return super.visit(node, data); } public Object visit(ASTAllocationExpression node, Object data) { // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (classID == -1 || getCurrentClassData() == null) { return data; } AllocData ad = new AllocData(node, packageName, getCurrentClassData().getClassQualifyingNamesList()); if (!ad.isArray()) { getCurrentClassData().addInstantiation(ad); } return super.visit(node, data); } private void processRule(Object ctx) { //check constructors of outerIterator against allocations of innerIterator for (ClassData outerDataSet : classDataList) { for (Iterator<ASTConstructorDeclaration> constructors = outerDataSet.getPrivateConstructorIterator(); constructors.hasNext();) { ASTConstructorDeclaration cd = constructors.next(); for (ClassData innerDataSet : classDataList) { if (outerDataSet == innerDataSet) { continue; } for (Iterator<AllocData> allocations = innerDataSet.getInstantiationIterator(); allocations.hasNext();) { AllocData ad = allocations.next(); //if the constructor matches the instantiation //flag the instantiation as a generator of an extra class if (outerDataSet.getClassName().equals(ad.getName()) && (cd.getParameterCount() == ad.getArgumentCount())) { addViolation(ctx, ad.getASTAllocationExpression()); } } } } } } private ClassData getCurrentClassData() { // TODO // this is a hack to bail out here // but I'm not sure why this is happening // TODO if (classID >= classDataList.size()) { return null; } return classDataList.get(classID); } private void setClassID(int id) { classID = id; } private int getClassID() { return classID; } //remove = Fire. //value = someFire.Fighter // 0123456789012345 //index = 4 //remove.size() = 5 //value.substring(0,4) = some //value.substring(4 + remove.size()) = Fighter //return "someFighter" // TODO move this into StringUtil private static String stripString(String remove, String value) { String returnValue; int index = value.indexOf(remove); if (index != -1) { //if the package name can start anywhere but 0 please inform the author because this will break returnValue = value.substring(0, index) + value.substring(index + remove.length()); } else { returnValue = value; } return returnValue; } }
bsd-3-clause